hilbert-chart-3d 0.3.0 → 0.3.1
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.
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
// Version 0.3.
|
|
1
|
+
// Version 0.3.1 hilbert-chart-3d - https://github.com/vasturiano/hilbert-chart-3d
|
|
2
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).HilbertChart3D=t()}(this,function(){"use strict";function e(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}var t="object"==typeof global&&global&&global.Object===Object&&global,i="object"==typeof self&&self&&self.Object===Object&&self,r=t||i||Function("return this")(),n=function(){return r.Date.now()},s=/\s/;var a=/^\s+/;function o(e){return e?e.slice(0,function(e){for(var t=e.length;t--&&s.test(e.charAt(t)););return t}(e)+1).replace(a,""):e}var l=r.Symbol,u=Object.prototype,c=u.hasOwnProperty,h=u.toString,d=l?l.toStringTag:void 0;var p=Object.prototype.toString;var f=l?l.toStringTag:void 0;function m(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":f&&f in Object(e)?function(e){var t=c.call(e,d),i=e[d];try{e[d]=void 0;var r=!0}catch(e){}var n=h.call(e);return r&&(t?e[d]=i:delete e[d]),n}(e):function(e){return p.call(e)}(e)}var g=/^[-+]0x[0-9a-f]+$/i,_=/^0b[01]+$/i,v=/^0o[0-7]+$/i,b=parseInt;function y(t){if("number"==typeof t)return t;if(function(e){return"symbol"==typeof e||function(e){return null!=e&&"object"==typeof e}(e)&&"[object Symbol]"==m(e)}(t))return NaN;if(e(t)){var i="function"==typeof t.valueOf?t.valueOf():t;t=e(i)?i+"":i}if("string"!=typeof t)return 0===t?t:+t;t=o(t);var r=_.test(t);return r||v.test(t)?b(t.slice(2),r?2:8):g.test(t)?NaN:+t}var x=Math.max,S=Math.min;function T(t,i,r){var s,a,o,l,u,c,h=0,d=!1,p=!1,f=!0;if("function"!=typeof t)throw new TypeError("Expected a function");function m(e){var i=s,r=a;return s=a=void 0,h=e,l=t.apply(r,i)}function g(e){var t=e-c;return void 0===c||t>=i||t<0||p&&e-h>=o}function _(){var e=n();if(g(e))return v(e);u=setTimeout(_,function(e){var t=i-(e-c);return p?S(t,o-(e-h)):t}(e))}function v(e){return u=void 0,f&&s?m(e):(s=a=void 0,l)}function b(){var e=n(),t=g(e);if(s=arguments,a=this,c=e,t){if(void 0===u)return function(e){return h=e,u=setTimeout(_,i),d?m(e):l}(c);if(p)return clearTimeout(u),u=setTimeout(_,i),m(c)}return void 0===u&&(u=setTimeout(_,i)),l}return i=y(i)||0,e(r)&&(d=!!r.leading,o=(p="maxWait"in r)?x(y(r.maxWait)||0,i):o,f="trailing"in r?!!r.trailing:f),b.cancel=function(){void 0!==u&&clearTimeout(u),h=0,s=c=a=u=void 0},b.flush=function(){return void 0===u?l:v(n())},b}function M(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,r=Array(t);i<t;i++)r[i]=e[i];return r}function E(e,t,i){return Object.defineProperty(e,"prototype",{writable:!1}),e}function w(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var i=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=i){var r,n,s,a,o=[],l=!0,u=!1;try{if(s=(i=i.call(e)).next,0===t);else for(;!(l=(r=s.call(i)).done)&&(o.push(r.value),o.length!==t);l=!0);}catch(e){u=!0,n=e}finally{try{if(!l&&null!=i.return&&(a=i.return(),Object(a)!==a))return}finally{if(u)throw n}}return o}}(e,t)||function(e,t){if(e){if("string"==typeof e)return M(e,t);var i={}.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?M(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 A=E(function e(t,i){var r=i.default,n=void 0===r?null:r,s=i.triggerUpdate,a=void 0===s||s,o=i.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=n,this.triggerUpdate=a,this.onChange=l});function R(e){var t=e.stateInit,i=void 0===t?function(){return{}}:t,r=e.props,n=void 0===r?{}:r,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(n).map(function(e){return new A(e,n[e])});return function e(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];var s=!!(this instanceof e?this.constructor:void 0),o=s?r.shift():void 0,u=r[0],h=void 0===u?{}:u,f=Object.assign({},i instanceof Function?i(h):i,{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=T(function(){f.initialised&&(d.call(g,f,m),m={})},1);return p.forEach(function(e){g[e.name]=function(e){var t=e.name,i=e.triggerUpdate,r=void 0!==i&&i,n=e.onChange,s=void 0===n?function(e,t){}:n,a=e.defaultVal,o=void 0===a?null:a;return function(e){var i=f[t];if(!arguments.length)return i;var n=void 0===e?o:e;return f[t]=n,s.call(g,n,f,i),!m.hasOwnProperty(t)&&(m[t]=i),r&&v(),g}}(e)}),Object.keys(a).forEach(function(e){g[e]=function(){for(var t,i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return(t=a[e]).call.apply(t,[g,f].concat(r))}}),Object.entries(l).forEach(function(e){var t=w(e,2),i=t[0],r=t[1];return g[i]=g[r]}),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 C=function(e){return"function"==typeof e?e:"string"==typeof e?function(t){return t[e]}:function(t){return e}};const N="187",P=0,L=1,D=2,U=0,I=1,F=2,O=3,B=1,k=3,z=0,G=1,V=2,H=100,W=101,j=102,$=103,X=104,q=200,Y=201,K=202,Z=203,Q=204,J=205,ee=206,te=207,ie=208,re=209,ne=210,se=211,ae=212,oe=213,le=214,ue=0,ce=1,he=2,de=3,pe=4,fe=5,me=6,ge=7,_e=0,ve=1,be=2,ye=1,xe=2,Se=3,Te=4,Me=5,Ee=6,we=7,Ae=301,Re=302,Ce=303,Ne=304,Pe=1e3,Le=1001,De=1002,Ue=1003,Ie=1004,Fe=1005,Oe=1006,Be=1007,ke=1008,ze=1009,Ge=1010,Ve=1011,He=1012,We=1013,je=1014,$e=1015,Xe=1016,qe=1017,Ye=1018,Ke=1020,Ze=35902,Qe=35899,Je=1021,et=1022,tt=1023,it=1026,rt=1027,nt=1028,st=1029,at=1030,ot=1031,lt=1032,ut=1033,ct=33776,ht=33777,dt=33778,pt=33779,ft=35840,mt=35841,gt=35842,_t=35843,vt=36196,bt=37492,yt=37496,xt=37488,St=37489,Tt=37490,Mt=37491,Et=37808,wt=37809,At=37810,Rt=37811,Ct=37812,Nt=37813,Pt=37814,Lt=37815,Dt=37816,Ut=37817,It=37818,Ft=37819,Ot=37820,Bt=37821,kt=36492,zt=36494,Gt=36495,Vt=36283,Ht=36284,Wt=36285,jt=36286,$t="",Xt="srgb",qt="srgb-linear",Yt="linear",Kt="srgb",Zt=7680,Qt=512,Jt=513,ei=514,ti=515,ii=516,ri=517,ni=518,si=519,ai=35044,oi=35048,li="300 es",ui=2e3,ci=2001,hi="compute",di="render",pi="depthTextureCompare",fi=0,mi=1,gi=2;function _i(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function vi(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}function bi(){const e=vi("canvas");return e.style.display="block",e}const yi={};function xi(...e){const t="THREE."+e.shift();console.log(t,...e)}function Si(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 Ti(...e){const t="THREE."+(e=Si(e)).shift();{const i=e[0];i&&i.isStackTrace?console.warn(i.getError(t)):console.warn(t,...e)}}function Mi(...e){const t="THREE."+(e=Si(e)).shift();{const i=e[0];i&&i.isStackTrace?console.error(i.getError(t)):console.error(t,...e)}}function Ei(...e){const t=e.join(" ");t in yi||(yi[t]=!0,Ti(...e))}function wi(){return"undefined"!=typeof self&&void 0!==self.scheduler&&void 0!==self.scheduler.yield?self.scheduler.yield():new Promise(e=>{requestAnimationFrame(e)})}const Ai={[ue]:0,[he]:6,[pe]:4,[de]:5,[ce]:1,[me]:2,[ge]:7,[fe]:3};class Ri{addEventListener(e,t){void 0===this._listeners&&(this._listeners={});const i=this._listeners;void 0===i[e]&&(i[e]=[]),-1===i[e].indexOf(t)&&i[e].push(t)}hasEventListener(e,t){const i=this._listeners;return void 0!==i&&(void 0!==i[e]&&-1!==i[e].indexOf(t))}removeEventListener(e,t){const i=this._listeners;if(void 0===i)return;const r=i[e];if(void 0!==r){const e=r.indexOf(t);-1!==e&&r.splice(e,1)}}dispatchEvent(e){const t=this._listeners;if(void 0===t)return;const i=t[e.type];if(void 0!==i){e.target=this;const t=i.slice(0);for(let i=0,r=t.length;i<r;i++)t[i].call(this,e);e.target=null}}}const Ci=["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 Ni=1234567;const Pi=Math.PI/180,Li=180/Math.PI;function Di(){const e=4294967295*Math.random()|0,t=4294967295*Math.random()|0,i=4294967295*Math.random()|0,r=4294967295*Math.random()|0;return(Ci[255&e]+Ci[e>>8&255]+Ci[e>>16&255]+Ci[e>>24&255]+"-"+Ci[255&t]+Ci[t>>8&255]+"-"+Ci[t>>16&15|64]+Ci[t>>24&255]+"-"+Ci[63&i|128]+Ci[i>>8&255]+"-"+Ci[i>>16&255]+Ci[i>>24&255]+Ci[255&r]+Ci[r>>8&255]+Ci[r>>16&255]+Ci[r>>24&255]).toLowerCase()}function Ui(e,t,i){return Math.max(t,Math.min(i,e))}function Ii(e,t){return(e%t+t)%t}function Fi(e,t,i){return(1-i)*e+i*t}function Oi(e){return Math.pow(2,Math.floor(Math.log(e)/Math.LN2))}function Bi(e){switch(e.constructor){case Uint32Array:return 4294967295;case Uint16Array:return 65535;case Uint8Array:case Uint8ClampedArray:return 255;case Int32Array:return 2147483647;case Int16Array:return 32767;case Int8Array:return 127;default:return}}function ki(e,t){if(t.constructor===Float32Array)return e;const i=Bi(t);if(void 0===i)throw new Error("THREE.MathUtils: Invalid component type.");return Math.max(e/i,-1)}function zi(e,t){if(t.constructor===Float32Array)return e;const i=Bi(t);if(void 0===i)throw new Error("THREE.MathUtils: Invalid component type.");return Math.round(e*i)}const Gi={DEG2RAD:Pi,RAD2DEG:Li,generateUUID:Di,clamp:Ui,euclideanModulo:Ii,mapLinear:function(e,t,i,r,n){return r+(e-t)*(n-r)/(i-t)},inverseLerp:function(e,t,i){return e!==t?(i-e)/(t-e):0},lerp:Fi,damp:function(e,t,i,r){return Fi(e,t,1-Math.exp(-i*r))},pingpong:function(e,t=1){return t-Math.abs(Ii(e,2*t)-t)},smoothstep:function(e,t,i){return e<=t?0:e>=i?1:(e=(e-t)/(i-t))*e*(3-2*e)},smootherstep:function(e,t,i){return e<=t?0:e>=i?1:(e=(e-t)/(i-t))*e*e*(e*(6*e-15)+10)},randInt:function(e,t){return e+Math.floor(Math.random()*(t-e+1))},randFloat:function(e,t){return e+Math.random()*(t-e)},randFloatSpread:function(e){return e*(.5-Math.random())},seededRandom:function(e){void 0!==e&&(Ni=e);let t=Ni+=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*Pi},radToDeg:function(e){return e*Li},isPowerOfTwo:function(e){return e>0&&Number.isInteger(e)&&2**Math.round(Math.log2(e))===e},ceilPowerOfTwo:function(e){return Math.pow(2,Math.ceil(Math.log(e)/Math.LN2))},floorPowerOfTwo:Oi,setQuaternionFromProperEuler:function(e,t,i,r,n){const s=Math.cos,a=Math.sin,o=s(i/2),l=a(i/2),u=s((t+r)/2),c=a((t+r)/2),h=s((t-r)/2),d=a((t-r)/2),p=s((r-t)/2),f=a((r-t)/2);switch(n){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:Ti("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+n)}},normalize:zi,denormalize:ki};class Vi{static{this.prototype.isVector2=!0}constructor(e=0,t=0){this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("THREE.Vector2: index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("THREE.Vector2: index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,i=this.y,r=e.elements;return this.x=r[0]*t+r[3]*i+r[6],this.y=r[1]*t+r[4]*i+r[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Ui(this.x,e.x,t.x),this.y=Ui(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=Ui(this.x,e,t),this.y=Ui(this.y,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Ui(i,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 i=this.dot(e)/t;return Math.acos(Ui(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y;return t*t+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const i=Math.cos(t),r=Math.sin(t),n=this.x-e.x,s=this.y-e.y;return this.x=n*i-s*r+e.x,this.y=n*r+s*i+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class Hi{constructor(e=0,t=0,i=0,r=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=i,this._w=r}static slerpFlat(e,t,i,r,n,s,a){let o=i[r+0],l=i[r+1],u=i[r+2],c=i[r+3],h=n[s+0],d=n[s+1],p=n[s+2],f=n[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 i=Math.acos(e),r=Math.sin(i);t=Math.sin(t*i)/r,o=o*t+h*(a=Math.sin(a*i)/r),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,i,r,n,s){const a=i[r],o=i[r+1],l=i[r+2],u=i[r+3],c=n[s],h=n[s+1],d=n[s+2],p=n[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,i,r){return this._x=e,this._y=t,this._z=i,this._w=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const i=e._x,r=e._y,n=e._z,s=e._order,a=Math.cos,o=Math.sin,l=a(i/2),u=a(r/2),c=a(n/2),h=o(i/2),d=o(r/2),p=o(n/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:Ti("Quaternion: .setFromEuler() encountered an unknown order: "+s)}return!0===t&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const i=t/2,r=Math.sin(i);return this._x=e.x*r,this._y=e.y*r,this._z=e.z*r,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,i=t[0],r=t[4],n=t[8],s=t[1],a=t[5],o=t[9],l=t[2],u=t[6],c=t[10],h=i+a+c;if(h>0){const e=.5/Math.sqrt(h+1);this._w=.25/e,this._x=(u-o)*e,this._y=(n-l)*e,this._z=(s-r)*e}else if(i>a&&i>c){const e=2*Math.sqrt(1+i-a-c);this._w=(u-o)/e,this._x=.25*e,this._y=(r+s)/e,this._z=(n+l)/e}else if(a>c){const e=2*Math.sqrt(1+a-i-c);this._w=(n-l)/e,this._x=(r+s)/e,this._y=.25*e,this._z=(o+u)/e}else{const e=2*Math.sqrt(1+c-i-a);this._w=(s-r)/e,this._x=(n+l)/e,this._y=(o+u)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let i=e.dot(t)+1;return i<1e-8?(i=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=i):(this._x=0,this._y=-e.z,this._z=e.y,this._w=i)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=i),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Ui(this.dot(e),-1,1)))}rotateTowards(e,t){const i=this.angleTo(e);if(0===i)return this;const r=Math.min(1,t/i);return this.slerp(e,r),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return 0===e?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const i=e._x,r=e._y,n=e._z,s=e._w,a=t._x,o=t._y,l=t._z,u=t._w;return this._x=i*u+s*a+r*l-n*o,this._y=r*u+s*o+n*a-i*l,this._z=n*u+s*l+i*o-r*a,this._w=s*u-i*a-r*o-n*l,this._onChangeCallback(),this}slerp(e,t){let i=e._x,r=e._y,n=e._z,s=e._w,a=this.dot(e);a<0&&(i=-i,r=-r,n=-n,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+i*t,this._y=this._y*o+r*t,this._z=this._z*o+n*t,this._w=this._w*o+s*t,this._onChangeCallback()}else this._x=this._x*o+i*t,this._y=this._y*o+r*t,this._z=this._z*o+n*t,this._w=this._w*o+s*t,this.normalize();return this}slerpQuaternions(e,t,i){return this.copy(e).slerp(t,i)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),i=Math.random(),r=Math.sqrt(1-i),n=Math.sqrt(i);return this.set(r*Math.sin(e),r*Math.cos(e),n*Math.sin(t),n*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class Wi{static{this.prototype.isVector3=!0}constructor(e=0,t=0,i=0){this.x=e,this.y=t,this.z=i}set(e,t,i){return void 0===i&&(i=this.z),this.x=e,this.y=t,this.z=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("THREE.Vector3: index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("THREE.Vector3: index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion($i.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion($i.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,i=this.y,r=this.z,n=e.elements;return this.x=n[0]*t+n[3]*i+n[6]*r,this.y=n[1]*t+n[4]*i+n[7]*r,this.z=n[2]*t+n[5]*i+n[8]*r,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,i=this.y,r=this.z,n=e.elements,s=1/(n[3]*t+n[7]*i+n[11]*r+n[15]);return this.x=(n[0]*t+n[4]*i+n[8]*r+n[12])*s,this.y=(n[1]*t+n[5]*i+n[9]*r+n[13])*s,this.z=(n[2]*t+n[6]*i+n[10]*r+n[14])*s,this}applyQuaternion(e){const t=this.x,i=this.y,r=this.z,n=e.x,s=e.y,a=e.z,o=e.w,l=2*(s*r-a*i),u=2*(a*t-n*r),c=2*(n*i-s*t);return this.x=t+o*l+s*c-a*u,this.y=i+o*u+a*l-n*c,this.z=r+o*c+n*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,i=this.y,r=this.z,n=e.elements;return this.x=n[0]*t+n[4]*i+n[8]*r,this.y=n[1]*t+n[5]*i+n[9]*r,this.z=n[2]*t+n[6]*i+n[10]*r,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Ui(this.x,e.x,t.x),this.y=Ui(this.y,e.y,t.y),this.z=Ui(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=Ui(this.x,e,t),this.y=Ui(this.y,e,t),this.z=Ui(this.z,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Ui(i,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,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const i=e.x,r=e.y,n=e.z,s=t.x,a=t.y,o=t.z;return this.x=r*o-n*a,this.y=n*s-i*o,this.z=i*a-r*s,this}projectOnVector(e){const t=e.lengthSq();if(0===t)return this.set(0,0,0);const i=e.dot(this)/t;return this.copy(e).multiplyScalar(i)}projectOnPlane(e){return ji.copy(this).projectOnVector(e),this.sub(ji)}reflect(e){return this.sub(ji.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(0===t)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(Ui(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y,r=this.z-e.z;return t*t+i*i+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,i){const r=Math.sin(t)*e;return this.x=r*Math.sin(i),this.y=Math.cos(t)*e,this.z=r*Math.cos(i),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,i){return this.x=e*Math.sin(t),this.y=i,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),i=this.setFromMatrixColumn(e,1).length(),r=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=i,this.z=r,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,4*t)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,3*t)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=2*Math.random()-1,i=Math.sqrt(1-t*t);return this.x=i*Math.cos(e),this.y=t,this.z=i*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const ji=new Wi,$i=new Hi;class Xi{static{this.prototype.isMatrix3=!0}constructor(e,t,i,r,n,s,a,o,l){this.elements=[1,0,0,0,1,0,0,0,1],void 0!==e&&this.set(e,t,i,r,n,s,a,o,l)}set(e,t,i,r,n,s,a,o,l){const u=this.elements;return u[0]=e,u[1]=r,u[2]=a,u[3]=t,u[4]=n,u[5]=o,u[6]=i,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,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],this}extractBasis(e,t,i){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,r=t.elements,n=this.elements,s=i[0],a=i[3],o=i[6],l=i[1],u=i[4],c=i[7],h=i[2],d=i[5],p=i[8],f=r[0],m=r[3],g=r[6],_=r[1],v=r[4],b=r[7],y=r[2],x=r[5],S=r[8];return n[0]=s*f+a*_+o*y,n[3]=s*m+a*v+o*x,n[6]=s*g+a*b+o*S,n[1]=l*f+u*_+c*y,n[4]=l*m+u*v+c*x,n[7]=l*g+u*b+c*S,n[2]=h*f+d*_+p*y,n[5]=h*m+d*v+p*x,n[8]=h*g+d*b+p*S,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[1],r=e[2],n=e[3],s=e[4],a=e[5],o=e[6],l=e[7],u=e[8];return t*s*u-t*a*l-i*n*u+i*a*o+r*n*l-r*s*o}invert(){const e=this.elements,t=e[0],i=e[1],r=e[2],n=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*n,d=l*n-s*o,p=t*c+i*h+r*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]=(r*l-u*i)*f,e[2]=(a*i-r*s)*f,e[3]=h*f,e[4]=(u*t-r*o)*f,e[5]=(r*n-a*t)*f,e[6]=d*f,e[7]=(i*o-l*t)*f,e[8]=(s*t-i*n)*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,i,r,n,s,a){const o=Math.cos(n),l=Math.sin(n);return this.set(i*o,i*l,-i*(o*s+l*a)+s+e,-r*l,r*o,-r*(-l*s+o*a)+a+t,0,0,1),this}scale(e,t){return Ei("Matrix3: .scale() is deprecated. Use .makeScale() instead."),this.premultiply(qi.makeScale(e,t)),this}rotate(e){return Ei("Matrix3: .rotate() is deprecated. Use .makeRotation() instead."),this.premultiply(qi.makeRotation(-e)),this}translate(e,t){return Ei("Matrix3: .translate() is deprecated. Use .makeTranslation() instead."),this.premultiply(qi.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,i,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,i=e.elements;for(let e=0;e<9;e++)if(t[e]!==i[e])return!1;return!0}fromArray(e,t=0){for(let i=0;i<9;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e}clone(){return(new this.constructor).fromArray(this.elements)}}const qi=new Xi,Yi=(new Xi).set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),Ki=(new Xi).set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Zi(){const e={enabled:!0,workingColorSpace:qt,spaces:{},convert:function(e,t,i){return!1!==this.enabled&&t!==i&&t&&i?(this.spaces[t].transfer===Kt&&(e.r=Ji(e.r),e.g=Ji(e.g),e.b=Ji(e.b)),this.spaces[t].primaries!==this.spaces[i].primaries&&(e.applyMatrix3(this.spaces[t].toXYZ),e.applyMatrix3(this.spaces[i].fromXYZ)),this.spaces[i].transfer===Kt&&(e.r=er(e.r),e.g=er(e.g),e.b=er(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===$t?Yt: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,i){return e.copy(this.spaces[i].fromXYZ).multiply(this.spaces[t].toXYZ)},_getDrawingBufferColorSpace:function(e){return this.spaces[e].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(e=this.workingColorSpace){return this.spaces[e].workingColorSpaceConfig.unpackColorSpace}},t=[.64,.33,.3,.6,.15,.06],i=[.2126,.7152,.0722],r=[.3127,.329];return e.define({[qt]:{primaries:t,whitePoint:r,transfer:Yt,toXYZ:Yi,fromXYZ:Ki,luminanceCoefficients:i,workingColorSpaceConfig:{unpackColorSpace:Xt},outputColorSpaceConfig:{drawingBufferColorSpace:Xt}},[Xt]:{primaries:t,whitePoint:r,transfer:Kt,toXYZ:Yi,fromXYZ:Ki,luminanceCoefficients:i,outputColorSpaceConfig:{drawingBufferColorSpace:Xt}}}),e}const Qi=Zi();function Ji(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function er(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}let tr;class ir{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src))return e.src;if("undefined"==typeof HTMLCanvasElement)return e.src;let i;if(e instanceof HTMLCanvasElement)i=e;else{void 0===tr&&(tr=vi("canvas")),tr.width=e.width,tr.height=e.height;const t=tr.getContext("2d");e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),i=tr}return i.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=vi("canvas");t.width=e.width,t.height=e.height;const i=t.getContext("2d");i.drawImage(e,0,0,e.width,e.height);const r=i.getImageData(0,0,e.width,e.height),n=r.data;for(let e=0;e<n.length;e++)n[e]=255*Ji(n[e]/255);return i.putImageData(r,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*Ji(t[e]/255)):t[e]=Ji(t[e]);return{data:t,width:e.width,height:e.height}}return Ti("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let rr=0;class nr{constructor(e=null){this.isTextureSource=!0,Object.defineProperty(this,"id",{value:rr++}),this.uuid=Di(),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.displayWidth,t.displayHeight,0):null!==t?e.set(t.width||0,t.height||0,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 i={uuid:this.uuid,url:""},r=this.data;if(null!==r){let e;if(Array.isArray(r)){e=[];for(let t=0,i=r.length;t<i;t++)r[t].isDataTexture?e.push(sr(r[t].image)):e.push(sr(r[t]))}else e=sr(r);i.url=e}return t||(e.images[this.uuid]=i),i}}function sr(e){return"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?ir.getDataURL(e):e.data?{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(Ti("Texture: Unable to serialize Texture."),{})}let ar=0;const or=new Wi;class lr extends Ri{constructor(e=lr.DEFAULT_IMAGE,t=lr.DEFAULT_MAPPING,i=1001,r=1001,n=1006,s=1008,a=1023,o=ze,l=lr.DEFAULT_ANISOTROPY,u=""){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:ar++}),this.uuid=Di(),this.name="",this.source=new nr(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=i,this.wrapT=r,this.magFilter=n,this.minFilter=s,this.anisotropy=l,this.format=a,this.internalFormat=null,this.type=o,this.offset=new Vi(0,0),this.repeat=new Vi(1,1),this.center=new Vi(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new Xi,this.generateMipmaps=!0,this.mipmapsAutoUpdate=!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,this.isPMREMTexture=!1,this.normalized=!1}get width(){return this.source.getSize(or).x}get height(){return this.source.getSize(or).y}get depth(){return this.source.getSize(or).z}get image(){return this.source.data}set image(e){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return(new this.constructor).copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.normalized=e.normalized,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.mipmapsAutoUpdate=e.mipmapsAutoUpdate,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.isPMREMTexture=e.isPMREMTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const t in e){const i=e[t];if(void 0===i){Ti(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const r=this[t];void 0!==r?r&&i&&r.isVector2&&i.isVector2||r&&i&&r.isVector3&&i.isVector3||r&&i&&r.isMatrix3&&i.isMatrix3?r.copy(i):this[t]=i:Ti(`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 i={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,normalized:this.normalized,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,mipmapsAutoUpdate:this.mipmapsAutoUpdate,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(i.userData=this.userData),t||(e.textures[this.uuid]=i),i}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 Pe:e.x=e.x-Math.floor(e.x);break;case Le:e.x=e.x<0?0:1;break;case De: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 Pe:e.y=e.y-Math.floor(e.y);break;case Le:e.y=e.y<0?0:1;break;case De: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++}}lr.DEFAULT_IMAGE=null,lr.DEFAULT_MAPPING=300,lr.DEFAULT_ANISOTROPY=1;class ur{static{this.prototype.isVector4=!0}constructor(e=0,t=0,i=0,r=1){this.x=e,this.y=t,this.z=i,this.w=r}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,i,r){return this.x=e,this.y=t,this.z=i,this.w=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("THREE.Vector4: index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("THREE.Vector4: index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=void 0!==e.w?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,i=this.y,r=this.z,n=this.w,s=e.elements;return this.x=s[0]*t+s[4]*i+s[8]*r+s[12]*n,this.y=s[1]*t+s[5]*i+s[9]*r+s[13]*n,this.z=s[2]*t+s[6]*i+s[10]*r+s[14]*n,this.w=s[3]*t+s[7]*i+s[11]*r+s[15]*n,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,i,r,n;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,b=(c+f)/4,y=(p+m)/4;return e>o&&e>_?e<s?(i=0,r=.707106781,n=.707106781):(i=Math.sqrt(e),r=v/i,n=b/i):o>_?o<s?(i=.707106781,r=0,n=.707106781):(r=Math.sqrt(o),i=v/r,n=y/r):_<s?(i=.707106781,r=.707106781,n=0):(n=Math.sqrt(_),i=b/n,r=y/n),this.set(i,r,n,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=Ui(this.x,e.x,t.x),this.y=Ui(this.y,e.y,t.y),this.z=Ui(this.z,e.z,t.z),this.w=Ui(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=Ui(this.x,e,t),this.y=Ui(this.y,e,t),this.z=Ui(this.z,e,t),this.w=Ui(this.w,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Ui(i,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,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this.w=e.w+(t.w-e.w)*i,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class cr extends Ri{constructor(e=1,t=1,i={}){super(),i=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Oe,depthBuffer:!0,stencilBuffer:!1,resolveColorBuffer:!0,resolveDepthBuffer:!0,resolveStencilBuffer:!0,storeMultisampledColorBuffer:!0,storeMultisampledDepthBuffer:!0,storeMultisampledStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1,useArrayDepthTexture:!1},i),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=i.depth,this.scissor=new ur(0,0,e,t),this.scissorTest=!1,this.viewport=new ur(0,0,e,t),this.textures=[];const r=i.count;for(let n=0;n<r;n++)this.textures[n]=new lr({width:e,height:t,depth:i.depth}),this.textures[n].isRenderTargetTexture=!0,this.textures[n].renderTarget=this;this._setTextureOptions(i),this.depthBuffer=i.depthBuffer,this.stencilBuffer=i.stencilBuffer,this.resolveColorBuffer=i.resolveColorBuffer,this.resolveDepthBuffer=i.resolveDepthBuffer,this.resolveStencilBuffer=i.resolveStencilBuffer,this.storeMultisampledColorBuffer=i.storeMultisampledColorBuffer,this.storeMultisampledDepthBuffer=i.storeMultisampledDepthBuffer,this.storeMultisampledStencilBuffer=i.storeMultisampledStencilBuffer,this._depthTexture=null,this.depthTexture=i.depthTexture,this.samples=i.samples,this.multiview=i.multiview,this.useArrayDepthTexture=i.useArrayDepthTexture}_setTextureOptions(e={}){const t={minFilter:Oe,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.mipmapsAutoUpdate&&(t.mipmapsAutoUpdate=e.mipmapsAutoUpdate),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===this&&(this._depthTexture.renderTarget=null),null!==e&&null===e.renderTarget&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,i=1){if(this.width!==e||this.height!==t||this.depth!==i){this.width=e,this.height=t,this.depth=i;for(let r=0,n=this.textures.length;r<n;r++)this.textures[r].image.width=e,this.textures[r].image.height=t,this.textures[r].image.depth=i,!0!==this.textures[r].isData3DTexture&&(this.textures[r].isArrayTexture=this.textures[r].image.depth>1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return(new this.constructor).copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,i=e.textures.length;t<i;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;const i=Object.assign({},e.textures[t].image);this.textures[t].source=new nr(i)}if(this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveColorBuffer=e.resolveColorBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,this.storeMultisampledColorBuffer=e.storeMultisampledColorBuffer,this.storeMultisampledDepthBuffer=e.storeMultisampledDepthBuffer,this.storeMultisampledStencilBuffer=e.storeMultisampledStencilBuffer,null!==e.depthTexture)if(e.depthTexture.renderTarget===e){const t=e.depthTexture.clone();t.renderTarget=null,this.depthTexture=t}else this.depthTexture=e.depthTexture;else this.depthTexture=null;return this.samples=e.samples,this.multiview=e.multiview,this.useArrayDepthTexture=e.useArrayDepthTexture,this}dispose(){this.dispatchEvent({type:"dispose"})}}class hr extends cr{constructor(e=1,t=1,i={}){super(e,t,i),this.isWebGLRenderTarget=!0}}class dr extends lr{constructor(e=null,t=1,i=1,r=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:i,depth:r},this.magFilter=Ue,this.minFilter=Ue,this.wrapR=Le,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}copy(e){return super.copy(e),this.wrapR=e.wrapR,this}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class pr extends lr{constructor(e=null,t=1,i=1,r=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:i,depth:r},this.magFilter=Ue,this.minFilter=Ue,this.wrapR=Le,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}copy(e){return super.copy(e),this.wrapR=e.wrapR,this}}class fr{static{this.prototype.isMatrix4=!0}constructor(e,t,i,r,n,s,a,o,l,u,c,h,d,p,f,m){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],void 0!==e&&this.set(e,t,i,r,n,s,a,o,l,u,c,h,d,p,f,m)}set(e,t,i,r,n,s,a,o,l,u,c,h,d,p,f,m){const g=this.elements;return g[0]=e,g[4]=t,g[8]=i,g[12]=r,g[1]=n,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 fr).fromArray(this.elements)}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],t[9]=i[9],t[10]=i[10],t[11]=i[11],t[12]=i[12],t[13]=i[13],t[14]=i[14],t[15]=i[15],this}copyPosition(e){const t=this.elements,i=e.elements;return t[12]=i[12],t[13]=i[13],t[14]=i[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,i){return 0===this.determinantAffine()?(e.set(1,0,0),t.set(0,1,0),i.set(0,0,1),this):(e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this)}makeBasis(e,t,i){return this.set(e.x,t.x,i.x,0,e.y,t.y,i.y,0,e.z,t.z,i.z,0,0,0,0,1),this}extractRotation(e){if(0===e.determinantAffine())return this.identity();const t=this.elements,i=e.elements,r=1/mr.setFromMatrixColumn(e,0).length(),n=1/mr.setFromMatrixColumn(e,1).length(),s=1/mr.setFromMatrixColumn(e,2).length();return t[0]=i[0]*r,t[1]=i[1]*r,t[2]=i[2]*r,t[3]=0,t[4]=i[4]*n,t[5]=i[5]*n,t[6]=i[6]*n,t[7]=0,t[8]=i[8]*s,t[9]=i[9]*s,t[10]=i[10]*s,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,i=e.x,r=e.y,n=e.z,s=Math.cos(i),a=Math.sin(i),o=Math.cos(r),l=Math.sin(r),u=Math.cos(n),c=Math.sin(n);if("XYZ"===e.order){const e=s*u,i=s*c,r=a*u,n=a*c;t[0]=o*u,t[4]=-o*c,t[8]=l,t[1]=i+r*l,t[5]=e-n*l,t[9]=-a*o,t[2]=n-e*l,t[6]=r+i*l,t[10]=s*o}else if("YXZ"===e.order){const e=o*u,i=o*c,r=l*u,n=l*c;t[0]=e+n*a,t[4]=r*a-i,t[8]=s*l,t[1]=s*c,t[5]=s*u,t[9]=-a,t[2]=i*a-r,t[6]=n+e*a,t[10]=s*o}else if("ZXY"===e.order){const e=o*u,i=o*c,r=l*u,n=l*c;t[0]=e-n*a,t[4]=-s*c,t[8]=r+i*a,t[1]=i+r*a,t[5]=s*u,t[9]=n-e*a,t[2]=-s*l,t[6]=a,t[10]=s*o}else if("ZYX"===e.order){const e=s*u,i=s*c,r=a*u,n=a*c;t[0]=o*u,t[4]=r*l-i,t[8]=e*l+n,t[1]=o*c,t[5]=n*l+e,t[9]=i*l-r,t[2]=-l,t[6]=a*o,t[10]=s*o}else if("YZX"===e.order){const e=s*o,i=s*l,r=a*o,n=a*l;t[0]=o*u,t[4]=n-e*c,t[8]=r*c+i,t[1]=c,t[5]=s*u,t[9]=-a*u,t[2]=-l*u,t[6]=i*c+r,t[10]=e-n*c}else if("XZY"===e.order){const e=s*o,i=s*l,r=a*o,n=a*l;t[0]=o*u,t[4]=-c,t[8]=l*u,t[1]=e*c+n,t[5]=s*u,t[9]=i*c-r,t[2]=r*c-i,t[6]=a*u,t[10]=n*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(_r,e,vr)}lookAt(e,t,i){const r=this.elements;return xr.subVectors(e,t),0===xr.lengthSq()&&(xr.z=1),xr.normalize(),br.crossVectors(i,xr),0===br.lengthSq()&&(1===Math.abs(i.z)?xr.x+=1e-4:xr.z+=1e-4,xr.normalize(),br.crossVectors(i,xr)),br.normalize(),yr.crossVectors(xr,br),r[0]=br.x,r[4]=yr.x,r[8]=xr.x,r[1]=br.y,r[5]=yr.y,r[9]=xr.y,r[2]=br.z,r[6]=yr.z,r[10]=xr.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,r=t.elements,n=this.elements,s=i[0],a=i[4],o=i[8],l=i[12],u=i[1],c=i[5],h=i[9],d=i[13],p=i[2],f=i[6],m=i[10],g=i[14],_=i[3],v=i[7],b=i[11],y=i[15],x=r[0],S=r[4],T=r[8],M=r[12],E=r[1],w=r[5],A=r[9],R=r[13],C=r[2],N=r[6],P=r[10],L=r[14],D=r[3],U=r[7],I=r[11],F=r[15];return n[0]=s*x+a*E+o*C+l*D,n[4]=s*S+a*w+o*N+l*U,n[8]=s*T+a*A+o*P+l*I,n[12]=s*M+a*R+o*L+l*F,n[1]=u*x+c*E+h*C+d*D,n[5]=u*S+c*w+h*N+d*U,n[9]=u*T+c*A+h*P+d*I,n[13]=u*M+c*R+h*L+d*F,n[2]=p*x+f*E+m*C+g*D,n[6]=p*S+f*w+m*N+g*U,n[10]=p*T+f*A+m*P+g*I,n[14]=p*M+f*R+m*L+g*F,n[3]=_*x+v*E+b*C+y*D,n[7]=_*S+v*w+b*N+y*U,n[11]=_*T+v*A+b*P+y*I,n[15]=_*M+v*R+b*L+y*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],i=e[4],r=e[8],n=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,b=a*h-o*c,y=s*d-l*u,x=s*h-o*u,S=s*c-a*u;return t*(f*_-m*v+g*b)-i*(p*_-m*y+g*x)+r*(p*v-f*y+g*S)-n*(p*b-f*x+m*S)}determinantAffine(){const e=this.elements,t=e[0],i=e[4],r=e[8],n=e[1],s=e[5],a=e[9],o=e[2],l=e[6],u=e[10];return t*(s*u-a*l)-i*(n*u-a*o)+r*(n*l-s*o)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,i){const r=this.elements;return e.isVector3?(r[12]=e.x,r[13]=e.y,r[14]=e.z):(r[12]=e,r[13]=t,r[14]=i),this}invert(){const e=this.elements,t=e[0],i=e[1],r=e[2],n=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-i*s,v=t*o-r*s,b=t*l-n*s,y=i*o-r*a,x=i*l-n*a,S=r*l-n*o,T=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+b*w+y*E-x*M+S*T;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]=(r*A-i*R-n*w)*N,e[2]=(f*S-m*x+g*y)*N,e[3]=(h*x-c*S-d*y)*N,e[4]=(o*E-s*R-l*M)*N,e[5]=(t*R-r*E+n*M)*N,e[6]=(m*b-p*S-g*v)*N,e[7]=(u*S-h*b+d*v)*N,e[8]=(s*A-a*E+l*T)*N,e[9]=(i*E-t*A-n*T)*N,e[10]=(p*x-f*b+g*_)*N,e[11]=(c*b-u*x-d*_)*N,e[12]=(a*M-s*w-o*T)*N,e[13]=(t*w-i*M+r*T)*N,e[14]=(f*v-p*y-m*_)*N,e[15]=(u*y-c*v+h*_)*N,this}scale(e){const t=this.elements,i=e.x,r=e.y,n=e.z;return t[0]*=i,t[4]*=r,t[8]*=n,t[1]*=i,t[5]*=r,t[9]*=n,t[2]*=i,t[6]*=r,t[10]*=n,t[3]*=i,t[7]*=r,t[11]*=n,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],i=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],r=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,i,r))}makeTranslation(e,t,i){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,i,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),i=Math.sin(e);return this.set(1,0,0,0,0,t,-i,0,0,i,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,0,i,0,0,1,0,0,-i,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,0,i,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const i=Math.cos(t),r=Math.sin(t),n=1-i,s=e.x,a=e.y,o=e.z,l=n*s,u=n*a;return this.set(l*s+i,l*a-r*o,l*o+r*a,0,l*a+r*o,u*a+i,u*o-r*s,0,l*o-r*a,u*o+r*s,n*o*o+i,0,0,0,0,1),this}makeScale(e,t,i){return this.set(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1),this}makeShear(e,t,i,r,n,s){return this.set(1,i,n,0,e,1,s,0,t,r,1,0,0,0,0,1),this}compose(e,t,i){const r=this.elements,n=t._x,s=t._y,a=t._z,o=t._w,l=n+n,u=s+s,c=a+a,h=n*l,d=n*u,p=n*c,f=s*u,m=s*c,g=a*c,_=o*l,v=o*u,b=o*c,y=i.x,x=i.y,S=i.z;return r[0]=(1-(f+g))*y,r[1]=(d+b)*y,r[2]=(p-v)*y,r[3]=0,r[4]=(d-b)*x,r[5]=(1-(h+g))*x,r[6]=(m+_)*x,r[7]=0,r[8]=(p+v)*S,r[9]=(m-_)*S,r[10]=(1-(h+f))*S,r[11]=0,r[12]=e.x,r[13]=e.y,r[14]=e.z,r[15]=1,this}decompose(e,t,i){const r=this.elements;e.x=r[12],e.y=r[13],e.z=r[14];const n=this.determinantAffine();if(0===n)return i.set(1,1,1),t.identity(),this;let s=mr.set(r[0],r[1],r[2]).length();const a=mr.set(r[4],r[5],r[6]).length(),o=mr.set(r[8],r[9],r[10]).length();n<0&&(s=-s),gr.copy(this);const l=1/s,u=1/a,c=1/o;return gr.elements[0]*=l,gr.elements[1]*=l,gr.elements[2]*=l,gr.elements[4]*=u,gr.elements[5]*=u,gr.elements[6]*=u,gr.elements[8]*=c,gr.elements[9]*=c,gr.elements[10]*=c,t.setFromRotationMatrix(gr),i.x=s,i.y=a,i.z=o,this}makePerspective(e,t,i,r,n,s,a=2e3,o=!1){const l=this.elements,u=2*n/(t-e),c=2*n/(i-r),h=(t+e)/(t-e),d=(i+r)/(i-r);let p,f;if(o)p=n/(s-n),f=s*n/(s-n);else if(a===ui)p=-(s+n)/(s-n),f=-2*s*n/(s-n);else{if(a!==ci)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);p=-s/(s-n),f=-s*n/(s-n)}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,i,r,n,s,a=2e3,o=!1){const l=this.elements,u=2/(t-e),c=2/(i-r),h=-(t+e)/(t-e),d=-(i+r)/(i-r);let p,f;if(o)p=1/(s-n),f=s/(s-n);else if(a===ui)p=-2/(s-n),f=-(s+n)/(s-n);else{if(a!==ci)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);p=-1/(s-n),f=-n/(s-n)}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,i=e.elements;for(let e=0;e<16;e++)if(t[e]!==i[e])return!1;return!0}fromArray(e,t=0){for(let i=0;i<16;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],e}}const mr=new Wi,gr=new fr,_r=new Wi(0,0,0),vr=new Wi(1,1,1),br=new Wi,yr=new Wi,xr=new Wi,Sr=new fr,Tr=new Hi;class Mr{constructor(e=0,t=0,i=0,r=Mr.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=i,this._order=r}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,i,r=this._order){return this._x=e,this._y=t,this._z=i,this._order=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,i=!0){const r=e.elements,n=r[0],s=r[4],a=r[8],o=r[1],l=r[5],u=r[9],c=r[2],h=r[6],d=r[10];switch(t){case"XYZ":this._y=Math.asin(Ui(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-u,d),this._z=Math.atan2(-s,n)):(this._x=Math.atan2(h,l),this._z=0);break;case"YXZ":this._x=Math.asin(-Ui(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(a,d),this._z=Math.atan2(o,l)):(this._y=Math.atan2(-c,n),this._z=0);break;case"ZXY":this._x=Math.asin(Ui(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,n));break;case"ZYX":this._y=Math.asin(-Ui(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(h,d),this._z=Math.atan2(o,n)):(this._x=0,this._z=Math.atan2(-s,l));break;case"YZX":this._z=Math.asin(Ui(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-u,l),this._y=Math.atan2(-c,n)):(this._x=0,this._y=Math.atan2(a,d));break;case"XZY":this._z=Math.asin(-Ui(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(h,l),this._y=Math.atan2(a,n)):(this._x=Math.atan2(-u,d),this._y=0);break;default:Ti("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,!0===i&&this._onChangeCallback(),this}setFromQuaternion(e,t,i){return Sr.makeRotationFromQuaternion(e),this.setFromRotationMatrix(Sr,t,i)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return Tr.setFromEuler(this),this.setFromQuaternion(Tr,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}}Mr.DEFAULT_ORDER="XYZ";class Er{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 wr=0;const Ar=new Wi,Rr=new Hi,Cr=new fr,Nr=new Wi,Pr=new Wi,Lr=new Wi,Dr=new Hi,Ur=new Wi(1,0,0),Ir=new Wi(0,1,0),Fr=new Wi(0,0,1),Or={type:"added"},Br={type:"removed"},kr={type:"childadded",child:null},zr={type:"childremoved",child:null};class Gr extends Ri{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:wr++}),this.uuid=Di(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Gr.DEFAULT_UP.clone();const e=new Wi,t=new Mr,i=new Hi,r=new Wi(1,1,1);t._onChange(function(){i.setFromEuler(t,!1)}),i._onChange(function(){t.setFromQuaternion(i,void 0,!1)}),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:i},scale:{configurable:!0,enumerable:!0,value:r},modelViewMatrix:{value:new fr},normalMatrix:{value:new Xi}}),this.matrix=new fr,this.matrixWorld=new fr,this.matrixAutoUpdate=Gr.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Gr.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new Er,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),null!==this.pivot&&this.position.copy(this.pivot).applyMatrix4(this.matrix).sub(this.pivot)}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 Rr.setFromAxisAngle(e,t),this.quaternion.multiply(Rr),this}rotateOnWorldAxis(e,t){return Rr.setFromAxisAngle(e,t),this.quaternion.premultiply(Rr),this}rotateX(e){return this.rotateOnAxis(Ur,e)}rotateY(e){return this.rotateOnAxis(Ir,e)}rotateZ(e){return this.rotateOnAxis(Fr,e)}translateOnAxis(e,t){return Ar.copy(e).applyQuaternion(this.quaternion),this.position.add(Ar.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(Ur,e)}translateY(e){return this.translateOnAxis(Ir,e)}translateZ(e){return this.translateOnAxis(Fr,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(Cr.copy(this.matrixWorld).invert())}lookAt(e,t,i){e.isVector3?Nr.copy(e):Nr.set(e,t,i);const r=this.parent;this.updateWorldMatrix(!0,!1),Pr.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Cr.lookAt(Pr,Nr,this.up):Cr.lookAt(Nr,Pr,this.up),this.quaternion.setFromRotationMatrix(Cr),r&&(Cr.extractRotation(r.matrixWorld),Rr.setFromRotationMatrix(Cr),this.quaternion.premultiply(Rr.invert()))}add(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return e===this?(Mi("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(Or),kr.child=e,this.dispatchEvent(kr),kr.child=null):Mi("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(Br),zr.child=e,this.dispatchEvent(zr),zr.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),Cr.copy(this.matrixWorld).invert(),null!==e.parent&&(e.parent.updateWorldMatrix(!0,!1),Cr.multiply(e.parent.matrixWorld)),e.applyMatrix4(Cr),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(Or),kr.child=e,this.dispatchEvent(kr),kr.child=null,this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let i=0,r=this.children.length;i<r;i++){const r=this.children[i].getObjectByProperty(e,t);if(void 0!==r)return r}}getObjectsByProperty(e,t,i=[]){this[e]===t&&i.push(this);const r=this.children;for(let n=0,s=r.length;n<s;n++)r[n].getObjectsByProperty(e,t,i);return i}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Pr,e,Lr),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Pr,Dr,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}intersectsFrustum(){return!0}traverse(e){e(this);const t=this.children;for(let i=0,r=t.length;i<r;i++)t[i].traverse(e)}traverseVisible(e){if(!1===this.visible)return;e(this);const t=this.children;for(let i=0,r=t.length;i<r;i++)t[i].traverseVisible(e)}traverseAncestors(e){const t=this.parent;null!==t&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale);const e=this.pivot;if(null!==e){const t=e.x,i=e.y,r=e.z,n=this.matrix.elements;n[12]+=t-n[0]*t-n[4]*i-n[8]*r,n[13]+=i-n[1]*t-n[5]*i-n[9]*r,n[14]+=r-n[2]*t-n[6]*i-n[10]*r}this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(!0===this.matrixWorldAutoUpdate&&(null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);const t=this.children;for(let i=0,r=t.length;i<r;i++){t[i].updateMatrixWorld(e)}}updateWorldMatrix(e,t,i=!1){const r=this.parent;if(!0===e&&null!==r&&r.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||i)&&(!0===this.matrixWorldAutoUpdate&&(null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,i=!0),!0===t){const e=this.children;for(let t=0,r=e.length;t<r;t++){e[t].updateWorldMatrix(!1,!0,i)}}}toJSON(e){const t=void 0===e||"string"==typeof e,i={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},i.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});const r={};function n(t,i){return void 0===t[i.uuid]&&(t[i.uuid]=i.toJSON(e)),i.uuid}if(r.uuid=this.uuid,r.type=this.type,r.name=this.name,r.castShadow=this.castShadow,r.receiveShadow=this.receiveShadow,r.visible=this.visible,r.frustumCulled=this.frustumCulled,r.renderOrder=this.renderOrder,r.static=this.static,r.matrixAutoUpdate=this.matrixAutoUpdate,Object.keys(this.userData).length>0&&(r.userData=this.userData),r.layers=this.layers.mask,r.matrix=this.matrix.toArray(),r.up=this.up.toArray(),null!==this.pivot&&(r.pivot=this.pivot.toArray()),void 0!==this.morphTargetDictionary&&(r.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),void 0!==this.morphTargetInfluences&&(r.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(r.type="InstancedMesh",r.count=this.count,r.instanceMatrix=this.instanceMatrix.toJSON(),null!==this.instanceColor&&(r.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(r.type="BatchedMesh",r.perObjectFrustumCulled=this.perObjectFrustumCulled,r.sortObjects=this.sortObjects,r.drawRanges=this._drawRanges,r.reservedRanges=this._reservedRanges,r.geometryInfo=this._geometryInfo.map(e=>({...e,boundingBox:e.boundingBox?e.boundingBox.toJSON():void 0,boundingSphere:e.boundingSphere?e.boundingSphere.toJSON():void 0})),r.instanceInfo=this._instanceInfo.map(e=>({...e})),r.availableInstanceIds=this._availableInstanceIds.slice(),r.availableGeometryIds=this._availableGeometryIds.slice(),r.nextIndexStart=this._nextIndexStart,r.nextVertexStart=this._nextVertexStart,r.geometryCount=this._geometryCount,r.maxInstanceCount=this._maxInstanceCount,r.maxVertexCount=this._maxVertexCount,r.maxIndexCount=this._maxIndexCount,r.geometryInitialized=this._geometryInitialized,r.matricesTexture=this._matricesTexture.toJSON(e),r.indirectTexture=this._indirectTexture.toJSON(e),null!==this._colorsTexture&&(r.colorsTexture=this._colorsTexture.toJSON(e)),null!==this.boundingSphere&&(r.boundingSphere=this.boundingSphere.toJSON()),null!==this.boundingBox&&(r.boundingBox=this.boundingBox.toJSON())),this.isScene)this.background&&(this.background.isColor?r.background=this.background.toJSON():this.background.isTexture&&(r.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&!0!==this.environment.isRenderTargetTexture&&(r.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){r.geometry=n(e.geometries,this.geometry);const t=this.geometry.parameters;if(void 0!==t&&void 0!==t.shapes){const i=t.shapes;if(Array.isArray(i))for(let t=0,r=i.length;t<r;t++){const r=i[t];n(e.shapes,r)}else n(e.shapes,i)}}if(this.isSkinnedMesh&&(r.bindMode=this.bindMode,r.bindMatrix=this.bindMatrix.toArray(),void 0!==this.skeleton&&(n(e.skeletons,this.skeleton),r.skeleton=this.skeleton.uuid)),void 0!==this.material)if(Array.isArray(this.material)){const t=[];for(let i=0,r=this.material.length;i<r;i++)t.push(n(e.materials,this.material[i]));r.material=t}else r.material=n(e.materials,this.material);if(this.children.length>0){r.children=[];for(let t=0;t<this.children.length;t++)r.children.push(this.children[t].toJSON(e).object)}if(this.animations.length>0){r.animations=[];for(let t=0;t<this.animations.length;t++){const i=this.animations[t];r.animations.push(n(e.animations,i))}}if(t){const t=s(e.geometries),r=s(e.materials),n=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&&(i.geometries=t),r.length>0&&(i.materials=r),n.length>0&&(i.textures=n),a.length>0&&(i.images=a),o.length>0&&(i.shapes=o),l.length>0&&(i.skeletons=l),u.length>0&&(i.animations=u),c.length>0&&(i.nodes=c)}return i.object=r,i;function s(e){const t=[];for(const i in e){const r=e[i];delete r.metadata,t.push(r)}return t}}clone(e){return(new this.constructor).copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.pivot=null!==e.pivot?e.pivot.clone():null,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 i=e.children[t];this.add(i.clone())}return this}dispose(){this.dispatchEvent({type:"dispose"})}}Gr.DEFAULT_UP=new Wi(0,1,0),Gr.DEFAULT_MATRIX_AUTO_UPDATE=!0,Gr.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;let Vr=class extends Gr{constructor(){super(),this.isGroup=!0,this.type="Group"}};const Hr={type:"move"};class Wr{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return null===this._hand&&(this._hand=new Vr,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 Vr,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new Wi,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new Wi),this._targetRay}getGripSpace(){return null===this._grip&&(this._grip=new Vr,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new Wi,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new Wi,this._grip.eventsEnabled=!1),this._grip}dispatchEvent(e){return null!==this._targetRay&&this._targetRay.dispatchEvent(e),null!==this._grip&&this._grip.dispatchEvent(e),null!==this._hand&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const i of e.hand.values())this._getHandJoint(t,i)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),null!==this._targetRay&&(this._targetRay.visible=!1),null!==this._grip&&(this._grip.visible=!1),null!==this._hand&&(this._hand.visible=!1),this}update(e,t,i){let r=null,n=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 r of e.hand.values()){const e=t.getJointPose(r,i),n=this._getHandJoint(l,r);null!==e&&(n.matrix.fromArray(e.transform.matrix),n.matrix.decompose(n.position,n.quaternion,n.scale),n.matrixWorldNeedsUpdate=!0,n.jointRadius=e.radius),n.visible=null!==e}const r=l.joints["index-finger-tip"],n=l.joints["thumb-tip"],a=r.position.distanceTo(n.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&&(n=t.getPose(e.gripSpace,i),null!==n&&(o.matrix.fromArray(n.transform.matrix),o.matrix.decompose(o.position,o.quaternion,o.scale),o.matrixWorldNeedsUpdate=!0,n.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(n.linearVelocity)):o.hasLinearVelocity=!1,n.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(n.angularVelocity)):o.hasAngularVelocity=!1,o.eventsEnabled&&o.dispatchEvent({type:"gripUpdated",data:e,target:this})));null!==a&&(r=t.getPose(e.targetRaySpace,i),null===r&&null!==n&&(r=n),null!==r&&(a.matrix.fromArray(r.transform.matrix),a.matrix.decompose(a.position,a.quaternion,a.scale),a.matrixWorldNeedsUpdate=!0,r.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(r.linearVelocity)):a.hasLinearVelocity=!1,r.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(r.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(Hr)))}return null!==a&&(a.visible=null!==r),null!==o&&(o.visible=null!==n),null!==l&&(l.visible=null!==s),this}_getHandJoint(e,t){if(void 0===e.joints[t.jointName]){const i=new Vr;i.matrixAutoUpdate=!1,i.visible=!1,e.joints[t.jointName]=i,e.add(i)}return e.joints[t.jointName]}}const jr={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},$r={h:0,s:0,l:0},Xr={h:0,s:0,l:0};function qr(e,t,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?e+6*(t-e)*i:i<.5?t:i<2/3?e+6*(t-e)*(2/3-i):e}let Yr=class{constructor(e,t,i){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,i)}set(e,t,i){if(void 0===t&&void 0===i){const t=e;t&&t.isColor?this.copy(t):"number"==typeof t?this.setHex(t):"string"==typeof t&&this.setStyle(t)}else this.setRGB(e,t,i);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Xt){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,Qi.colorSpaceToWorking(this,t),this}setRGB(e,t,i,r=Qi.workingColorSpace){return this.r=e,this.g=t,this.b=i,Qi.colorSpaceToWorking(this,r),this}setHSL(e,t,i,r=Qi.workingColorSpace){if(e=Ii(e,1),t=Ui(t,0,1),i=Ui(i,0,1),0===t)this.r=this.g=this.b=i;else{const r=i<=.5?i*(1+t):i+t-i*t,n=2*i-r;this.r=qr(n,r,e+1/3),this.g=qr(n,r,e),this.b=qr(n,r,e-1/3)}return Qi.colorSpaceToWorking(this,r),this}setStyle(e,t=Xt){function i(t){void 0!==t&&parseFloat(t)<1&&Ti("Color: Alpha component of "+e+" will be ignored.")}let r;if(r=/^(\w+)\(([^\)]*)\)/.exec(e)){let n;const s=r[1],a=r[2];switch(s){case"rgb":case"rgba":if(n=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?|\.\d+)\s*)?$/.exec(a))return i(n[4]),this.setRGB(Math.min(255,parseInt(n[1],10))/255,Math.min(255,parseInt(n[2],10))/255,Math.min(255,parseInt(n[3],10))/255,t);if(n=/^\s*(\d+(?:\.\d+)?|\.\d+)\%\s*,\s*(\d+(?:\.\d+)?|\.\d+)\%\s*,\s*(\d+(?:\.\d+)?|\.\d+)\%\s*(?:,\s*(\d+(?:\.\d+)?|\.\d+)\s*)?$/.exec(a))return i(n[4]),this.setRGB(Math.min(100,parseFloat(n[1]))/100,Math.min(100,parseFloat(n[2]))/100,Math.min(100,parseFloat(n[3]))/100,t);break;case"hsl":case"hsla":if(n=/^\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))\s*,\s*(\d+(?:\.\d+)?|\.\d+)\%\s*,\s*(\d+(?:\.\d+)?|\.\d+)\%\s*(?:,\s*(\d+(?:\.\d+)?|\.\d+)\s*)?$/.exec(a))return i(n[4]),this.setHSL(parseFloat(n[1])/360,parseFloat(n[2])/100,parseFloat(n[3])/100,t);break;default:Ti("Color: Unknown color model "+e)}}else if(r=/^\#([A-Fa-f\d]+)$/.exec(e)){const i=r[1],n=i.length;if(3===n)return this.setRGB(parseInt(i.charAt(0),16)/15,parseInt(i.charAt(1),16)/15,parseInt(i.charAt(2),16)/15,t);if(6===n)return this.setHex(parseInt(i,16),t);Ti("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Xt){const i=jr[e.toLowerCase()];return void 0!==i?this.setHex(i,t):Ti("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=Ji(e.r),this.g=Ji(e.g),this.b=Ji(e.b),this}copyLinearToSRGB(e){return this.r=er(e.r),this.g=er(e.g),this.b=er(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Xt){return Qi.workingToColorSpace(Kr.copy(this),e),65536*Math.round(Ui(255*Kr.r,0,255))+256*Math.round(Ui(255*Kr.g,0,255))+Math.round(Ui(255*Kr.b,0,255))}getHexString(e=Xt){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Qi.workingColorSpace){Qi.workingToColorSpace(Kr.copy(this),t);const i=Kr.r,r=Kr.g,n=Kr.b,s=Math.max(i,r,n),a=Math.min(i,r,n);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 i:o=(r-n)/e+(r<n?6:0);break;case r:o=(n-i)/e+2;break;case n:o=(i-r)/e+4}o/=6}return e.h=o,e.s=l,e.l=u,e}getRGB(e,t=Qi.workingColorSpace){return Qi.workingToColorSpace(Kr.copy(this),t),e.r=Kr.r,e.g=Kr.g,e.b=Kr.b,e}getStyle(e=Xt){Qi.workingToColorSpace(Kr.copy(this),e);const t=Kr.r,i=Kr.g,r=Kr.b;return e!==Xt?`color(${e} ${t.toFixed(3)} ${i.toFixed(3)} ${r.toFixed(3)})`:`rgb(${Math.round(255*t)},${Math.round(255*i)},${Math.round(255*r)})`}offsetHSL(e,t,i){return this.getHSL($r),this.setHSL($r.h+e,$r.s+t,$r.l+i)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,i){return this.r=e.r+(t.r-e.r)*i,this.g=e.g+(t.g-e.g)*i,this.b=e.b+(t.b-e.b)*i,this}lerpHSL(e,t){this.getHSL($r),e.getHSL(Xr);const i=Fi($r.h,Xr.h,t),r=Fi($r.s,Xr.s,t),n=Fi($r.l,Xr.l,t);return this.setHSL(i,r,n),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const t=this.r,i=this.g,r=this.b,n=e.elements;return this.r=n[0]*t+n[3]*i+n[6]*r,this.g=n[1]*t+n[4]*i+n[7]*r,this.b=n[2]*t+n[5]*i+n[8]*r,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}};const Kr=new Yr;Yr.NAMES=jr;class Zr extends Gr{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 Mr,this.environmentIntensity=1,this.environmentRotation=new Mr,this.overrideMaterial=null,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),this.background=null!==e.background?e.background.clone():null,this.environment=null!==e.environment?e.environment.clone():null,this.fog=null!==e.fog?e.fog.clone():null,this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),this.overrideMaterial=null!==e.overrideMaterial?e.overrideMaterial.clone():null,this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return null!==this.fog&&(t.object.fog=this.fog.toJSON()),t.object.backgroundBlurriness=this.backgroundBlurriness,t.object.backgroundIntensity=this.backgroundIntensity,t.object.backgroundRotation=this.backgroundRotation.toArray(),t.object.environmentIntensity=this.environmentIntensity,t.object.environmentRotation=this.environmentRotation.toArray(),t}}const Qr=new Wi,Jr=new Wi,en=new Wi,tn=new Wi,rn=new Wi,nn=new Wi,sn=new Wi,an=new Wi,on=new Wi,ln=new Wi,un=new ur,cn=new ur,hn=new ur;class dn{constructor(e=new Wi,t=new Wi,i=new Wi){this.a=e,this.b=t,this.c=i}static getNormal(e,t,i,r){r.subVectors(i,t),Qr.subVectors(e,t),r.cross(Qr);const n=r.lengthSq();return n>0?r.multiplyScalar(1/Math.sqrt(n)):r.set(0,0,0)}static getBarycoord(e,t,i,r,n){Qr.subVectors(r,t),Jr.subVectors(i,t),en.subVectors(e,t);const s=Qr.dot(Qr),a=Qr.dot(Jr),o=Qr.dot(en),l=Jr.dot(Jr),u=Jr.dot(en),c=s*l-a*a;if(0===c)return n.set(0,0,0),null;const h=1/c,d=(l*o-a*u)*h,p=(s*u-a*o)*h;return n.set(1-d-p,p,d)}static containsPoint(e,t,i,r){return null!==this.getBarycoord(e,t,i,r,tn)&&(tn.x>=0&&tn.y>=0&&tn.x+tn.y<=1)}static getInterpolation(e,t,i,r,n,s,a,o){return null===this.getBarycoord(e,t,i,r,tn)?(o.x=0,o.y=0,"z"in o&&(o.z=0),"w"in o&&(o.w=0),null):(o.setScalar(0),o.addScaledVector(n,tn.x),o.addScaledVector(s,tn.y),o.addScaledVector(a,tn.z),o)}static getInterpolatedAttribute(e,t,i,r,n,s){return un.setScalar(0),cn.setScalar(0),hn.setScalar(0),un.fromBufferAttribute(e,t),cn.fromBufferAttribute(e,i),hn.fromBufferAttribute(e,r),s.setScalar(0),s.addScaledVector(un,n.x),s.addScaledVector(cn,n.y),s.addScaledVector(hn,n.z),s}static isFrontFacing(e,t,i,r){return Qr.subVectors(i,t),Jr.subVectors(e,t),Qr.cross(Jr).dot(r)<0}set(e,t,i){return this.a.copy(e),this.b.copy(t),this.c.copy(i),this}setFromPointsAndIndices(e,t,i,r){return this.a.copy(e[t]),this.b.copy(e[i]),this.c.copy(e[r]),this}setFromAttributeAndIndices(e,t,i,r){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,i),this.c.fromBufferAttribute(e,r),this}clone(){return(new this.constructor).copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Qr.subVectors(this.c,this.b),Jr.subVectors(this.a,this.b),.5*Qr.cross(Jr).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return dn.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return dn.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,i,r,n){return dn.getInterpolation(e,this.a,this.b,this.c,t,i,r,n)}containsPoint(e){return dn.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return dn.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const i=this.a,r=this.b,n=this.c;let s,a;rn.subVectors(r,i),nn.subVectors(n,i),an.subVectors(e,i);const o=rn.dot(an),l=nn.dot(an);if(o<=0&&l<=0)return t.copy(i);on.subVectors(e,r);const u=rn.dot(on),c=nn.dot(on);if(u>=0&&c<=u)return t.copy(r);const h=o*c-u*l;if(h<=0&&o>=0&&u<=0&&o-u>0)return s=o/(o-u),t.copy(i).addScaledVector(rn,s);ln.subVectors(e,n);const d=rn.dot(ln),p=nn.dot(ln);if(p>=0&&d<=p)return t.copy(n);const f=d*l-o*p;if(f<=0&&l>=0&&p<=0)return a=l/(l-p),t.copy(i).addScaledVector(nn,a);const m=u*p-d*c;if(m<=0&&c-u>=0&&d-p>=0)return sn.subVectors(n,r),a=(c-u)/(c-u+(d-p)),t.copy(r).addScaledVector(sn,a);const g=1/(m+f+h);return s=f*g,a=h*g,t.copy(i).addScaledVector(rn,s).addScaledVector(nn,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}class pn{constructor(e=new Wi(1/0,1/0,1/0),t=new Wi(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,i=e.length;t<i;t+=3)this.expandByPoint(mn.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,i=e.count;t<i;t++)this.expandByPoint(mn.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,i=e.length;t<i;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){const i=mn.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(i),this.max.copy(e).add(i),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return(new this.constructor).copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);const i=e.geometry;if(void 0!==i){const r=i.getAttribute("position");if(!0===t&&void 0!==r&&!0!==e.isInstancedMesh&&!0!==e.isBatchedMesh)for(let t=0,i=r.count;t<i;t++)!0===e.isMesh?e.getVertexPosition(t,mn):mn.fromBufferAttribute(r,t),mn.applyMatrix4(e.matrixWorld),this.expandByPoint(mn);else void 0!==e.boundingBox?(null===e.boundingBox&&e.computeBoundingBox(),gn.copy(e.boundingBox)):(null===i.boundingBox&&i.computeBoundingBox(),gn.copy(i.boundingBox)),gn.applyMatrix4(e.matrixWorld),this.union(gn)}const r=e.children;for(let e=0,i=r.length;e<i;e++)this.expandByObject(r[e],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,mn),mn.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,i;return e.normal.x>0?(t=e.normal.x*this.min.x,i=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,i=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,i+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,i+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,i+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,i+=e.normal.z*this.min.z),t<=-e.constant&&i>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Tn),Mn.subVectors(this.max,Tn),_n.subVectors(e.a,Tn),vn.subVectors(e.b,Tn),bn.subVectors(e.c,Tn),yn.subVectors(vn,_n),xn.subVectors(bn,vn),Sn.subVectors(_n,bn);let t=[0,-yn.z,yn.y,0,-xn.z,xn.y,0,-Sn.z,Sn.y,yn.z,0,-yn.x,xn.z,0,-xn.x,Sn.z,0,-Sn.x,-yn.y,yn.x,0,-xn.y,xn.x,0,-Sn.y,Sn.x,0];return!!An(t,_n,vn,bn,Mn)&&(t=[1,0,0,0,1,0,0,0,1],!!An(t,_n,vn,bn,Mn)&&(En.crossVectors(yn,xn),t=[En.x,En.y,En.z],An(t,_n,vn,bn,Mn)))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,mn).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=.5*this.getSize(mn).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()||(fn[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),fn[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),fn[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),fn[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),fn[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),fn[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),fn[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),fn[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(fn)),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 fn=[new Wi,new Wi,new Wi,new Wi,new Wi,new Wi,new Wi,new Wi],mn=new Wi,gn=new pn,_n=new Wi,vn=new Wi,bn=new Wi,yn=new Wi,xn=new Wi,Sn=new Wi,Tn=new Wi,Mn=new Wi,En=new Wi,wn=new Wi;function An(e,t,i,r,n){for(let s=0,a=e.length-3;s<=a;s+=3){wn.fromArray(e,s);const a=n.x*Math.abs(wn.x)+n.y*Math.abs(wn.y)+n.z*Math.abs(wn.z),o=t.dot(wn),l=i.dot(wn),u=r.dot(wn);if(Math.max(-Math.max(o,l,u),Math.min(o,l,u))>a)return!1}return!0}const Rn=Cn();function Cn(){const e=new ArrayBuffer(4),t=new Float32Array(e),i=new Uint32Array(e),r=new Uint32Array(512),n=new Uint32Array(512);for(let e=0;e<256;++e){const t=e-127;t<-27?(r[e]=0,r[256|e]=32768,n[e]=24,n[256|e]=24):t<-14?(r[e]=1024>>-t-14,r[256|e]=1024>>-t-14|32768,n[e]=-t-1,n[256|e]=-t-1):t<=15?(r[e]=t+15<<10,r[256|e]=t+15<<10|32768,n[e]=13,n[256|e]=13):t<128?(r[e]=31744,r[256|e]=64512,n[e]=24,n[256|e]=24):(r[e]=31744,r[256|e]=64512,n[e]=13,n[256|e]=13)}const s=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let e=1;e<1024;++e){let t=e<<13,i=0;for(;!(8388608&t);)t<<=1,i-=8388608;t&=-8388609,i+=947912704,s[e]=t|i}for(let e=1024;e<2048;++e)s[e]=939524096+(e-1024<<13);for(let e=1;e<31;++e)a[e]=e<<23;a[31]=1199570944,a[32]=2147483648;for(let e=33;e<63;++e)a[e]=2147483648+(e-32<<23);a[63]=3347054592;for(let e=1;e<64;++e)32!==e&&(o[e]=1024);return{floatView:t,uint32View:i,baseTable:r,shiftTable:n,mantissaTable:s,exponentTable:a,offsetTable:o}}function Nn(e){Math.abs(e)>65504&&Ti("DataUtils.toHalfFloat(): Value out of range."),e=Ui(e,-65504,65504),Rn.floatView[0]=e;const t=Rn.uint32View[0],i=t>>23&511;return Rn.baseTable[i]+((8388607&t)>>Rn.shiftTable[i])}function Pn(e){const t=e>>10;return Rn.uint32View[0]=Rn.mantissaTable[Rn.offsetTable[t]+(1023&e)]+Rn.exponentTable[t],Rn.floatView[0]}const Ln=new Wi,Dn=new Vi;let Un=0;class In extends Ri{constructor(e,t,i=!1){if(super(),Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:Un++}),this.name="",this.array=e,this.itemSize=t,this.count=void 0!==e?e.length/t:0,this.normalized=i,this.usage=ai,this.updateRanges=[],this.gpuType=$e,this.version=0,this._normalizationScale=void 0!==e?Bi(e):void 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._normalizationScale=e._normalizationScale,this}copyAt(e,t,i){e*=this.itemSize,i*=t.itemSize;for(let r=0,n=this.itemSize;r<n;r++)this.array[e+r]=t.array[i+r];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(2===this.itemSize)for(let t=0,i=this.count;t<i;t++)Dn.fromBufferAttribute(this,t),Dn.applyMatrix3(e),this.setXY(t,Dn.x,Dn.y);else if(3===this.itemSize)for(let t=0,i=this.count;t<i;t++)Ln.fromBufferAttribute(this,t),Ln.applyMatrix3(e),this.setXYZ(t,Ln.x,Ln.y,Ln.z);return this}applyMatrix4(e){for(let t=0,i=this.count;t<i;t++)Ln.fromBufferAttribute(this,t),Ln.applyMatrix4(e),this.setXYZ(t,Ln.x,Ln.y,Ln.z);return this}applyNormalMatrix(e){for(let t=0,i=this.count;t<i;t++)Ln.fromBufferAttribute(this,t),Ln.applyNormalMatrix(e),this.setXYZ(t,Ln.x,Ln.y,Ln.z);return this}transformDirection(e){for(let t=0,i=this.count;t<i;t++)Ln.fromBufferAttribute(this,t),Ln.transformDirection(e),this.setXYZ(t,Ln.x,Ln.y,Ln.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let i=this.array[e*this.itemSize+t];return this.normalized&&(i=this._denormalize(i)),i}setComponent(e,t,i){return this.normalized&&(i=this._normalize(i)),this.array[e*this.itemSize+t]=i,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=this._denormalize(t)),t}setX(e,t){return this.normalized&&(t=this._normalize(t)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=this._denormalize(t)),t}setY(e,t){return this.normalized&&(t=this._normalize(t)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=this._denormalize(t)),t}setZ(e,t){return this.normalized&&(t=this._normalize(t)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=this._denormalize(t)),t}setW(e,t){return this.normalized&&(t=this._normalize(t)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,i){return e*=this.itemSize,this.normalized&&(t=this._normalize(t),i=this._normalize(i)),this.array[e+0]=t,this.array[e+1]=i,this}setXYZ(e,t,i,r){return e*=this.itemSize,this.normalized&&(t=this._normalize(t),i=this._normalize(i),r=this._normalize(r)),this.array[e+0]=t,this.array[e+1]=i,this.array[e+2]=r,this}setXYZW(e,t,i,r,n){return e*=this.itemSize,this.normalized&&(t=this._normalize(t),i=this._normalize(i),r=this._normalize(r),n=this._normalize(n)),this.array[e+0]=t,this.array[e+1]=i,this.array[e+2]=r,this.array[e+3]=n,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 e.name=this.name,e.usage=this.usage,e.gpuType=this.gpuType,e}dispose(){this.dispatchEvent({type:"dispose"})}_denormalize(e){const t=this._normalizationScale;return void 0!==t?Math.max(e/t,-1):ki(e,this.array)}_normalize(e){const t=this._normalizationScale;return void 0!==t?Math.round(e*t):zi(e,this.array)}}class Fn extends In{constructor(e,t,i){super(new Uint16Array(e),t,i)}}class On extends In{constructor(e,t,i){super(new Uint32Array(e),t,i)}}class Bn extends In{constructor(e,t,i){super(new Uint16Array(e),t,i),this.isFloat16BufferAttribute=!0}getX(e){let t=Pn(this.array[e*this.itemSize]);return this.normalized&&(t=ki(t,this.array)),t}setX(e,t){return this.normalized&&(t=zi(t,this.array)),this.array[e*this.itemSize]=Nn(t),this}getY(e){let t=Pn(this.array[e*this.itemSize+1]);return this.normalized&&(t=ki(t,this.array)),t}setY(e,t){return this.normalized&&(t=zi(t,this.array)),this.array[e*this.itemSize+1]=Nn(t),this}getZ(e){let t=Pn(this.array[e*this.itemSize+2]);return this.normalized&&(t=ki(t,this.array)),t}setZ(e,t){return this.normalized&&(t=zi(t,this.array)),this.array[e*this.itemSize+2]=Nn(t),this}getW(e){let t=Pn(this.array[e*this.itemSize+3]);return this.normalized&&(t=ki(t,this.array)),t}setW(e,t){return this.normalized&&(t=zi(t,this.array)),this.array[e*this.itemSize+3]=Nn(t),this}setXY(e,t,i){return e*=this.itemSize,this.normalized&&(t=zi(t,this.array),i=zi(i,this.array)),this.array[e+0]=Nn(t),this.array[e+1]=Nn(i),this}setXYZ(e,t,i,r){return e*=this.itemSize,this.normalized&&(t=zi(t,this.array),i=zi(i,this.array),r=zi(r,this.array)),this.array[e+0]=Nn(t),this.array[e+1]=Nn(i),this.array[e+2]=Nn(r),this}setXYZW(e,t,i,r,n){return e*=this.itemSize,this.normalized&&(t=zi(t,this.array),i=zi(i,this.array),r=zi(r,this.array),n=zi(n,this.array)),this.array[e+0]=Nn(t),this.array[e+1]=Nn(i),this.array[e+2]=Nn(r),this.array[e+3]=Nn(n),this}}class kn extends In{constructor(e,t,i){super(new Float32Array(e),t,i)}}const zn=new pn,Gn=new Wi,Vn=new Wi;class Hn{constructor(e=new Wi,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const i=this.center;void 0!==t?i.copy(t):zn.setFromPoints(e).getCenter(i);let r=0;for(let t=0,n=e.length;t<n;t++)r=Math.max(r,i.distanceToSquared(e[t]));return this.radius=Math.sqrt(r),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){const t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){const i=this.center.distanceToSquared(e);return t.copy(e),i>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Gn.subVectors(e,this.center);const t=Gn.lengthSq();if(t>this.radius*this.radius){const e=Math.sqrt(t),i=.5*(e-this.radius);this.center.addScaledVector(Gn,i/e),this.radius+=i}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(!0===this.center.equals(e.center)?this.radius=Math.max(this.radius,e.radius):(Vn.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Gn.copy(e.center).add(Vn)),this.expandByPoint(Gn.copy(e.center).sub(Vn))),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 Wn=0;const jn=new fr,$n=new Gr,Xn=new Wi,qn=new pn,Yn=new pn,Kn=new Wi;class Zn extends Ri{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:Wn++}),this.uuid=Di(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={},this._transformed=!1}getIndex(){return this.index}setIndex(e){return 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)?On:Fn)(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,i=0){this.groups.push({start:e,count:t,materialIndex:i})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;void 0!==t&&(t.applyMatrix4(e),t.needsUpdate=!0);const i=this.attributes.normal;if(void 0!==i){const t=(new Xi).getNormalMatrix(e);i.applyNormalMatrix(t),i.needsUpdate=!0}const r=this.attributes.tangent;return void 0!==r&&(r.transformDirection(e),r.needsUpdate=!0),null!==this.boundingBox&&this.computeBoundingBox(),null!==this.boundingSphere&&this.computeBoundingSphere(),this._transformed=!0,this}applyQuaternion(e){return jn.makeRotationFromQuaternion(e),this.applyMatrix4(jn),this}rotateX(e){return jn.makeRotationX(e),this.applyMatrix4(jn),this}rotateY(e){return jn.makeRotationY(e),this.applyMatrix4(jn),this}rotateZ(e){return jn.makeRotationZ(e),this.applyMatrix4(jn),this}translate(e,t,i){return jn.makeTranslation(e,t,i),this.applyMatrix4(jn),this}scale(e,t,i){return jn.makeScale(e,t,i),this.applyMatrix4(jn),this}lookAt(e){return $n.lookAt(e),$n.updateMatrix(),this.applyMatrix4($n.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Xn).negate(),this.translate(Xn.x,Xn.y,Xn.z),this}setFromPoints(e){const t=this.getAttribute("position");if(void 0===t){const t=[];for(let i=0,r=e.length;i<r;i++){const r=e[i];t.push(r.x,r.y,r.z||0)}this.setAttribute("position",new kn(t,3))}else{const i=Math.min(e.length,t.count);for(let r=0;r<i;r++){const i=e[r];t.setXYZ(r,i.x,i.y,i.z||0)}e.length>t.count&&Ti("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 pn);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return Mi("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),void this.boundingBox.set(new Wi(-1/0,-1/0,-1/0),new Wi(1/0,1/0,1/0));if(void 0!==e){if(this.boundingBox.setFromBufferAttribute(e),t)for(let e=0,i=t.length;e<i;e++){const i=t[e];qn.setFromBufferAttribute(i),this.morphTargetsRelative?(Kn.addVectors(this.boundingBox.min,qn.min),this.boundingBox.expandByPoint(Kn),Kn.addVectors(this.boundingBox.max,qn.max),this.boundingBox.expandByPoint(Kn)):(this.boundingBox.expandByPoint(qn.min),this.boundingBox.expandByPoint(qn.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&Mi('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 Hn);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return Mi("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),void this.boundingSphere.set(new Wi,1/0);if(e){const i=this.boundingSphere.center;if(qn.setFromBufferAttribute(e),t)for(let e=0,i=t.length;e<i;e++){const i=t[e];Yn.setFromBufferAttribute(i),this.morphTargetsRelative?(Kn.addVectors(qn.min,Yn.min),qn.expandByPoint(Kn),Kn.addVectors(qn.max,Yn.max),qn.expandByPoint(Kn)):(qn.expandByPoint(Yn.min),qn.expandByPoint(Yn.max))}qn.getCenter(i);let r=0;for(let t=0,n=e.count;t<n;t++)Kn.fromBufferAttribute(e,t),r=Math.max(r,i.distanceToSquared(Kn));if(t)for(let n=0,s=t.length;n<s;n++){const s=t[n],a=this.morphTargetsRelative;for(let t=0,n=s.count;t<n;t++)Kn.fromBufferAttribute(s,t),a&&(Xn.fromBufferAttribute(e,t),Kn.add(Xn)),r=Math.max(r,i.distanceToSquared(Kn))}this.boundingSphere.radius=Math.sqrt(r),isNaN(this.boundingSphere.radius)&&Mi('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 Mi("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");const i=t.position,r=t.normal,n=t.uv;let s=this.getAttribute("tangent");void 0!==s&&s.count===i.count||(s=new In(new Float32Array(4*i.count),4),this.setAttribute("tangent",s));const a=[],o=[],l=new Uint8Array(i.count);for(let e=0;e<i.count;e++)a[e]=new Wi,o[e]=new Wi;const u=new Wi,c=new Wi,h=new Wi,d=new Vi,p=new Vi,f=new Vi,m=new Wi,g=new Wi;function _(e,t,r){l[e]=l[t]=l[r]=1,u.fromBufferAttribute(i,e),c.fromBufferAttribute(i,t),h.fromBufferAttribute(i,r),d.fromBufferAttribute(n,e),p.fromBufferAttribute(n,t),f.fromBufferAttribute(n,r),c.sub(u),h.sub(u),p.sub(d),f.sub(d);const s=1/(p.x*f.y-f.x*p.y);isFinite(s)&&(m.copy(c).multiplyScalar(f.y).addScaledVector(h,-p.y).multiplyScalar(s),g.copy(h).multiplyScalar(p.x).addScaledVector(c,-f.x).multiplyScalar(s),a[e].add(m),a[t].add(m),a[r].add(m),o[e].add(g),o[t].add(g),o[r].add(g))}let v=this.groups;0===v.length&&(v=[{start:0,count:e.count}]);for(let t=0,i=v.length;t<i;++t){const i=v[t],r=i.start;for(let t=r,n=r+i.count;t<n;t+=3)_(e.getX(t+0),e.getX(t+1),e.getX(t+2))}const b=new Wi,y=new Wi,x=new Wi,S=new Wi;function T(e){x.fromBufferAttribute(r,e),S.copy(x);const t=a[e];b.copy(t),b.sub(x.multiplyScalar(x.dot(t))).normalize(),y.crossVectors(S,t);const i=y.dot(o[e])<0?-1:1;s.setXYZW(e,b.x,b.y,b.z,i)}for(let e=0,t=i.count;e<t;++e)l[e]&&T(e);this._transformed=!0}computeVertexNormals(){const e=this.index,t=this.getAttribute("position");if(void 0!==t){let i=this.getAttribute("normal");if(void 0===i||i.count!==t.count)i=new In(new Float32Array(3*t.count),3),this.setAttribute("normal",i);else for(let e=0,t=i.count;e<t;e++)i.setXYZ(e,0,0,0);const r=new Wi,n=new Wi,s=new Wi,a=new Wi,o=new Wi,l=new Wi,u=new Wi,c=new Wi;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);r.fromBufferAttribute(t,d),n.fromBufferAttribute(t,p),s.fromBufferAttribute(t,f),u.subVectors(s,n),c.subVectors(r,n),u.cross(c),a.fromBufferAttribute(i,d),o.fromBufferAttribute(i,p),l.fromBufferAttribute(i,f),a.add(u),o.add(u),l.add(u),i.setXYZ(d,a.x,a.y,a.z),i.setXYZ(p,o.x,o.y,o.z),i.setXYZ(f,l.x,l.y,l.z)}else for(let e=0,a=t.count;e<a;e+=3)r.fromBufferAttribute(t,e+0),n.fromBufferAttribute(t,e+1),s.fromBufferAttribute(t,e+2),u.subVectors(s,n),c.subVectors(r,n),u.cross(c),i.setXYZ(e+0,u.x,u.y,u.z),i.setXYZ(e+1,u.x,u.y,u.z),i.setXYZ(e+2,u.x,u.y,u.z);this.normalizeNormals(),i.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,i=e.count;t<i;t++)Kn.fromBufferAttribute(e,t),Kn.normalize(),e.setXYZ(t,Kn.x,Kn.y,Kn.z)}toNonIndexed(){function e(e,t){const i=e.array,r=e.itemSize,n=e.normalized,s=new i.constructor(t.length*r);let a=0,o=0;for(let n=0,l=t.length;n<l;n++){a=e.isInterleavedBufferAttribute?t[n]*e.data.stride+e.offset:t[n]*r;for(let e=0;e<r;e++)s[o++]=i[a++]}return new In(s,r,n)}if(null===this.index)return Ti("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new Zn,i=this.index.array,r=this.attributes;for(const n in r){const s=e(r[n],i);t.setAttribute(n,s)}const n=this.morphAttributes;for(const r in n){const s=[],a=n[r];for(let t=0,r=a.length;t<r;t++){const r=e(a[t],i);s.push(r)}t.morphAttributes[r]=s}t.morphTargetsRelative=this.morphTargetsRelative;const s=this.groups;for(let e=0,i=s.length;e<i;e++){const i=s[e];t.addGroup(i.start,i.count,i.materialIndex)}return t}toJSON(){const e={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=void 0!==this.parameters&&!0===this._transformed?"BufferGeometry":this.type,e.name=this.name,Object.keys(this.userData).length>0&&(e.userData=this.userData),void 0!==this.parameters&&!0!==this._transformed){const t=this.parameters;for(const i in t)void 0!==t[i]&&(e[i]=t[i]);return e}e.data={attributes:{}};const t=this.index;null!==t&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const i=this.attributes;for(const t in i){const r=i[t];e.data.attributes[t]=r.toJSON(e.data)}const r={};let n=!1;for(const t in this.morphAttributes){const i=this.morphAttributes[t],s=[];for(let t=0,r=i.length;t<r;t++){const r=i[t];s.push(r.toJSON(e.data))}s.length>0&&(r[t]=s,n=!0)}n&&(e.data.morphAttributes=r,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 i=e.index;null!==i&&this.setIndex(i.clone());const r=e.attributes;for(const e in r){const i=r[e];this.setAttribute(e,i.clone(t))}const n=e.morphAttributes;for(const e in n){const i=[],r=n[e];for(let e=0,n=r.length;e<n;e++)i.push(r[e].clone(t));this.morphAttributes[e]=i}this.morphTargetsRelative=e.morphTargetsRelative;const s=e.groups;for(let e=0,t=s.length;e<t;e++){const t=s[e];this.addGroup(t.start,t.count,t.materialIndex)}const a=e.boundingBox;null!==a&&(this.boundingBox=a.clone());const o=e.boundingSphere;return null!==o&&(this.boundingSphere=o.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this._transformed=e._transformed,this}dispose(){this.dispatchEvent({type:"dispose"})}}class Qn{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=void 0!==e?e.length/t:0,this.usage=ai,this.updateRanges=[],this.version=0,this.uuid=Di()}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,i){e*=this.stride,i*=t.stride;for(let r=0,n=this.stride;r<n;r++)this.array[e+r]=t.array[i+r];return this}set(e,t=0){return this.array.set(e,t),this}clone(e){void 0===e.arrayBuffers&&(e.arrayBuffers={});const t=Jn(this.array);void 0===e.arrayBuffers[t]&&(e.arrayBuffers[t]=this.array.slice(0).buffer);const i=new this.array.constructor(e.arrayBuffers[t]),r=new this.constructor(i,this.stride);return r.setUsage(this.usage),r}onUpload(e){return this.onUploadCallback=e,this}toJSON(e){void 0===e.arrayBuffers&&(e.arrayBuffers={});const t=Jn(this.array);void 0===e.arrayBuffers[t]&&(e.arrayBuffers[t]=Array.from(new Uint32Array(this.array.slice(0).buffer)));const i={uuid:this.uuid,buffer:t,type:this.array.constructor.name,stride:this.stride};return i.usage=this.usage,i}}function Jn(e){return void 0===e.buffer._uuid&&(e.buffer._uuid=Di()),0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer._uuid:e.buffer._uuid+":"+e.byteOffset+":"+e.byteLength}const es=new Wi;class ts{constructor(e,t,i,r=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=e,this.itemSize=t,this.offset=i,this.normalized=r,this._normalizationScale=void 0!==e?Bi(e.array):void 0}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(e){this.data.needsUpdate=e}applyMatrix4(e){for(let t=0,i=this.data.count;t<i;t++)es.fromBufferAttribute(this,t),es.applyMatrix4(e),this.setXYZ(t,es.x,es.y,es.z);return this}applyNormalMatrix(e){for(let t=0,i=this.count;t<i;t++)es.fromBufferAttribute(this,t),es.applyNormalMatrix(e),this.setXYZ(t,es.x,es.y,es.z);return this}transformDirection(e){for(let t=0,i=this.count;t<i;t++)es.fromBufferAttribute(this,t),es.transformDirection(e),this.setXYZ(t,es.x,es.y,es.z);return this}getComponent(e,t){let i=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(i=this._denormalize(i)),i}setComponent(e,t,i){return this.normalized&&(i=this._normalize(i)),this.data.array[e*this.data.stride+this.offset+t]=i,this}setX(e,t){return this.normalized&&(t=this._normalize(t)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=this._normalize(t)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=this._normalize(t)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=this._normalize(t)),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=this._denormalize(t)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=this._denormalize(t)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=this._denormalize(t)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=this._denormalize(t)),t}setXY(e,t,i){return e=e*this.data.stride+this.offset,this.normalized&&(t=this._normalize(t),i=this._normalize(i)),this.data.array[e+0]=t,this.data.array[e+1]=i,this}setXYZ(e,t,i,r){return e=e*this.data.stride+this.offset,this.normalized&&(t=this._normalize(t),i=this._normalize(i),r=this._normalize(r)),this.data.array[e+0]=t,this.data.array[e+1]=i,this.data.array[e+2]=r,this}setXYZW(e,t,i,r,n){return e=e*this.data.stride+this.offset,this.normalized&&(t=this._normalize(t),i=this._normalize(i),r=this._normalize(r),n=this._normalize(n)),this.data.array[e+0]=t,this.data.array[e+1]=i,this.data.array[e+2]=r,this.data.array[e+3]=n,this}clone(e){if(void 0===e){xi("InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");const e=[];for(let t=0;t<this.count;t++){const i=t*this.data.stride+this.offset;for(let t=0;t<this.itemSize;t++)e.push(this.data.array[i+t])}return new In(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 ts(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(void 0===e){xi("InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");const e=[];for(let t=0;t<this.count;t++){const i=t*this.data.stride+this.offset;for(let t=0;t<this.itemSize;t++)e.push(this.data.array[i+t])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:e,normalized:this.normalized}}return void 0===e.interleavedBuffers&&(e.interleavedBuffers={}),void 0===e.interleavedBuffers[this.data.uuid]&&(e.interleavedBuffers[this.data.uuid]=this.data.toJSON(e)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}_denormalize(e){const t=this._normalizationScale;return void 0!==t?Math.max(e/t,-1):ki(e,this.data.array)}_normalize(e){const t=this._normalizationScale;return void 0!==t?Math.round(e*t):zi(e,this.data.array)}}const is=new Wi,rs=new Wi,ns=new Xi;class ss{constructor(e=new Wi(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,i,r){return this.normal.set(e,t,i),this.constant=r,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,i){const r=is.subVectors(i,t).cross(rs.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(r,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,i=!0){const r=e.delta(is),n=this.normal.dot(r);if(0===n)return 0===this.distanceToPoint(e.start)?t.copy(e.start):null;const s=-(e.start.dot(this.normal)+this.constant)/n;return!0===i&&(s<0||s>1)?null:t.copy(e.start).addScaledVector(r,s)}intersectsLine(e){const t=this.distanceToPoint(e.start),i=this.distanceToPoint(e.end);return t<0&&i>0||i<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const i=t||ns.getNormalMatrix(e),r=this.coplanarPoint(is).applyMatrix4(e),n=this.normal.applyMatrix3(i).normalize();return this.constant=-r.dot(n),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return(new this.constructor).copy(this)}toJSON(){return{normal:this.normal.toArray(),constant:this.constant}}fromJSON(e){return this.normal.fromArray(e.normal),this.constant=e.constant,this}}let as=0;class os extends Ri{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:as++}),this.uuid=Di(),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=Q,this.blendDst=J,this.blendEquation=H,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Yr(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=Zt,this.stencilZFail=Zt,this.stencilZPass=Zt,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 i=e[t];if(void 0===i){Ti(`Material: parameter '${t}' has value of undefined.`);continue}const r=this[t];void 0!==r?r&&r.isColor?r.set(i):r&&r.isVector2&&i&&i.isVector2||r&&r.isEuler&&i&&i.isEuler||r&&r.isVector3&&i&&i.isVector3?r.copy(i):this[t]=i:Ti(`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 i={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};function r(e){const t=[];for(const i in e){const r=e[i];delete r.metadata,t.push(r)}return t}if(i.uuid=this.uuid,i.type=this.type,i.blending=this.blending,i.side=this.side,i.shadowSide=this.shadowSide,i.vertexColors=this.vertexColors,i.opacity=this.opacity,i.transparent=this.transparent,i.blendSrc=this.blendSrc,i.blendDst=this.blendDst,i.blendEquation=this.blendEquation,i.blendSrcAlpha=this.blendSrcAlpha,i.blendDstAlpha=this.blendDstAlpha,i.blendEquationAlpha=this.blendEquationAlpha,i.blendColor=this.blendColor.getHex(),i.blendAlpha=this.blendAlpha,i.depthFunc=this.depthFunc,i.depthTest=this.depthTest,i.depthWrite=this.depthWrite,i.colorWrite=this.colorWrite,i.clipIntersection=this.clipIntersection,i.clipShadows=this.clipShadows,i.stencilWriteMask=this.stencilWriteMask,i.stencilFunc=this.stencilFunc,i.stencilRef=this.stencilRef,i.stencilFuncMask=this.stencilFuncMask,i.stencilFail=this.stencilFail,i.stencilZFail=this.stencilZFail,i.stencilZPass=this.stencilZPass,i.stencilWrite=this.stencilWrite,i.polygonOffset=this.polygonOffset,i.polygonOffsetFactor=this.polygonOffsetFactor,i.polygonOffsetUnits=this.polygonOffsetUnits,i.dithering=this.dithering,i.alphaTest=this.alphaTest,i.alphaHash=this.alphaHash,i.alphaToCoverage=this.alphaToCoverage,i.premultipliedAlpha=this.premultipliedAlpha,i.forceSinglePass=this.forceSinglePass,i.allowOverride=this.allowOverride,i.visible=this.visible,i.toneMapped=this.toneMapped,i.name=this.name,this.color&&this.color.isColor&&(i.color=this.color.getHex()),void 0!==this.roughness&&(i.roughness=this.roughness),void 0!==this.metalness&&(i.metalness=this.metalness),void 0!==this.sheen&&(i.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(i.sheenColor=this.sheenColor.getHex()),void 0!==this.sheenRoughness&&(i.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(i.emissive=this.emissive.getHex()),void 0!==this.emissiveIntensity&&(i.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(i.specular=this.specular.getHex()),void 0!==this.specularIntensity&&(i.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(i.specularColor=this.specularColor.getHex()),void 0!==this.shininess&&(i.shininess=this.shininess),void 0!==this.clearcoat&&(i.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(i.clearcoatRoughness=this.clearcoatRoughness),void 0!==this.diffuseRoughness&&(i.diffuseRoughness=this.diffuseRoughness),this.diffuseRoughnessMap&&this.diffuseRoughnessMap.isTexture&&(i.diffuseRoughnessMap=this.diffuseRoughnessMap.toJSON(e).uuid),this.clearcoatMap&&this.clearcoatMap.isTexture&&(i.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(i.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(i.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,i.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(i.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(i.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),void 0!==this.dispersion&&(i.dispersion=this.dispersion),void 0!==this.retroreflectivity&&(i.retroreflectivity=this.retroreflectivity),void 0!==this.iridescence&&(i.iridescence=this.iridescence),void 0!==this.iridescenceIOR&&(i.iridescenceIOR=this.iridescenceIOR),void 0!==this.iridescenceThicknessMinimum&&(i.iridescenceThicknessMinimum=this.iridescenceThicknessMinimum),void 0!==this.iridescenceThicknessMaximum&&(i.iridescenceThicknessMaximum=this.iridescenceThicknessMaximum),this.iridescenceMap&&this.iridescenceMap.isTexture&&(i.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(i.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),void 0!==this.anisotropy&&(i.anisotropy=this.anisotropy),void 0!==this.anisotropyRotation&&(i.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(i.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(i.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(i.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(i.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(i.lightMap=this.lightMap.toJSON(e).uuid,i.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(i.aoMap=this.aoMap.toJSON(e).uuid,i.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(i.bumpMap=this.bumpMap.toJSON(e).uuid,i.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(i.normalMap=this.normalMap.toJSON(e).uuid,i.normalMapType=this.normalMapType,i.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(i.displacementMap=this.displacementMap.toJSON(e).uuid,i.displacementScale=this.displacementScale,i.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(i.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(i.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(i.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(i.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(i.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(i.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(i.envMap=this.envMap.toJSON(e).uuid,void 0!==this.combine&&(i.combine=this.combine)),void 0!==this.envMapRotation&&(i.envMapRotation=this.envMapRotation.toArray()),void 0!==this.envMapIntensity&&(i.envMapIntensity=this.envMapIntensity),void 0!==this.reflectivity&&(i.reflectivity=this.reflectivity),void 0!==this.refractionRatio&&(i.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(i.gradientMap=this.gradientMap.toJSON(e).uuid),void 0!==this.transmission&&(i.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(i.transmissionMap=this.transmissionMap.toJSON(e).uuid),void 0!==this.thickness&&(i.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(i.thicknessMap=this.thicknessMap.toJSON(e).uuid),void 0!==this.attenuationDistance&&(i.attenuationDistance=this.attenuationDistance),void 0!==this.attenuationColor&&(i.attenuationColor=this.attenuationColor.getHex()),void 0!==this.size&&(i.size=this.size),void 0!==this.sizeAttenuation&&(i.sizeAttenuation=this.sizeAttenuation),Array.isArray(this.clippingPlanes)&&this.clippingPlanes.length>0&&(i.clippingPlanes=this.clippingPlanes.map(e=>e.toJSON())),void 0!==this.rotation&&(i.rotation=this.rotation),void 0!==this.depthPacking&&(i.depthPacking=this.depthPacking),void 0!==this.linewidth&&(i.linewidth=this.linewidth),void 0!==this.linecap&&(i.linecap=this.linecap),void 0!==this.linejoin&&(i.linejoin=this.linejoin),void 0!==this.dashSize&&(i.dashSize=this.dashSize),void 0!==this.gapSize&&(i.gapSize=this.gapSize),void 0!==this.scale&&(i.scale=this.scale),void 0!==this.wireframe&&(i.wireframe=this.wireframe),void 0!==this.wireframeLinewidth&&(i.wireframeLinewidth=this.wireframeLinewidth),void 0!==this.wireframeLinecap&&(i.wireframeLinecap=this.wireframeLinecap),void 0!==this.wireframeLinejoin&&(i.wireframeLinejoin=this.wireframeLinejoin),void 0!==this.flatShading&&(i.flatShading=this.flatShading),void 0!==this.fog&&(i.fog=this.fog),Object.keys(this.userData).length>0&&(i.userData=this.userData),t){const t=r(e.textures),n=r(e.images);t.length>0&&(i.textures=t),n.length>0&&(i.images=n)}return i}fromJSON(e,t){if(void 0!==e.uuid&&(this.uuid=e.uuid),void 0!==e.name&&(this.name=e.name),void 0!==e.color&&void 0!==this.color&&this.color.setHex(e.color),void 0!==e.roughness&&(this.roughness=e.roughness),void 0!==e.metalness&&(this.metalness=e.metalness),void 0!==e.sheen&&(this.sheen=e.sheen),void 0!==e.sheenColor&&(this.sheenColor=(new Yr).setHex(e.sheenColor)),void 0!==e.sheenRoughness&&(this.sheenRoughness=e.sheenRoughness),void 0!==e.emissive&&void 0!==this.emissive&&this.emissive.setHex(e.emissive),void 0!==e.specular&&void 0!==this.specular&&this.specular.setHex(e.specular),void 0!==e.specularIntensity&&(this.specularIntensity=e.specularIntensity),void 0!==e.specularColor&&void 0!==this.specularColor&&this.specularColor.setHex(e.specularColor),void 0!==e.shininess&&(this.shininess=e.shininess),void 0!==e.clearcoat&&(this.clearcoat=e.clearcoat),void 0!==e.clearcoatRoughness&&(this.clearcoatRoughness=e.clearcoatRoughness),void 0!==e.diffuseRoughness&&(this.diffuseRoughness=e.diffuseRoughness),void 0!==e.dispersion&&(this.dispersion=e.dispersion),void 0!==e.retroreflectivity&&(this.retroreflectivity=e.retroreflectivity),void 0!==e.iridescence&&(this.iridescence=e.iridescence),void 0!==e.iridescenceIOR&&(this.iridescenceIOR=e.iridescenceIOR),void 0!==e.iridescenceThicknessMinimum&&(this.iridescenceThicknessMinimum=e.iridescenceThicknessMinimum),void 0!==e.iridescenceThicknessMaximum&&(this.iridescenceThicknessMaximum=e.iridescenceThicknessMaximum),void 0!==e.iridescenceThicknessRange&&(this.iridescenceThicknessMinimum=e.iridescenceThicknessRange[0],this.iridescenceThicknessMaximum=e.iridescenceThicknessRange[1]),void 0!==e.transmission&&(this.transmission=e.transmission),void 0!==e.thickness&&(this.thickness=e.thickness),void 0!==e.attenuationDistance&&(this.attenuationDistance=e.attenuationDistance),void 0!==e.attenuationColor&&void 0!==this.attenuationColor&&this.attenuationColor.setHex(e.attenuationColor),void 0!==e.anisotropy&&(this.anisotropy=e.anisotropy),void 0!==e.anisotropyRotation&&(this.anisotropyRotation=e.anisotropyRotation),void 0!==e.fog&&(this.fog=e.fog),void 0!==e.flatShading&&(this.flatShading=e.flatShading),void 0!==e.blending&&(this.blending=e.blending),void 0!==e.combine&&(this.combine=e.combine),void 0!==e.side&&(this.side=e.side),void 0!==e.shadowSide&&(this.shadowSide=e.shadowSide),void 0!==e.opacity&&(this.opacity=e.opacity),void 0!==e.transparent&&(this.transparent=e.transparent),void 0!==e.alphaTest&&(this.alphaTest=e.alphaTest),void 0!==e.alphaHash&&(this.alphaHash=e.alphaHash),void 0!==e.depthFunc&&(this.depthFunc=e.depthFunc),void 0!==e.depthTest&&(this.depthTest=e.depthTest),void 0!==e.depthWrite&&(this.depthWrite=e.depthWrite),void 0!==e.colorWrite&&(this.colorWrite=e.colorWrite),void 0!==e.clippingPlanes&&(this.clippingPlanes=e.clippingPlanes.map(e=>(new ss).fromJSON(e))),void 0!==e.clipIntersection&&(this.clipIntersection=e.clipIntersection),void 0!==e.clipShadows&&(this.clipShadows=e.clipShadows),void 0!==e.depthPacking&&(this.depthPacking=e.depthPacking),void 0!==e.blendSrc&&(this.blendSrc=e.blendSrc),void 0!==e.blendDst&&(this.blendDst=e.blendDst),void 0!==e.blendEquation&&(this.blendEquation=e.blendEquation),void 0!==e.blendSrcAlpha&&(this.blendSrcAlpha=e.blendSrcAlpha),void 0!==e.blendDstAlpha&&(this.blendDstAlpha=e.blendDstAlpha),void 0!==e.blendEquationAlpha&&(this.blendEquationAlpha=e.blendEquationAlpha),void 0!==e.blendColor&&void 0!==this.blendColor&&this.blendColor.setHex(e.blendColor),void 0!==e.blendAlpha&&(this.blendAlpha=e.blendAlpha),void 0!==e.stencilWriteMask&&(this.stencilWriteMask=e.stencilWriteMask),void 0!==e.stencilFunc&&(this.stencilFunc=e.stencilFunc),void 0!==e.stencilRef&&(this.stencilRef=e.stencilRef),void 0!==e.stencilFuncMask&&(this.stencilFuncMask=e.stencilFuncMask),void 0!==e.stencilFail&&(this.stencilFail=e.stencilFail),void 0!==e.stencilZFail&&(this.stencilZFail=e.stencilZFail),void 0!==e.stencilZPass&&(this.stencilZPass=e.stencilZPass),void 0!==e.stencilWrite&&(this.stencilWrite=e.stencilWrite),void 0!==e.wireframe&&(this.wireframe=e.wireframe),void 0!==e.wireframeLinewidth&&(this.wireframeLinewidth=e.wireframeLinewidth),void 0!==e.wireframeLinecap&&(this.wireframeLinecap=e.wireframeLinecap),void 0!==e.wireframeLinejoin&&(this.wireframeLinejoin=e.wireframeLinejoin),void 0!==e.rotation&&(this.rotation=e.rotation),void 0!==e.linewidth&&(this.linewidth=e.linewidth),void 0!==e.linecap&&(this.linecap=e.linecap),void 0!==e.linejoin&&(this.linejoin=e.linejoin),void 0!==e.dashSize&&(this.dashSize=e.dashSize),void 0!==e.gapSize&&(this.gapSize=e.gapSize),void 0!==e.scale&&(this.scale=e.scale),void 0!==e.polygonOffset&&(this.polygonOffset=e.polygonOffset),void 0!==e.polygonOffsetFactor&&(this.polygonOffsetFactor=e.polygonOffsetFactor),void 0!==e.polygonOffsetUnits&&(this.polygonOffsetUnits=e.polygonOffsetUnits),void 0!==e.dithering&&(this.dithering=e.dithering),void 0!==e.alphaToCoverage&&(this.alphaToCoverage=e.alphaToCoverage),void 0!==e.premultipliedAlpha&&(this.premultipliedAlpha=e.premultipliedAlpha),void 0!==e.forceSinglePass&&(this.forceSinglePass=e.forceSinglePass),void 0!==e.allowOverride&&(this.allowOverride=e.allowOverride),void 0!==e.visible&&(this.visible=e.visible),void 0!==e.toneMapped&&(this.toneMapped=e.toneMapped),void 0!==e.userData&&(this.userData=e.userData),void 0!==e.vertexColors&&("number"==typeof e.vertexColors?this.vertexColors=e.vertexColors>0:this.vertexColors=e.vertexColors),void 0!==e.size&&(this.size=e.size),void 0!==e.sizeAttenuation&&(this.sizeAttenuation=e.sizeAttenuation),void 0!==e.map&&(this.map=t[e.map]||null),void 0!==e.matcap&&(this.matcap=t[e.matcap]||null),void 0!==e.alphaMap&&(this.alphaMap=t[e.alphaMap]||null),void 0!==e.bumpMap&&(this.bumpMap=t[e.bumpMap]||null),void 0!==e.bumpScale&&(this.bumpScale=e.bumpScale),void 0!==e.normalMap&&(this.normalMap=t[e.normalMap]||null),void 0!==e.normalMapType&&(this.normalMapType=e.normalMapType),void 0!==e.normalScale){let t=e.normalScale;!1===Array.isArray(t)&&(t=[t,t]),this.normalScale=(new Vi).fromArray(t)}return void 0!==e.displacementMap&&(this.displacementMap=t[e.displacementMap]||null),void 0!==e.displacementScale&&(this.displacementScale=e.displacementScale),void 0!==e.displacementBias&&(this.displacementBias=e.displacementBias),void 0!==e.roughnessMap&&(this.roughnessMap=t[e.roughnessMap]||null),void 0!==e.metalnessMap&&(this.metalnessMap=t[e.metalnessMap]||null),void 0!==e.emissiveMap&&(this.emissiveMap=t[e.emissiveMap]||null),void 0!==e.emissiveIntensity&&(this.emissiveIntensity=e.emissiveIntensity),void 0!==e.specularMap&&(this.specularMap=t[e.specularMap]||null),void 0!==e.specularIntensityMap&&(this.specularIntensityMap=t[e.specularIntensityMap]||null),void 0!==e.specularColorMap&&(this.specularColorMap=t[e.specularColorMap]||null),void 0!==e.envMap&&(this.envMap=t[e.envMap]||null),void 0!==e.envMapRotation&&this.envMapRotation.fromArray(e.envMapRotation),void 0!==e.envMapIntensity&&(this.envMapIntensity=e.envMapIntensity),void 0!==e.reflectivity&&(this.reflectivity=e.reflectivity),void 0!==e.refractionRatio&&(this.refractionRatio=e.refractionRatio),void 0!==e.lightMap&&(this.lightMap=t[e.lightMap]||null),void 0!==e.lightMapIntensity&&(this.lightMapIntensity=e.lightMapIntensity),void 0!==e.aoMap&&(this.aoMap=t[e.aoMap]||null),void 0!==e.aoMapIntensity&&(this.aoMapIntensity=e.aoMapIntensity),void 0!==e.gradientMap&&(this.gradientMap=t[e.gradientMap]||null),void 0!==e.clearcoatMap&&(this.clearcoatMap=t[e.clearcoatMap]||null),void 0!==e.clearcoatRoughnessMap&&(this.clearcoatRoughnessMap=t[e.clearcoatRoughnessMap]||null),void 0!==e.clearcoatNormalMap&&(this.clearcoatNormalMap=t[e.clearcoatNormalMap]||null),void 0!==e.clearcoatNormalScale&&(this.clearcoatNormalScale=(new Vi).fromArray(e.clearcoatNormalScale)),void 0!==e.diffuseRoughnessMap&&(this.diffuseRoughnessMap=t[e.diffuseRoughnessMap]||null),void 0!==e.iridescenceMap&&(this.iridescenceMap=t[e.iridescenceMap]||null),void 0!==e.iridescenceThicknessMap&&(this.iridescenceThicknessMap=t[e.iridescenceThicknessMap]||null),void 0!==e.transmissionMap&&(this.transmissionMap=t[e.transmissionMap]||null),void 0!==e.thicknessMap&&(this.thicknessMap=t[e.thicknessMap]||null),void 0!==e.anisotropyMap&&(this.anisotropyMap=t[e.anisotropyMap]||null),void 0!==e.sheenColorMap&&(this.sheenColorMap=t[e.sheenColorMap]||null),void 0!==e.sheenRoughnessMap&&(this.sheenRoughnessMap=t[e.sheenRoughnessMap]||null),this}clone(){return(new this.constructor).copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let i=null;if(null!==t){const e=t.length;i=new Array(e);for(let r=0;r!==e;++r)i[r]=t[r].clone()}return this.clippingPlanes=i,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.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 ls extends os{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new Yr(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 us=new Wi,cs=new Wi,hs=new Wi,ds=new Wi;class ps{constructor(e=new Wi,t=new Wi(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,us)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const i=t.dot(this.direction);return i<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,i)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=us.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(us.copy(this.origin).addScaledVector(this.direction,t),us.distanceToSquared(e))}distanceSqToSegment(e,t,i,r){cs.copy(e).add(t).multiplyScalar(.5),hs.copy(t).sub(e).normalize(),ds.copy(this.origin).sub(cs);const n=.5*e.distanceTo(t),s=-this.direction.dot(hs),a=ds.dot(this.direction),o=-ds.dot(hs),l=ds.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=n*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=n,c=Math.max(0,-(s*h+a)),d=-c*c+h*(h+2*o)+l;else h=-n,c=Math.max(0,-(s*h+a)),d=-c*c+h*(h+2*o)+l;else h<=-p?(c=Math.max(0,-(-s*n+a)),h=c>0?-n:Math.min(Math.max(-n,-o),n),d=-c*c+h*(h+2*o)+l):h<=p?(c=0,h=Math.min(Math.max(-n,-o),n),d=h*(h+2*o)+l):(c=Math.max(0,-(s*n+a)),h=c>0?n:Math.min(Math.max(-n,-o),n),d=-c*c+h*(h+2*o)+l);else h=s>0?-n:n,c=Math.max(0,-(s*h+a)),d=-c*c+h*(h+2*o)+l;return i&&i.copy(this.origin).addScaledVector(this.direction,c),r&&r.copy(cs).addScaledVector(hs,h),d}intersectSphere(e,t){if(e.radius<0)return null;us.subVectors(e.center,this.origin);const i=us.dot(this.direction),r=us.dot(us)-i*i,n=e.radius*e.radius;if(r>n)return null;const s=Math.sqrt(n-r),a=i-s,o=i+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 i=-(this.origin.dot(e.normal)+e.constant)/t;return i>=0?i:null}intersectPlane(e,t){const i=this.distanceToPlane(e);return null===i?null:this.at(i,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);if(0===t)return!0;return e.normal.dot(this.direction)*t<0}intersectBox(e,t){let i,r,n,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?(i=(e.min.x-h.x)*l,r=(e.max.x-h.x)*l):(i=(e.max.x-h.x)*l,r=(e.min.x-h.x)*l),u>=0?(n=(e.min.y-h.y)*u,s=(e.max.y-h.y)*u):(n=(e.max.y-h.y)*u,s=(e.min.y-h.y)*u),i>s||n>r?null:((n>i||isNaN(i))&&(i=n),(s<r||isNaN(r))&&(r=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),i>o||a>r?null:((a>i||i!=i)&&(i=a),(o<r||r!=r)&&(r=o),r<0?null:this.at(i>=0?i:r,t)))}intersectsBox(e){return null!==this.intersectBox(e,us)}intersectTriangle(e,t,i,r,n){const s=this.origin,a=this.direction,o=a.x,l=a.y,u=a.z,c=e.x-s.x,h=e.y-s.y,d=e.z-s.z,p=t.x-s.x,f=t.y-s.y,m=t.z-s.z,g=i.x-s.x,_=i.y-s.y,v=i.z-s.z,b=Math.abs(o),y=Math.abs(l),x=Math.abs(u);let S,T,M,E,w,A,R,C,N,P,L,D;if(b>=y&&b>=x?(M=o,A=c,N=p,D=g,o>=0?(S=l,T=u,E=h,w=d,R=f,C=m,P=_,L=v):(S=u,T=l,E=d,w=h,R=m,C=f,P=v,L=_)):y>=x?(M=l,A=h,N=f,D=_,l>=0?(S=u,T=o,E=d,w=c,R=m,C=p,P=v,L=g):(S=o,T=u,E=c,w=d,R=p,C=m,P=g,L=v)):(M=u,A=d,N=m,D=v,u>=0?(S=o,T=l,E=c,w=h,R=p,C=f,P=g,L=_):(S=l,T=o,E=h,w=c,R=f,C=p,P=_,L=g)),0===M)return null;const U=S/M,I=T/M,F=E-U*A,O=w-I*A,B=R-U*N,k=C-I*N,z=P-U*D,G=L-I*D,V=z*k-G*B,H=F*G-O*z,W=B*O-k*F;if(r){if(V<0||H<0||W<0)return null}else if((V<0||H<0||W<0)&&(V>0||H>0||W>0))return null;const j=V+H+W;if(0===j)return null;const $=1/M*(V*A+H*N+W*D);return(j>0?$<0:$>0)?null:this.at($/j,n)}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 fs extends os{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Yr(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 Mr,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 ms=new fr,gs=new ps,_s=new Hn,vs=new Wi,bs=new Wi,ys=new Wi,xs=new Wi,Ss=new Wi,Ts=new Wi,Ms=new Wi,Es=new Wi;class ws extends Gr{constructor(e=new Zn,t=new fs){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():this.morphTargetInfluences=void 0,void 0!==e.morphTargetDictionary?this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary):this.morphTargetDictionary=void 0,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 i=e[t[0]];if(void 0!==i){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=i.length;e<t;e++){const t=i[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}getVertexPosition(e,t){const i=this.geometry,r=i.attributes.position,n=i.morphAttributes.position,s=i.morphTargetsRelative;t.fromBufferAttribute(r,e);const a=this.morphTargetInfluences;if(n&&a){Ts.set(0,0,0);for(let i=0,r=n.length;i<r;i++){const r=a[i],o=n[i];0!==r&&(Ss.fromBufferAttribute(o,e),s?Ts.addScaledVector(Ss,r):Ts.addScaledVector(Ss.sub(t),r))}t.add(Ts)}return t}intersectsFrustum(e){return e.intersectsObject(this)}raycast(e,t){const i=this.geometry,r=this.material,n=this.matrixWorld;if(void 0!==r){if(null===i.boundingSphere&&i.computeBoundingSphere(),_s.copy(i.boundingSphere),_s.applyMatrix4(n),gs.copy(e.ray).recast(e.near),!1===_s.containsPoint(gs.origin)){if(null===gs.intersectSphere(_s,vs))return;if(gs.origin.distanceToSquared(vs)>(e.far-e.near)**2)return}ms.copy(n).invert(),gs.copy(e.ray).applyMatrix4(ms),null!==i.boundingBox&&!1===gs.intersectsBox(i.boundingBox)||this._computeIntersections(e,t,gs)}}_computeIntersections(e,t,i){let r;const n=this.geometry,s=this.material,a=n.index,o=n.attributes.position,l=n.attributes.uv,u=n.attributes.uv1,c=n.attributes.normal,h=n.groups,d=n.drawRange;if(null!==a)if(Array.isArray(s))for(let n=0,o=h.length;n<o;n++){const o=h[n],p=s[o.materialIndex];for(let n=Math.max(o.start,d.start),s=Math.min(a.count,Math.min(o.start+o.count,d.start+d.count));n<s;n+=3){r=As(this,p,e,i,l,u,c,a.getX(n),a.getX(n+1),a.getX(n+2)),r&&(r.faceIndex=Math.floor(n/3),r.face.materialIndex=o.materialIndex,t.push(r))}}else{for(let n=Math.max(0,d.start),o=Math.min(a.count,d.start+d.count);n<o;n+=3){r=As(this,s,e,i,l,u,c,a.getX(n),a.getX(n+1),a.getX(n+2)),r&&(r.faceIndex=Math.floor(n/3),t.push(r))}}else if(void 0!==o)if(Array.isArray(s))for(let n=0,a=h.length;n<a;n++){const a=h[n],p=s[a.materialIndex];for(let n=Math.max(a.start,d.start),s=Math.min(o.count,Math.min(a.start+a.count,d.start+d.count));n<s;n+=3){r=As(this,p,e,i,l,u,c,n,n+1,n+2),r&&(r.faceIndex=Math.floor(n/3),r.face.materialIndex=a.materialIndex,t.push(r))}}else{for(let n=Math.max(0,d.start),a=Math.min(o.count,d.start+d.count);n<a;n+=3){r=As(this,s,e,i,l,u,c,n,n+1,n+2),r&&(r.faceIndex=Math.floor(n/3),t.push(r))}}}}function As(e,t,i,r,n,s,a,o,l,u){e.getVertexPosition(o,bs),e.getVertexPosition(l,ys),e.getVertexPosition(u,xs);const c=function(e,t,i,r,n,s,a,o){let l;if(l=1===t.side?r.intersectTriangle(a,s,n,!0,o):r.intersectTriangle(n,s,a,0===t.side,o),null===l)return null;Es.copy(o),Es.applyMatrix4(e.matrixWorld);const u=i.ray.origin.distanceTo(Es);return u<i.near||u>i.far?null:{distance:u,point:Es.clone(),object:e}}(e,t,i,r,bs,ys,xs,Ms);if(c){const e=new Wi;dn.getBarycoord(Ms,bs,ys,xs,e),n&&(c.uv=dn.getInterpolatedAttribute(n,o,l,u,e,new Vi)),s&&(c.uv1=dn.getInterpolatedAttribute(s,o,l,u,e,new Vi)),a&&(c.normal=dn.getInterpolatedAttribute(a,o,l,u,e,new Wi),c.normal.dot(r.direction)>0&&c.normal.multiplyScalar(-1));const t={a:o,b:l,c:u,normal:new Wi,materialIndex:0};dn.getNormal(bs,ys,xs,t.normal),c.face=t,c.barycoord=e}return c}class Rs extends lr{constructor(e=null,t=1,i=1,r,n,s,a,o,l=1003,u=1003,c,h){super(null,s,a,o,l,u,r,n,c,h),this.isDataTexture=!0,this.image={data:e,width:t,height:i},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class Cs extends In{constructor(e,t,i,r=1){super(e,t,i),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=r}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 Ns=new fr,Ps=new fr,Ls=[],Ds=new pn,Us=new fr,Is=new ws,Fs=new Hn;class Os extends ws{constructor(e,t,i){super(e,t),this.isInstancedMesh=!0,this.instanceMatrix=new Cs(new Float32Array(16*i),16),this.instanceColor=null,this.morphTexture=null,this.count=i,this.boundingBox=null,this.boundingSphere=null;for(let e=0;e<i;e++)this.setMatrixAt(e,Us)}computeBoundingBox(){const e=this.geometry,t=this.count;null===this.boundingBox&&(this.boundingBox=new pn),null===e.boundingBox&&e.computeBoundingBox(),this.boundingBox.makeEmpty();for(let i=0;i<t;i++)this.getMatrixAt(i,Ns),Ds.copy(e.boundingBox).applyMatrix4(Ns),this.boundingBox.union(Ds)}computeBoundingSphere(){const e=this.geometry,t=this.count;null===this.boundingSphere&&(this.boundingSphere=new Hn),null===e.boundingSphere&&e.computeBoundingSphere(),this.boundingSphere.makeEmpty();for(let i=0;i<t;i++)this.getMatrixAt(i,Ns),Fs.copy(e.boundingSphere).applyMatrix4(Ns),this.boundingSphere.union(Fs)}copy(e,t){return super.copy(e,t),this.instanceMatrix.copy(e.instanceMatrix),this.morphTexture=null!==e.morphTexture?e.morphTexture.clone():null,this.instanceColor=null!==e.instanceColor?e.instanceColor.clone():null,this.count=e.count,this.boundingBox=null!==e.boundingBox?e.boundingBox.clone():null,this.boundingSphere=null!==e.boundingSphere?e.boundingSphere.clone():null,this}getColorAt(e,t){return null===this.instanceColor?t.setRGB(1,1,1):t.fromArray(this.instanceColor.array,3*e)}getMatrixAt(e,t){return t.fromArray(this.instanceMatrix.array,16*e)}getMorphAt(e,t){const i=t.morphTargetInfluences,r=this.morphTexture.source.data.data,n=e*(i.length+1)+1;for(let e=0;e<i.length;e++)i[e]=r[n+e]}raycast(e,t){const i=this.matrixWorld,r=this.count;if(Is.geometry=this.geometry,Is.material=this.material,void 0!==Is.material&&(null===this.boundingSphere&&this.computeBoundingSphere(),Fs.copy(this.boundingSphere),Fs.applyMatrix4(i),!1!==e.ray.intersectsSphere(Fs)))for(let n=0;n<r;n++){this.getMatrixAt(n,Ns),Ps.multiplyMatrices(i,Ns),Is.matrixWorld=Ps,Is.raycast(e,Ls);for(let e=0,i=Ls.length;e<i;e++){const i=Ls[e];i.instanceId=n,i.object=this,t.push(i)}Ls.length=0}}setColorAt(e,t){return null===this.instanceColor&&(this.instanceColor=new Cs(new Float32Array(3*this.instanceMatrix.count).fill(1),3)),t.toArray(this.instanceColor.array,3*e),this}setMatrixAt(e,t){return t.toArray(this.instanceMatrix.array,16*e),this}setMorphAt(e,t){const i=t.morphTargetInfluences,r=i.length+1;null===this.morphTexture&&(this.morphTexture=new Rs(new Float32Array(r*this.count),r,this.count,nt,$e));const n=this.morphTexture.source.data.data;let s=0;for(let e=0;e<i.length;e++)s+=i[e];const a=this.geometry.morphTargetsRelative?1:1-s,o=r*e;return n[o]=a,n.set(i,o+1),this}updateMorphTargets(){}dispose(){super.dispose(),this.instanceMatrix.dispose(),null!==this.instanceColor&&this.instanceColor.dispose(),null!==this.morphTexture&&(this.morphTexture.dispose(),this.morphTexture=null)}}const Bs=new Hn,ks=new Vi(.5,.5),zs=new Wi;class Gs{constructor(e=new ss,t=new ss,i=new ss,r=new ss,n=new ss,s=new ss){this.planes=[e,t,i,r,n,s]}set(e,t,i,r,n,s){const a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(i),a[3].copy(r),a[4].copy(n),a[5].copy(s),this}copy(e){const t=this.planes;for(let i=0;i<6;i++)t[i].copy(e.planes[i]);return this}setFromProjectionMatrix(e,t=2e3,i=!1){const r=this.planes,n=e.elements,s=n[0],a=n[1],o=n[2],l=n[3],u=n[4],c=n[5],h=n[6],d=n[7],p=n[8],f=n[9],m=n[10],g=n[11],_=n[12],v=n[13],b=n[14],y=n[15];if(r[0].setComponents(l-s,d-u,g-p,y-_).normalize(),r[1].setComponents(l+s,d+u,g+p,y+_).normalize(),r[2].setComponents(l+a,d+c,g+f,y+v).normalize(),r[3].setComponents(l-a,d-c,g-f,y-v).normalize(),i)r[4].setComponents(o,h,m,b).normalize(),r[5].setComponents(l-o,d-h,g-m,y-b).normalize();else if(r[4].setComponents(l-o,d-h,g-m,y-b).normalize(),t===ui)r[5].setComponents(l+o,d+h,g+m,y+b).normalize();else{if(t!==ci)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);r[5].setComponents(o,h,m,b).normalize()}return this}intersectsObject(e){if(void 0!==e.boundingSphere)null===e.boundingSphere&&e.computeBoundingSphere(),Bs.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;null===t.boundingSphere&&t.computeBoundingSphere(),Bs.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Bs)}intersectsSprite(e){Bs.center.set(0,0,0);const t=ks.distanceTo(e.center);return Bs.radius=.7071067811865476+t,Bs.applyMatrix4(e.matrixWorld),this.intersectsSphere(Bs)}intersectsSphere(e){const t=this.planes,i=e.center,r=-e.radius;for(let e=0;e<6;e++){if(t[e].distanceToPoint(i)<r)return!1}return!0}intersectsBox(e){const t=this.planes;for(let i=0;i<6;i++){const r=t[i];if(zs.x=r.normal.x>0?e.max.x:e.min.x,zs.y=r.normal.y>0?e.max.y:e.min.y,zs.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(zs)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let i=0;i<6;i++)if(t[i].distanceToPoint(e)<0)return!1;return!0}clone(){return(new this.constructor).copy(this)}}const Vs=new fr;class Hs{constructor(){this.coordinateSystem=ui,this._frustums=[],this._count=0}setFromArrayCamera(e){const t=e.cameras,i=this._frustums;for(let e=0;e<t.length;e++){const r=t[e];Vs.multiplyMatrices(r.projectionMatrix,r.matrixWorldInverse),void 0===i[e]&&(i[e]=new Gs),i[e].setFromProjectionMatrix(Vs,r.coordinateSystem,r.reversedDepth)}return this._count=t.length,this}getFrustum(e){return this._frustums[e]}intersectsObject(e){const t=this._frustums;for(let i=0;i<this._count;i++)if(t[i].intersectsObject(e))return!0;return!1}intersectsSprite(e){const t=this._frustums;for(let i=0;i<this._count;i++)if(t[i].intersectsSprite(e))return!0;return!1}intersectsSphere(e){const t=this._frustums;for(let i=0;i<this._count;i++)if(t[i].intersectsSphere(e))return!0;return!1}intersectsBox(e){const t=this._frustums;for(let i=0;i<this._count;i++)if(t[i].intersectsBox(e))return!0;return!1}containsPoint(e){const t=this._frustums;for(let i=0;i<this._count;i++)if(t[i].containsPoint(e))return!0;return!1}copy(e){this.coordinateSystem=e.coordinateSystem;const t=this._frustums,i=e._frustums;for(let r=0;r<e._count;r++)void 0===t[r]&&(t[r]=new Gs),t[r].copy(i[r]);return this._count=e._count,this}clone(){return(new Hs).copy(this)}}class Ws extends os{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new Yr(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}}class js extends os{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new Yr(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 $s extends lr{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=Ue,this.minFilter=Ue,this.generateMipmaps=!1,this.needsUpdate=!0}copy(e){return super.copy(e),this.source=new nr(Object.assign({},e.image)),this}}class Xs extends lr{constructor(e=[],t=301,i,r,n,s,a,o,l,u){super(e,t,i,r,n,s,a,o,l,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class qs extends lr{constructor(e,t,i,r,n,s,a,o,l){super(e,t,i,r,n,s,a,o,l),this.isCanvasTexture=!0,this.needsUpdate=!0}}class Ys extends lr{constructor(e,t,i=1014,r,n,s,a=1003,o=1003,l,u=1026,c=1){if(u!==it&&u!==rt)throw new Error("THREE.DepthTexture: format must be either THREE.DepthFormat or THREE.DepthStencilFormat");super({width:e,height:t,depth:c},r,n,s,a,o,u,i,l),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new nr(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return t.compareFunction=this.compareFunction,t}}class Ks extends Ys{constructor(e,t=1014,i=301,r,n,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,i,r,n,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 Zs extends lr{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}class Qs extends Zn{constructor(e=1,t=1,i=1,r=1,n=1,s=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:i,widthSegments:r,heightSegments:n,depthSegments:s};const a=this;r=Math.floor(r),n=Math.floor(n),s=Math.floor(s);const o=[],l=[],u=[],c=[];let h=0,d=0;function p(e,t,i,r,n,s,p,f,m,g,_){const v=s/m,b=p/g,y=s/2,x=p/2,S=f/2,T=m+1,M=g+1;let E=0,w=0;const A=new Wi;for(let s=0;s<M;s++){const a=s*b-x;for(let o=0;o<T;o++){const h=o*v-y;A[e]=h*r,A[t]=a*n,A[i]=S,l.push(A.x,A.y,A.z),A[e]=0,A[t]=0,A[i]=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 i=h+t+T*e,r=h+t+T*(e+1),n=h+(t+1)+T*(e+1),s=h+(t+1)+T*e;o.push(i,r,s),o.push(r,n,s),w+=6}a.addGroup(d,w,_),d+=w,h+=E}p("z","y","x",-1,-1,i,t,e,s,n,0),p("z","y","x",1,-1,i,t,-e,s,n,1),p("x","z","y",1,1,e,i,t,r,s,2),p("x","z","y",1,-1,e,i,-t,r,s,3),p("x","y","z",1,-1,e,t,i,r,n,4),p("x","y","z",-1,-1,e,t,-i,r,n,5),this.setIndex(o),this.setAttribute("position",new kn(l,3)),this.setAttribute("normal",new kn(u,3)),this.setAttribute("uv",new kn(c,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Qs(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}class Js extends Zn{constructor(e=1,t=1,i=1,r=32,n=1,s=!1,a=0,o=2*Math.PI){super(),this.type="CylinderGeometry",this.parameters={radiusTop:e,radiusBottom:t,height:i,radialSegments:r,heightSegments:n,openEnded:s,thetaStart:a,thetaLength:o};const l=this;r=Math.floor(r),n=Math.floor(n);const u=[],c=[],h=[],d=[];let p=0;const f=[],m=i/2;let g=0;function _(i){const n=p,s=new Vi,f=new Wi;let _=0;const v=!0===i?e:t,b=!0===i?1:-1;for(let e=1;e<=r;e++)c.push(0,m*b,0),h.push(0,b,0),d.push(.5,.5),p++;const y=p;for(let e=0;e<=r;e++){const t=e/r*o+a,i=Math.cos(t),n=Math.sin(t);f.x=v*n,f.y=m*b,f.z=v*i,c.push(f.x,f.y,f.z),h.push(0,b,0),s.x=.5*i+.5,s.y=.5*n*b+.5,d.push(s.x,s.y),p++}for(let e=0;e<r;e++){const t=n+e,r=y+e;!0===i?u.push(r,r+1,t):u.push(r+1,r,t),_+=3}l.addGroup(g,_,!0===i?1:2),g+=_}!function(){const s=new Wi,_=new Wi;let v=0;const b=(t-e)/i;for(let l=0;l<=n;l++){const u=[],g=l/n,v=g*(t-e)+e;for(let e=0;e<=r;e++){const t=e/r,n=t*o+a,l=Math.sin(n),f=Math.cos(n);_.x=v*l,_.y=-g*i+m,_.z=v*f,c.push(_.x,_.y,_.z),s.set(l,b,f).normalize(),h.push(s.x,s.y,s.z),d.push(t,1-g),u.push(p++)}f.push(u)}for(let i=0;i<r;i++)for(let r=0;r<n;r++){const s=f[r][i],a=f[r+1][i],o=f[r+1][i+1],l=f[r][i+1];(e>0||0!==r)&&(u.push(s,a,l),v+=3),(t>0||r!==n-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 kn(c,3)),this.setAttribute("normal",new kn(h,3)),this.setAttribute("uv",new kn(d,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Js(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class ea extends Zn{constructor(e=1,t=1,i=1,r=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:i,heightSegments:r};const n=e/2,s=t/2,a=Math.floor(i),o=Math.floor(r),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 i=0;i<l;i++){const r=i*c-n;p.push(r,-t,0),f.push(0,0,1),m.push(i/a),m.push(1-e/o)}}for(let e=0;e<o;e++)for(let t=0;t<a;t++){const i=t+l*e,r=t+l*(e+1),n=t+1+l*(e+1),s=t+1+l*e;d.push(i,r,s),d.push(r,n,s)}this.setIndex(d),this.setAttribute("position",new kn(p,3)),this.setAttribute("normal",new kn(f,3)),this.setAttribute("uv",new kn(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new ea(e.width,e.height,e.widthSegments,e.heightSegments)}}class ta extends Zn{constructor(e=1,t=32,i=16,r=0,n=2*Math.PI,s=0,a=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:e,widthSegments:t,heightSegments:i,phiStart:r,phiLength:n,thetaStart:s,thetaLength:a},t=Math.max(3,Math.floor(t)),i=Math.max(2,Math.floor(i));const o=Math.min(s+a,Math.PI);let l=0;const u=[],c=new Wi,h=new Wi,d=[],p=[],f=[],m=[];for(let d=0;d<=i;d++){const g=[],_=d/i,v=s+_*a,b=e*Math.cos(v),y=Math.sqrt(e*e-b*b);let x=0;0===d&&0===s?x=.5/t:d===i&&o===Math.PI&&(x=-.5/t);for(let e=0;e<=t;e++){const i=e/t,s=r+i*n;c.x=-y*Math.cos(s),c.y=b,c.z=y*Math.sin(s),p.push(c.x,c.y,c.z),h.copy(c).normalize(),f.push(h.x,h.y,h.z),m.push(i+x,1-_),g.push(l++)}u.push(g)}for(let e=0;e<i;e++)for(let r=0;r<t;r++){const t=u[e][r+1],n=u[e][r],a=u[e+1][r],l=u[e+1][r+1];(0!==e||s>0)&&d.push(t,n,l),(e!==i-1||o<Math.PI)&&d.push(n,a,l)}this.setIndex(d),this.setAttribute("position",new kn(p,3)),this.setAttribute("normal",new kn(f,3)),this.setAttribute("uv",new kn(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new ta(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}class ia extends os{constructor(e){super(),this.isShadowMaterial=!0,this.type="ShadowMaterial",this.color=new Yr(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 ra(e){const t={};for(const i in e){t[i]={};for(const r in e[i]){const n=e[i][r];if(sa(n))n.isRenderTargetTexture?(Ti("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),t[i][r]=null):t[i][r]=n.clone();else if(Array.isArray(n))if(sa(n[0])){const e=[];for(let t=0,i=n.length;t<i;t++)e[t]=n[t].clone();t[i][r]=e}else t[i][r]=n.slice();else t[i][r]=n}}return t}function na(e){const t={};for(let i=0;i<e.length;i++){const r=ra(e[i]);for(const e in r)t[e]=r[e]}return t}function sa(e){return e&&(e.isColor||e.isMatrix3||e.isMatrix4||e.isVector2||e.isVector3||e.isVector4||e.isTexture||e.isQuaternion)}function aa(e){const t=e.getRenderTarget();return null===t?e.outputColorSpace:!0===t.isXRRenderTarget?t.texture.colorSpace:Qi.workingColorSpace}const oa={clone:ra,merge:na};class la extends os{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=ra(e.uniforms),this.uniformsGroups=function(e){const t=[];for(let i=0;i<e.length;i++)t.push(e[i].clone());return t}(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this.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 i in this.uniforms){const r=this.uniforms[i].value;r&&r.isTexture?t.uniforms[i]={type:"t",value:r.toJSON(e).uuid}:r&&r.isColor?t.uniforms[i]={type:"c",value:r.getHex()}:r&&r.isVector2?t.uniforms[i]={type:"v2",value:r.toArray()}:r&&r.isVector3?t.uniforms[i]={type:"v3",value:r.toArray()}:r&&r.isVector4?t.uniforms[i]={type:"v4",value:r.toArray()}:r&&r.isMatrix3?t.uniforms[i]={type:"m3",value:r.toArray()}:r&&r.isMatrix4?t.uniforms[i]={type:"m4",value:r.toArray()}:t.uniforms[i]={value:r}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const i={};for(const e in this.extensions)!0===this.extensions[e]&&(i[e]=!0);return Object.keys(i).length>0&&(t.extensions=i),t}fromJSON(e,t){if(super.fromJSON(e,t),void 0!==e.uniforms)for(const i in e.uniforms){const r=e.uniforms[i];switch(this.uniforms[i]={},r.type){case"t":this.uniforms[i].value=t[r.value]||null;break;case"c":this.uniforms[i].value=(new Yr).setHex(r.value);break;case"v2":this.uniforms[i].value=(new Vi).fromArray(r.value);break;case"v3":this.uniforms[i].value=(new Wi).fromArray(r.value);break;case"v4":this.uniforms[i].value=(new ur).fromArray(r.value);break;case"m3":this.uniforms[i].value=(new Xi).fromArray(r.value);break;case"m4":this.uniforms[i].value=(new fr).fromArray(r.value);break;default:this.uniforms[i].value=r.value}}if(void 0!==e.defines&&(this.defines=e.defines),void 0!==e.vertexShader&&(this.vertexShader=e.vertexShader),void 0!==e.fragmentShader&&(this.fragmentShader=e.fragmentShader),void 0!==e.glslVersion&&(this.glslVersion=e.glslVersion),void 0!==e.extensions)for(const t in e.extensions)this.extensions[t]=e.extensions[t];return void 0!==e.lights&&(this.lights=e.lights),void 0!==e.clipping&&(this.clipping=e.clipping),this}}class ua extends la{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class ca extends os{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new Yr(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 Yr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Vi(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 Mr,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 ha extends ca{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 Vi(1,1),this.clearcoatNormalMap=null,this.diffuseRoughnessMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return Ui(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.iridescenceThicknessMinimum=100,this.iridescenceThicknessMaximum=400,this.iridescenceThicknessMap=null,this.sheenColor=new Yr(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 Yr(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new Yr(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._diffuseRoughness=0,this._dispersion=0,this._iridescence=0,this._retroreflectivity=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get diffuseRoughness(){return this._diffuseRoughness}set diffuseRoughness(e){this._diffuseRoughness>0!=e>0&&this.version++,this._diffuseRoughness=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get retroreflectivity(){return this._retroreflectivity}set retroreflectivity(e){this._retroreflectivity>0!=e>0&&this.version++,this._retroreflectivity=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}get iridescenceThicknessRange(){return Ei('MeshPhysicalMaterial: The "iridescenceThicknessRange" property has been replaced by "iridescenceThicknessMinimum" and "iridescenceThicknessMaximum".'),[this.iridescenceThicknessMinimum,this.iridescenceThicknessMaximum]}set iridescenceThicknessRange(e){Ei('MeshPhysicalMaterial: The "iridescenceThicknessRange" property has been replaced by "iridescenceThicknessMinimum" and "iridescenceThicknessMaximum".'),this.iridescenceThicknessMinimum=e[0],this.iridescenceThicknessMaximum=e[1]}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.diffuseRoughness=e.diffuseRoughness,this.diffuseRoughnessMap=e.diffuseRoughnessMap,this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessMinimum=e.iridescenceThicknessMinimum,this.iridescenceThicknessMaximum=e.iridescenceThicknessMaximum,this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.retroreflectivity=e.retroreflectivity,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}}class da extends os{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new Yr(16777215),this.specular=new Yr(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Yr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Vi(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Mr,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 pa extends os{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new Yr(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Yr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Vi(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 fa extends os{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Vi(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 ma extends os{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new Yr(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Yr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Vi(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Mr,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 ga extends os{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 _a extends os{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 va extends os{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new Yr(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Vi(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 ba extends Ws{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 ya={enabled:!1,files:{},add:function(e,t){!1!==this.enabled&&(xa(e)||(this.files[e]=t))},get:function(e){if(!1!==this.enabled&&!xa(e))return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}};function xa(e){try{const t=e.slice(e.indexOf(":")+1);return"blob:"===new URL(t).protocol}catch(e){return!1}}class Sa{constructor(e,t,i){const r=this;let n,s=!1,a=0,o=0;const l=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=i,this._abortController=null,this.itemStart=function(e){o++,!1===s&&void 0!==r.onStart&&r.onStart(e,a,o),s=!0},this.itemEnd=function(e){a++,void 0!==r.onProgress&&r.onProgress(e,a,o),a===o&&(s=!1,void 0!==r.onLoad&&r.onLoad())},this.itemError=function(e){void 0!==r.onError&&r.onError(e)},this.resolveURL=function(e){return e=e.normalize("NFC"),n?n(e):e},this.setURLModifier=function(e){return n=e,this},this.addHandler=function(e,t){return l.push(e,t),this},this.removeHandler=function(e){const t=l.indexOf(e);return-1!==t&&l.splice(t,2),this},this.getHandler=function(e){for(let t=0,i=l.length;t<i;t+=2){const i=l[t],r=l[t+1];if(i.global&&(i.lastIndex=0),i.test(e))return r}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 Ta=new Sa;class Ma{constructor(e){this.manager=void 0!==e?e:Ta,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={},this.priority="auto",this.cache="default","undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}load(){}loadAsync(e,t){const i=this;return new Promise(function(r,n){i.load(e,r,t,n)})}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}setPriority(e){return this.priority=e,this}setCache(e){return this.cache=e,this}abort(){return this}}Ma.DEFAULT_MATERIAL_NAME="__DEFAULT";const Ea=new WeakMap;class wa extends Ma{constructor(e){super(e)}load(e,t,i,r){void 0!==this.path&&(e=this.path+e),e=this.manager.resolveURL(e);const n=this,s=ya.get(`image:${e}`);if(void 0!==s){if(!0===s.complete)n.manager.itemStart(e),setTimeout(function(){t&&t(s),n.manager.itemEnd(e)},0);else{let e=Ea.get(s);void 0===e&&(e=[],Ea.set(s,e)),e.push({onLoad:t,onError:r})}return s}const a=vi("img");function o(){u(),t&&t(this);const i=Ea.get(this)||[];for(let e=0;e<i.length;e++){const t=i[e];t.onLoad&&t.onLoad(this)}Ea.delete(this),n.manager.itemEnd(e)}function l(t){u(),r&&r(t),ya.remove(`image:${e}`);const i=Ea.get(this)||[];for(let e=0;e<i.length;e++){const r=i[e];r.onError&&r.onError(t)}Ea.delete(this),n.manager.itemError(e),n.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),ya.add(`image:${e}`,a),n.manager.itemStart(e),a.fetchPriority=this.priority,a.src=e,a}}class Aa extends Gr{static registerNode(e){this.prototype._lightNode=e}constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new Yr(e),this.intensity=t}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 Ra extends Aa{constructor(e,t,i){super(e,i),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(Gr.DEFAULT_UP),this.updateMatrix(),this.groundColor=new Yr(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 Ca=new fr,Na=new Wi,Pa=new Wi;class La{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 Vi(512,512),this.mapType=ze,this.map=null,this.mapPass=null,this.matrix=new fr,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new Gs,this._frameExtents=new Vi(1,1),this._viewportCount=1,this._viewports=[new ur(0,0,1,1)]}getViewportCount(){return this._viewportCount}getCamera(){return this.camera}getFrustum(){return this._frustum}updateMatrices(e){const t=this.camera;Na.setFromMatrixPosition(e.matrixWorld),t.position.copy(Na),Pa.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(Pa),t.updateMatrixWorld(),this._updateMatrix(t,this.matrix,this._frustum)}_updateMatrix(e,t,i,r){Ca.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),i.setFromProjectionMatrix(Ca,e.coordinateSystem,e.reversedDepth);const n=this._frameExtents,s=r?r.z/n.x:1,a=r?r.w/n.y:1,o=r?r.x/n.x:0,l=r?r.y/n.y:0;e.coordinateSystem===ci||e.reversedDepth?t.set(.5*s,0,0,.5*s+o,0,.5*a,0,.5*a+l,0,0,1,0,0,0,0,1):t.set(.5*s,0,0,.5*s+o,0,.5*a,0,.5*a+l,0,0,.5,.5,0,0,0,1),t.multiply(Ca)}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.mapType=e.mapType,this.biasNode=e.biasNode,this}clone(){return(new this.constructor).copy(this)}toJSON(){const e={};return e.intensity=this.intensity,e.bias=this.bias,e.normalBias=this.normalBias,e.radius=this.radius,e.blurSamples=this.blurSamples,e.mapSize=this.mapSize.toArray(),e.mapType=this.mapType,e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}}const Da=new Wi,Ua=new Hi,Ia=new Wi;class Fa extends Gr{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new fr,this.projectionMatrix=new fr,this.projectionMatrixInverse=new fr,this.coordinateSystem=ui,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(Da,Ua,Ia),1===Ia.x&&1===Ia.y&&1===Ia.z?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(Da,Ua,Ia.set(1,1,1)).invert()}updateWorldMatrix(e,t,i=!1){super.updateWorldMatrix(e,t,i),this.matrixWorld.decompose(Da,Ua,Ia),1===Ia.x&&1===Ia.y&&1===Ia.z?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(Da,Ua,Ia.set(1,1,1)).invert()}clone(){return(new this.constructor).copy(this)}}const Oa=new Wi,Ba=new Vi,ka=new Vi;class za extends Fa{constructor(e=50,t=1,i=.1,r=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=i,this.far=r,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=null===e.view?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=2*Li*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(.5*Pi*this.fov);return.5*this.getFilmHeight()/e}getEffectiveFOV(){return 2*Li*Math.atan(Math.tan(.5*Pi*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,i){Oa.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Oa.x,Oa.y).multiplyScalar(-e/Oa.z),Oa.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),i.set(Oa.x,Oa.y).multiplyScalar(-e/Oa.z)}getViewSize(e,t){return this.getViewBounds(e,Ba,ka),t.subVectors(ka,Ba)}setViewOffset(e,t,i,r,n,s){this.aspect=e/t,null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=i,this.view.offsetY=r,this.view.width=n,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*Pi*this.fov)/this.zoom,i=2*t,r=this.aspect*i,n=-.5*r;const s=this.view;if(null!==this.view&&this.view.enabled){const e=s.fullWidth,a=s.fullHeight;n+=s.offsetX*r/e,t-=s.offsetY*i/a,r*=s.width/e,i*=s.height/a}const a=this.filmOffset;0!==a&&(n+=e*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(n,n+r,t,t-i,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 Ga extends La{constructor(){super(new za(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(e){const t=this.camera,i=2*Li*e.angle*this.focus,r=this.mapSize.width/this.mapSize.height*this.aspect,n=e.distance||t.far;i===t.fov&&r===t.aspect&&n===t.far||(t.fov=i,t.aspect=r,t.far=n,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this.aspect=e.aspect,this}toJSON(){const e=super.toJSON();return e.focus=this.focus,e.aspect=this.aspect,e}}class Va extends Aa{constructor(e,t,i=0,r=Math.PI/3,n=0,s=2){super(e,t),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(Gr.DEFAULT_UP),this.updateMatrix(),this.target=new Gr,this.distance=i,this.angle=r,this.penumbra=n,this.decay=s,this.map=null,this.shadow=new Ga}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 Ha extends La{constructor(){super(new za(90,1,.5,500)),this.isPointLightShadow=!0}}class Wa extends Aa{constructor(e,t,i=0,r=2){super(e,t),this.isPointLight=!0,this.type="PointLight",this.distance=i,this.decay=r,this.shadow=new Ha}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 ja extends Fa{constructor(e=-1,t=1,i=1,r=-1,n=.1,s=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=i,this.bottom=r,this.near=n,this.far=s,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=null===e.view?null:Object.assign({},e.view),this}setViewOffset(e,t,i,r,n,s){null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=i,this.view.offsetY=r,this.view.width=n,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),i=(this.right+this.left)/2,r=(this.top+this.bottom)/2;let n=i-e,s=i+e,a=r+t,o=r-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;n+=e*this.view.offsetX,s=n+e*this.view.width,a-=t*this.view.offsetY,o=a-t*this.view.height}this.projectionMatrix.makeOrthographic(n,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 $a extends La{constructor(){super(new ja(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class Xa extends Aa{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(Gr.DEFAULT_UP),this.updateMatrix(),this.target=new Gr,this.shadow=new $a}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 qa extends Aa{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}}class Ya extends Aa{constructor(e,t,i=10,r=10){super(e,t),this.isRectAreaLight=!0,this.type="RectAreaLight",this.width=i,this.height=r}get power(){return this.intensity*this.width*this.height*Math.PI}set power(e){this.intensity=e/(this.width*this.height*Math.PI)}copy(e){return super.copy(e),this.width=e.width,this.height=e.height,this}toJSON(e){const t=super.toJSON(e);return t.object.width=this.width,t.object.height=this.height,t}}class Ka{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let e=0;e<9;e++)this.coefficients.push(new Wi)}set(e){for(let t=0;t<9;t++)this.coefficients[t].copy(e[t]);return this}zero(){for(let e=0;e<9;e++)this.coefficients[e].set(0,0,0);return this}getAt(e,t){const i=e.x,r=e.y,n=e.z,s=this.coefficients;return t.copy(s[0]).multiplyScalar(.282095),t.addScaledVector(s[1],.488603*r),t.addScaledVector(s[2],.488603*n),t.addScaledVector(s[3],.488603*i),t.addScaledVector(s[4],i*r*1.092548),t.addScaledVector(s[5],r*n*1.092548),t.addScaledVector(s[6],.315392*(3*n*n-1)),t.addScaledVector(s[7],i*n*1.092548),t.addScaledVector(s[8],.546274*(i*i-r*r)),t}getIrradianceAt(e,t){const i=e.x,r=e.y,n=e.z,s=this.coefficients;return t.copy(s[0]).multiplyScalar(.886227),t.addScaledVector(s[1],1.023328*r),t.addScaledVector(s[2],1.023328*n),t.addScaledVector(s[3],1.023328*i),t.addScaledVector(s[4],.858086*i*r),t.addScaledVector(s[5],.858086*r*n),t.addScaledVector(s[6],.743125*n*n-.247708),t.addScaledVector(s[7],.858086*i*n),t.addScaledVector(s[8],.429043*(i*i-r*r)),t}add(e){for(let t=0;t<9;t++)this.coefficients[t].add(e.coefficients[t]);return this}addScaledSH(e,t){for(let i=0;i<9;i++)this.coefficients[i].addScaledVector(e.coefficients[i],t);return this}scale(e){for(let t=0;t<9;t++)this.coefficients[t].multiplyScalar(e);return this}lerp(e,t){for(let i=0;i<9;i++)this.coefficients[i].lerp(e.coefficients[i],t);return this}equals(e){for(let t=0;t<9;t++)if(!this.coefficients[t].equals(e.coefficients[t]))return!1;return!0}copy(e){return this.set(e.coefficients)}clone(){return(new this.constructor).copy(this)}fromArray(e,t=0){const i=this.coefficients;for(let r=0;r<9;r++)i[r].fromArray(e,t+3*r);return this}toArray(e=[],t=0){const i=this.coefficients;for(let r=0;r<9;r++)i[r].toArray(e,t+3*r);return e}static getBasisAt(e,t){const i=e.x,r=e.y,n=e.z;t[0]=.282095,t[1]=.488603*r,t[2]=.488603*n,t[3]=.488603*i,t[4]=1.092548*i*r,t[5]=1.092548*r*n,t[6]=.315392*(3*n*n-1),t[7]=1.092548*i*n,t[8]=.546274*(i*i-r*r)}}class Za extends Aa{constructor(e=new Ka,t=1){super(void 0,t),this.isLightProbe=!0,this.type="LightProbe",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 Qa=-90;class Ja extends Gr{constructor(e,t,i){super(),this.type="CubeCamera",this.renderTarget=i,this.coordinateSystem=null,this.activeMipmapLevel=0;const r=new za(Qa,1,e,t);r.layers=this.layers,this.add(r);const n=new za(Qa,1,e,t);n.layers=this.layers,this.add(n);const s=new za(Qa,1,e,t);s.layers=this.layers,this.add(s);const a=new za(Qa,1,e,t);a.layers=this.layers,this.add(a);const o=new za(Qa,1,e,t);o.layers=this.layers,this.add(o);const l=new za(Qa,1,e,t);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[i,r,n,s,a,o]=t;for(const e of t)this.remove(e);if(e===ui)i.up.set(0,1,0),i.lookAt(1,0,0),r.up.set(0,1,0),r.lookAt(-1,0,0),n.up.set(0,0,-1),n.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!==ci)throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);i.up.set(0,-1,0),i.lookAt(-1,0,0),r.up.set(0,-1,0),r.lookAt(1,0,0),n.up.set(0,0,1),n.lookAt(0,1,0),s.up.set(0,0,-1),s.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),o.up.set(0,-1,0),o.lookAt(0,0,-1)}for(const e of t)this.add(e),e.updateMatrixWorld()}update(e,t){null===this.parent&&this.updateMatrixWorld();const{renderTarget:i,activeMipmapLevel:r}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[n,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=i.texture.mipmapsAutoUpdate;i.texture.mipmapsAutoUpdate=!1;let m=!1;m=!0===e.isWebGLRenderer?e.state.buffers.depth.getReversed():e.reversedDepthBuffer,e.setRenderTarget(i,0,r),m&&!1===e.autoClear&&e.clearDepth(),e.render(t,n),e.setRenderTarget(i,1,r),m&&!1===e.autoClear&&e.clearDepth(),e.render(t,s),e.setRenderTarget(i,2,r),m&&!1===e.autoClear&&e.clearDepth(),e.render(t,a),e.setRenderTarget(i,3,r),m&&!1===e.autoClear&&e.clearDepth(),e.render(t,o),e.setRenderTarget(i,4,r),m&&!1===e.autoClear&&e.clearDepth(),e.render(t,l),i.texture.mipmapsAutoUpdate=f,e.setRenderTarget(i,5,r),m&&!1===e.autoClear&&e.clearDepth(),e.render(t,u),e.setRenderTarget(c,h,d),e.xr.enabled=p,i.texture.needsPMREMUpdate=!0}}class eo extends za{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e,this.perCameraFrustumCulled=!1}}class to{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=io.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 io(){!1===this._document.hidden&&this.reset()}const ro=new fr;function no(e,t){return e.distance-t.distance}function so(e,t,i,r){let n=!0;if(e.layers.test(t.layers)){!1===e.raycast(t,i)&&(n=!1)}if(!0===n&&!0===r){const r=e.children;for(let e=0,n=r.length;e<n;e++)so(r[e],t,i,!0)}}class ao{constructor(e=1,t=0,i=0){this.radius=e,this.phi=t,this.theta=i}set(e,t,i){return this.radius=e,this.phi=t,this.theta=i,this}copy(e){return this.radius=e.radius,this.phi=e.phi,this.theta=e.theta,this}makeSafe(){const e=1e-6;return this.phi=Ui(this.phi,e,Math.PI-e),this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,t,i){return this.radius=Math.sqrt(e*e+t*t+i*i),0===this.radius?(this.theta=0,this.phi=0):(this.theta=Math.atan2(e,i),this.phi=Math.acos(Ui(t/this.radius,-1,1))),this}clone(){return(new this.constructor).copy(this)}}class oo{static{this.prototype.isMatrix2=!0}constructor(e,t,i,r){this.elements=[1,0,0,1],void 0!==e&&this.set(e,t,i,r)}identity(){return this.set(1,0,0,1),this}fromArray(e,t=0){for(let i=0;i<4;i++)this.elements[i]=e[i+t];return this}set(e,t,i,r){const n=this.elements;return n[0]=e,n[2]=t,n[1]=i,n[3]=r,this}}class lo extends Ri{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){null!==this.domElement&&this.disconnect(),this.domElement=e}disconnect(){}dispose(){}update(){}}function uo(e,t,i,r){const n=function(e){switch(e){case ze:case Ge:return{byteLength:1,components:1};case He:case Ve:case Xe:return{byteLength:2,components:1};case qe:case Ye:return{byteLength:2,components:4};case je:case We:case $e:return{byteLength:4,components:1};case Ze:case Qe:return{byteLength:4,components:3}}throw new Error(`THREE.TextureUtils: Unknown texture type ${e}.`)}(r);switch(i){case Je:return e*t;case nt:case st:return e*t/n.components*n.byteLength;case at:case ot:return e*t*2/n.components*n.byteLength;case et:return e*t*3/n.components*n.byteLength;case tt:case ut:return e*t*4/n.components*n.byteLength;case ct:case ht:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case dt:case pt:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case mt:case _t:return Math.max(e,16)*Math.max(t,8)/4;case ft:case gt:return Math.max(e,8)*Math.max(t,8)/2;case vt:case bt:case xt:case St:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case yt:case Tt:case Mt:case Et:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case wt:return Math.floor((e+4)/5)*Math.floor((t+3)/4)*16;case At:return Math.floor((e+4)/5)*Math.floor((t+4)/5)*16;case Rt:return Math.floor((e+5)/6)*Math.floor((t+4)/5)*16;case Ct:return Math.floor((e+5)/6)*Math.floor((t+5)/6)*16;case Nt:return Math.floor((e+7)/8)*Math.floor((t+4)/5)*16;case Pt:return Math.floor((e+7)/8)*Math.floor((t+5)/6)*16;case Lt:return Math.floor((e+7)/8)*Math.floor((t+7)/8)*16;case Dt:return Math.floor((e+9)/10)*Math.floor((t+4)/5)*16;case Ut:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case It:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case Ft:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case Ot:return Math.floor((e+11)/12)*Math.floor((t+9)/10)*16;case Bt:return Math.floor((e+11)/12)*Math.floor((t+11)/12)*16;case kt:case zt:case Gt:return Math.ceil(e/4)*Math.ceil(t/4)*16;case Vt:case Ht:return Math.ceil(e/4)*Math.ceil(t/4)*8;case Wt:case jt:return Math.ceil(e/4)*Math.ceil(t/4)*16}throw new Error(`Unable to determine texture byte length for ${i} format.`)}function co(){let e=null,t=!1,i=null,r=null;function n(t,s){r=e.requestAnimationFrame(n),i(t,s)}return{start:function(){!0!==t&&null!==i&&null!==e&&(r=e.requestAnimationFrame(n),t=!0)},stop:function(){null!==e&&e.cancelAnimationFrame(r),t=!1},setAnimationLoop:function(e){i=e},setContext:function(t){e=t}}}function ho(e){const t=new WeakMap;return{get:function(e){return e.isInterleavedBufferAttribute&&(e=e.data),t.get(e)},remove:function(i){i.isInterleavedBufferAttribute&&(i=i.data);const r=t.get(i);r&&(e.deleteBuffer(r.buffer),t.delete(i))},update:function(i,r){if(i.isInterleavedBufferAttribute&&(i=i.data),i.isGLBufferAttribute){const e=t.get(i);return void((!e||e.version<i.version)&&t.set(i,{buffer:i.buffer,type:i.type,bytesPerElement:i.elementSize,version:i.version}))}const n=t.get(i);if(void 0===n)t.set(i,function(t,i){const r=t.array,n=t.usage,s=r.byteLength,a=e.createBuffer();let o;if(e.bindBuffer(i,a),e.bufferData(i,r,n),t.onUploadCallback(),r instanceof Float32Array)o=e.FLOAT;else if("undefined"!=typeof Float16Array&&r instanceof Float16Array)o=e.HALF_FLOAT;else if(r instanceof Uint16Array)o=t.isFloat16BufferAttribute?e.HALF_FLOAT:e.UNSIGNED_SHORT;else if(r instanceof Int16Array)o=e.SHORT;else if(r instanceof Uint32Array)o=e.UNSIGNED_INT;else if(r instanceof Int32Array)o=e.INT;else if(r instanceof Int8Array)o=e.BYTE;else if(r instanceof Uint8Array)o=e.UNSIGNED_BYTE;else{if(!(r instanceof Uint8ClampedArray))throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+r);o=e.UNSIGNED_BYTE}return{buffer:a,type:o,bytesPerElement:r.BYTES_PER_ELEMENT,version:t.version,size:s}}(i,r));else if(n.version<i.version){if(n.size!==i.array.byteLength)throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.");!function(t,i,r){const n=i.array,s=i.updateRanges;if(e.bindBuffer(r,t),0===s.length)e.bufferSubData(r,0,n);else{s.sort((e,t)=>e.start-t.start);let t=0;for(let e=1;e<s.length;e++){const i=s[t],r=s[e];r.start<=i.start+i.count+1?i.count=Math.max(i.count,r.start+r.count-i.start):(++t,s[t]=r)}s.length=t+1;for(let t=0,i=s.length;t<i;t++){const i=s[t];e.bufferSubData(r,i.start*n.BYTES_PER_ELEMENT,n,i.start,i.count)}i.clearUpdateRanges()}i.onUploadCallback()}(n.buffer,i,r),n.version=i.version}}}}"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:N}})),"undefined"!=typeof window&&(window.__THREE__?Ti("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=N);const po={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}\n#define inverseTransformDirection transformDirectionByInverseViewMatrix\nvec3 transformNormalByInverseViewMatrix( in vec3 normal, in mat4 viewMatrix ) {\n\treturn normalize( ( vec4( normal, 0.0 ) * viewMatrix ).xyz );\n}\nvec3 transformDirectionByInverseViewMatrix( in vec3 dir, in mat4 viewMatrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * viewMatrix ).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",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#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 = transformNormalByInverseViewMatrix( 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 * reflectVec );\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 mat3 envMapRotation;\n\tuniform samplerCube envMap;\n\t#ifdef ENVMAP_TYPE_PMREM\n\t\tfloat roughnessToMip( const in float roughness ) {\n\t\t\tfloat r = clamp( roughness, 0.0, 1.0 );\n\t\t\treturn ENVMAP_MAX_LOD * r * ( 2.0 - r );\n\t\t}\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_PMREM\n\t\t\tvec3 worldNormal = transformNormalByInverseViewMatrix( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureLod( envMap, envMapRotation * worldNormal, ENVMAP_MAX_LOD );\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_PMREM\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, pow4( roughness ) ) );\n\t\t\treflectVec = transformDirectionByInverseViewMatrix( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureLod( envMap, envMapRotation * reflectVec, roughnessToMip( 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_RETROREFLECTION\n\t\tvec3 getIBLRetroRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t\t#ifdef ENVMAP_TYPE_PMREM\n\t\t\t\tvec3 retroVec = normalize( mix( viewDir, normal, pow4( roughness ) ) );\n\t\t\t\tretroVec = transformDirectionByInverseViewMatrix( retroVec, viewMatrix );\n\t\t\t\tvec4 envMapColor = textureLod( envMap, envMapRotation * retroVec, roughnessToMip( roughness ) );\n\t\t\t\treturn envMapColor.rgb * envMapIntensity;\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\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_PMREM\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\t#ifdef USE_RETROREFLECTION\n\t\t\tvec3 getIBLAnisotropyRetroRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n\t\t\t\t#ifdef ENVMAP_TYPE_PMREM\n\t\t\t\t\tvec3 bentNormal = cross( bitangent, viewDir );\n\t\t\t\t\tbentNormal = normalize( cross( bentNormal, bitangent ) );\n\t\t\t\t\tbentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n\t\t\t\t\treturn getIBLRetroRadiance( viewDir, bentNormal, roughness );\n\t\t\t\t#else\n\t\t\t\t\treturn vec3( 0.0 );\n\t\t\t\t#endif\n\t\t\t}\n\t\t#endif\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 = transformNormalByInverseViewMatrix( 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 = transformNormalByInverseViewMatrix( 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_SUN_LIGHTS > 0\n\tstruct SunLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform SunLight sunLights[ NUM_SUN_LIGHTS ];\n\tvoid getSunLightInfo( const in SunLight sunLight, out IncidentLight light ) {\n\t\tlight.color = sunLight.color;\n\t\tlight.direction = sunLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\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\n#include <lightprobes_pars_fragment>",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.045 );\nmaterial.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef USE_DIFFUSE_ROUGHNESS\n\tfloat diffuseRoughnessFactor = diffuseRoughness;\n\t#ifdef USE_DIFFUSE_ROUGHNESSMAP\n\t\tdiffuseRoughnessFactor *= texture2D( diffuseRoughnessMap, vDiffuseRoughnessMapUv ).r;\n\t#endif\n\tmaterial.diffuseRoughness = saturate( diffuseRoughnessFactor );\n#endif\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.045 );\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_RETROREFLECTION\n\tmaterial.retroreflectivity = retroreflectivity;\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\tvec2 dfg;\n\tvec3 multiScatteringCompensation;\n\t#ifdef USE_DIFFUSE_ROUGHNESS\n\t\tfloat diffuseRoughness;\n\t#endif\n\t#ifdef USE_RETROREFLECTION\n\t\tfloat retroreflectivity;\n\t#endif\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 iridescenceF0Dielectric;\n\t\tvec3 iridescenceF0Metallic;\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}\n#ifdef USE_DIFFUSE_ROUGHNESS\n\tconst float EON_EPSILON = 1e-7;\n\tfloat FON_DirectionalAlbedo( const in float mu, const in float roughness, const in float A ) {\n\t\tfloat muComp = 1.0 - mu;\n\t\tfloat gOverPi = muComp * ( 0.0571085289 + muComp * ( 0.491881867 + muComp * ( - 0.332181442 + muComp * 0.0714429953 ) ) );\n\t\treturn A * ( 1.0 + roughness * gOverPi );\n\t}\n\tvec3 BRDF_EON( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 diffuseColor, const in float roughness ) {\n\t\tvec3 rho = saturate( diffuseColor );\n\t\tif ( roughness <= EON_EPSILON ) return BRDF_Lambert( rho );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat s = dot( lightDir, viewDir ) - dotNL * dotNV;\n\t\tfloat sOverT = ( s > 0.0 ) ? s / max( max( dotNL, dotNV ), EON_EPSILON ) : s;\n\t\tfloat A = 1.0 / ( 1.0 + ( 0.5 - 2.0 / ( 3.0 * PI ) ) * roughness );\n\t\tvec3 singleScatter = rho * RECIPROCAL_PI * A * ( 1.0 + roughness * sOverT );\n\t\tfloat averageAlbedo = A * ( 1.0 + ( 2.0 / 3.0 - 28.0 / ( 15.0 * PI ) ) * roughness );\n\t\tfloat albedoV = FON_DirectionalAlbedo( dotNV, roughness, A );\n\t\tfloat albedoL = FON_DirectionalAlbedo( dotNL, roughness, A );\n\t\tvec3 rhoMultiScatter = rho * rho * averageAlbedo / max( vec3( EON_EPSILON ), vec3( 1.0 ) - rho * ( 1.0 - averageAlbedo ) );\n\t\tvec3 multiScatter = rhoMultiScatter * RECIPROCAL_PI\n\t\t\t* max( EON_EPSILON, 1.0 - albedoV )\n\t\t\t* max( EON_EPSILON, 1.0 - albedoL )\n\t\t\t/ max( EON_EPSILON, 1.0 - averageAlbedo );\n\t\treturn singleScatter + multiScatter;\n\t}\n\tvec3 EON_DirectionalAlbedo( const in vec3 diffuseColor, const in float roughness, const in float dotNV ) {\n\t\tvec3 rho = saturate( diffuseColor );\n\t\tif ( roughness <= EON_EPSILON ) return rho;\n\t\tfloat A = 1.0 / ( 1.0 + ( 0.5 - 2.0 / ( 3.0 * PI ) ) * roughness );\n\t\tfloat directionalAlbedo = FON_DirectionalAlbedo( dotNV, roughness, A );\n\t\tfloat averageAlbedo = A * ( 1.0 + ( 2.0 / 3.0 - 28.0 / ( 15.0 * PI ) ) * roughness );\n\t\tvec3 rhoMultiScatter = rho * rho * averageAlbedo / max( vec3( EON_EPSILON ), vec3( 1.0 ) - rho * ( 1.0 - averageAlbedo ) );\n\t\treturn rho * directionalAlbedo + rhoMultiScatter * ( 1.0 - directionalAlbedo );\n\t}\n#endif\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\treturn 0.5 / max( gv + gl, EPSILON );\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 = max( material.clearcoatRoughness, 0.045 );\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 = max( material.roughness, 0.045 );\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 alphaT = max( material.alphaT, alpha );\n\t\tfloat V = V_GGX_SmithCorrelated_Anisotropic( alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n\t\tfloat D = D_GGX_Anisotropic( 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 vec2 fab, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec2 fab, const in vec3 specularColor, const in float specularF90, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometryNormal;\n\t\tvec3 viewDir = geometryViewDir;\n\t\tvec3 position = geometryPosition;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.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\tvec3 specularBRDF = BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );\n\t#ifdef USE_RETROREFLECTION\n\t\tvec3 retroViewDir = reflect( - geometryViewDir, geometryNormal );\n\t\tvec3 retroSpecularBRDF = BRDF_GGX( directLight.direction, retroViewDir, geometryNormal, material );\n\t\tspecularBRDF = mix( specularBRDF, retroSpecularBRDF, saturate( material.retroreflectivity ) );\n\t#endif\n\treflectedLight.directSpecular += irradiance * specularBRDF * material.multiScatteringCompensation;\n\tvec3 halfDir = normalize( directLight.direction + geometryViewDir );\n\tfloat dotVH = saturate( dot( geometryViewDir, halfDir ) );\n\tvec3 F = F_Schlick( material.specularColor, material.specularF90, dotVH );\n\t#ifdef USE_RETROREFLECTION\n\t\tvec3 retroHalfDir = normalize( directLight.direction + retroViewDir );\n\t\tfloat dotRetroVH = saturate( dot( retroViewDir, retroHalfDir ) );\n\t\tvec3 retroF = F_Schlick( material.specularColor, material.specularF90, dotRetroVH );\n\t\tF = mix( F, retroF, saturate( material.retroreflectivity ) );\n\t#endif\n\t#ifdef USE_DIFFUSE_ROUGHNESS\n\t\tvec3 diffuseBRDF = BRDF_EON( directLight.direction, geometryViewDir, geometryNormal, material.diffuseColor, material.diffuseRoughness ) * ( 1.0 - material.metalness );\n\t#else\n\t\tvec3 diffuseBRDF = BRDF_Lambert( material.diffuseContribution );\n\t#endif\n\treflectedLight.directDiffuse += irradiance * diffuseBRDF * ( 1.0 - F );\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 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( material.dfg, material.specularColor, material.specularF90, material.iridescence, material.iridescenceF0Dielectric, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( material.dfg, material.specularColor, material.specularF90, singleScattering, multiScattering );\n\t#endif\n\t#ifdef USE_DIFFUSE_ROUGHNESS\n\t\tfloat dotNV = saturate( dot( geometryNormal, geometryViewDir ) );\n\t\tvec3 diffuseAlbedo = EON_DirectionalAlbedo( material.diffuseColor, material.diffuseRoughness, dotNV ) * ( 1.0 - material.metalness );\n\t\tvec3 diffuse = irradiance * RECIPROCAL_PI * diffuseAlbedo * ( 1.0 - singleScattering - multiScattering );\n\t#else\n\t\tvec3 diffuse = irradiance * BRDF_Lambert( material.diffuseContribution ) * ( 1.0 - singleScattering - multiScattering );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tfloat sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t\tsheenSpecularIndirect += irradiance * material.sheenColor * sheenAlbedo * RECIPROCAL_PI;\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( material.dfg, material.specularColor, material.specularF90, material.iridescence, material.iridescenceF0Dielectric, singleScatteringDielectric, multiScatteringDielectric );\n\t\tcomputeMultiscatteringIridescence( material.dfg, material.diffuseColor, material.specularF90, material.iridescence, material.iridescenceF0Metallic, singleScatteringMetallic, multiScatteringMetallic );\n\t#else\n\t\tcomputeMultiscattering( material.dfg, material.specularColor, material.specularF90, singleScatteringDielectric, multiScatteringDielectric );\n\t\tcomputeMultiscattering( material.dfg, material.diffuseColor, material.specularF90, 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\t#ifdef USE_DIFFUSE_ROUGHNESS\n\t\tfloat dotNV = saturate( dot( geometryNormal, geometryViewDir ) );\n\t\tvec3 diffuse = EON_DirectionalAlbedo( material.diffuseColor, material.diffuseRoughness, dotNV ) * ( 1.0 - material.metalness ) * ( 1.0 - totalScatteringDielectric );\n\t#else\n\t\tvec3 diffuse = material.diffuseContribution * ( 1.0 - totalScatteringDielectric );\n\t#endif\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\tvec3 iridescenceFresnelDielectric = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tvec3 iridescenceFresnelMetallic = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.diffuseColor );\n\t\tmaterial.iridescenceFresnel = mix( iridescenceFresnelDielectric, iridescenceFresnelMetallic, material.metalness );\n\t\tmaterial.iridescenceF0Dielectric = Schlick_to_F0( iridescenceFresnelDielectric, 1.0, dotNVi );\n\t\tmaterial.iridescenceF0Metallic = Schlick_to_F0( iridescenceFresnelMetallic, 1.0, dotNVi );\n\t}\n#endif\n#ifdef STANDARD\n\tfloat dotNVms = saturate( dot( geometryNormal, geometryViewDir ) );\n\tmaterial.dfg = texture2D( dfgLUT, vec2( material.roughness, dotNVms ) ).rg;\n\t#if ( NUM_SUN_LIGHTS > 0 || NUM_DIR_LIGHTS > 0 || NUM_POINT_LIGHTS > 0 || NUM_SPOT_LIGHTS > 0 )\n\t\tfloat EssMs = material.dfg.x + material.dfg.y;\n\t\tmaterial.multiScatteringCompensation = 1.0 + material.specularColorBlended * ( 1.0 / EssMs - 1.0 );\n\t#endif\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_SUN_LIGHTS > 0 ) && defined( RE_Direct )\n\tSunLight sunLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SUN_LIGHT_SHADOWS > 0\n\tSunLightShadow sunLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SUN_LIGHTS; i ++ ) {\n\t\tsunLight = sunLights[ i ];\n\t\tgetSunLightInfo( sunLight, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SUN_LIGHT_SHADOWS )\n\t\tsunLightShadow = sunLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getSunShadow( sunShadowMap[ i ], sunLightShadow, UNROLLED_LOOP_INDEX ) : 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\t#if NUM_LIGHT_PROBE_GRIDS > 0\n\t\tvec3 probeWorldPos = ( ( vec4( geometryPosition, 1.0 ) - viewMatrix[ 3 ] ) * viewMatrix ).xyz;\n\t\tvec3 probeWorldNormal = transformNormalByInverseViewMatrix( geometryNormal, viewMatrix );\n\t\tint probeGrid = - 1;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_LIGHT_PROBE_GRIDS; i ++ ) {\n\t\t\tif ( isInsideLightProbeGrid( probeWorldPos, probeWorldNormal, probesMin[ i ], probesMax[ i ], probesResolution[ i ] ) ) probeGrid = UNROLLED_LOOP_INDEX;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_LIGHT_PROBE_GRIDS; i ++ ) {\n\t\t\tif ( probeGrid == UNROLLED_LOOP_INDEX ) irradiance += getLightProbeGridIrradiance( probesSH[ i ], probesMin[ i ], probesMax[ i ], probesResolution[ i ], probeWorldPos, probeWorldNormal );\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_PMREM )\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\tvec3 iblRadiance = getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n\t#else\n\t\tvec3 iblRadiance = getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );\n\t#endif\n\t#ifdef USE_RETROREFLECTION\n\t\t#ifdef USE_ANISOTROPY\n\t\t\tvec3 retroIBLRadiance = getIBLAnisotropyRetroRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n\t\t#else\n\t\t\tvec3 retroIBLRadiance = getIBLRetroRadiance( geometryViewDir, geometryNormal, material.roughness );\n\t\t#endif\n\t\tiblRadiance = mix( iblRadiance, retroIBLRadiance, saturate( material.retroreflectivity ) );\n\t#endif\n\tradiance += iblRadiance;\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",lightprobes_pars_fragment:"#if NUM_LIGHT_PROBE_GRIDS > 0\nuniform highp sampler3D probesSH[ NUM_LIGHT_PROBE_GRIDS ];\nuniform vec3 probesMin[ NUM_LIGHT_PROBE_GRIDS ];\nuniform vec3 probesMax[ NUM_LIGHT_PROBE_GRIDS ];\nuniform vec3 probesResolution[ NUM_LIGHT_PROBE_GRIDS ];\nbool isInsideLightProbeGrid( vec3 worldPos, vec3 worldNormal, vec3 probesMin, vec3 probesMax, vec3 probesResolution ) {\n\tvec3 spacing = ( probesMax - probesMin ) / probesResolution;\n\tvec3 samplePos = worldPos + worldNormal * spacing * 0.5;\n\tvec3 margin = spacing * 0.01;\n\treturn all( greaterThanEqual( samplePos, probesMin - margin ) ) && all( lessThanEqual( samplePos, probesMax + margin ) );\n}\nvec3 getLightProbeGridIrradiance( highp sampler3D probesSH, vec3 probesMin, vec3 probesMax, vec3 probesResolution, vec3 worldPos, vec3 worldNormal ) {\n\tvec3 res = probesResolution;\n\tvec3 gridRange = probesMax - probesMin;\n\tvec3 probeSpacing = gridRange / res;\n\tvec3 samplePos = worldPos + worldNormal * probeSpacing * 0.5;\n\tvec3 uvw = clamp( ( samplePos - probesMin ) / gridRange, 0.5 / res, 1.0 - 0.5 / res );\n\tfloat nz = res.z;\n\tfloat paddedSlices = nz + 2.0;\n\tfloat atlasDepth = 7.0 * paddedSlices;\n\tfloat uvZBase = uvw.z * nz + 1.0;\n\tvec4 s0 = texture( probesSH, vec3( uvw.xy, ( uvZBase ) / atlasDepth ) );\n\tvec4 s1 = texture( probesSH, vec3( uvw.xy, ( uvZBase + paddedSlices ) / atlasDepth ) );\n\tvec4 s2 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 2.0 * paddedSlices ) / atlasDepth ) );\n\tvec4 s3 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 3.0 * paddedSlices ) / atlasDepth ) );\n\tvec4 s4 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 4.0 * paddedSlices ) / atlasDepth ) );\n\tvec4 s5 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 5.0 * paddedSlices ) / atlasDepth ) );\n\tvec4 s6 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 6.0 * paddedSlices ) / atlasDepth ) );\n\tvec3 c0 = s0.xyz;\n\tvec3 c1 = vec3( s0.w, s1.xy );\n\tvec3 c2 = vec3( s1.zw, s2.x );\n\tvec3 c3 = s2.yzw;\n\tvec3 c4 = s3.xyz;\n\tvec3 c5 = vec3( s3.w, s4.xy );\n\tvec3 c6 = vec3( s4.zw, s5.x );\n\tvec3 c7 = s5.yzw;\n\tvec3 c8 = s6.xyz;\n\tfloat x = worldNormal.x, y = worldNormal.y, z = worldNormal.z;\n\tvec3 result = c0 * 0.886227;\n\tresult += c1 * 2.0 * 0.511664 * y;\n\tresult += c2 * 2.0 * 0.511664 * z;\n\tresult += c3 * 2.0 * 0.511664 * x;\n\tresult += c4 * 2.0 * 0.429043 * x * y;\n\tresult += c5 * 2.0 * 0.429043 * y * z;\n\tresult += c6 * ( 0.743125 * z * z - 0.247708 );\n\tresult += c7 * 2.0 * 0.429043 * x * z;\n\tresult += c8 * 0.429043 * ( x * x - y * y );\n\treturn max( result, vec3( 0.0 ) );\n}\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\t#if defined( USE_COLOR_ALPHA )\n\t\tvColor *= morphTargetBaseInfluence;\n\t#elif defined( USE_COLOR )\n\t\tvColor.rgb *= morphTargetBaseInfluence;\n\t#endif\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.rgb += 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#ifdef DOUBLE_SIDED\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#ifdef DOUBLE_SIDED\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\t#if defined( USE_PACKED_NORMALMAP )\n\t\tmapN = vec3( mapN.xy, sqrt( saturate( 1.0 - dot( mapN.xy, mapN.xy ) ) ) );\n\t#endif\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\t#ifdef FLIP_SIDED\n\t\t\tvBitangent = - vBitangent;\n\t\t#endif\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_SUN_LIGHT_SHADOWS > 0\n\t\t#define SUN_LIGHT_CASCADES 2\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform sampler2DShadow sunShadowMap[ NUM_SUN_LIGHT_SHADOWS ];\n\t\t#else\n\t\t\tuniform sampler2D sunShadowMap[ NUM_SUN_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tuniform mat4 sunShadowMatrix[ NUM_SUN_LIGHT_SHADOWS * SUN_LIGHT_CASCADES ];\n\t\tuniform vec4 sunShadowCascade[ NUM_SUN_LIGHT_SHADOWS * SUN_LIGHT_CASCADES ];\n\t\tvarying vec4 vSunShadowWorldPosition;\n\t\tvarying vec3 vSunShadowWorldNormal;\n\t\tstruct SunLightShadow {\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 SunLightShadow sunLightShadows[ NUM_SUN_LIGHT_SHADOWS ];\n\t#endif\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\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 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\t\tvec2 radius = shadowRadius * texelSize;\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_SUN_LIGHT_SHADOWS > 0\n\t\tfloat getSunShadow(\n\t\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\t\tsampler2DShadow shadowMap,\n\t\t\t#else\n\t\t\t\tsampler2D shadowMap,\n\t\t\t#endif\n\t\t\tSunLightShadow sunLightShadow,\n\t\t\tint shadowIndex\n\t\t) {\n\t\t\tvec4 shadowWorldPosition = vec4( vSunShadowWorldPosition.xyz + vSunShadowWorldNormal * sunLightShadow.shadowNormalBias, 1.0 );\n\t\t\tfloat viewDepth = vSunShadowWorldPosition.w;\n\t\t\tint cascadeOffset = shadowIndex * SUN_LIGHT_CASCADES;\n\t\t\tfloat shadow = 1.0;\n\t\t\tfor ( int i = SUN_LIGHT_CASCADES - 1; i >= 0; i -- ) {\n\t\t\t\tvec4 cascade = sunShadowCascade[ cascadeOffset + i ];\n\t\t\t\tif ( viewDepth >= cascade.x && viewDepth < cascade.y ) {\n\t\t\t\t\tfloat cascadeShadow = getShadow(\n\t\t\t\t\t\tshadowMap,\n\t\t\t\t\t\tsunLightShadow.shadowMapSize,\n\t\t\t\t\t\tsunLightShadow.shadowIntensity,\n\t\t\t\t\t\tsunLightShadow.shadowBias,\n\t\t\t\t\t\tsunLightShadow.shadowRadius,\n\t\t\t\t\t\tsunShadowMatrix[ cascadeOffset + i ] * shadowWorldPosition\n\t\t\t\t\t);\n\t\t\t\t\tshadow = mix( cascadeShadow, shadow, smoothstep( cascade.z, cascade.y, viewDepth ) );\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn shadow;\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\tfloat lightDistance = length( lightToPosition );\n\t\t\tfloat depthRange = shadowCameraFar - shadowCameraNear;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tfloat depthA = - shadowCameraNear / depthRange - shadowBias;\n\t\t\t\tfloat depthB = shadowCameraNear * shadowCameraFar / ( depthRange * lightDistance );\n\t\t\t#else\n\t\t\t\tfloat depthA = shadowCameraFar / depthRange + shadowBias;\n\t\t\t\tfloat depthB = - shadowCameraNear * shadowCameraFar / ( depthRange * lightDistance );\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\tshadow = 0.0;\n\t\t\tfor ( int i = 0; i < 5; i ++ ) {\n\t\t\t\tvec2 offset = vogelDiskSample( i, 5, phi );\n\t\t\t\tvec3 direction = bd3D + ( tangent * offset.x + bitangent * offset.y ) * texelSize;\n\t\t\t\tvec3 absDirection = abs( direction );\n\t\t\t\tfloat dp = depthA + depthB / max( max( absDirection.x, absDirection.y ), absDirection.z );\n\t\t\t\tshadow += texture( shadowMap, vec4( direction, dp ) );\n\t\t\t}\n\t\t\tshadow *= 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_SUN_LIGHT_SHADOWS > 0\n\t\tvarying vec4 vSunShadowWorldPosition;\n\t\tvarying vec3 vSunShadowWorldNormal;\n\t#endif\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_SUN_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\t#ifdef HAS_NORMAL\n\t\tvec3 shadowWorldNormal = transformNormalByInverseViewMatrix( transformedNormal, viewMatrix );\n\t#else\n\t\tvec3 shadowWorldNormal = vec3( 0.0 );\n\t#endif\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_SUN_LIGHT_SHADOWS > 0\n\t\tvSunShadowWorldPosition = vec4( worldPosition.xyz, - mvPosition.z );\n\t\tvSunShadowWorldNormal = shadowWorldNormal;\n\t#endif\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_SUN_LIGHT_SHADOWS > 0\n\tSunLightShadow sunLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SUN_LIGHT_SHADOWS; i ++ ) {\n\t\tsunLight = sunLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getSunShadow( sunShadowMap[ i ], sunLight, UNROLLED_LOOP_INDEX ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\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 = transformNormalByInverseViewMatrix( 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_DIFFUSE_ROUGHNESSMAP\n\tvarying vec2 vDiffuseRoughnessMapUv;\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_DIFFUSE_ROUGHNESSMAP\n\tuniform mat3 diffuseRoughnessMapTransform;\n\tvarying vec2 vDiffuseRoughnessMapUv;\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_DIFFUSE_ROUGHNESSMAP\n\tvDiffuseRoughnessMapUv = ( diffuseRoughnessMapTransform * vec3( DIFFUSE_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:"uniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nuniform mat3 backgroundRotation;\nvarying vec3 vWorldDirection;\n#include <envmap_common_pars_fragment>\nvoid main() {\n\t#ifdef ENVMAP_TYPE_PMREM\n\t\tvec4 texColor = textureLod( envMap, backgroundRotation * vWorldDirection, roughnessToMip( backgroundBlurriness ) );\n\t#else\n\t\tvec4 texColor = textureCube( envMap, backgroundRotation * vWorldDirection );\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 <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 <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_DIFFUSE_ROUGHNESS\n\tuniform float diffuseRoughness;\n\t#ifdef USE_DIFFUSE_ROUGHNESSMAP\n\t\tuniform sampler2D diffuseRoughnessMap;\n\t#endif\n#endif\n#ifdef USE_DISPERSION\n\tuniform float dispersion;\n#endif\n#ifdef USE_RETROREFLECTION\n\tuniform float retroreflectivity;\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 <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}"},fo={common:{diffuse:{value:new Yr(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Xi},alphaMap:{value:null},alphaMapTransform:{value:new Xi},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Xi}},envmap:{envMap:{value:null},envMapRotation:{value:new Xi},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Xi}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Xi}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Xi},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Xi},normalScale:{value:new Vi(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Xi},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Xi}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Xi}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Xi}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Yr(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},sunLights:{value:[],properties:{direction:{},color:{}}},sunLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},sunShadowMatrix:{value:[]},sunShadowCascade:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null},probesSH:{value:[]},probesMin:{value:[]},probesMax:{value:[]},probesResolution:{value:[]}},points:{diffuse:{value:new Yr(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Xi},alphaTest:{value:0},uvTransform:{value:new Xi}},sprite:{diffuse:{value:new Yr(16777215)},opacity:{value:1},center:{value:new Vi(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Xi},alphaMap:{value:null},alphaMapTransform:{value:new Xi},alphaTest:{value:0}}},mo={basic:{uniforms:na([fo.common,fo.specularmap,fo.envmap,fo.aomap,fo.lightmap,fo.fog]),vertexShader:po.meshbasic_vert,fragmentShader:po.meshbasic_frag},lambert:{uniforms:na([fo.common,fo.specularmap,fo.envmap,fo.aomap,fo.lightmap,fo.emissivemap,fo.bumpmap,fo.normalmap,fo.displacementmap,fo.fog,fo.lights,{emissive:{value:new Yr(0)},envMapIntensity:{value:1}}]),vertexShader:po.meshlambert_vert,fragmentShader:po.meshlambert_frag},phong:{uniforms:na([fo.common,fo.specularmap,fo.envmap,fo.aomap,fo.lightmap,fo.emissivemap,fo.bumpmap,fo.normalmap,fo.displacementmap,fo.fog,fo.lights,{emissive:{value:new Yr(0)},specular:{value:new Yr(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:po.meshphong_vert,fragmentShader:po.meshphong_frag},standard:{uniforms:na([fo.common,fo.envmap,fo.aomap,fo.lightmap,fo.emissivemap,fo.bumpmap,fo.normalmap,fo.displacementmap,fo.roughnessmap,fo.metalnessmap,fo.fog,fo.lights,{emissive:{value:new Yr(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:po.meshphysical_vert,fragmentShader:po.meshphysical_frag},toon:{uniforms:na([fo.common,fo.aomap,fo.lightmap,fo.emissivemap,fo.bumpmap,fo.normalmap,fo.displacementmap,fo.gradientmap,fo.fog,fo.lights,{emissive:{value:new Yr(0)}}]),vertexShader:po.meshtoon_vert,fragmentShader:po.meshtoon_frag},matcap:{uniforms:na([fo.common,fo.bumpmap,fo.normalmap,fo.displacementmap,fo.fog,{matcap:{value:null}}]),vertexShader:po.meshmatcap_vert,fragmentShader:po.meshmatcap_frag},points:{uniforms:na([fo.points,fo.fog]),vertexShader:po.points_vert,fragmentShader:po.points_frag},dashed:{uniforms:na([fo.common,fo.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:po.linedashed_vert,fragmentShader:po.linedashed_frag},depth:{uniforms:na([fo.common,fo.displacementmap]),vertexShader:po.depth_vert,fragmentShader:po.depth_frag},normal:{uniforms:na([fo.common,fo.bumpmap,fo.normalmap,fo.displacementmap,{opacity:{value:1}}]),vertexShader:po.meshnormal_vert,fragmentShader:po.meshnormal_frag},sprite:{uniforms:na([fo.sprite,fo.fog]),vertexShader:po.sprite_vert,fragmentShader:po.sprite_frag},background:{uniforms:{uvTransform:{value:new Xi},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:po.background_vert,fragmentShader:po.background_frag},backgroundCube:{uniforms:{envMap:{value:null},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new Xi}},vertexShader:po.backgroundCube_vert,fragmentShader:po.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:po.cube_vert,fragmentShader:po.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:po.equirect_vert,fragmentShader:po.equirect_frag},distance:{uniforms:na([fo.common,fo.displacementmap,{referencePosition:{value:new Wi},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:po.distance_vert,fragmentShader:po.distance_frag},shadow:{uniforms:na([fo.lights,fo.fog,{color:{value:new Yr(0)},opacity:{value:1}}]),vertexShader:po.shadow_vert,fragmentShader:po.shadow_frag}};mo.physical={uniforms:na([mo.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Xi},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Xi},clearcoatNormalScale:{value:new Vi(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Xi},diffuseRoughness:{value:0},diffuseRoughnessMap:{value:null},diffuseRoughnessMapTransform:{value:new Xi},dispersion:{value:0},retroreflectivity:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Xi},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Xi},sheen:{value:0},sheenColor:{value:new Yr(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Xi},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Xi},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Xi},transmissionSamplerSize:{value:new Vi},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Xi},attenuationDistance:{value:0},attenuationColor:{value:new Yr(0)},specularColor:{value:new Yr(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Xi},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Xi},anisotropyVector:{value:new Vi},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Xi}}]),vertexShader:po.meshphysical_vert,fragmentShader:po.meshphysical_frag};const go={r:0,b:0,g:0},_o=new fr,vo=new Xi;function bo(e,t,i,r,n,s){const a=new Yr(0);let o,l,u=!0===n?0:1,c=null,h=0,d=null;function p(e){let i=!0===e.isScene?e.background:null;if(i&&i.isTexture){const r=e.backgroundBlurriness>0;i=t.get(i,r)}return i}function f(t,r){t.getRGB(go,aa(e)),i.buffers.color.setClear(go.r,go.g,go.b,r,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 r=!1;const n=p(t);null===n?f(a,u):n&&n.isColor&&(f(n,1),r=!0);const o=e.xr.getEnvironmentBlendMode();"additive"===o?i.buffers.color.setClear(0,0,0,1,s):"alpha-blend"===o&&i.buffers.color.setClear(0,0,0,0,s),(e.autoClear||r)&&(i.buffers.depth.setTest(!0),i.buffers.depth.setMask(!0),i.buffers.color.setMask(!0),e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil))},addToRenderList:function(t,i){const n=p(i);n&&n.isCubeTexture?(void 0===l&&(l=new ws(new Qs(1,1,1),new la({name:"BackgroundCubeMaterial",uniforms:ra(mo.backgroundCube.uniforms),vertexShader:mo.backgroundCube.vertexShader,fragmentShader:mo.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,i){this.matrixWorld.copyPosition(i.matrixWorld)},Object.defineProperty(l.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),r.update(l)),l.material.uniforms.envMap.value=n,l.material.uniforms.backgroundBlurriness.value=i.backgroundBlurriness,l.material.uniforms.backgroundIntensity.value=i.backgroundIntensity,l.material.uniforms.backgroundRotation.value.setFromMatrix4(_o.makeRotationFromEuler(i.backgroundRotation)).transpose(),!1===n.isRenderTargetTexture&&l.material.uniforms.backgroundRotation.value.premultiply(vo),l.material.toneMapped=Qi.getTransfer(n.colorSpace)!==Kt,c===n&&h===n.version&&d===e.toneMapping||(l.material.needsUpdate=!0,c=n,h=n.version,d=e.toneMapping),l.layers.enableAll(),t.unshift(l,l.geometry,l.material,0,0,null)):n&&n.isTexture&&(void 0===o&&(o=new ws(new ea(2,2),new la({name:"BackgroundMaterial",uniforms:ra(mo.background.uniforms),vertexShader:mo.background.vertexShader,fragmentShader:mo.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}}),r.update(o)),o.material.uniforms.t2D.value=n,o.material.uniforms.backgroundIntensity.value=i.backgroundIntensity,o.material.toneMapped=Qi.getTransfer(n.colorSpace)!==Kt,!0===n.matrixAutoUpdate&&n.updateMatrix(),o.material.uniforms.uvTransform.value.copy(n.matrix),c===n&&h===n.version&&d===e.toneMapping||(o.material.needsUpdate=!0,c=n,h=n.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 yo(e,t){const i=e.getParameter(e.MAX_VERTEX_ATTRIBS),r={},n=u(null);let s=n,a=!1;function o(t){return e.bindVertexArray(t)}function l(t){return e.deleteVertexArray(t)}function u(e){const t=[],r=[],n=[];for(let e=0;e<i;e++)t[e]=0,r[e]=0,n[e]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:t,enabledAttributes:r,attributeDivisors:n,object:e,attributes:{},index:null}}function c(){const e=s.newAttributes;for(let t=0,i=e.length;t<i;t++)e[t]=0}function h(e){d(e,0)}function d(t,i){const r=s.newAttributes,n=s.enabledAttributes,a=s.attributeDivisors;r[t]=1,0===n[t]&&(e.enableVertexAttribArray(t),n[t]=1),a[t]!==i&&(e.vertexAttribDivisor(t,i),a[t]=i)}function p(){const t=s.newAttributes,i=s.enabledAttributes;for(let r=0,n=i.length;r<n;r++)i[r]!==t[r]&&(e.disableVertexAttribArray(r),i[r]=0)}function f(t,i,r,n,s,a,o){!0===o?e.vertexAttribIPointer(t,i,r,s,a):e.vertexAttribPointer(t,i,r,n,s,a)}function m(){g(),a=!0,s!==n&&(s=n,o(s.object))}function g(){n.geometry=null,n.program=null,n.wireframe=!1}return{setup:function(i,n,l,m,g){let _=!1;const v=function(t,i,n,s){const a=!0===s.wireframe;let o=r[i.id];void 0===o&&(o={},r[i.id]=o);const l=!0===t.isInstancedMesh?t.id:0;let c=o[l];void 0===c&&(c={},o[l]=c);let h=c[n.id];void 0===h&&(h={},c[n.id]=h);let d=h[a];void 0===d&&(d=u(e.createVertexArray()),h[a]=d);return d}(i,m,l,n);s!==v&&(s=v,o(s.object)),_=function(e,t,i,r){const n=s.attributes,a=t.attributes;let o=0;const l=i.getAttributes();for(const t in l){if(l[t].location>=0){const i=n[t];let r=a[t];if(void 0===r&&("instanceMatrix"===t&&e.instanceMatrix&&(r=e.instanceMatrix),"instanceColor"===t&&e.instanceColor&&(r=e.instanceColor)),void 0===i)return!0;if(i.attribute!==r)return!0;if(r&&i.data!==r.data)return!0;o++}}return s.attributesNum!==o||s.index!==r}(i,m,l,g),_&&function(e,t,i,r){const n={},a=t.attributes;let o=0;const l=i.getAttributes();for(const t in l){if(l[t].location>=0){let i=a[t];void 0===i&&("instanceMatrix"===t&&e.instanceMatrix&&(i=e.instanceMatrix),"instanceColor"===t&&e.instanceColor&&(i=e.instanceColor));const r={};r.attribute=i,i&&i.data&&(r.data=i.data),n[t]=r,o++}}s.attributes=n,s.attributesNum=o,s.index=r}(i,m,l,g),null!==g&&t.update(g,e.ELEMENT_ARRAY_BUFFER),(_||a)&&(a=!1,function(i,r,n,s){c();const a=s.attributes,o=n.getAttributes(),l=r.defaultAttributeValues;for(const r in o){const n=o[r];if(n.location>=0){let o=a[r];if(void 0===o&&("instanceMatrix"===r&&i.instanceMatrix&&(o=i.instanceMatrix),"instanceColor"===r&&i.instanceColor&&(o=i.instanceColor)),void 0!==o){const r=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===We;if(o.isInterleavedBufferAttribute){const t=o.data,l=!0===t.isInterleavedBuffer?t.stride:t.itemSize,g=o.offset;if(t.isInstancedInterleavedBuffer||t.isInstancedBufferAttribute){for(let e=0;e<n.locationSize;e++)d(n.location+e,t.meshPerAttribute);!0!==i.isInstancedMesh&&void 0===s._maxInstanceCount&&(s._maxInstanceCount=t.meshPerAttribute*t.count)}else for(let e=0;e<n.locationSize;e++)h(n.location+e);e.bindBuffer(e.ARRAY_BUFFER,u);for(let e=0;e<n.locationSize;e++)f(n.location+e,a/n.locationSize,c,r,l*p,(g+a/n.locationSize*e)*p,m)}else{if(o.isInstancedBufferAttribute){for(let e=0;e<n.locationSize;e++)d(n.location+e,o.meshPerAttribute);!0!==i.isInstancedMesh&&void 0===s._maxInstanceCount&&(s._maxInstanceCount=o.meshPerAttribute*o.count)}else for(let e=0;e<n.locationSize;e++)h(n.location+e);e.bindBuffer(e.ARRAY_BUFFER,u);for(let e=0;e<n.locationSize;e++)f(n.location+e,a/n.locationSize,c,r,a*p,a/n.locationSize*e*p,m)}}else if(void 0!==l){const t=l[r];if(void 0!==t)switch(t.length){case 2:e.vertexAttrib2fv(n.location,t);break;case 3:e.vertexAttrib3fv(n.location,t);break;case 4:e.vertexAttrib4fv(n.location,t);break;default:e.vertexAttrib1fv(n.location,t)}}}}p()}(i,n,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 r){const t=r[e];for(const e in t){const i=t[e];for(const e in i){const t=i[e];for(const e in t)l(t[e].object),delete t[e];delete i[e]}}delete r[e]}},releaseStatesOfGeometry:function(e){if(void 0===r[e.id])return;const t=r[e.id];for(const e in t){const i=t[e];for(const e in i){const t=i[e];for(const e in t)l(t[e].object),delete t[e];delete i[e]}}delete r[e.id]},releaseStatesOfObject:function(e){for(const t in r){const i=r[t],n=!0===e.isInstancedMesh?e.id:0,s=i[n];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 i[n],0===Object.keys(i).length&&delete r[t]}}},releaseStatesOfProgram:function(e){for(const t in r){const i=r[t];for(const t in i){const r=i[t];if(void 0===r[e.id])continue;const n=r[e.id];for(const e in n)l(n[e].object),delete n[e];delete r[e.id]}}},initAttributes:c,enableAttribute:h,disableUnusedAttributes:p}}function xo(e,t,i){let r;this.setMode=function(e){r=e},this.render=function(t,n){e.drawArrays(r,t,n),i.update(n,r,1)},this.renderInstances=function(t,n,s){0!==s&&(e.drawArraysInstanced(r,t,n,s),i.update(n,r,s))},this.renderMultiDraw=function(e,n,s){if(0===s)return;t.get("WEBGL_multi_draw").multiDrawArraysWEBGL(r,e,0,n,0,s);let a=0;for(let e=0;e<s;e++)a+=n[e];i.update(a,r,1)}}function So(e,t,i,r){let n;function s(t){if("highp"===t){if(e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return"highp";t="mediump"}return"mediump"===t&&e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let a=void 0!==i.precision?i.precision:"highp";const o=s(a);o!==a&&(Ti("WebGLRenderer:",a,"not supported, using",o,"instead."),a=o);const l=!0===i.reversedDepthBuffer&&t.has("EXT_clip_control"),u=!0===i.logarithmicDepthBuffer&&!1===l;!0===i.reversedDepthBuffer&&!1===l&&Ti("WebGLRenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer."),!0===i.logarithmicDepthBuffer&&!0===l&&Ti("WebGLRenderer: Logarithmic depth buffer is ignored when reversed depth buffer is enabled.");return{isWebGL2:!0,getMaxAnisotropy:function(){if(void 0!==n)return n;if(!0===t.has("EXT_texture_filter_anisotropic")){const i=t.get("EXT_texture_filter_anisotropic");n=e.getParameter(i.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else n=0;return n},getMaxPrecision:s,textureFormatReadable:function(t){return t===tt||r.convert(t)===e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)},textureTypeReadable:function(i){const n=i===Xe&&(t.has("EXT_color_buffer_half_float")||t.has("EXT_color_buffer_float"));return!(i!==ze&&i!==$e&&!n&&r.convert(i)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE))},precision:a,logarithmicDepthBuffer:u,reversedDepthBuffer:l,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 To(e){const t=this;let i=null,r=0,n=!1,s=!1;const a=new ss,o=new Xi,l={value:null,needsUpdate:!1};function u(e,i,r,n){const s=null!==e?e.length:0;let u=null;if(0!==s){if(u=l.value,!0!==n||null===u){const t=r+4*s,n=i.matrixWorldInverse;o.getNormalMatrix(n),(null===u||u.length<t)&&(u=new Float32Array(t));for(let t=0,i=r;t!==s;++t,i+=4)a.copy(e[t]).applyMatrix4(n,o),a.normal.toArray(u,i),u[i+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 i=0!==e.length||t||0!==r||n;return n=t,r=e.length,i},this.beginShadows=function(){s=!0,u(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(e,t){i=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(!n||null===h||0===h.length||s&&!p)s?u(null):function(){l.value!==i&&(l.value=i,l.needsUpdate=r>0);t.numPlanes=r,t.numIntersection=0}();else{const e=s?0:r,t=4*e;let n=f.clippingState||null;l.value=n,n=u(h,o,t,c);for(let e=0;e!==t;++e)n[e]=i[e];f.clippingState=n,this.numIntersection=d?this.numPlanes:0,this.numPlanes+=e}}}vo.set(-1,0,0,0,1,0,0,0,1);class Mo extends hr{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const i={width:e,height:e,depth:1},r=[i,i,i,i,i,i];this.texture=new Xs(r),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const i={uniforms:{tEquirect:{value:null}},vertexShader:"\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include <begin_vertex>\n\t\t\t\t\t#include <project_vertex>\n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include <common>\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t"},r=new Qs(5,5,5),n=new la({name:"CubemapFromEquirect",uniforms:ra(i.uniforms),vertexShader:i.vertexShader,fragmentShader:i.fragmentShader,side:1,blending:0});n.uniforms.tEquirect.value=t;const s=new ws(r,n),a=t.minFilter;t.minFilter===ke&&(t.minFilter=Oe);return new Ja(1,10,this).update(e,s),t.minFilter=a,s.geometry.dispose(),s.material.dispose(),this}clear(e,t=!0,i=!0,r=!0){const n=e.getRenderTarget();for(let n=0;n<6;n++)e.setRenderTarget(this,n),e.clear(t,i,r);e.setRenderTarget(n)}}const Eo=new Wi,wo=new Yr;let Ao=class e{constructor(e){this._renderer=e,this._cubeSize=0,this._sourceTarget=null,this._cubeCamera=new Ja(1,10,null),this._boxMesh=new ws(new Qs(5,5,5),null),this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null,this._integrationMaterial=null}fromScene(e,t=0,i=.1,r=100,n={}){const{size:s=256,position:a=Eo}=n,o=this._renderer;this._setSize(s);const l=this._allocateTarget(),u=this._getSourceTarget(!0);t>0&&(u.texture.mipmapsAutoUpdate=!1);const c=o.autoClear,h=o.autoClearColor,d=o.autoClearDepth,p=o.autoClearStencil,f=e.background;o.autoClear=!0,o.autoClearColor=!0,o.autoClearDepth=!0,o.autoClearStencil=!0,null===f&&(e.background=o.getClearColor(wo));const m=new Ja(i,r,u);return m.position.copy(a),m.update(o,e),o.autoClear=c,o.autoClearColor=h,o.autoClearDepth=d,o.autoClearStencil=p,e.background=f,t>0&&(u.texture.mipmapsAutoUpdate=!0,this._blur(l,t)),this._applyPMREM(l),l}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=Po(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=No(),this._compileMaterial(this._equirectMaterial))}dispose(){null!==this._sourceTarget&&this._sourceTarget.dispose(),null!==this._cubemapMaterial&&this._cubemapMaterial.dispose(),null!==this._equirectMaterial&&this._equirectMaterial.dispose(),null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._ggxMaterial&&this._ggxMaterial.dispose(),null!==this._integrationMaterial&&this._integrationMaterial.dispose(),this._boxMesh.geometry.dispose()}static lodToRoughness(e,t){return t>0?1-Math.sqrt(1-e/t):0}_setSize(e){this._cubeSize=Math.max(256,Oi(e))}_fromTexture(e,t){e.mapping===Ae||e.mapping===Re?this._setSize(0===e.image.length?256:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4);const i=t||this._allocateTarget();return this._textureToCubemap(e),this._applyPMREM(i),i}_allocateTarget(){const e=this._cubeSize,t=Ro(e,!1,!1),i=Math.log2(e)-3;for(let r=0;r<=i;r++)t.texture.mipmaps.push({width:e>>r,height:e>>r});return t.texture.name="PMREM",t.texture.isPMREMTexture=!0,t}_getSourceTarget(e=!1){const t=this._cubeSize,i=this._sourceTarget;return(null===i||i.width!==t||e&&!1===i.depthBuffer)&&(null!==i&&i.dispose(),this._sourceTarget=Ro(t,!0,e)),this._sourceTarget}_compileMaterial(e){this._boxMesh.material=e,this._renderer.compile(this._boxMesh,this._cubeCamera.children[0])}_renderCube(e,t,i){const r=this._boxMesh,n=this._cubeCamera;r.material=i,n.renderTarget=e,n.activeMipmapLevel=t;const s=e.width>>t;e.viewport.set(0,0,s,s),n.update(this._renderer,r),e.viewport.set(0,0,e.width,e.height)}_textureToCubemap(e){let t;e.mapping===Ae||e.mapping===Re?(null===this._cubemapMaterial&&(this._cubemapMaterial=Po()),t=this._cubemapMaterial,t.uniforms.flipEnvMap.value=!1===e.isRenderTargetTexture?-1:1):(null===this._equirectMaterial&&(this._equirectMaterial=No()),t=this._equirectMaterial),t.uniforms.envMap.value=e,this._renderCube(this._getSourceTarget(),0,t)}_applyPMREM(t){null===this._ggxMaterial&&(this._ggxMaterial=Co("PMREMGGXConvolution",{envMap:{value:null},roughness:{value:0},lodBias:{value:0}},"\n\n\t\t#define GGX_SAMPLES 256u\n\n\t\tvarying vec3 vWorldDirection;\n\n\t\tuniform samplerCube envMap;\n\t\tuniform float roughness;\n\t\tuniform float lodBias;\n\n\t\t#include <common>\n\n\t\t// Van der Corput radical inverse\n\t\tfloat radicalInverse_VdC( uint bits ) {\n\n\t\t\tbits = ( bits << 16u ) | ( bits >> 16u );\n\t\t\tbits = ( ( bits & 0x55555555u ) << 1u ) | ( ( bits & 0xAAAAAAAAu ) >> 1u );\n\t\t\tbits = ( ( bits & 0x33333333u ) << 2u ) | ( ( bits & 0xCCCCCCCCu ) >> 2u );\n\t\t\tbits = ( ( bits & 0x0F0F0F0Fu ) << 4u ) | ( ( bits & 0xF0F0F0F0u ) >> 4u );\n\t\t\tbits = ( ( bits & 0x00FF00FFu ) << 8u ) | ( ( bits & 0xFF00FF00u ) >> 8u );\n\t\t\treturn float( bits ) * 2.3283064365386963e-10; // / 0x100000000\n\n\t\t}\n\n\t\t// Hammersley sequence\n\t\tvec2 hammersley( uint i, uint N ) {\n\n\t\t\treturn vec2( float( i ) / float( N ), radicalInverse_VdC( i ) );\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\tvec3 N = normalize( vWorldDirection );\n\n\t\t\t// For very low roughness, just sample the environment directly\n\t\t\tif ( roughness < 0.001 ) {\n\n\t\t\t\tgl_FragColor = vec4( textureLod( envMap, N, 0.0 ).rgb, 1.0 );\n\t\t\t\treturn;\n\n\t\t\t}\n\n\t\t\tfloat alpha = roughness * roughness;\n\t\t\tfloat alpha2 = alpha * alpha;\n\n\t\t\t// Tangent space basis for VNDF sampling\n\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\tvec3 tangent = normalize( cross( up, N ) );\n\t\t\tvec3 bitangent = cross( N, tangent );\n\n\t\t\tvec3 prefilteredColor = vec3( 0.0 );\n\t\t\tfloat totalWeight = 0.0;\n\n\t\t\tfor ( uint i = 0u; i < GGX_SAMPLES; i ++ ) {\n\n\t\t\t\tvec2 Xi = hammersley( i, GGX_SAMPLES );\n\n\t\t\t\t// With V = N, sample the reflected direction directly.\n\t\t\t\tfloat invQ = 1.0 / ( 1.0 - Xi.x + alpha2 * Xi.x );\n\t\t\t\tfloat NdotL = ( 1.0 - Xi.x - alpha2 * Xi.x ) * invQ;\n\n\t\t\t\tif ( NdotL > 0.0 ) {\n\n\t\t\t\t\tfloat phi = 2.0 * PI * Xi.y;\n\t\t\t\t\tfloat sinTheta = 2.0 * alpha * sqrt( Xi.x * ( 1.0 - Xi.x ) ) * invQ;\n\t\t\t\t\tvec3 L = N * NdotL + ( tangent * cos( phi ) + bitangent * sin( phi ) ) * sinTheta;\n\n\t\t\t\t\t// Match the source mip to the sample's solid angle. The terms\n\t\t\t\t\t// independent of the sample are precomputed in lodBias.\n\t\t\t\t\tfloat d = alpha2 * invQ;\n\t\t\t\t\tfloat lod = max( log2( d ) + lodBias, 0.0 );\n\n\t\t\t\t\t// Weight by NdotL for the split-sum approximation\n\t\t\t\t\tprefilteredColor += textureLod( envMap, L, lod ).rgb * NdotL;\n\t\t\t\t\ttotalWeight += NdotL;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tgl_FragColor = vec4( prefilteredColor / totalWeight, 1.0 );\n\n\t\t}\n\t"),this._integrationMaterial=Co("PMREMGGXIntegration",{envMap:{value:null},roughness:{value:0},sourceLod:{value:0},sourceSize:{value:16}},"\n\n\t\tvarying vec3 vWorldDirection;\n\n\t\tuniform samplerCube envMap;\n\t\tuniform float roughness;\n\t\tuniform float sourceLod;\n\t\tuniform int sourceSize;\n\n\t\tvoid main() {\n\n\t\t\tvec3 N = normalize( vWorldDirection );\n\n\t\t\tfloat alpha = roughness * roughness;\n\t\t\tfloat alpha2 = alpha * alpha;\n\n\t\t\tfloat texelSize = 2.0 / float( sourceSize );\n\n\t\t\tvec3 prefilteredColor = vec3( 0.0 );\n\t\t\tfloat totalWeight = 0.0;\n\n\t\t\t// Pair opposite texels: only the one in N's hemisphere contributes.\n\t\t\tfor ( int face = 0; face < 3; face ++ ) {\n\n\t\t\t\tfor ( int y = 0; y < sourceSize; y ++ ) {\n\n\t\t\t\t\tfor ( int x = 0; x < sourceSize; x ++ ) {\n\n\t\t\t\t\t\tvec2 uv = ( vec2( x, y ) + 0.5 ) * texelSize - 1.0;\n\t\t\t\t\t\tvec3 texelDirection = face == 0 ? vec3( 1.0, uv ) : ( face == 1 ? vec3( uv.x, 1.0, uv.y ) : vec3( uv, 1.0 ) );\n\n\t\t\t\t\t\tfloat invDistance = inversesqrt( 1.0 + dot( uv, uv ) );\n\t\t\t\t\t\tfloat NdotL = dot( N, texelDirection );\n\t\t\t\t\t\ttexelDirection *= NdotL < 0.0 ? - 1.0 : 1.0;\n\t\t\t\t\t\tNdotL = abs( NdotL ) * invDistance;\n\n\t\t\t\t\t\t// With V = N, NdotH squared is ( 1 + NdotL ) / 2. Common factors\n\t\t\t\t\t\t// in the GGX distribution and texel solid angle cancel when normalized.\n\t\t\t\t\t\tfloat d = 1.0 + alpha2 + ( alpha2 - 1.0 ) * NdotL;\n\t\t\t\t\t\tfloat weight = NdotL * invDistance * invDistance * invDistance / ( d * d );\n\n\t\t\t\t\t\tprefilteredColor += textureLod( envMap, texelDirection, sourceLod ).rgb * weight;\n\t\t\t\t\t\ttotalWeight += weight;\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tgl_FragColor = vec4( prefilteredColor / totalWeight, 1.0 );\n\n\t\t}\n\t"));const i=this._cubeSize,r=t.texture.mipmaps.length-1,n=this._ggxMaterial.uniforms;n.envMap.value=this._sourceTarget.texture;const s=this._integrationMaterial.uniforms;s.envMap.value=this._sourceTarget.texture,s.sourceLod.value=Math.log2(i/16);for(let a=0;a<=r;a++){const o=e.lodToRoughness(a,r);if(a>r-3)s.roughness.value=o,this._renderCube(t,a,this._integrationMaterial);else{const e=o>0?Math.log2(i)+.5*Math.log2(6/(256*Math.pow(o,4)))+.5:0;n.roughness.value=o,n.lodBias.value=e,this._renderCube(t,a,this._ggxMaterial)}}}_blur(e,t){null===this._blurMaterial&&(this._blurMaterial=Co("PMREMSphericalGaussianBlur",{envMap:{value:null},sigma:{value:0}},"\n\n\t\t#define SAMPLES 20\n\t\t#define GOLDEN_ANGLE 2.39996322973\n\n\t\tvarying vec3 vWorldDirection;\n\n\t\tuniform samplerCube envMap;\n\t\tuniform float sigma;\n\n\t\t#include <common>\n\n\t\tvoid main() {\n\n\t\t\tvec3 outputDirection = normalize( vWorldDirection );\n\n\t\t\tvec3 up = abs( outputDirection.z ) < 0.999 ? vec3( 0.0, 0.0, 1.0 ) : vec3( 1.0, 0.0, 0.0 );\n\t\t\tvec3 tangent = normalize( cross( up, outputDirection ) );\n\t\t\tvec3 bitangent = cross( outputDirection, tangent );\n\n\t\t\t// Truncate the kernel at three standard deviations or at the antipode.\n\t\t\tfloat thetaMax = min( 3.0 * sigma, PI );\n\t\t\tfloat truncation = 1.0 - exp( - 0.5 * thetaMax * thetaMax / ( sigma * sigma ) );\n\n\t\t\tvec3 accumColor = vec3( 0.0 );\n\t\t\tfloat accumWeight = 0.0;\n\n\t\t\tfor ( int i = 0; i < SAMPLES; i ++ ) {\n\n\t\t\t\t// Stratified inverse-CDF sampling of the Gaussian, placed on a golden-angle spiral.\n\t\t\t\tfloat stratum = ( float( i ) + 0.5 ) / float( SAMPLES );\n\t\t\t\tfloat theta = sigma * sqrt( - 2.0 * log( 1.0 - stratum * truncation ) );\n\t\t\t\tfloat phi = float( i ) * GOLDEN_ANGLE;\n\n\t\t\t\tvec3 offset = cos( phi ) * tangent + sin( phi ) * bitangent;\n\t\t\t\tvec3 sampleDirection = cos( theta ) * outputDirection + sin( theta ) * offset;\n\n\t\t\t\t// Correct the planar sample density to solid angle.\n\t\t\t\tfloat weight = sin( theta ) / theta;\n\n\t\t\t\taccumColor += weight * textureLod( envMap, sampleDirection, 0.0 ).rgb;\n\t\t\t\taccumWeight += weight;\n\n\t\t\t}\n\n\t\t\tgl_FragColor = vec4( accumColor / accumWeight, 1.0 );\n\n\t\t}\n\t"));const i=this._blurMaterial,r=i.uniforms,n=this._sourceTarget;r.sigma.value=Math.min(t,Math.PI)/Math.SQRT2,r.envMap.value=n.texture,this._renderCube(e,0,i),r.envMap.value=e.texture,this._renderCube(n,0,i)}};function Ro(e,t,i){return new Mo(e,{minFilter:ke,generateMipmaps:t,type:Xe,colorSpace:qt,depthBuffer:i})}function Co(e,t,i){return new la({name:e,uniforms:t,vertexShader:po.cube_vert,fragmentShader:i,side:1,blending:0,depthTest:!1,depthWrite:!1})}function No(){return Co("PMREMEquirectangularToCubemap",{envMap:{value:null}},"\n\n\t\tvarying vec3 vWorldDirection;\n\n\t\tuniform sampler2D envMap;\n\n\t\t#include <common>\n\n\t\tvoid main() {\n\n\t\t\t// Average four subpixel samples to preserve small, bright features.\n\t\t\tvec3 direction = normalize( vWorldDirection );\n\t\t\tvec3 dx = dFdx( direction ) * 0.25;\n\t\t\tvec3 dy = dFdy( direction ) * 0.25;\n\n\t\t\tvec3 color = textureLod( envMap, equirectUv( normalize( direction - dx - dy ) ), 0.0 ).rgb;\n\t\t\tcolor += textureLod( envMap, equirectUv( normalize( direction + dx - dy ) ), 0.0 ).rgb;\n\t\t\tcolor += textureLod( envMap, equirectUv( normalize( direction - dx + dy ) ), 0.0 ).rgb;\n\t\t\tcolor += textureLod( envMap, equirectUv( normalize( direction + dx + dy ) ), 0.0 ).rgb;\n\t\t\tgl_FragColor = vec4( color * 0.25, 1.0 );\n\n\t\t}\n\t")}function Po(){return Co("PMREMCubemapToCubemap",{envMap:{value:null},flipEnvMap:{value:-1}},"\n\n\t\tvarying vec3 vWorldDirection;\n\n\t\tuniform samplerCube envMap;\n\t\tuniform float flipEnvMap;\n\n\t\tvoid main() {\n\n\t\t\tgl_FragColor = vec4( textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) ).rgb, 1.0 );\n\n\t\t}\n\t")}function Lo(e){let t=new WeakMap,i=new WeakMap,r=null;function n(e,t){return t===Ce?e.mapping=Ae:t===Ne&&(e.mapping=Re),e}function s(e){const i=e.target;i.removeEventListener("dispose",s);const r=t.get(i);void 0!==r&&(t.delete(i),r.dispose())}function a(e){const t=e.target;t.removeEventListener("dispose",a);const r=i.get(t);void 0!==r&&(i.delete(t),r.dispose())}return{get:function(o,l=!1){return null==o?null:l?function(t){if(t&&t.isTexture&&!0!==t.isPMREMTexture){const n=t.mapping,s=n===Ce||n===Ne,o=n===Ae||n===Re;if(s||o){let n=i.get(t);const l=void 0!==n?n.texture.pmremVersion:0;if(t.isRenderTargetTexture&&t.pmremVersion!==l)return null===r&&(r=new Ao(e)),n=s?r.fromEquirectangular(t,n):r.fromCubemap(t,n),n.texture.pmremVersion=t.pmremVersion,i.set(t,n),n.texture;if(void 0!==n)return n.texture;{const l=t.image;return s&&l&&l.height>0||o&&l&&function(e){let t=0;const i=6;for(let r=0;r<i;r++)void 0!==e[r]&&t++;return t===i}(l)?(null===r&&(r=new Ao(e)),n=s?r.fromEquirectangular(t):r.fromCubemap(t),n.texture.pmremVersion=t.pmremVersion,i.set(t,n),t.addEventListener("dispose",a),n.texture):null}}}return t}(o):function(i){if(i&&i.isTexture){const r=i.mapping;if(r===Ce||r===Ne){if(t.has(i)){return n(t.get(i).texture,i.mapping)}{const r=i.image;if(r&&r.height>0){const a=new Mo(r.height);return a.fromEquirectangularTexture(e,i),t.set(i,a),i.addEventListener("dispose",s),n(a.texture,i.mapping)}return null}}}return i}(o)},dispose:function(){t=new WeakMap,i=new WeakMap,null!==r&&(r.dispose(),r=null)}}}function Do(e){const t={};function i(i){if(void 0!==t[i])return t[i];const r=e.getExtension(i);return t[i]=r,r}return{has:function(e){return null!==i(e)},init:function(){i("EXT_color_buffer_float"),i("WEBGL_clip_cull_distance"),i("OES_texture_float_linear"),i("EXT_color_buffer_half_float"),i("WEBGL_multisampled_render_to_texture"),i("WEBGL_render_shared_exponent")},get:function(e){const t=i(e);return null===t&&Ei("WebGLRenderer: "+e+" extension not supported."),t}}}function Uo(e,t,i,r){const n={},s=new WeakMap,a=new FinalizationRegistry(e=>delete n[e]);function o(e){l(e.target)}function l(e){null!==e.index&&t.remove(e.index);for(const i in e.attributes)t.remove(e.attributes[i]);e.removeEventListener("dispose",o),delete n[e.id],a.unregister(e);const l=s.get(e);l&&(t.remove(l),s.delete(e)),r.releaseStatesOfGeometry(e),!0===e.isInstancedBufferGeometry&&delete e._maxInstanceCount,i.memory.geometries--}function u(e){const i=e.index,r=e.attributes.position;let n=0;if(void 0===r)return;const a=null!==i?i.array.length:r.array.length/3-1,o=new(r.count>=65535?On:Fn)(6*Math.ceil(a/3),1),l=o.array;if(null!==i){const e=i.array;n=i.version;for(let t=0,i=0;t<a;t+=3){const r=e[t+0],n=e[t+1],s=e[t+2];l[i++]=r,l[i++]=n,l[i++]=n,l[i++]=s,l[i++]=s,l[i++]=r}}else{n=r.version;for(let e=0,t=0;e<a;e+=3){const i=e+0,r=e+1,n=e+2;l[t++]=i,l[t++]=r,l[t++]=r,l[t++]=n,l[t++]=n,l[t++]=i}}o.version=n;const u=s.get(e);u&&t.remove(u),s.set(e,o)}return{get:function(e,t){return void 0!==n[t.id]||(t.addEventListener("dispose",o),n[t.id]=new WeakRef(t),a.register(t,t.id,t),i.memory.geometries++),t},update:function(i){const r=i.attributes;for(const i in r)t.update(r[i],e.ARRAY_BUFFER)},getWireframeAttribute:function(e){const t=s.get(e);if(t){const i=e.index;null!==i&&t.version<i.version&&u(e)}else u(e);return s.get(e)},dispose:function(){for(const e in n){const t=n[e].deref();void 0!==t&&l(t)}}}}function Io(e,t,i){let r,n,s;this.setMode=function(e){r=e},this.setIndex=function(e){n=e.type,s=e.bytesPerElement},this.render=function(t,a){e.drawElements(r,a,n,t*s),i.update(a,r,1)},this.renderInstances=function(t,a,o){0!==o&&(e.drawElementsInstanced(r,a,n,t*s,o),i.update(a,r,o))},this.renderMultiDraw=function(e,s,a){if(0===a)return;t.get("WEBGL_multi_draw").multiDrawElementsWEBGL(r,s,0,n,e,0,a);let o=0;for(let e=0;e<a;e++)o+=s[e];i.update(o,r,1)}}function Fo(e){const t={frame:0,calls:0,triangles:0,points:0,lines:0};return{memory:{geometries:0,textures:0},render:t,programs:null,autoReset:!0,reset:function(){t.calls=0,t.triangles=0,t.points=0,t.lines=0},update:function(i,r,n){switch(t.calls++,r){case e.TRIANGLES:t.triangles+=n*(i/3);break;case e.LINES:t.lines+=n*(i/2);break;case e.LINE_STRIP:t.lines+=n*(i-1);break;case e.LINE_LOOP:t.lines+=n*i;break;case e.POINTS:t.points+=n*i;break;default:Mi("WebGLInfo: Unknown draw mode:",r)}}}}function Oo(e,t,i){const r=new WeakMap,n=new ur;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=r.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 b=a.attributes.position.count*v,y=1;b>t.maxTextureSize&&(y=Math.ceil(b/t.maxTextureSize),b=t.maxTextureSize);const x=new Float32Array(b*y*4*c),S=new dr(x,b,y,c);S.type=$e,S.needsUpdate=!0;const T=4*v;for(let E=0;E<c;E++){const w=m[E],A=g[E],R=_[E],C=b*y*4*E;for(let N=0;N<w.count;N++){const P=N*T;!0===d&&(n.fromBufferAttribute(w,N),x[C+P+0]=n.x,x[C+P+1]=n.y,x[C+P+2]=n.z,x[C+P+3]=0),!0===p&&(n.fromBufferAttribute(A,N),x[C+P+4]=n.x,x[C+P+5]=n.y,x[C+P+6]=n.z,x[C+P+7]=0),!0===f&&(n.fromBufferAttribute(R,N),x[C+P+8]=n.x,x[C+P+9]=n.y,x[C+P+10]=n.z,x[C+P+11]=4===R.itemSize?n.w:1)}}function M(){S.dispose(),r.delete(a),a.removeEventListener("dispose",M)}h={count:c,texture:S,size:new Vi(b,y)},r.set(a,h),a.addEventListener("dispose",M)}if(!0===s.isInstancedMesh&&null!==s.morphTexture)o.getUniforms().setValue(e,"morphTexture",s.morphTexture,i);else{let L=0;for(let U=0;U<l.length;U++)L+=l[U];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,i),o.getUniforms().setValue(e,"morphTargetsTextureSize",h.size)}}}function Bo(e,t,i,r,n){let s=new WeakMap;function a(e){const t=e.target;t.removeEventListener("dispose",a),r.releaseStatesOfObject(t),i.remove(t.instanceMatrix),null!==t.instanceColor&&i.remove(t.instanceColor)}return{update:function(r){const o=n.render.frame,l=r.geometry,u=t.get(r,l);if(s.get(u)!==o&&(t.update(u),s.set(u,o)),r.isInstancedMesh&&(!1===r.hasEventListener("dispose",a)&&r.addEventListener("dispose",a),s.get(r)!==o&&(i.update(r.instanceMatrix,e.ARRAY_BUFFER),null!==r.instanceColor&&i.update(r.instanceColor,e.ARRAY_BUFFER),s.set(r,o))),r.isSkinnedMesh){const e=r.skeleton;s.get(e)!==o&&(e.update(),s.set(e,o))}return u},dispose:function(){s=new WeakMap}}}const ko={[ye]:"LINEAR_TONE_MAPPING",[xe]:"REINHARD_TONE_MAPPING",[Se]:"CINEON_TONE_MAPPING",[Te]:"ACES_FILMIC_TONE_MAPPING",[Ee]:"AGX_TONE_MAPPING",[we]:"NEUTRAL_TONE_MAPPING",[Me]:"CUSTOM_TONE_MAPPING"};function zo(e,t,i,r,n,s){const a=new hr(t,i,{type:e,depthBuffer:n,stencilBuffer:s,samples:r?4:0,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,resolveDepthBuffer:!1,resolveStencilBuffer:!1});let o=null,l=null,u=null;const c=new Zn;c.setAttribute("position",new kn([-1,3,0,-1,-1,0,3,-1,0],3)),c.setAttribute("uv",new kn([0,2,0,0,2,0],2));const h=new ua({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}),d=new ws(c,h),p=new ja(-1,1,1,-1,0,1);let f,m=null,g=null,_=!1,v=null,b=[],y=!1;this.setSize=function(e,t){a.setSize(e,t),null!==o&&o.setSize(e,t),null!==l&&l.setSize(e,t);for(let i=0;i<b.length;i++){const r=b[i];r.setSize&&r.setSize(e,t)}},this.setEffects=function(e){b=e,y=b.length>0&&!0===b[0].isRenderPass;const t=a.width,i=a.height;b.length>0&&null===o&&(o=new hr(t,i,{type:Xe,depthBuffer:!1,stencilBuffer:!1}),l=new hr(t,i,{type:Xe,depthBuffer:!1,stencilBuffer:!1}));const r=!0===n&&b.some(e=>!0===e.needsDepthTexture);r!==(null!==a.depthTexture)&&(!0===r&&null===u&&(u=new Ys(t,i),!0===s&&(u.format=rt,u.type=Ke)),a.dispose(),a.depthTexture=r?u:null,a.resolveDepthBuffer=r,a.storeMultisampledDepthBuffer=r);for(let e=0;e<b.length;e++){const n=b[e];n.setSize&&n.setSize(t,i),r&&!0===n.needsDepthTexture&&n.setDepthTexture&&n.setDepthTexture(u)}},this.begin=function(e,t){if(_)return!1;if(0===e.toneMapping&&0===b.length)return!1;if(v=t,null!==t){const e=t.width,i=t.height;a.width===e&&a.height===i||this.setSize(e,i)}return!1===y&&e.setRenderTarget(a),f=e.toneMapping,e.toneMapping=0,!0},this.hasRenderPass=function(){return y},this.end=function(e,t){e.toneMapping=f,_=!0;let i=a,r=o;for(let n=0;n<b.length;n++){const s=b[n];!1!==s.enabled&&(s.render(e,r,i,t),!1!==s.needsSwap&&(i=r,r=r===o?l:o))}if(m!==e.outputColorSpace||g!==e.toneMapping){m=e.outputColorSpace,g=e.toneMapping,h.defines={},Qi.getTransfer(m)===Kt&&(h.defines.SRGB_TRANSFER="");const t=ko[g];t&&(h.defines[t]=""),h.needsUpdate=!0}h.uniforms.tDiffuse.value=i.texture,e.setRenderTarget(v),e.render(d,p),v=null,_=!1},this.isCompositing=function(){return _},this.dispose=function(){a.dispose(),null!==o&&o.dispose(),null!==l&&l.dispose(),c.dispose(),h.dispose()}}const Go=new lr,Vo=new Ys(1,1),Ho=new Ks(1),Wo=new dr,jo=new pr,$o=new Xs,Xo=[],qo=[],Yo=new Float32Array(16),Ko=new Float32Array(9),Zo=new Float32Array(4);function Qo(e,t,i){const r=e[0];if(r<=0||r>0)return e;const n=t*i;let s=Xo[n];if(void 0===s&&(s=new Float32Array(n),Xo[n]=s),0!==t){r.toArray(s,0);for(let r=1,n=0;r!==t;++r)n+=i,e[r].toArray(s,n)}return s}function Jo(e,t){if(e.length!==t.length)return!1;for(let i=0,r=e.length;i<r;i++)if(e[i]!==t[i])return!1;return!0}function el(e,t){for(let i=0,r=t.length;i<r;i++)e[i]=t[i]}function tl(e,t){let i=qo[t];void 0===i&&(i=new Int32Array(t),qo[t]=i);for(let r=0;r!==t;++r)i[r]=e.allocateTextureUnit();return i}function il(e,t){const i=this.cache;i[0]!==t&&(e.uniform1f(this.addr,t),i[0]=t)}function rl(e,t){const i=this.cache;if(void 0!==t.x)i[0]===t.x&&i[1]===t.y||(e.uniform2f(this.addr,t.x,t.y),i[0]=t.x,i[1]=t.y);else{if(Jo(i,t))return;e.uniform2fv(this.addr,t),el(i,t)}}function nl(e,t){const i=this.cache;if(void 0!==t.x)i[0]===t.x&&i[1]===t.y&&i[2]===t.z||(e.uniform3f(this.addr,t.x,t.y,t.z),i[0]=t.x,i[1]=t.y,i[2]=t.z);else if(void 0!==t.r)i[0]===t.r&&i[1]===t.g&&i[2]===t.b||(e.uniform3f(this.addr,t.r,t.g,t.b),i[0]=t.r,i[1]=t.g,i[2]=t.b);else{if(Jo(i,t))return;e.uniform3fv(this.addr,t),el(i,t)}}function sl(e,t){const i=this.cache;if(void 0!==t.x)i[0]===t.x&&i[1]===t.y&&i[2]===t.z&&i[3]===t.w||(e.uniform4f(this.addr,t.x,t.y,t.z,t.w),i[0]=t.x,i[1]=t.y,i[2]=t.z,i[3]=t.w);else{if(Jo(i,t))return;e.uniform4fv(this.addr,t),el(i,t)}}function al(e,t){const i=this.cache,r=t.elements;if(void 0===r){if(Jo(i,t))return;e.uniformMatrix2fv(this.addr,!1,t),el(i,t)}else{if(Jo(i,r))return;Zo.set(r),e.uniformMatrix2fv(this.addr,!1,Zo),el(i,r)}}function ol(e,t){const i=this.cache,r=t.elements;if(void 0===r){if(Jo(i,t))return;e.uniformMatrix3fv(this.addr,!1,t),el(i,t)}else{if(Jo(i,r))return;Ko.set(r),e.uniformMatrix3fv(this.addr,!1,Ko),el(i,r)}}function ll(e,t){const i=this.cache,r=t.elements;if(void 0===r){if(Jo(i,t))return;e.uniformMatrix4fv(this.addr,!1,t),el(i,t)}else{if(Jo(i,r))return;Yo.set(r),e.uniformMatrix4fv(this.addr,!1,Yo),el(i,r)}}function ul(e,t){const i=this.cache;i[0]!==t&&(e.uniform1i(this.addr,t),i[0]=t)}function cl(e,t){const i=this.cache;if(void 0!==t.x)i[0]===t.x&&i[1]===t.y||(e.uniform2i(this.addr,t.x,t.y),i[0]=t.x,i[1]=t.y);else{if(Jo(i,t))return;e.uniform2iv(this.addr,t),el(i,t)}}function hl(e,t){const i=this.cache;if(void 0!==t.x)i[0]===t.x&&i[1]===t.y&&i[2]===t.z||(e.uniform3i(this.addr,t.x,t.y,t.z),i[0]=t.x,i[1]=t.y,i[2]=t.z);else{if(Jo(i,t))return;e.uniform3iv(this.addr,t),el(i,t)}}function dl(e,t){const i=this.cache;if(void 0!==t.x)i[0]===t.x&&i[1]===t.y&&i[2]===t.z&&i[3]===t.w||(e.uniform4i(this.addr,t.x,t.y,t.z,t.w),i[0]=t.x,i[1]=t.y,i[2]=t.z,i[3]=t.w);else{if(Jo(i,t))return;e.uniform4iv(this.addr,t),el(i,t)}}function pl(e,t){const i=this.cache;i[0]!==t&&(e.uniform1ui(this.addr,t),i[0]=t)}function fl(e,t){const i=this.cache;if(void 0!==t.x)i[0]===t.x&&i[1]===t.y||(e.uniform2ui(this.addr,t.x,t.y),i[0]=t.x,i[1]=t.y);else{if(Jo(i,t))return;e.uniform2uiv(this.addr,t),el(i,t)}}function ml(e,t){const i=this.cache;if(void 0!==t.x)i[0]===t.x&&i[1]===t.y&&i[2]===t.z||(e.uniform3ui(this.addr,t.x,t.y,t.z),i[0]=t.x,i[1]=t.y,i[2]=t.z);else{if(Jo(i,t))return;e.uniform3uiv(this.addr,t),el(i,t)}}function gl(e,t){const i=this.cache;if(void 0!==t.x)i[0]===t.x&&i[1]===t.y&&i[2]===t.z&&i[3]===t.w||(e.uniform4ui(this.addr,t.x,t.y,t.z,t.w),i[0]=t.x,i[1]=t.y,i[2]=t.z,i[3]=t.w);else{if(Jo(i,t))return;e.uniform4uiv(this.addr,t),el(i,t)}}function _l(e){return 0===e.version&&(e.compareFunction=si,e.needsUpdate=!0),e}function vl(e,t,i){const r=this.cache,n=i.allocateTextureUnit();let s;r[0]!==n&&(e.uniform1i(this.addr,n),r[0]=n),s=this.type===e.SAMPLER_2D_SHADOW?_l(Vo):Go,i.setTexture2D(t||s,n)}function bl(e,t,i){const r=this.cache,n=i.allocateTextureUnit();r[0]!==n&&(e.uniform1i(this.addr,n),r[0]=n),i.setTexture3D(t||jo,n)}function yl(e,t,i){const r=this.cache,n=i.allocateTextureUnit();let s;r[0]!==n&&(e.uniform1i(this.addr,n),r[0]=n),s=this.type===e.SAMPLER_CUBE_SHADOW?_l(Ho):$o,i.setTextureCube(t||s,n)}function xl(e,t,i){const r=this.cache,n=i.allocateTextureUnit();r[0]!==n&&(e.uniform1i(this.addr,n),r[0]=n),i.setTexture2DArray(t||Wo,n)}function Sl(e,t){e.uniform1fv(this.addr,t)}function Tl(e,t){const i=Qo(t,this.size,2);e.uniform2fv(this.addr,i)}function Ml(e,t){const i=Qo(t,this.size,3);e.uniform3fv(this.addr,i)}function El(e,t){const i=Qo(t,this.size,4);e.uniform4fv(this.addr,i)}function wl(e,t){const i=Qo(t,this.size,4);e.uniformMatrix2fv(this.addr,!1,i)}function Al(e,t){const i=Qo(t,this.size,9);e.uniformMatrix3fv(this.addr,!1,i)}function Rl(e,t){const i=Qo(t,this.size,16);e.uniformMatrix4fv(this.addr,!1,i)}function Cl(e,t){e.uniform1iv(this.addr,t)}function Nl(e,t){e.uniform2iv(this.addr,t)}function Pl(e,t){e.uniform3iv(this.addr,t)}function Ll(e,t){e.uniform4iv(this.addr,t)}function Dl(e,t){e.uniform1uiv(this.addr,t)}function Ul(e,t){e.uniform2uiv(this.addr,t)}function Il(e,t){e.uniform3uiv(this.addr,t)}function Fl(e,t){e.uniform4uiv(this.addr,t)}function Ol(e,t,i){const r=this.cache,n=t.length,s=tl(i,n);let a;Jo(r,s)||(e.uniform1iv(this.addr,s),el(r,s)),a=this.type===e.SAMPLER_2D_SHADOW?_l(Vo):Go;for(let e=0;e!==n;++e)i.setTexture2D(t[e]||a,s[e])}function Bl(e,t,i){const r=this.cache,n=t.length,s=tl(i,n);Jo(r,s)||(e.uniform1iv(this.addr,s),el(r,s));for(let e=0;e!==n;++e)i.setTexture3D(t[e]||jo,s[e])}function kl(e,t,i){const r=this.cache,n=t.length,s=tl(i,n);let a;Jo(r,s)||(e.uniform1iv(this.addr,s),el(r,s)),a=this.type===e.SAMPLER_CUBE_SHADOW?_l(Ho):$o;for(let e=0;e!==n;++e)i.setTextureCube(t[e]||a,s[e])}function zl(e,t,i){const r=this.cache,n=t.length,s=tl(i,n);Jo(r,s)||(e.uniform1iv(this.addr,s),el(r,s));for(let e=0;e!==n;++e)i.setTexture2DArray(t[e]||Wo,s[e])}class Gl{constructor(e,t,i){this.id=e,this.addr=i,this.cache=[],this.type=t.type,this.setValue=function(e){switch(e){case 5126:return il;case 35664:return rl;case 35665:return nl;case 35666:return sl;case 35674:return al;case 35675:return ol;case 35676:return ll;case 5124:case 35670:return ul;case 35667:case 35671:return cl;case 35668:case 35672:return hl;case 35669:case 35673:return dl;case 5125:return pl;case 36294:return fl;case 36295:return ml;case 36296:return gl;case 35678:case 36198:case 36298:case 36306:case 35682:return vl;case 35679:case 36299:case 36307:return bl;case 35680:case 36300:case 36308:case 36293:return yl;case 36289:case 36303:case 36311:case 36292:return xl}}(t.type)}}class Vl{constructor(e,t,i){this.id=e,this.addr=i,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=function(e){switch(e){case 5126:return Sl;case 35664:return Tl;case 35665:return Ml;case 35666:return El;case 35674:return wl;case 35675:return Al;case 35676:return Rl;case 5124:case 35670:return Cl;case 35667:case 35671:return Nl;case 35668:case 35672:return Pl;case 35669:case 35673:return Ll;case 5125:return Dl;case 36294:return Ul;case 36295:return Il;case 36296:return Fl;case 35678:case 36198:case 36298:case 36306:case 35682:return Ol;case 35679:case 36299:case 36307:return Bl;case 35680:case 36300:case 36308:case 36293:return kl;case 36289:case 36303:case 36311:case 36292:return zl}}(t.type)}}class Hl{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,i){const r=this.seq;for(let n=0,s=r.length;n!==s;++n){const s=r[n];s.setValue(e,t[s.id],i)}}}const Wl=/(\w+)(\])?(\[|\.)?/g;function jl(e,t){e.seq.push(t),e.map[t.id]=t}function $l(e,t,i){const r=e.name,n=r.length;for(Wl.lastIndex=0;;){const s=Wl.exec(r),a=Wl.lastIndex;let o=s[1];const l="]"===s[2],u=s[3];if(l&&(o|=0),void 0===u||"["===u&&a+2===n){jl(i,void 0===u?new Gl(o,e,t):new Vl(o,e,t));break}{let e=i.map[o];void 0===e&&(e=new Hl(o),jl(i,e)),i=e}}}class Xl{constructor(e,t){this.seq=[],this.map={};const i=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let r=0;r<i;++r){const i=e.getActiveUniform(t,r);$l(i,e.getUniformLocation(t,i.name),this)}const r=[],n=[];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?r.push(t):n.push(t);r.length>0&&(this.seq=r.concat(n))}setValue(e,t,i,r){const n=this.map[t];void 0!==n&&n.setValue(e,i,r)}setOptional(e,t,i){const r=t[i];void 0!==r&&this.setValue(e,i,r)}static upload(e,t,i,r){for(let n=0,s=t.length;n!==s;++n){const s=t[n],a=i[s.id];!1!==a.needsUpdate&&s.setValue(e,a.value,r)}}static seqWithValue(e,t){const i=[];for(let r=0,n=e.length;r!==n;++r){const n=e[r];n.id in t&&i.push(n)}return i}}function ql(e,t,i){const r=e.createShader(t);return e.shaderSource(r,i),e.compileShader(r),r}let Yl=0;const Kl=new Xi;function Zl(e,t,i){const r=e.getShaderParameter(t,e.COMPILE_STATUS),n=(e.getShaderInfoLog(t)||"").trim();if(r&&""===n)return"";const s=/ERROR: 0:(\d+)/.exec(n);if(s){const r=parseInt(s[1]);return i.toUpperCase()+"\n\n"+n+"\n\n"+function(e,t){const i=e.split("\n"),r=[],n=Math.max(t-6,0),s=Math.min(t+6,i.length);for(let e=n;e<s;e++){const n=e+1;r.push(`${n===t?">":" "} ${n}: ${i[e]}`)}return r.join("\n")}(e.getShaderSource(t),r)}return n}function Ql(e,t){const i=function(e){Qi._getMatrix(Kl,Qi.workingColorSpace,e);const t=`mat3( ${Kl.elements.map(e=>e.toFixed(4))} )`;switch(Qi.getTransfer(e)){case Yt:return[t,"LinearTransferOETF"];case Kt:return[t,"sRGBTransferOETF"];default:return Ti("WebGLProgram: Unsupported color space: ",e),[t,"LinearTransferOETF"]}}(t);return[`vec4 ${e}( vec4 value ) {`,`\treturn ${i[1]}( vec4( ${i[0]} * value.rgb, value.a ) );`,"}"].join("\n")}const Jl={[ye]:"Linear",[xe]:"Reinhard",[Se]:"Cineon",[Te]:"ACESFilmic",[Ee]:"AgX",[we]:"Neutral",[Me]:"Custom"};function eu(e,t){const i=Jl[t];return void 0===i?(Ti("WebGLProgram: Unsupported toneMapping:",t),"vec3 "+e+"( vec3 color ) { return LinearToneMapping( color ); }"):"vec3 "+e+"( vec3 color ) { return "+i+"ToneMapping( color ); }"}const tu=new Wi;function iu(){Qi.getLuminanceCoefficients(tu);return["float luminance( const in vec3 rgb ) {",`\tconst vec3 weights = vec3( ${tu.x.toFixed(4)}, ${tu.y.toFixed(4)}, ${tu.z.toFixed(4)} );`,"\treturn dot( weights, rgb );","}"].join("\n")}function ru(e){return""!==e}function nu(e,t){const i=t.numSpotLightShadows+t.numSpotLightMaps-t.numSpotLightShadowsWithMaps;return e.replace(/NUM_SUN_LIGHTS/g,t.numSunLights).replace(/NUM_DIR_LIGHTS/g,t.numDirLights).replace(/NUM_SPOT_LIGHTS/g,t.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,t.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,i).replace(/NUM_RECT_AREA_LIGHTS/g,t.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,t.numPointLights).replace(/NUM_HEMI_LIGHTS/g,t.numHemiLights).replace(/NUM_SUN_LIGHT_SHADOWS/g,t.numSunLightShadows).replace(/NUM_DIR_LIGHT_SHADOWS/g,t.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,t.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,t.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,t.numPointLightShadows).replace(/NUM_LIGHT_PROBE_GRIDS/g,t.numLightProbeGrids)}function su(e,t){return e.replace(/NUM_CLIPPING_PLANES/g,t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,t.numClippingPlanes-t.numClipIntersection)}const au=/^[ \t]*#include +<([\w\d./]+)>/gm;function ou(e){return e.replace(au,lu)}function lu(e,t){const i=po[t];if(void 0===i)throw new Error("THREE.WebGLProgram: Can not resolve #include <"+t+">");return ou(i)}const uu=/#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 cu(e){return e.replace(uu,hu)}function hu(e,t,i,r){let n="";for(let e=parseInt(t);e<parseInt(i);e++)n+=r.replace(/\[\s*i\s*\]/g,"[ "+e+" ]").replace(/UNROLLED_LOOP_INDEX/g,e);return n}function du(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 pu={[B]:"SHADOWMAP_TYPE_PCF",[k]:"SHADOWMAP_TYPE_VSM"};const fu={[Re]:"ENVMAP_MODE_REFRACTION"};const mu={[_e]:"ENVMAP_BLENDING_MULTIPLY",[ve]:"ENVMAP_BLENDING_MIX",[be]:"ENVMAP_BLENDING_ADD"};function gu(e,t,i,r){const n=e.getContext(),s=i.defines;let a=i.vertexShader,o=i.fragmentShader;const l=function(e){return pu[e.shadowMapType]||"SHADOWMAP_TYPE_BASIC"}(i),u=!0===i.envMapPMREM?"ENVMAP_TYPE_PMREM":"ENVMAP_TYPE_CUBE",c=function(e){return!1===e.envMap?"ENVMAP_MODE_REFLECTION":fu[e.envMapMode]||"ENVMAP_MODE_REFLECTION"}(i),h=function(e){return!1===e.envMap?"ENVMAP_BLENDING_NONE":mu[e.combine]||"ENVMAP_BLENDING_NONE"}(i),d=function(e){return[e.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",e.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(ru).join("\n")}(i),p=function(e){const t=[];for(const i in e){const r=e[i];!1!==r&&t.push("#define "+i+" "+r)}return t.join("\n")}(s),f=n.createProgram();let m,g,_=i.glslVersion?"#version "+i.glslVersion+"\n":"";i.isRawShaderMaterial?(m=["#define SHADER_TYPE "+i.shaderType,"#define SHADER_NAME "+i.shaderName,p].filter(ru).join("\n"),m.length>0&&(m+="\n"),g=["#define SHADER_TYPE "+i.shaderType,"#define SHADER_NAME "+i.shaderName,p].filter(ru).join("\n"),g.length>0&&(g+="\n")):(m=[du(i),"#define SHADER_TYPE "+i.shaderType,"#define SHADER_NAME "+i.shaderName,p,i.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",i.batching?"#define USE_BATCHING":"",i.batchingColor?"#define USE_BATCHING_COLOR":"",i.instancing?"#define USE_INSTANCING":"",i.instancingColor?"#define USE_INSTANCING_COLOR":"",i.instancingMorph?"#define USE_INSTANCING_MORPH":"",i.useFog&&i.fog?"#define USE_FOG":"",i.useFog&&i.fogExp2?"#define FOG_EXP2":"",i.map?"#define USE_MAP":"",i.envMap?"#define USE_ENVMAP":"",i.envMap?"#define "+c:"",i.lightMap?"#define USE_LIGHTMAP":"",i.aoMap?"#define USE_AOMAP":"",i.bumpMap?"#define USE_BUMPMAP":"",i.normalMap?"#define USE_NORMALMAP":"",i.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",i.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",i.displacementMap?"#define USE_DISPLACEMENTMAP":"",i.emissiveMap?"#define USE_EMISSIVEMAP":"",i.anisotropy?"#define USE_ANISOTROPY":"",i.anisotropyMap?"#define USE_ANISOTROPYMAP":"",i.clearcoatMap?"#define USE_CLEARCOATMAP":"",i.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",i.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",i.diffuseRoughnessMap?"#define USE_DIFFUSE_ROUGHNESSMAP":"",i.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",i.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",i.specularMap?"#define USE_SPECULARMAP":"",i.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",i.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",i.roughnessMap?"#define USE_ROUGHNESSMAP":"",i.metalnessMap?"#define USE_METALNESSMAP":"",i.alphaMap?"#define USE_ALPHAMAP":"",i.alphaHash?"#define USE_ALPHAHASH":"",i.transmission?"#define USE_TRANSMISSION":"",i.transmissionMap?"#define USE_TRANSMISSIONMAP":"",i.thicknessMap?"#define USE_THICKNESSMAP":"",i.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",i.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",i.mapUv?"#define MAP_UV "+i.mapUv:"",i.alphaMapUv?"#define ALPHAMAP_UV "+i.alphaMapUv:"",i.lightMapUv?"#define LIGHTMAP_UV "+i.lightMapUv:"",i.aoMapUv?"#define AOMAP_UV "+i.aoMapUv:"",i.emissiveMapUv?"#define EMISSIVEMAP_UV "+i.emissiveMapUv:"",i.bumpMapUv?"#define BUMPMAP_UV "+i.bumpMapUv:"",i.normalMapUv?"#define NORMALMAP_UV "+i.normalMapUv:"",i.displacementMapUv?"#define DISPLACEMENTMAP_UV "+i.displacementMapUv:"",i.metalnessMapUv?"#define METALNESSMAP_UV "+i.metalnessMapUv:"",i.roughnessMapUv?"#define ROUGHNESSMAP_UV "+i.roughnessMapUv:"",i.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+i.anisotropyMapUv:"",i.clearcoatMapUv?"#define CLEARCOATMAP_UV "+i.clearcoatMapUv:"",i.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+i.clearcoatNormalMapUv:"",i.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+i.clearcoatRoughnessMapUv:"",i.diffuseRoughnessMapUv?"#define DIFFUSE_ROUGHNESSMAP_UV "+i.diffuseRoughnessMapUv:"",i.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+i.iridescenceMapUv:"",i.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+i.iridescenceThicknessMapUv:"",i.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+i.sheenColorMapUv:"",i.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+i.sheenRoughnessMapUv:"",i.specularMapUv?"#define SPECULARMAP_UV "+i.specularMapUv:"",i.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+i.specularColorMapUv:"",i.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+i.specularIntensityMapUv:"",i.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+i.transmissionMapUv:"",i.thicknessMapUv?"#define THICKNESSMAP_UV "+i.thicknessMapUv:"",i.vertexTangents&&!1===i.flatShading?"#define USE_TANGENT":"",i.vertexNormals?"#define HAS_NORMAL":"",i.vertexColors?"#define USE_COLOR":"",i.vertexAlphas?"#define USE_COLOR_ALPHA":"",i.vertexUv1s?"#define USE_UV1":"",i.vertexUv2s?"#define USE_UV2":"",i.vertexUv3s?"#define USE_UV3":"",i.pointsUvs?"#define USE_POINTS_UV":"",i.flatShading?"#define FLAT_SHADED":"",i.skinning?"#define USE_SKINNING":"",i.morphTargets?"#define USE_MORPHTARGETS":"",i.morphNormals&&!1===i.flatShading?"#define USE_MORPHNORMALS":"",i.morphColors?"#define USE_MORPHCOLORS":"",i.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+i.morphTextureStride:"",i.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+i.morphTargetsCount:"",i.doubleSided?"#define DOUBLE_SIDED":"",i.flipSided?"#define FLIP_SIDED":"",i.shadowMapEnabled?"#define USE_SHADOWMAP":"",i.shadowMapEnabled?"#define "+l:"",i.sizeAttenuation?"#define USE_SIZEATTENUATION":"",i.numLightProbes>0?"#define USE_LIGHT_PROBES":"",i.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",i.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(ru).join("\n"),g=[du(i),"#define SHADER_TYPE "+i.shaderType,"#define SHADER_NAME "+i.shaderName,p,i.useFog&&i.fog?"#define USE_FOG":"",i.useFog&&i.fogExp2?"#define FOG_EXP2":"",i.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",i.map?"#define USE_MAP":"",i.matcap?"#define USE_MATCAP":"",i.envMap?"#define USE_ENVMAP":"",i.envMap?"#define "+u:"",i.envMap?"#define "+c:"",i.envMap?"#define "+h:"",i.envMapPMREM?"#define ENVMAP_MAX_LOD "+i.envMapMaxLod+".0":"",i.envMapPMREM?"#define ENVMAP_SIZE "+i.envMapSize+".0":"",i.lightMap?"#define USE_LIGHTMAP":"",i.aoMap?"#define USE_AOMAP":"",i.bumpMap?"#define USE_BUMPMAP":"",i.normalMap?"#define USE_NORMALMAP":"",i.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",i.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",i.packedNormalMap?"#define USE_PACKED_NORMALMAP":"",i.emissiveMap?"#define USE_EMISSIVEMAP":"",i.anisotropy?"#define USE_ANISOTROPY":"",i.anisotropyMap?"#define USE_ANISOTROPYMAP":"",i.clearcoat?"#define USE_CLEARCOAT":"",i.clearcoatMap?"#define USE_CLEARCOATMAP":"",i.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",i.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",i.diffuseRoughness?"#define USE_DIFFUSE_ROUGHNESS":"",i.diffuseRoughnessMap?"#define USE_DIFFUSE_ROUGHNESSMAP":"",i.dispersion?"#define USE_DISPERSION":"",i.retroreflection?"#define USE_RETROREFLECTION":"",i.iridescence?"#define USE_IRIDESCENCE":"",i.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",i.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",i.specularMap?"#define USE_SPECULARMAP":"",i.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",i.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",i.roughnessMap?"#define USE_ROUGHNESSMAP":"",i.metalnessMap?"#define USE_METALNESSMAP":"",i.alphaMap?"#define USE_ALPHAMAP":"",i.alphaTest?"#define USE_ALPHATEST":"",i.alphaHash?"#define USE_ALPHAHASH":"",i.sheen?"#define USE_SHEEN":"",i.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",i.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",i.transmission?"#define USE_TRANSMISSION":"",i.transmissionMap?"#define USE_TRANSMISSIONMAP":"",i.thicknessMap?"#define USE_THICKNESSMAP":"",i.vertexTangents&&!1===i.flatShading?"#define USE_TANGENT":"",i.vertexColors||i.instancingColor?"#define USE_COLOR":"",i.vertexAlphas||i.batchingColor?"#define USE_COLOR_ALPHA":"",i.vertexUv1s?"#define USE_UV1":"",i.vertexUv2s?"#define USE_UV2":"",i.vertexUv3s?"#define USE_UV3":"",i.pointsUvs?"#define USE_POINTS_UV":"",i.gradientMap?"#define USE_GRADIENTMAP":"",i.flatShading?"#define FLAT_SHADED":"",i.doubleSided?"#define DOUBLE_SIDED":"",i.flipSided?"#define FLIP_SIDED":"",i.shadowMapEnabled?"#define USE_SHADOWMAP":"",i.shadowMapEnabled?"#define "+l:"",i.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",i.numLightProbes>0?"#define USE_LIGHT_PROBES":"",i.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",i.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",i.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",i.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",0!==i.toneMapping?"#define TONE_MAPPING":"",0!==i.toneMapping?po.tonemapping_pars_fragment:"",0!==i.toneMapping?eu("toneMapping",i.toneMapping):"",i.dithering?"#define DITHERING":"",i.opaque?"#define OPAQUE":"",po.colorspace_pars_fragment,Ql("linearToOutputTexel",i.outputColorSpace),iu(),i.useDepthPacking?"#define DEPTH_PACKING "+i.depthPacking:"","\n"].filter(ru).join("\n")),a=ou(a),a=nu(a,i),a=su(a,i),o=ou(o),o=nu(o,i),o=su(o,i),a=cu(a),o=cu(o),!0!==i.isRawShaderMaterial&&(_="#version 300 es\n",m=[d,"#define attribute in","#define varying out","#define texture2D texture"].join("\n")+"\n"+m,g=["#define varying in",i.glslVersion===li?"":"layout(location = 0) out highp vec4 pc_fragColor;",i.glslVersion===li?"":"#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"+g);const v=_+m+a,b=_+g+o,y=ql(n,n.VERTEX_SHADER,v),x=ql(n,n.FRAGMENT_SHADER,b);function S(t){if(e.debug.checkShaderErrors){const i=n.getProgramInfoLog(f)||"",r=n.getShaderInfoLog(y)||"",s=n.getShaderInfoLog(x)||"",a=i.trim(),o=r.trim(),l=s.trim();let u=!0,c=!0;if(!1===n.getProgramParameter(f,n.LINK_STATUS))if(u=!1,"function"==typeof e.debug.onShaderError)e.debug.onShaderError(n,f,y,x);else{const e=Zl(n,y,"vertex"),i=Zl(n,x,"fragment");Mi("WebGLProgram: Shader Error "+n.getError()+" - VALIDATE_STATUS "+n.getProgramParameter(f,n.VALIDATE_STATUS)+"\n\nMaterial Name: "+t.name+"\nMaterial Type: "+t.type+"\n\nProgram Info Log: "+a+"\n"+e+"\n"+i)}else""!==a?Ti("WebGLProgram: Program Info Log:",a):""!==o&&""!==l||(c=!1);c&&(t.diagnostics={runnable:u,programLog:a,vertexShader:{log:o,prefix:m},fragmentShader:{log:l,prefix:g}})}n.deleteShader(y),n.deleteShader(x),T=new Xl(n,f),M=function(e,t){const i={},r=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let n=0;n<r;n++){const r=e.getActiveAttrib(t,n),s=r.name;let a=1;r.type===e.FLOAT_MAT2&&(a=2),r.type===e.FLOAT_MAT3&&(a=3),r.type===e.FLOAT_MAT4&&(a=4),i[s]={type:r.type,location:e.getAttribLocation(t,s),locationSize:a}}return i}(n,f)}let T,M;n.attachShader(f,y),n.attachShader(f,x),void 0!==i.index0AttributeName?n.bindAttribLocation(f,0,i.index0AttributeName):!0===i.hasPositionAttribute&&n.bindAttribLocation(f,0,"position"),n.linkProgram(f),this.getUniforms=function(){return void 0===T&&S(this),T},this.getAttributes=function(){return void 0===M&&S(this),M};let E=!1===i.rendererExtensionParallelShaderCompile;return this.isReady=function(){return!1===E&&(E=n.getProgramParameter(f,37297)),E},this.destroy=function(){r.releaseStatesOfProgram(this),n.deleteProgram(f),this.program=void 0},this.type=i.shaderType,this.name=i.shaderName,this.id=Yl++,this.cacheKey=t,this.usedTimes=1,this.program=f,this.vertexShader=y,this.fragmentShader=x,this}let _u=0;class vu{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e,t,i){const r=this._getShaderCacheForMaterial(e);return!1===r.has(t)&&(r.add(t),t.usedTimes++),!1===r.has(i)&&(r.add(i),i.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}getVertexShaderStage(e){return this._getShaderStage(e.vertexShader)}getFragmentShaderStage(e){return this._getShaderStage(e.fragmentShader)}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let i=t.get(e);return void 0===i&&(i=new Set,t.set(e,i)),i}_getShaderStage(e){const t=this.shaderCache;let i=t.get(e);return void 0===i&&(i=new bu(e),t.set(e,i)),i}}class bu{constructor(e){this.id=_u++,this.code=e,this.usedTimes=0}}function yu(e){return e===at||e===Tt||e===Wt}function xu(e,t,i,r,n,s){const a=new Er,o=new vu,l=new Set,u=[],c=new Map,h=r.logarithmicDepthBuffer,d={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 p(e){return l.add(e),0===e?"uv":`uv${e}`}return{getParameters:function(n,a,u,c,f,m){const g=c.fog,_=f.geometry,v=n.isMeshStandardMaterial||n.isMeshLambertMaterial||n.isMeshPhongMaterial?c.environment:null,b=n.isMeshStandardMaterial||n.isMeshLambertMaterial&&!n.envMap||n.isMeshPhongMaterial&&!n.envMap,y=t.get(n.envMap||v,b),x=d[n.type];let S=r.precision;null!==n.precision&&(S=r.getMaxPrecision(n.precision),S!==n.precision&&Ti("WebGLProgram.getParameters:",n.precision,"not supported, using",S,"instead."));const T=_.morphAttributes.position||_.morphAttributes.normal||_.morphAttributes.color,M=void 0!==T?T.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),x){const e=mo[x];E=e.vertexShader,w=e.fragmentShader}else{E=n.vertexShader,w=n.fragmentShader;const e=o.getVertexShaderStage(n),t=o.getFragmentShaderStage(n);o.update(n,e,t),A=e.id,R=t.id}const N=e.getRenderTarget(),P=e.state.buffers.depth.getReversed(),L=!0===f.isInstancedMesh,D=!0===f.isBatchedMesh,U=!!n.map,I=!!n.matcap,F=!!y,O=F&&!0===y.isPMREMTexture,B=!!n.aoMap,k=!!n.lightMap,z=!!n.bumpMap&&!1===n.wireframe,G=!!n.normalMap,V=!!n.displacementMap,H=!!n.emissiveMap,W=!!n.metalnessMap,j=!!n.roughnessMap,$=n.anisotropy>0,X=n.clearcoat>0,q=n.diffuseRoughness>0,Y=n.dispersion>0,K=n.retroreflectivity>0,Z=n.iridescence>0,Q=n.sheen>0,J=n.transmission>0,ee=$&&!!n.anisotropyMap,te=X&&!!n.clearcoatMap,ie=X&&!!n.clearcoatNormalMap,re=X&&!!n.clearcoatRoughnessMap,ne=q&&!!n.diffuseRoughnessMap,se=Z&&!!n.iridescenceMap,ae=Z&&!!n.iridescenceThicknessMap,oe=Q&&!!n.sheenColorMap,le=Q&&!!n.sheenRoughnessMap,ue=!!n.specularMap,ce=!!n.specularColorMap,he=!!n.specularIntensityMap,de=J&&!!n.transmissionMap,pe=J&&!!n.thicknessMap,fe=!!n.gradientMap,me=!!n.alphaMap,ge=n.alphaTest>0,_e=!!n.alphaHash,ve=!!n.extensions;let be=0;n.toneMapped&&(null!==N&&!0!==N.isXRRenderTarget||(be=e.toneMapping));const ye=O?y.isCompressedCubeTexture?y.image[0].mipmaps:y.mipmaps:null,xe={shaderID:x,shaderType:n.type,shaderName:n.name,vertexShader:E,fragmentShader:w,defines:n.defines,customVertexShaderID:A,customFragmentShaderID:R,isRawShaderMaterial:!0===n.isRawShaderMaterial,glslVersion:n.glslVersion,precision:S,batching:D,batchingColor:D&&null!==f._colorsTexture,instancing:L,instancingColor:L&&null!==f.instanceColor,instancingMorph:L&&null!==f.morphTexture,outputColorSpace:null===N?e.outputColorSpace:!0===N.isXRRenderTarget?N.texture.colorSpace:Qi.workingColorSpace,alphaToCoverage:!!n.alphaToCoverage,map:U,matcap:I,envMap:F,envMapMode:F&&y.mapping,envMapPMREM:O,envMapMaxLod:O?ye.length-1:null,envMapSize:O?ye[0].width:null,aoMap:B,lightMap:k,bumpMap:z,normalMap:G,displacementMap:V,emissiveMap:H,normalMapObjectSpace:G&&1===n.normalMapType,normalMapTangentSpace:G&&0===n.normalMapType,packedNormalMap:G&&0===n.normalMapType&&yu(n.normalMap.format),metalnessMap:W,roughnessMap:j,anisotropy:$,anisotropyMap:ee,clearcoat:X,clearcoatMap:te,clearcoatNormalMap:ie,clearcoatRoughnessMap:re,diffuseRoughness:q,diffuseRoughnessMap:ne,dispersion:Y,retroreflection:K,iridescence:Z,iridescenceMap:se,iridescenceThicknessMap:ae,sheen:Q,sheenColorMap:oe,sheenRoughnessMap:le,specularMap:ue,specularColorMap:ce,specularIntensityMap:he,transmission:J,transmissionMap:de,thicknessMap:pe,gradientMap:fe,opaque:!1===n.transparent&&1===n.blending&&!1===n.alphaToCoverage,alphaMap:me,alphaTest:ge,alphaHash:_e,combine:n.combine,mapUv:U&&p(n.map.channel),aoMapUv:B&&p(n.aoMap.channel),lightMapUv:k&&p(n.lightMap.channel),bumpMapUv:z&&p(n.bumpMap.channel),normalMapUv:G&&p(n.normalMap.channel),displacementMapUv:V&&p(n.displacementMap.channel),emissiveMapUv:H&&p(n.emissiveMap.channel),metalnessMapUv:W&&p(n.metalnessMap.channel),roughnessMapUv:j&&p(n.roughnessMap.channel),anisotropyMapUv:ee&&p(n.anisotropyMap.channel),clearcoatMapUv:te&&p(n.clearcoatMap.channel),clearcoatNormalMapUv:ie&&p(n.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:re&&p(n.clearcoatRoughnessMap.channel),diffuseRoughnessMapUv:ne&&p(n.diffuseRoughnessMap.channel),iridescenceMapUv:se&&p(n.iridescenceMap.channel),iridescenceThicknessMapUv:ae&&p(n.iridescenceThicknessMap.channel),sheenColorMapUv:oe&&p(n.sheenColorMap.channel),sheenRoughnessMapUv:le&&p(n.sheenRoughnessMap.channel),specularMapUv:ue&&p(n.specularMap.channel),specularColorMapUv:ce&&p(n.specularColorMap.channel),specularIntensityMapUv:he&&p(n.specularIntensityMap.channel),transmissionMapUv:de&&p(n.transmissionMap.channel),thicknessMapUv:pe&&p(n.thicknessMap.channel),alphaMapUv:me&&p(n.alphaMap.channel),vertexTangents:!!_.attributes.tangent&&(G||$),vertexNormals:!!_.attributes.normal,vertexColors:n.vertexColors,vertexAlphas:!0===n.vertexColors&&!!_.attributes.color&&4===_.attributes.color.itemSize,pointsUvs:!0===f.isPoints&&!!_.attributes.uv&&(U||me),fog:!!g,useFog:!0===n.fog,fogExp2:!!g&&g.isFogExp2,flatShading:!1===n.wireframe&&(!0===n.flatShading||void 0===_.attributes.normal&&!1===G&&(n.isMeshLambertMaterial||n.isMeshPhongMaterial||n.isMeshStandardMaterial||n.isMeshPhysicalMaterial)),sizeAttenuation:!0===n.sizeAttenuation,logarithmicDepthBuffer:h,reversedDepthBuffer:P,skinning:!0===f.isSkinnedMesh,hasPositionAttribute:void 0!==_.attributes.position,morphTargets:void 0!==_.morphAttributes.position,morphNormals:void 0!==_.morphAttributes.normal,morphColors:void 0!==_.morphAttributes.color,morphTargetsCount:M,morphTextureStride:C,numSunLights:a.sun.length,numDirLights:a.directional.length,numPointLights:a.point.length,numSpotLights:a.spot.length,numSpotLightMaps:a.spotLightMap.length,numRectAreaLights:a.rectArea.length,numHemiLights:a.hemi.length,numSunLightShadows:a.sunShadowMap.length,numDirLightShadows:a.directionalShadowMap.length,numPointLightShadows:a.pointShadowMap.length,numSpotLightShadows:a.spotShadowMap.length,numSpotLightShadowsWithMaps:a.numSpotLightShadowsWithMaps,numLightProbes:a.numLightProbes,numLightProbeGrids:m.filter(e=>null!==e.texture).length,numClippingPlanes:s.numPlanes,numClipIntersection:s.numIntersection,dithering:n.dithering,shadowMapEnabled:e.shadowMap.enabled&&u.length>0,shadowMapType:e.shadowMap.type,toneMapping:be,decodeVideoTexture:U&&!0===n.map.isVideoTexture&&Qi.getTransfer(n.map.colorSpace)===Kt,decodeVideoTextureEmissive:H&&!0===n.emissiveMap.isVideoTexture&&Qi.getTransfer(n.emissiveMap.colorSpace)===Kt,premultipliedAlpha:n.premultipliedAlpha,doubleSided:2===n.side,flipSided:1===n.side,useDepthPacking:n.depthPacking>=0,depthPacking:n.depthPacking||0,index0AttributeName:n.index0AttributeName,extensionClipCullDistance:ve&&!0===n.extensions.clipCullDistance&&i.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(ve&&!0===n.extensions.multiDraw||D)&&i.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:i.has("KHR_parallel_shader_compile"),customProgramCacheKey:n.customProgramCacheKey()};return xe.vertexUv1s=l.has(1),xe.vertexUv2s=l.has(2),xe.vertexUv3s=l.has(3),l.clear(),xe},getProgramCacheKey:function(t){const i=[];if(t.shaderID?i.push(t.shaderID):(i.push(t.customVertexShaderID),i.push(t.customFragmentShaderID)),void 0!==t.defines)for(const e in t.defines)i.push(e),i.push(t.defines[e]);return!1===t.isRawShaderMaterial&&(!function(e,t){e.push(t.precision),e.push(t.outputColorSpace),e.push(t.envMapMode),e.push(t.envMapPMREM),e.push(t.envMapMaxLod),e.push(t.envMapSize),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.diffuseRoughnessMapUv),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.numSunLights),e.push(t.numDirLights),e.push(t.numPointLights),e.push(t.numSpotLights),e.push(t.numSpotLightMaps),e.push(t.numHemiLights),e.push(t.numRectAreaLights),e.push(t.numSunLightShadows),e.push(t.numDirLightShadows),e.push(t.numPointLightShadows),e.push(t.numSpotLightShadows),e.push(t.numSpotLightShadowsWithMaps),e.push(t.numLightProbes),e.push(t.numLightProbeGrids),e.push(t.shadowMapType),e.push(t.toneMapping),e.push(t.numClippingPlanes),e.push(t.numClipIntersection),e.push(t.depthPacking)}(i,t),function(e,t){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.retroreflection&&a.enable(24);t.diffuseRoughness&&a.enable(25);t.batchingColor&&a.enable(20);t.gradientMap&&a.enable(21);t.packedNormalMap&&a.enable(22);t.vertexNormals&&a.enable(23);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);t.numLightProbeGrids>0&&a.enable(22);t.hasPositionAttribute&&a.enable(23);e.push(a.mask)}(i,t),i.push(e.outputColorSpace)),i.push(t.customProgramCacheKey),i.join()},getUniforms:function(e){const t=d[e.type];let i;if(t){const e=mo[t];i=oa.clone(e.uniforms)}else i=e.uniforms;return i},acquireProgram:function(t,i){let r=c.get(i);return void 0!==r?++r.usedTimes:(r=new gu(e,i,t,n),u.push(r),c.set(i,r)),r},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 Su(){let e=new WeakMap;return{has:function(t){return e.has(t)},get:function(t){let i=e.get(t);return void 0===i&&(i={},e.set(t,i)),i},remove:function(t){e.delete(t)},update:function(t,i,r){e.get(t)[i]=r},dispose:function(){e=new WeakMap}}}function Tu(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 Mu(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 Eu(){const e=[];let t=0;const i=[],r=[],n=[];function s(e){let t=0;return e.isInstancedMesh&&(t+=2),e.isSkinnedMesh&&(t+=1),t}function a(i,r,n,a,o,l){let u=e[t];return void 0===u?(u={id:i.id,object:i,geometry:r,material:n,materialVariant:s(i),groupOrder:a,renderOrder:i.renderOrder,z:o,group:l},e[t]=u):(u.id=i.id,u.object=i,u.geometry=r,u.material=n,u.materialVariant=s(i),u.groupOrder=a,u.renderOrder=i.renderOrder,u.z=o,u.group=l),t++,u}return{opaque:i,transmissive:r,transparent:n,init:function(){t=0,i.length=0,r.length=0,n.length=0},push:function(e,t,s,o,l,u,c){!0===c.reversedDepth&&(l=-l);const h=a(e,t,s,o,l,u);s.transmission>0?r.push(h):!0===s.transparent?n.push(h):i.push(h)},unshift:function(e,t,s,o,l,u){const c=a(e,t,s,o,l,u);s.transmission>0?r.unshift(c):!0===s.transparent?n.unshift(c):i.unshift(c)},finish:function(){for(let i=t,r=e.length;i<r;i++){const t=e[i];if(null===t.id)break;t.id=null,t.object=null,t.geometry=null,t.material=null,t.group=null}},sort:function(e,t){i.length>1&&i.sort(e||Tu),r.length>1&&r.sort(t||Mu),n.length>1&&n.sort(t||Mu)}}}function wu(){let e=new WeakMap;return{get:function(t,i){const r=e.get(t);let n;return void 0===r?(n=new Eu,e.set(t,[n])):i>=r.length?(n=new Eu,r.push(n)):n=r[i],n},dispose:function(){e=new WeakMap}}}function Au(){const e={};return{get:function(t){if(void 0!==e[t.id])return e[t.id];let i;switch(t.type){case"SunLight":case"DirectionalLight":i={direction:new Wi,color:new Yr};break;case"SpotLight":i={position:new Wi,direction:new Wi,color:new Yr,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":i={position:new Wi,color:new Yr,distance:0,decay:0};break;case"HemisphereLight":i={direction:new Wi,skyColor:new Yr,groundColor:new Yr};break;case"RectAreaLight":i={color:new Yr,position:new Wi,halfWidth:new Wi,halfHeight:new Wi}}return e[t.id]=i,i}}}let Ru=0;function Cu(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+(t.map?1:0)-(e.map?1:0)}function Nu(e){const t=new Au,i=function(){const e={};return{get:function(t){if(void 0!==e[t.id])return e[t.id];let i;switch(t.type){case"SunLight":case"DirectionalLight":case"SpotLight":i={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Vi};break;case"PointLight":i={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Vi,shadowCameraNear:1,shadowCameraFar:1e3}}return e[t.id]=i,i}}}(),r={version:0,hash:{sunLength:-1,directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numSunShadows:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],sun:[],sunShadow:[],sunShadowMap:[],sunShadowMatrix:[],sunShadowCascade:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let e=0;e<9;e++)r.probe.push(new Wi);const n=new Wi,s=new fr,a=new fr;return{setup:function(n){let s=0,a=0,o=0;for(let e=0;e<9;e++)r.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,b=0,y=0,x=0;n.sort(Cu);for(let e=0,S=n.length;e<S;e++){const S=n[e],T=S.color,M=S.intensity,E=S.distance;let w=null;if(S.shadow&&S.shadow.map&&(w=S.shadow.map.texture.format===at?S.shadow.map.texture:S.shadow.map.depthTexture||S.shadow.map.texture),S.isAmbientLight)s+=T.r*M,a+=T.g*M,o+=T.b*M;else if(S.isLightProbe){for(let e=0;e<9;e++)r.probe[e].addScaledVector(S.sh.coefficients[e],M);x++}else if(S.isSunLight){const e=t.get(S);if(e.color.copy(S.color).multiplyScalar(S.intensity),S.castShadow){const e=S.shadow,t=i.get(S);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize.copy(e.mapSize).multiply(e.getFrameExtents()),r.sunShadow[u]=t,r.sunShadowMap[u]=w;const n=e.getViewportCount();for(let t=0;t<n;t++)r.sunShadowMatrix[c+t]=e.getMatrix(t),r.sunShadowCascade[c+t]=e._cascadeData[t];c+=n,u++}r.sun[l]=e,l++}else if(S.isDirectionalLight){const e=t.get(S);if(e.color.copy(S.color).multiplyScalar(S.intensity),S.castShadow){const e=S.shadow,t=i.get(S);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,r.directionalShadow[h]=t,r.directionalShadowMap[h]=w,r.directionalShadowMatrix[h]=S.shadow.matrix,g++}r.directional[h]=e,h++}else if(S.isSpotLight){const e=t.get(S);e.position.setFromMatrixPosition(S.matrixWorld),e.color.copy(T).multiplyScalar(M),e.distance=E,e.coneCos=Math.cos(S.angle),e.penumbraCos=Math.cos(S.angle*(1-S.penumbra)),e.decay=S.decay,r.spot[p]=e;const n=S.shadow;if(S.map&&(r.spotLightMap[b]=S.map,b++,n.updateMatrices(S),S.castShadow&&y++),r.spotLightMatrix[p]=n.matrix,S.castShadow){const e=i.get(S);e.shadowIntensity=n.intensity,e.shadowBias=n.bias,e.shadowNormalBias=n.normalBias,e.shadowRadius=n.radius,e.shadowMapSize=n.mapSize,r.spotShadow[p]=e,r.spotShadowMap[p]=w,v++}p++}else if(S.isRectAreaLight){const e=t.get(S);e.color.copy(T).multiplyScalar(M),e.halfWidth.set(.5*S.width,0,0),e.halfHeight.set(0,.5*S.height,0),r.rectArea[f]=e,f++}else if(S.isPointLight){const e=t.get(S);if(e.color.copy(S.color).multiplyScalar(S.intensity),e.distance=S.distance,e.decay=S.decay,S.castShadow){const e=S.shadow,t=i.get(S);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,t.shadowCameraNear=e.camera.near,t.shadowCameraFar=e.camera.far,r.pointShadow[d]=t,r.pointShadowMap[d]=w,r.pointShadowMatrix[d]=S.shadow.matrix,_++}r.point[d]=e,d++}else if(S.isHemisphereLight){const e=t.get(S);e.skyColor.copy(S.color).multiplyScalar(M),e.groundColor.copy(S.groundColor).multiplyScalar(M),r.hemi[m]=e,m++}}f>0&&(!0===e.has("OES_texture_float_linear")?(r.rectAreaLTC1=fo.LTC_FLOAT_1,r.rectAreaLTC2=fo.LTC_FLOAT_2):(r.rectAreaLTC1=fo.LTC_HALF_1,r.rectAreaLTC2=fo.LTC_HALF_2)),r.ambient[0]=s,r.ambient[1]=a,r.ambient[2]=o;const S=r.hash;S.sunLength===l&&S.directionalLength===h&&S.pointLength===d&&S.spotLength===p&&S.rectAreaLength===f&&S.hemiLength===m&&S.numSunShadows===u&&S.numDirectionalShadows===g&&S.numPointShadows===_&&S.numSpotShadows===v&&S.numSpotMaps===b&&S.numLightProbes===x||(r.sun.length=l,r.directional.length=h,r.spot.length=p,r.rectArea.length=f,r.point.length=d,r.hemi.length=m,r.sunShadow.length=u,r.sunShadowMap.length=u,r.sunShadowMatrix.length=c,r.sunShadowCascade.length=c,r.directionalShadow.length=g,r.directionalShadowMap.length=g,r.directionalShadowMatrix.length=g,r.pointShadow.length=_,r.pointShadowMap.length=_,r.pointShadowMatrix.length=_,r.spotShadow.length=v,r.spotShadowMap.length=v,r.spotLightMatrix.length=v+b-y,r.spotLightMap.length=b,r.numSpotLightShadowsWithMaps=y,r.numLightProbes=x,S.sunLength=l,S.directionalLength=h,S.pointLength=d,S.spotLength=p,S.rectAreaLength=f,S.hemiLength=m,S.numSunShadows=u,S.numDirectionalShadows=g,S.numPointShadows=_,S.numSpotShadows=v,S.numSpotMaps=b,S.numLightProbes=x,r.version=Ru++)},setupView:function(e,t){let i=0,o=0,l=0,u=0,c=0,h=0;const d=t.matrixWorldInverse;for(let t=0,p=e.length;t<p;t++){const p=e[t];if(p.isSunLight){const e=r.sun[i];e.direction.setFromMatrixPosition(p.matrixWorld),e.direction.transformDirection(d),i++}else if(p.isDirectionalLight){const e=r.directional[o];e.direction.setFromMatrixPosition(p.matrixWorld),n.setFromMatrixPosition(p.target.matrixWorld),e.direction.sub(n),e.direction.transformDirection(d),o++}else if(p.isSpotLight){const e=r.spot[u];e.position.setFromMatrixPosition(p.matrixWorld),e.position.applyMatrix4(d),e.direction.setFromMatrixPosition(p.matrixWorld),n.setFromMatrixPosition(p.target.matrixWorld),e.direction.sub(n),e.direction.transformDirection(d),u++}else if(p.isRectAreaLight){const e=r.rectArea[c];e.position.setFromMatrixPosition(p.matrixWorld),e.position.applyMatrix4(d),a.identity(),s.copy(p.matrixWorld),s.premultiply(d),a.extractRotation(s),e.halfWidth.set(.5*p.width,0,0),e.halfHeight.set(0,.5*p.height,0),e.halfWidth.applyMatrix4(a),e.halfHeight.applyMatrix4(a),c++}else if(p.isPointLight){const e=r.point[l];e.position.setFromMatrixPosition(p.matrixWorld),e.position.applyMatrix4(d),l++}else if(p.isHemisphereLight){const e=r.hemi[h];e.direction.setFromMatrixPosition(p.matrixWorld),e.direction.transformDirection(d),h++}}},state:r}}function Pu(e){const t=new Nu(e),i=[],r=[],n=[];const s={lightsArray:i,shadowsArray:r,lightProbeGridArray:n,camera:null,lights:t,transmissionRenderTarget:{},textureUnits:0};return{init:function(e){s.camera=e,i.length=0,r.length=0,n.length=0},state:s,setupLights:function(){t.setup(i),n.sort((e,t)=>e.priority-t.priority||e.id-t.id)},setupLightsView:function(e){t.setupView(i,e)},pushLight:function(e){e.isLightProbeGrid?n.push(e):i.push(e)},pushShadow:function(e){r.push(e)}}}function Lu(e){let t=new WeakMap;return{get:function(i,r=0){const n=t.get(i);let s;return void 0===n?(s=new Pu(e),t.set(i,[s])):r>=n.length?(s=new Pu(e),n.push(s)):s=n[r],s},dispose:function(){t=new WeakMap}}}const Du=[new Wi(1,0,0),new Wi(-1,0,0),new Wi(0,1,0),new Wi(0,-1,0),new Wi(0,0,1),new Wi(0,0,-1)],Uu=[new Wi(0,-1,0),new Wi(0,-1,0),new Wi(0,0,1),new Wi(0,0,-1),new Wi(0,-1,0),new Wi(0,-1,0)],Iu=new fr,Fu=new Wi,Ou=new Wi;function Bu(e,t,i){let r=new Gs;const n=new Vi,s=new Vi,a=new ur,o=new ga,l=new _a,u={},c=i.maxTextureSize,h={[z]:1,[G]:0,[V]:2},d=new la({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Vi},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 Zn;f.setAttribute("position",new In(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const m=new ws(f,d),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let _=this.type;function v(i,r){const s=t.update(m);d.defines.VSM_SAMPLES!==i.blurSamples&&(d.defines.VSM_SAMPLES=i.blurSamples,p.defines.VSM_SAMPLES=i.blurSamples,d.needsUpdate=!0,p.needsUpdate=!0),null===i.mapPass?i.mapPass=new hr(n.x,n.y,{format:at,type:Xe}):i.mapPass.width===i.map.width&&i.mapPass.height===i.map.height||i.mapPass.setSize(i.map.width,i.map.height),d.uniforms.shadow_pass.value=i.map.depthTexture,d.uniforms.resolution.value.set(i.map.width,i.map.height),d.uniforms.radius.value=i.radius,e.setRenderTarget(i.mapPass),e.clear(),e.renderBufferDirect(r,null,s,d,m,null),p.uniforms.shadow_pass.value=i.mapPass.texture,p.uniforms.resolution.value.set(i.map.width,i.map.height),p.uniforms.radius.value=i.radius,e.setRenderTarget(i.map),e.clear(),e.renderBufferDirect(r,null,s,p,m,null)}function b(t,i,r,n){let s=null;const a=!0===r.isPointLight?t.customDistanceMaterial:t.customDepthMaterial;if(void 0!==a)s=a;else if(s=!0===r.isPointLight?l:o,e.localClippingEnabled&&!0===i.clipShadows&&Array.isArray(i.clippingPlanes)&&0!==i.clippingPlanes.length||i.displacementMap&&0!==i.displacementScale||i.alphaMap&&i.alphaTest>0||i.map&&i.alphaTest>0||!0===i.alphaToCoverage){const e=s.uuid,t=i.uuid;let r=u[e];void 0===r&&(r={},u[e]=r);let n=r[t];void 0===n&&(n=s.clone(),r[t]=n,i.addEventListener("dispose",x)),s=n}if(s.visible=i.visible,s.wireframe=i.wireframe,s.side=3===n?null!==i.shadowSide?i.shadowSide:i.side:null!==i.shadowSide?i.shadowSide:h[i.side],s.alphaMap=i.alphaMap,s.alphaTest=!0===i.alphaToCoverage?.5:i.alphaTest,s.map=i.map,s.clipShadows=i.clipShadows,s.clippingPlanes=i.clippingPlanes,s.clipIntersection=i.clipIntersection,s.displacementMap=i.displacementMap,s.displacementScale=i.displacementScale,s.displacementBias=i.displacementBias,s.wireframeLinewidth=i.wireframeLinewidth,s.linewidth=i.linewidth,!0===r.isPointLight&&!0===s.isMeshDistanceMaterial){e.properties.get(s).light=r}return s}function y(i,n,s,a,o,l){if(!1===i.visible)return;if(i.layers.test(o)&&(i.isMesh||i.isLine||i.isPoints)&&(i.castShadow||i.receiveShadow&&3===l)&&(!i.frustumCulled||i.intersectsFrustum(r))){i.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,i.matrixWorld);const r=t.update(i),o=i.material;if(Array.isArray(o)){const t=r.groups;for(let u=0,c=t.length;u<c;u++){const c=t[u],h=o[c.materialIndex];if(h&&h.visible){const t=b(i,h,a,l);i.onBeforeShadow(e,i,n,s,r,t,c),e.renderBufferDirect(s,null,r,t,i,c),i.onAfterShadow(e,i,n,s,r,t,c)}}}else if(o.visible){const t=b(i,o,a,l);i.onBeforeShadow(e,i,n,s,r,t,null),e.renderBufferDirect(s,null,r,t,i,null),i.onAfterShadow(e,i,n,s,r,t,null)}}const u=i.children;for(let e=0,t=u.length;e<t;e++)y(u[e],n,s,a,o,l)}function x(e){e.target.removeEventListener("dispose",x);for(const t in u){const i=u[t],r=e.target.uuid;if(r in i){i[r].dispose(),delete i[r]}}}this.render=function(t,i,o){if(!1===g.enabled)return;if(!1===g.autoUpdate&&!1===g.needsUpdate)return;if(0===t.length)return;2===this.type&&(Ti("WebGLShadowMap: PCFSoftShadowMap has been removed. 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=_!==this.type;p&&i.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){Ti("WebGLShadowMap:",u,"has no shadow.");continue}if(!1===h.autoUpdate&&!1===h.needsUpdate)continue;n.copy(h.mapSize);const f=h.getFrameExtents();n.multiply(f),s.copy(h.mapSize),(n.x>c||n.y>c)&&(n.x>c&&(s.x=Math.floor(c/f.x),n.x=s.x*f.x,h.mapSize.x=s.x),n.y>c&&(s.y=Math.floor(c/f.y),n.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){Ti("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}h.map=new hr(n.x,n.y,{format:at,type:Xe,minFilter:Oe,magFilter:Oe,generateMipmaps:!1}),h.map.texture.name=u.name+".shadowMap",h.map.depthTexture=new Ys(n.x,n.y,$e),h.map.depthTexture.name=u.name+".shadowMapDepth",h.map.depthTexture.format=it,h.map.depthTexture.compareFunction=null,h.map.depthTexture.minFilter=Ue,h.map.depthTexture.magFilter=Ue}else u.isPointLight?(h.map=new Mo(n.x),h.map.depthTexture=new Ks(n.x,je)):(h.map=new hr(n.x,n.y),h.map.depthTexture=new Ys(n.x,n.y,je)),h.map.depthTexture.name=u.name+".shadowMap",h.map.depthTexture.format=it,1===this.type?(h.map.depthTexture.compareFunction=m?ni:ti,h.map.depthTexture.minFilter=Oe,h.map.depthTexture.magFilter=Oe):(h.map.depthTexture.compareFunction=null,h.map.depthTexture.minFilter=Ue,h.map.depthTexture.magFilter=Ue);h.camera.updateProjectionMatrix()}!0===h.map.isWebGLCubeRenderTarget||h.map.width===n.x&&h.map.height===n.y||h.map.setSize(n.x,n.y);const g=h.map.isWebGLCubeRenderTarget?6:h.getViewportCount();!0!==u.isPointLight&&h.updateMatrices(u,o);const _=4294967294&h.camera.layers.mask?h.camera.layers:o.layers;for(let t=0;t<g;t++){const n=h.getCamera(t);if(u.isPointLight){const e=h.camera,i=h.matrix,r=u.distance||e.far;r!==e.far&&(e.far=r,e.updateProjectionMatrix()),Fu.setFromMatrixPosition(u.matrixWorld),e.position.copy(Fu),Ou.copy(e.position),Ou.add(Du[t]),e.up.copy(Uu[t]),e.lookAt(Ou),e.updateMatrixWorld(),i.makeTranslation(-Fu.x,-Fu.y,-Fu.z),Iu.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),h._frustum.setFromProjectionMatrix(Iu,e.coordinateSystem,e.reversedDepth)}if(h.map.isWebGLCubeRenderTarget)e.setRenderTarget(h.map,t),e.clear();else{0===t&&(e.setRenderTarget(h.map),e.clear());const i=h.getViewport(t);a.set(s.x*i.x,s.y*i.y,s.x*i.z,s.y*i.w),d.viewport(a)}r=h.getFrustum(t),y(i,o,n,u,_,this.type)}!0!==h.isPointLightShadow&&3===this.type&&v(h,o),h.needsUpdate=!1}_=this.type,g.needsUpdate=!1,e.setRenderTarget(l,u,h)}}function ku(e,t){const i=new function(){let t=!1;const i=new ur;let r=null;const n=new ur(0,0,0,0);return{setMask:function(i){r===i||t||(e.colorMask(i,i,i,i),r=i)},setLocked:function(e){t=e},setClear:function(t,r,s,a,o){!0===o&&(t*=a,r*=a,s*=a),i.set(t,r,s,a),!1===n.equals(i)&&(e.clearColor(t,r,s,a),n.copy(i))},reset:function(){t=!1,r=null,n.set(-1,0,0,0)}}},r=new function(){let i=!1,r=!1,n=null,s=null,a=null;return{setReversed:function(e){if(r!==e){const i=t.get("EXT_clip_control");e?i.clipControlEXT(i.LOWER_LEFT_EXT,i.ZERO_TO_ONE_EXT):i.clipControlEXT(i.LOWER_LEFT_EXT,i.NEGATIVE_ONE_TO_ONE_EXT),r=e;const n=a;a=null,this.setClear(n)}},getReversed:function(){return r},setTest:function(t){t?G(e.DEPTH_TEST):V(e.DEPTH_TEST)},setMask:function(t){n===t||i||(e.depthMask(t),n=t)},setFunc:function(t){if(r&&(t=Ai[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){i=e},setClear:function(t){a!==t&&(a=t,r&&(t=1-t),e.clearDepth(t))},reset:function(){i=!1,n=null,s=null,a=null,r=!1}}},n=new function(){let t=!1,i=null,r=null,n=null,s=null,a=null,o=null,l=null,u=null;return{setTest:function(i){t||(i?G(e.STENCIL_TEST):V(e.STENCIL_TEST))},setMask:function(r){i===r||t||(e.stencilMask(r),i=r)},setFunc:function(t,i,a){r===t&&n===i&&s===a||(e.stencilFunc(t,i,a),r=t,n=i,s=a)},setOp:function(t,i,r){a===t&&o===i&&l===r||(e.stencilOp(t,i,r),a=t,o=i,l=r)},setLocked:function(e){t=e},setClear:function(t){u!==t&&(e.clearStencil(t),u=t)},reset:function(){t=!1,i=null,r=null,n=null,s=null,a=null,o=null,l=null,u=null}}};let s={};const a=new WeakMap;let o={},l={},u={},c=new WeakMap,h=[],d=null,p=!1,f=null,m=null,g=null,_=null,v=null,b=null,y=null,x=new Yr(0,0,0),S=0,T=!1,M=null,E=null,w=null,A=null,R=null;const C=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let N=!1,P=0;const L=e.getParameter(e.VERSION);-1!==L.indexOf("WebGL")?(P=parseFloat(/^WebGL (\d)/.exec(L)[1]),N=P>=1):-1!==L.indexOf("OpenGL ES")&&(P=parseFloat(/^OpenGL ES (\d)/.exec(L)[1]),N=P>=2);let D=null,U={};const I=e.getParameter(e.SCISSOR_BOX),F=e.getParameter(e.VIEWPORT),O=(new ur).fromArray(I),B=(new ur).fromArray(F);function k(t,i,r,n){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<r;a++)t===e.TEXTURE_3D||t===e.TEXTURE_2D_ARRAY?e.texImage3D(i,0,e.RGBA,1,1,n,0,e.RGBA,e.UNSIGNED_BYTE,s):e.texImage2D(i+a,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,s);return a}const z={};function G(t){!0!==o[t]&&(e.enable(t),o[t]=!0)}function V(t){!1!==o[t]&&(e.disable(t),o[t]=!1)}z[e.TEXTURE_2D]=k(e.TEXTURE_2D,e.TEXTURE_2D,1),z[e.TEXTURE_CUBE_MAP]=k(e.TEXTURE_CUBE_MAP,e.TEXTURE_CUBE_MAP_POSITIVE_X,6),z[e.TEXTURE_2D_ARRAY]=k(e.TEXTURE_2D_ARRAY,e.TEXTURE_2D_ARRAY,1,1),z[e.TEXTURE_3D]=k(e.TEXTURE_3D,e.TEXTURE_3D,1,1),i.setClear(0,0,0,1),r.setClear(1),n.setClear(0),G(e.DEPTH_TEST),r.setFunc(3),ce(!1),he(1),G(e.CULL_FACE),ue(0);const $={[H]:e.FUNC_ADD,[W]:e.FUNC_SUBTRACT,[j]:e.FUNC_REVERSE_SUBTRACT};$[103]=e.MIN,$[104]=e.MAX;const X={[q]:e.ZERO,[Y]:e.ONE,[K]:e.SRC_COLOR,[Q]:e.SRC_ALPHA,[ne]:e.SRC_ALPHA_SATURATE,[ie]:e.DST_COLOR,[ee]:e.DST_ALPHA,[Z]:e.ONE_MINUS_SRC_COLOR,[J]:e.ONE_MINUS_SRC_ALPHA,[re]:e.ONE_MINUS_DST_COLOR,[te]:e.ONE_MINUS_DST_ALPHA,[se]:e.CONSTANT_COLOR,[ae]:e.ONE_MINUS_CONSTANT_COLOR,[oe]:e.CONSTANT_ALPHA,[le]:e.ONE_MINUS_CONSTANT_ALPHA};function ue(t,i,r,n,s,a,o,l,u,c){if(0!==t){if(!1===p&&(G(e.BLEND),p=!0),5===t)s=s||i,a=a||r,o=o||n,i===m&&s===v||(e.blendEquationSeparate($[i],$[s]),m=i,v=s),r===g&&n===_&&a===b&&o===y||(e.blendFuncSeparate(X[r],X[n],X[a],X[o]),g=r,_=n,b=a,y=o),!1!==l.equals(x)&&u===S||(e.blendColor(l.r,l.g,l.b,u),x.copy(l),S=u),f=t,T=!1;else if(t!==f||c!==T){if(m===H&&v===H||(e.blendEquation(e.FUNC_ADD),m=H,v=H),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:Mi("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:Mi("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case 4:Mi("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:Mi("WebGLState: Invalid blending: ",t)}g=null,_=null,b=null,y=null,x.set(0,0,0),S=0,f=t,T=c}}else!0===p&&(V(e.BLEND),p=!1)}function ce(t){M!==t&&(t?e.frontFace(e.CW):e.frontFace(e.CCW),M=t)}function he(t){0!==t?(G(e.CULL_FACE),t!==E&&(1===t?e.cullFace(e.BACK):2===t?e.cullFace(e.FRONT):e.cullFace(e.FRONT_AND_BACK))):V(e.CULL_FACE),E=t}function de(t,i,n){t?(G(e.POLYGON_OFFSET_FILL),A===i&&R===n||(A=i,R=n,r.getReversed()&&(i=-i,n=-n),e.polygonOffset(i,n))):V(e.POLYGON_OFFSET_FILL)}return{buffers:{color:i,depth:r,stencil:n},enable:G,disable:V,bindFramebuffer:function(t,i){return u[t]!==i&&(e.bindFramebuffer(t,i),u[t]=i,t===e.DRAW_FRAMEBUFFER&&(u[e.FRAMEBUFFER]=i),t===e.FRAMEBUFFER&&(u[e.DRAW_FRAMEBUFFER]=i),!0)},drawBuffers:function(t,i){let r=h,n=!1;if(t){r=c.get(i),void 0===r&&(r=[],c.set(i,r));const s=t.textures;if(r.length!==s.length||r[0]!==e.COLOR_ATTACHMENT0){for(let t=0,i=s.length;t<i;t++)r[t]=e.COLOR_ATTACHMENT0+t;r.length=s.length,n=!0}}else r[0]!==e.BACK&&(r[0]=e.BACK,n=!0);n&&e.drawBuffers(r)},useProgram:function(t){return d!==t&&(e.useProgram(t),d=t,!0)},setBlending:ue,setMaterial:function(t,s){2===t.side?V(e.CULL_FACE):G(e.CULL_FACE);let a=1===t.side;s&&(a=!a),ce(a),1===t.blending&&!1===t.transparent?ue(0):ue(t.blending,t.blendEquation,t.blendSrc,t.blendDst,t.blendEquationAlpha,t.blendSrcAlpha,t.blendDstAlpha,t.blendColor,t.blendAlpha,t.premultipliedAlpha),r.setFunc(t.depthFunc),r.setTest(t.depthTest),r.setMask(t.depthWrite),i.setMask(t.colorWrite);const o=t.stencilWrite;n.setTest(o),o&&(n.setMask(t.stencilWriteMask),n.setFunc(t.stencilFunc,t.stencilRef,t.stencilFuncMask),n.setOp(t.stencilFail,t.stencilZFail,t.stencilZPass)),de(t.polygonOffset,t.polygonOffsetFactor,t.polygonOffsetUnits),!0===t.alphaToCoverage?G(e.SAMPLE_ALPHA_TO_COVERAGE):V(e.SAMPLE_ALPHA_TO_COVERAGE)},setFlipSided:ce,setCullFace:he,setLineWidth:function(t){t!==w&&(N&&e.lineWidth(t),w=t)},setPolygonOffset:de,setScissorTest:function(t){t?G(e.SCISSOR_TEST):V(e.SCISSOR_TEST)},activeTexture:function(t){void 0===t&&(t=e.TEXTURE0+C-1),D!==t&&(e.activeTexture(t),D=t)},bindTexture:function(t,i,r){void 0===r&&(r=null===D?e.TEXTURE0+C-1:D);let n=U[r];void 0===n&&(n={type:void 0,texture:void 0},U[r]=n),n.type===t&&n.texture===i||(D!==r&&(e.activeTexture(r),D=r),e.bindTexture(t,i||z[t]),n.type=t,n.texture=i)},unbindTexture:function(){const t=U[D];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){Mi("WebGLState:",e)}},compressedTexImage3D:function(){try{e.compressedTexImage3D(...arguments)}catch(e){Mi("WebGLState:",e)}},texImage2D:function(){try{e.texImage2D(...arguments)}catch(e){Mi("WebGLState:",e)}},texImage3D:function(){try{e.texImage3D(...arguments)}catch(e){Mi("WebGLState:",e)}},pixelStorei:function(t,i){l[t]!==i&&(e.pixelStorei(t,i),l[t]=i)},getParameter:function(t){return void 0!==l[t]?l[t]:e.getParameter(t)},updateUBOMapping:function(t,i){let r=a.get(i);void 0===r&&(r=new WeakMap,a.set(i,r));let n=r.get(t);void 0===n&&(n=e.getUniformBlockIndex(i,t.name),e.uniformBlockBinding(i,n,n),r.set(t,n))},uniformBlockBinding:function(t,i,r){const n=a.get(i).get(t);s[n]!==r&&(e.bindBufferBase(e.UNIFORM_BUFFER,n,r),s[n]=r)},texStorage2D:function(){try{e.texStorage2D(...arguments)}catch(e){Mi("WebGLState:",e)}},texStorage3D:function(){try{e.texStorage3D(...arguments)}catch(e){Mi("WebGLState:",e)}},texSubImage2D:function(){try{e.texSubImage2D(...arguments)}catch(e){Mi("WebGLState:",e)}},texSubImage3D:function(){try{e.texSubImage3D(...arguments)}catch(e){Mi("WebGLState:",e)}},compressedTexSubImage2D:function(){try{e.compressedTexSubImage2D(...arguments)}catch(e){Mi("WebGLState:",e)}},compressedTexSubImage3D:function(){try{e.compressedTexSubImage3D(...arguments)}catch(e){Mi("WebGLState:",e)}},scissor:function(t){!1===O.equals(t)&&(e.scissor(t.x,t.y,t.z,t.w),O.copy(t))},viewport:function(t){!1===B.equals(t)&&(e.viewport(t.x,t.y,t.z,t.w),B.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),r.setReversed(!1),e.clearDepth(1),e.stencilMask(4294967295),e.stencilFunc(e.ALWAYS,0,4294967295),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.clearStencil(0),e.cullFace(e.BACK),e.frontFace(e.CCW),e.polygonOffset(0,0),e.activeTexture(e.TEXTURE0),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),e.bindFramebuffer(e.READ_FRAMEBUFFER,null),e.useProgram(null),e.lineWidth(1),e.scissor(0,0,e.canvas.width,e.canvas.height),e.viewport(0,0,e.canvas.width,e.canvas.height),e.pixelStorei(e.PACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!1),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.BROWSER_DEFAULT_WEBGL),e.pixelStorei(e.PACK_ROW_LENGTH,0),e.pixelStorei(e.PACK_SKIP_PIXELS,0),e.pixelStorei(e.PACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_ROW_LENGTH,0),e.pixelStorei(e.UNPACK_IMAGE_HEIGHT,0),e.pixelStorei(e.UNPACK_SKIP_PIXELS,0),e.pixelStorei(e.UNPACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_SKIP_IMAGES,0),o={},l={},D=null,U={},u={},s={},c=new WeakMap,h=[],d=null,p=!1,f=null,m=null,g=null,_=null,v=null,b=null,y=null,x=new Yr(0,0,0),S=0,T=!1,M=null,E=null,w=null,A=null,R=null,O.set(0,0,e.canvas.width,e.canvas.height),B.set(0,0,e.canvas.width,e.canvas.height),i.reset(),r.reset(),n.reset()}}}function zu(e,t,i,r,n,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 Vi,c=new WeakMap,h=new Set;let d;const p=new WeakMap,f=new Set,m=new FinalizationRegistry(e=>f.delete(e));let g=!1;try{g="undefined"!=typeof OffscreenCanvas&&null!==new OffscreenCanvas(1,1).getContext("2d")}catch(e){}function _(e,t){return g?new OffscreenCanvas(e,t):vi("canvas")}function v(e,t,i){let r=1;const n=K(e);if((n.width>i||n.height>i)&&(r=i/Math.max(n.width,n.height)),r<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 i=Math.floor(r*n.width),s=Math.floor(r*n.height);void 0===d&&(d=_(i,s));const a=t?_(i,s):d;a.width=i,a.height=s;return a.getContext("2d").drawImage(e,0,0,i,s),Ti("WebGLRenderer: Texture has been resized from ("+n.width+"x"+n.height+") to ("+i+"x"+s+")."),a}return"data"in e&&Ti("WebGLRenderer: Image in DataTexture is too big ("+n.width+"x"+n.height+")."),e}return e}function b(e){return e.generateMipmaps}function y(t){e.generateMipmap(t)}function x(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 S(i,r,n,s,a,o=!1){if(null!==i){if(void 0!==e[i])return e[i];Ti("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+i+"'")}let l;s&&(l=t.get("EXT_texture_norm16"),l||Ti("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let u=r;if(r===e.RED&&(n===e.FLOAT&&(u=e.R32F),n===e.HALF_FLOAT&&(u=e.R16F),n===e.UNSIGNED_BYTE&&(u=e.R8),n===e.UNSIGNED_SHORT&&l&&(u=l.R16_EXT),n===e.SHORT&&l&&(u=l.R16_SNORM_EXT)),r===e.RED_INTEGER&&(n===e.UNSIGNED_BYTE&&(u=e.R8UI),n===e.UNSIGNED_SHORT&&(u=e.R16UI),n===e.UNSIGNED_INT&&(u=e.R32UI),n===e.BYTE&&(u=e.R8I),n===e.SHORT&&(u=e.R16I),n===e.INT&&(u=e.R32I)),r===e.RG&&(n===e.FLOAT&&(u=e.RG32F),n===e.HALF_FLOAT&&(u=e.RG16F),n===e.UNSIGNED_BYTE&&(u=e.RG8),n===e.UNSIGNED_SHORT&&l&&(u=l.RG16_EXT),n===e.SHORT&&l&&(u=l.RG16_SNORM_EXT)),r===e.RG_INTEGER&&(n===e.UNSIGNED_BYTE&&(u=e.RG8UI),n===e.UNSIGNED_SHORT&&(u=e.RG16UI),n===e.UNSIGNED_INT&&(u=e.RG32UI),n===e.BYTE&&(u=e.RG8I),n===e.SHORT&&(u=e.RG16I),n===e.INT&&(u=e.RG32I)),r===e.RGB_INTEGER&&(n===e.UNSIGNED_BYTE&&(u=e.RGB8UI),n===e.UNSIGNED_SHORT&&(u=e.RGB16UI),n===e.UNSIGNED_INT&&(u=e.RGB32UI),n===e.BYTE&&(u=e.RGB8I),n===e.SHORT&&(u=e.RGB16I),n===e.INT&&(u=e.RGB32I)),r===e.RGBA_INTEGER&&(n===e.UNSIGNED_BYTE&&(u=e.RGBA8UI),n===e.UNSIGNED_SHORT&&(u=e.RGBA16UI),n===e.UNSIGNED_INT&&(u=e.RGBA32UI),n===e.BYTE&&(u=e.RGBA8I),n===e.SHORT&&(u=e.RGBA16I),n===e.INT&&(u=e.RGBA32I)),r===e.RGB&&(n===e.UNSIGNED_SHORT&&l&&(u=l.RGB16_EXT),n===e.SHORT&&l&&(u=l.RGB16_SNORM_EXT),n===e.UNSIGNED_INT_5_9_9_9_REV&&(u=e.RGB9_E5),n===e.UNSIGNED_INT_10F_11F_11F_REV&&(u=e.R11F_G11F_B10F)),r===e.RGBA){const t=o?Yt:Qi.getTransfer(a);n===e.FLOAT&&(u=e.RGBA32F),n===e.HALF_FLOAT&&(u=e.RGBA16F),n===e.UNSIGNED_BYTE&&(u=t===Kt?e.SRGB8_ALPHA8:e.RGBA8),n===e.UNSIGNED_SHORT&&l&&(u=l.RGBA16_EXT),n===e.SHORT&&l&&(u=l.RGBA16_SNORM_EXT),n===e.UNSIGNED_SHORT_4_4_4_4&&(u=e.RGBA4),n===e.UNSIGNED_SHORT_5_5_5_1&&(u=e.RGB5_A1)}return u!==e.R16F&&u!==e.R32F&&u!==e.RG16F&&u!==e.RG32F&&u!==e.RGBA16F&&u!==e.RGBA32F||t.get("EXT_color_buffer_float"),u}function T(t,i){let r;return t?null===i||i===je||i===Ke?r=e.DEPTH24_STENCIL8:i===$e?r=e.DEPTH32F_STENCIL8:i===He&&(r=e.DEPTH24_STENCIL8,Ti("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):null===i||i===je||i===Ke?r=e.DEPTH_COMPONENT24:i===$e?r=e.DEPTH_COMPONENT32F:i===He&&(r=e.DEPTH_COMPONENT16),r}function M(e,t){return!0===b(e)||e.isFramebufferTexture&&e.minFilter!==Ue&&e.minFilter!==Oe?Math.log2(Math.max(t.width,t.height))+1:e.mipmaps.length>0?e.mipmaps.length:e.isCompressedTexture&&Array.isArray(e.image)?t.mipmaps.length:1}function E(e){const t=new WeakRef(e);r.get(e).__ref=t,f.add(t),m.register(e,t,t)}function w(e){const t=r.get(e).__ref;void 0!==t&&(f.delete(t),m.unregister(t))}function A(e){C(e.target)}function R(e){N(e.target)}function C(e){e.removeEventListener("dispose",A),w(e),function(e){const t=r.get(e);if(void 0===t.__webglInit)return;const i=e.source,n=p.get(i);if(n){const r=n[t.__cacheKey];r.usedTimes--,0===r.usedTimes&&P(e),0===Object.keys(n).length&&p.delete(i)}r.remove(e)}(e),e.isVideoTexture&&c.delete(e),e.isHTMLTexture&&h.delete(e)}function N(t){t.removeEventListener("dispose",R),w(t),function(t){const i=r.get(t);i.__depthDisposeCallback&&i.__depthDisposeCallback();const n=t.depthTexture;n&&n.renderTarget===t&&C(n);if(t.isWebGLCubeRenderTarget)for(let t=0;t<6;t++){if(Array.isArray(i.__webglFramebuffer[t]))for(let r=0;r<i.__webglFramebuffer[t].length;r++)e.deleteFramebuffer(i.__webglFramebuffer[t][r]);else e.deleteFramebuffer(i.__webglFramebuffer[t]);i.__webglDepthbuffer&&e.deleteRenderbuffer(i.__webglDepthbuffer[t])}else{if(Array.isArray(i.__webglFramebuffer))for(let t=0;t<i.__webglFramebuffer.length;t++)e.deleteFramebuffer(i.__webglFramebuffer[t]);else e.deleteFramebuffer(i.__webglFramebuffer);if(i.__webglDepthbuffer&&e.deleteRenderbuffer(i.__webglDepthbuffer),i.__webglMultisampledFramebuffer&&e.deleteFramebuffer(i.__webglMultisampledFramebuffer),i.__webglColorRenderbuffer)for(let t=0;t<i.__webglColorRenderbuffer.length;t++)i.__webglColorRenderbuffer[t]&&e.deleteRenderbuffer(i.__webglColorRenderbuffer[t]);i.__webglDepthRenderbuffer&&e.deleteRenderbuffer(i.__webglDepthRenderbuffer)}const s=t.textures;for(let t=0,i=s.length;t<i;t++){const i=r.get(s[t]);i.__webglTexture&&(e.deleteTexture(i.__webglTexture),a.memory.textures--),r.remove(s[t])}r.remove(t)}(t)}function P(t){const i=r.get(t);e.deleteTexture(i.__webglTexture);const n=t.source;delete p.get(n)[i.__cacheKey],a.memory.textures--}let L=0;function D(t,n){const s=r.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)Ti("WebGLRenderer: Texture marked for update but no image data found.");else{if(!1!==e.complete)return void G(s,t,n);Ti("WebGLRenderer: Texture marked for update but image is incomplete")}}else t.isExternalTexture&&(s.__webglTexture=t.sourceTexture?t.sourceTexture:null);i.bindTexture(e.TEXTURE_2D,s.__webglTexture,e.TEXTURE0+n)}function U(t,a){const o=r.get(t);t.version>0&&o.__version!==t.version?function(t,a,o){if(6!==a.image.length)return;const l=k(t,a),u=a.source;i.bindTexture(e.TEXTURE_CUBE_MAP,t.__webglTexture,e.TEXTURE0+o);const c=r.get(u);if(u.version!==c.__version||!0===l){i.activeTexture(e.TEXTURE0+o);const t=Qi.getPrimaries(Qi.workingColorSpace),r=a.colorSpace===$t?null:Qi.getPrimaries(a.colorSpace),h=a.colorSpace===$t||t===r?e.NONE:e.BROWSER_DEFAULT_WEBGL;i.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,a.flipY),i.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a.premultiplyAlpha),i.pixelStorei(e.UNPACK_ALIGNMENT,a.unpackAlignment),i.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]:v(a.image[e],!0,n.maxCubemapSize),f[e]=Y(a,f[e]);const m=f[0],g=s.convert(a.format,a.colorSpace),_=s.convert(a.type);let x=S(a.internalFormat,g,_,a.normalized,a.colorSpace);const E=!0!==a.isVideoTexture,w=void 0===c.__version||!0===l,A=u.dataReady;let R,C=M(a,m);if(B(e.TEXTURE_CUBE_MAP,a),a.isDepthTexture){if(x=T(a.format===rt,a.type),w)if(E)i.texStorage2D(e.TEXTURE_CUBE_MAP,1,x,m.width,m.height);else for(let t=0;t<6;t++)i.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,x,m.width,m.height,0,g,_,null)}else if(d){E&&w&&i.texStorage2D(e.TEXTURE_CUBE_MAP,C,x,m.width,m.height);for(let t=0;t<6;t++){R=f[t].mipmaps;for(let r=0;r<R.length;r++){const n=R[r];a.format!==tt?null!==g?E?A&&i.compressedTexSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,0,0,n.width,n.height,g,n.data):i.compressedTexImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,x,n.width,n.height,0,n.data):Ti("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):E?A&&i.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,0,0,n.width,n.height,g,_,n.data):i.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,x,n.width,n.height,0,g,_,n.data)}}}else{if(R=a.mipmaps,E&&w){R.length>0&&C++;const t=K(f[0]);i.texStorage2D(e.TEXTURE_CUBE_MAP,C,x,t.width,t.height)}for(let t=0;t<6;t++)if(p){E?A&&i.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,f[t].width,f[t].height,g,_,f[t].data):i.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,x,f[t].width,f[t].height,0,g,_,f[t].data);for(let r=0;r<R.length;r++){const n=R[r].image[t].image;E?A&&i.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,0,0,n.width,n.height,g,_,n.data):i.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,x,n.width,n.height,0,g,_,n.data)}}else{E?A&&i.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,g,_,f[t]):i.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,x,g,_,f[t]);for(let r=0;r<R.length;r++){const n=R[r];E?A&&i.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,0,0,g,_,n.image[t]):i.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,x,g,_,n.image[t])}}}b(a)&&!0===a.mipmapsAutoUpdate&&y(e.TEXTURE_CUBE_MAP),c.__version=u.version,a.onUpdate&&a.onUpdate(a)}t.__version=a.version}(o,t,a):i.bindTexture(e.TEXTURE_CUBE_MAP,o.__webglTexture,e.TEXTURE0+a)}const I={[Pe]:e.REPEAT,[Le]:e.CLAMP_TO_EDGE,[De]:e.MIRRORED_REPEAT},F={[Ue]:e.NEAREST,[Ie]:e.NEAREST_MIPMAP_NEAREST,[Fe]:e.NEAREST_MIPMAP_LINEAR,[Oe]:e.LINEAR,[Be]:e.LINEAR_MIPMAP_NEAREST,[ke]:e.LINEAR_MIPMAP_LINEAR},O={[Qt]:e.NEVER,[si]:e.ALWAYS,[Jt]:e.LESS,[ti]:e.LEQUAL,[ei]:e.EQUAL,[ni]:e.GEQUAL,[ii]:e.GREATER,[ri]:e.NOTEQUAL};function B(i,s){if(s.type!==$e||!1!==t.has("OES_texture_float_linear")||s.magFilter!==Oe&&s.magFilter!==Be&&s.magFilter!==Fe&&s.magFilter!==ke&&s.minFilter!==Oe&&s.minFilter!==Be&&s.minFilter!==Fe&&s.minFilter!==ke||Ti("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),e.texParameteri(i,e.TEXTURE_WRAP_S,I[s.wrapS]),e.texParameteri(i,e.TEXTURE_WRAP_T,I[s.wrapT]),i!==e.TEXTURE_3D&&i!==e.TEXTURE_2D_ARRAY||e.texParameteri(i,e.TEXTURE_WRAP_R,I[s.wrapR]),e.texParameteri(i,e.TEXTURE_MAG_FILTER,F[s.magFilter]),e.texParameteri(i,e.TEXTURE_MIN_FILTER,F[s.minFilter]),s.compareFunction&&(e.texParameteri(i,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(i,e.TEXTURE_COMPARE_FUNC,O[s.compareFunction])),!0===t.has("EXT_texture_filter_anisotropic")){if(s.magFilter===Ue)return;if(s.minFilter!==Fe&&s.minFilter!==ke)return;if(s.type===$e&&!1===t.has("OES_texture_float_linear"))return;if(s.anisotropy>1||r.get(s).__currentAnisotropy){const a=t.get("EXT_texture_filter_anisotropic");e.texParameterf(i,a.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(s.anisotropy,n.getMaxAnisotropy())),r.get(s).__currentAnisotropy=s.anisotropy}}}function k(t,i){let r=!1;void 0===t.__webglInit&&(t.__webglInit=!0,i.addEventListener("dispose",A),E(i));const n=i.source;let s=p.get(n);void 0===s&&(s={},p.set(n,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.mipmapsAutoUpdate),t.push(e.premultiplyAlpha),t.push(e.flipY),t.push(e.unpackAlignment),t.push(e.colorSpace),t.join()}(i);if(o!==t.__cacheKey){void 0===s[o]&&(s[o]={texture:e.createTexture(),usedTimes:0},a.memory.textures++,r=!0),s[o].usedTimes++;const n=s[t.__cacheKey];void 0!==n&&(s[t.__cacheKey].usedTimes--,0===n.usedTimes&&P(i)),t.__cacheKey=o,t.__webglTexture=s[o].texture}return r}function z(e,t,i){return Math.floor(Math.floor(e/i)/t)}function G(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=k(t,a),c=a.source;i.bindTexture(l,t.__webglTexture,e.TEXTURE0+o);const d=r.get(c);if(c.version!==d.__version||!0===u){i.activeTexture(e.TEXTURE0+o);if(!1===("undefined"!=typeof ImageBitmap&&a.image instanceof ImageBitmap)){const t=Qi.getPrimaries(Qi.workingColorSpace),r=a.colorSpace===$t?null:Qi.getPrimaries(a.colorSpace),n=a.colorSpace===$t||t===r?e.NONE:e.BROWSER_DEFAULT_WEBGL;i.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,a.flipY),i.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a.premultiplyAlpha),i.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,n)}i.pixelStorei(e.UNPACK_ALIGNMENT,a.unpackAlignment);let t=v(a.image,!1,n.maxTextureSize);t=Y(a,t);const r=s.convert(a.format,a.colorSpace),p=s.convert(a.type);let f,m=S(a.internalFormat,r,p,a.normalized,a.colorSpace,a.isVideoTexture);B(l,a);const g=a.mipmaps,_=!0!==a.isVideoTexture,x=void 0===d.__version||!0===u,E=c.dataReady,w=M(a,t);if(a.isDepthTexture)m=T(a.format===rt,a.type),x&&(_?i.texStorage2D(e.TEXTURE_2D,1,m,t.width,t.height):i.texImage2D(e.TEXTURE_2D,0,m,t.width,t.height,0,r,p,null));else if(a.isDataTexture)if(g.length>0){_&&x&&i.texStorage2D(e.TEXTURE_2D,w,m,g[0].width,g[0].height);for(let t=0,n=g.length;t<n;t++)f=g[t],_?E&&i.texSubImage2D(e.TEXTURE_2D,t,0,0,f.width,f.height,r,p,f.data):i.texImage2D(e.TEXTURE_2D,t,m,f.width,f.height,0,r,p,f.data);a.generateMipmaps=!1}else _?(x&&i.texStorage2D(e.TEXTURE_2D,w,m,t.width,t.height),E&&function(t,r,n,s){const a=t.updateRanges;if(0===a.length)i.texSubImage2D(e.TEXTURE_2D,0,0,0,r.width,r.height,n,s,r.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],i=a[e],n=t.start+t.count,s=z(i.start,r.width,4),l=z(t.start,r.width,4);i.start<=n+1&&s===l&&z(i.start+i.count-1,r.width,4)===s?t.count=Math.max(t.count,i.start+i.count-t.start):(++o,a[o]=i)}a.length=o+1;const l=i.getParameter(e.UNPACK_ROW_LENGTH),u=i.getParameter(e.UNPACK_SKIP_PIXELS),c=i.getParameter(e.UNPACK_SKIP_ROWS);i.pixelStorei(e.UNPACK_ROW_LENGTH,r.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%r.width,h=Math.floor(l/r.width),d=u,p=1;i.pixelStorei(e.UNPACK_SKIP_PIXELS,c),i.pixelStorei(e.UNPACK_SKIP_ROWS,h),i.texSubImage2D(e.TEXTURE_2D,0,c,h,d,p,n,s,r.data)}t.clearUpdateRanges(),i.pixelStorei(e.UNPACK_ROW_LENGTH,l),i.pixelStorei(e.UNPACK_SKIP_PIXELS,u),i.pixelStorei(e.UNPACK_SKIP_ROWS,c)}}(a,t,r,p)):i.texImage2D(e.TEXTURE_2D,0,m,t.width,t.height,0,r,p,t.data);else if(a.isCompressedTexture)if(a.isCompressedArrayTexture){_&&x&&i.texStorage3D(e.TEXTURE_2D_ARRAY,w,m,g[0].width,g[0].height,t.depth);for(let n=0,s=g.length;n<s;n++)if(f=g[n],a.format!==tt)if(null!==r)if(_){if(E)if(a.layerUpdates.size>0){const t=uo(f.width,f.height,a.format,a.type);for(const s of a.layerUpdates){const a=f.data.subarray(s*t/f.data.BYTES_PER_ELEMENT,(s+1)*t/f.data.BYTES_PER_ELEMENT);i.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,n,0,0,s,f.width,f.height,1,r,a)}}else i.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,n,0,0,0,f.width,f.height,t.depth,r,f.data)}else i.compressedTexImage3D(e.TEXTURE_2D_ARRAY,n,m,f.width,f.height,t.depth,0,f.data,0,0);else Ti("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else _?E&&i.texSubImage3D(e.TEXTURE_2D_ARRAY,n,0,0,0,f.width,f.height,t.depth,r,p,f.data):i.texImage3D(e.TEXTURE_2D_ARRAY,n,m,f.width,f.height,t.depth,0,r,p,f.data);a.layerUpdates.size>0&&a.clearLayerUpdates()}else{_&&x&&i.texStorage2D(e.TEXTURE_2D,w,m,g[0].width,g[0].height);for(let t=0,n=g.length;t<n;t++)f=g[t],a.format!==tt?null!==r?_?E&&i.compressedTexSubImage2D(e.TEXTURE_2D,t,0,0,f.width,f.height,r,f.data):i.compressedTexImage2D(e.TEXTURE_2D,t,m,f.width,f.height,0,f.data):Ti("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):_?E&&i.texSubImage2D(e.TEXTURE_2D,t,0,0,f.width,f.height,r,p,f.data):i.texImage2D(e.TEXTURE_2D,t,m,f.width,f.height,0,r,p,f.data)}else if(a.isDataArrayTexture)if(_){if(x&&i.texStorage3D(e.TEXTURE_2D_ARRAY,w,m,t.width,t.height,t.depth),E)if(a.layerUpdates.size>0){const n=uo(t.width,t.height,a.format,a.type);for(const s of a.layerUpdates){const a=t.data.subarray(s*n/t.data.BYTES_PER_ELEMENT,(s+1)*n/t.data.BYTES_PER_ELEMENT);i.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,s,t.width,t.height,1,r,p,a)}a.clearLayerUpdates()}else i.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,t.width,t.height,t.depth,r,p,t.data)}else i.texImage3D(e.TEXTURE_2D_ARRAY,0,m,t.width,t.height,t.depth,0,r,p,t.data);else if(a.isData3DTexture)_?(x&&i.texStorage3D(e.TEXTURE_3D,w,m,t.width,t.height,t.depth),E&&i.texSubImage3D(e.TEXTURE_3D,0,0,0,0,t.width,t.height,t.depth,r,p,t.data)):i.texImage3D(e.TEXTURE_3D,0,m,t.width,t.height,t.depth,0,r,p,t.data);else if(a.isFramebufferTexture){if(x)if(_)i.texStorage2D(e.TEXTURE_2D,w,m,t.width,t.height);else{let n=t.width,s=t.height;for(let t=0;t<w;t++)i.texImage2D(e.TEXTURE_2D,t,m,n,s,0,r,p,null),n>>=1,s>>=1}}else if(a.isHTMLTexture){if("texElementImage2D"in e){const i=e.canvas;if(i.hasAttribute("layoutsubtree")||i.setAttribute("layoutsubtree","true"),t.parentNode!==i)return i.appendChild(t),h.add(a),i.onpaint=e=>{const t=e.changedElements;for(const e of h)t.includes(e.image)&&(e.needsUpdate=!0)},void i.requestPaint();if(3===e.texElementImage2D.length)e.texElementImage2D(e.TEXTURE_2D,e.RGBA8,t);else{const i=0,r=e.RGBA,n=e.RGBA,s=e.UNSIGNED_BYTE;e.texElementImage2D(e.TEXTURE_2D,i,r,n,s,t)}e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}}else if(g.length>0){if(_&&x){const t=K(g[0]);i.texStorage2D(e.TEXTURE_2D,w,m,t.width,t.height)}for(let t=0,n=g.length;t<n;t++)f=g[t],_?E&&i.texSubImage2D(e.TEXTURE_2D,t,0,0,r,p,f):i.texImage2D(e.TEXTURE_2D,t,m,r,p,f);a.generateMipmaps=!1}else if(_){if(x){const r=K(t);i.texStorage2D(e.TEXTURE_2D,w,m,r.width,r.height)}E&&i.texSubImage2D(e.TEXTURE_2D,0,0,0,r,p,t)}else i.texImage2D(e.TEXTURE_2D,0,m,r,p,t);b(a)&&!0===a.mipmapsAutoUpdate&&y(l),d.__version=c.version,a.onUpdate&&a.onUpdate(a)}t.__version=a.version}function V(t,n,a,l,u,c){const h=s.convert(a.format,a.colorSpace),d=s.convert(a.type),p=S(a.internalFormat,h,d,a.normalized,a.colorSpace),f=r.get(n),m=r.get(a);if(m.__renderTarget=n,!f.__hasExternalTextures){const t=Math.max(1,n.width>>c),r=Math.max(1,n.height>>c);u===e.TEXTURE_3D||u===e.TEXTURE_2D_ARRAY?i.texImage3D(u,c,p,t,r,n.depth,0,h,d,null):i.texImage2D(u,c,p,t,r,0,h,d,null)}i.bindFramebuffer(e.FRAMEBUFFER,t),q(n)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,l,u,m.__webglTexture,0,X(n)):(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),i.bindFramebuffer(e.FRAMEBUFFER,null)}function H(t,i,r){if(e.bindRenderbuffer(e.RENDERBUFFER,t),i.depthBuffer){const n=i.depthTexture,s=n&&n.isDepthTexture?n.type:null,a=T(i.stencilBuffer,s),l=i.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;q(i)?o.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,X(i),a,i.width,i.height):r?e.renderbufferStorageMultisample(e.RENDERBUFFER,X(i),a,i.width,i.height):e.renderbufferStorage(e.RENDERBUFFER,a,i.width,i.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,l,e.RENDERBUFFER,t)}else{const t=i.textures;for(let n=0;n<t.length;n++){const a=t[n],l=s.convert(a.format,a.colorSpace),u=s.convert(a.type),c=S(a.internalFormat,l,u,a.normalized,a.colorSpace);q(i)?o.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,X(i),c,i.width,i.height):r?e.renderbufferStorageMultisample(e.RENDERBUFFER,X(i),c,i.width,i.height):e.renderbufferStorage(e.RENDERBUFFER,c,i.width,i.height)}}e.bindRenderbuffer(e.RENDERBUFFER,null)}function W(t,n,s){const a=!0===n.isWebGLCubeRenderTarget;if(i.bindFramebuffer(e.FRAMEBUFFER,t),!n.depthTexture||!n.depthTexture.isDepthTexture)throw new Error("THREE.WebGLTextures: renderTarget.depthTexture must be an instance of THREE.DepthTexture.");const l=r.get(n.depthTexture);l.__renderTarget=n;const u=a?n.depthTexture.image[0]:n.depthTexture.image;l.__webglTexture&&u.width===n.width&&u.height===n.height||(u.width=n.width,u.height=n.height,n.depthTexture.needsUpdate=!0),a?U(n.depthTexture,0):D(n.depthTexture,0);const c=l.__webglTexture,h=X(n),d=a?e.TEXTURE_CUBE_MAP_POSITIVE_X+s:e.TEXTURE_2D,p=n.depthTexture.format===rt?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;if(n.depthTexture.format===it)q(n)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,p,d,c,0,h):e.framebufferTexture2D(e.FRAMEBUFFER,p,d,c,0);else{if(n.depthTexture.format!==rt)throw new Error("THREE.WebGLTextures: Unknown depthTexture format.");q(n)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,p,d,c,0,h):e.framebufferTexture2D(e.FRAMEBUFFER,p,d,c,0)}}function j(t){const n=r.get(t),s=!0===t.isWebGLCubeRenderTarget;if(n.__boundDepthTexture!==t.depthTexture){const e=t.depthTexture;if(n.__depthDisposeCallback&&n.__depthDisposeCallback(),e){const t=()=>{delete n.__boundDepthTexture,delete n.__depthDisposeCallback,e.removeEventListener("dispose",t)};e.addEventListener("dispose",t),n.__depthDisposeCallback=t}n.__boundDepthTexture=e}if(t.depthTexture&&!n.__autoAllocateDepthBuffer)if(s)for(let e=0;e<6;e++)W(n.__webglFramebuffer[e],t,e);else{t.texture.mipmaps.length>0?W(n.__webglFramebuffer[0],t,0):W(n.__webglFramebuffer,t,0)}else if(s){n.__webglDepthbuffer=[];for(let r=0;r<6;r++)if(i.bindFramebuffer(e.FRAMEBUFFER,n.__webglFramebuffer[r]),void 0===n.__webglDepthbuffer[r])n.__webglDepthbuffer[r]=e.createRenderbuffer(),H(n.__webglDepthbuffer[r],t,!1);else{const i=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,s=n.__webglDepthbuffer[r];e.bindRenderbuffer(e.RENDERBUFFER,s),e.framebufferRenderbuffer(e.FRAMEBUFFER,i,e.RENDERBUFFER,s)}}else{if(t.texture.mipmaps.length>0?i.bindFramebuffer(e.FRAMEBUFFER,n.__webglFramebuffer[0]):i.bindFramebuffer(e.FRAMEBUFFER,n.__webglFramebuffer),void 0===n.__webglDepthbuffer)n.__webglDepthbuffer=e.createRenderbuffer(),H(n.__webglDepthbuffer,t,!1);else{const i=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,r=n.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,r),e.framebufferRenderbuffer(e.FRAMEBUFFER,i,e.RENDERBUFFER,r)}}i.bindFramebuffer(e.FRAMEBUFFER,null)}const $=[];function X(e){return Math.min(n.maxSamples,e.samples)}function q(e){const i=r.get(e);return e.samples>0&&!0===t.has("WEBGL_multisampled_render_to_texture")&&!1!==i.__useRenderToTexture}function Y(e,t){const i=e.colorSpace,r=e.format,n=e.type;return!0===e.isCompressedTexture||!0===e.isVideoTexture||i!==qt&&i!==$t&&(Qi.getTransfer(i)===Kt?r===tt&&n===ze||Ti("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):Mi("WebGLTextures: Unsupported texture color space:",i)),t}function K(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=L;return e>=n.maxTextures&&Ti("WebGLTextures: Trying to use "+(e+1)+" texture units while this GPU supports only "+n.maxTextures),L+=1,e},this.resetTextureUnits=function(){L=0},this.getTextureUnits=function(){return L},this.setTextureUnits=function(e){L=e},this.setTexture2D=D,this.setTexture2DArray=function(t,n){const s=r.get(t);!1===t.isRenderTargetTexture&&t.version>0&&s.__version!==t.version?G(s,t,n):(t.isExternalTexture&&(s.__webglTexture=t.sourceTexture?t.sourceTexture:null),i.bindTexture(e.TEXTURE_2D_ARRAY,s.__webglTexture,e.TEXTURE0+n))},this.setTexture3D=function(t,n){const s=r.get(t);!1===t.isRenderTargetTexture&&t.version>0&&s.__version!==t.version?G(s,t,n):i.bindTexture(e.TEXTURE_3D,s.__webglTexture,e.TEXTURE0+n)},this.setTextureCube=U,this.rebindTextures=function(t,i,n){const s=r.get(t);void 0!==i&&V(s.__webglFramebuffer,t,t.texture,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,0),void 0!==n&&j(t)},this.setupRenderTarget=function(t){const n=t.texture,o=r.get(t),l=r.get(n);t.addEventListener("dispose",R),E(t);const u=t.textures,c=!0===t.isWebGLCubeRenderTarget,h=u.length>1;if(h||(void 0===l.__webglTexture&&(l.__webglTexture=e.createTexture()),l.__version=n.version,a.memory.textures++),c){o.__webglFramebuffer=[];for(let t=0;t<6;t++)if(n.mipmaps.length>0){o.__webglFramebuffer[t]=[];for(let i=0;i<n.mipmaps.length;i++)o.__webglFramebuffer[t][i]=e.createFramebuffer()}else o.__webglFramebuffer[t]=e.createFramebuffer()}else{if(n.mipmaps.length>0){o.__webglFramebuffer=[];for(let t=0;t<n.mipmaps.length;t++)o.__webglFramebuffer[t]=e.createFramebuffer()}else o.__webglFramebuffer=e.createFramebuffer();if(h)for(let t=0,i=u.length;t<i;t++){const i=r.get(u[t]);void 0===i.__webglTexture&&(i.__webglTexture=e.createTexture(),a.memory.textures++)}if(t.samples>0&&!1===q(t)){o.__webglMultisampledFramebuffer=e.createFramebuffer(),o.__webglColorRenderbuffer=[],i.bindFramebuffer(e.FRAMEBUFFER,o.__webglMultisampledFramebuffer);for(let i=0;i<u.length;i++){const r=u[i];o.__webglColorRenderbuffer[i]=e.createRenderbuffer(),e.bindRenderbuffer(e.RENDERBUFFER,o.__webglColorRenderbuffer[i]);const n=s.convert(r.format,r.colorSpace),a=s.convert(r.type),l=S(r.internalFormat,n,a,r.normalized,r.colorSpace,!0===t.isXRRenderTarget),c=X(t);e.renderbufferStorageMultisample(e.RENDERBUFFER,c,l,t.width,t.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+i,e.RENDERBUFFER,o.__webglColorRenderbuffer[i])}e.bindRenderbuffer(e.RENDERBUFFER,null),t.depthBuffer&&(o.__webglDepthRenderbuffer=e.createRenderbuffer(),H(o.__webglDepthRenderbuffer,t,!0)),i.bindFramebuffer(e.FRAMEBUFFER,null)}}if(c){i.bindTexture(e.TEXTURE_CUBE_MAP,l.__webglTexture),B(e.TEXTURE_CUBE_MAP,n);for(let i=0;i<6;i++)if(n.mipmaps.length>0)for(let r=0;r<n.mipmaps.length;r++)V(o.__webglFramebuffer[i][r],t,n,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+i,r);else V(o.__webglFramebuffer[i],t,n,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+i,0);b(n)?y(e.TEXTURE_CUBE_MAP):n.mipmaps.length>0&&e.texParameteri(e.TEXTURE_CUBE_MAP,e.TEXTURE_MAX_LEVEL,n.mipmaps.length-1),i.unbindTexture()}else if(h){for(let n=0,s=u.length;n<s;n++){const s=u[n],a=r.get(s);let l=e.TEXTURE_2D;(t.isWebGL3DRenderTarget||t.isWebGLArrayRenderTarget)&&(l=t.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),i.bindTexture(l,a.__webglTexture),B(l,s),V(o.__webglFramebuffer,t,s,e.COLOR_ATTACHMENT0+n,l,0),b(s)&&y(l)}i.unbindTexture()}else{let r=e.TEXTURE_2D;if((t.isWebGL3DRenderTarget||t.isWebGLArrayRenderTarget)&&(r=t.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),i.bindTexture(r,l.__webglTexture),B(r,n),n.mipmaps.length>0)for(let i=0;i<n.mipmaps.length;i++)V(o.__webglFramebuffer[i],t,n,e.COLOR_ATTACHMENT0,r,i);else V(o.__webglFramebuffer,t,n,e.COLOR_ATTACHMENT0,r,0);b(n)?y(r):n.mipmaps.length>0&&e.texParameteri(r,e.TEXTURE_MAX_LEVEL,n.mipmaps.length-1),i.unbindTexture()}t.depthBuffer&&j(t)},this.updateRenderTargetMipmap=function(e){const t=e.textures;for(let n=0,s=t.length;n<s;n++){const s=t[n];if(b(s)&&!0===s.mipmapsAutoUpdate){const t=x(e),n=r.get(s).__webglTexture;i.bindTexture(t,n),y(t),i.unbindTexture()}}},this.updateMultisampleRenderTarget=function(t){if(t.samples>0)if(!1===q(t)){const n=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=r.get(t),h=n.length>1;if(h)for(let t=0;t<n.length;t++)i.bindFramebuffer(e.FRAMEBUFFER,c.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,null),i.bindFramebuffer(e.FRAMEBUFFER,c.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,null,0);i.bindFramebuffer(e.READ_FRAMEBUFFER,c.__webglMultisampledFramebuffer);t.texture.mipmaps.length>0?i.bindFramebuffer(e.DRAW_FRAMEBUFFER,c.__webglFramebuffer[0]):i.bindFramebuffer(e.DRAW_FRAMEBUFFER,c.__webglFramebuffer);for(let i=0;i<n.length;i++){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[i]);const t=r.get(n[i]).__webglTexture;e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)}e.blitFramebuffer(0,0,s,a,0,0,s,a,o,e.NEAREST),!0===l&&($.length=0,$.push(e.COLOR_ATTACHMENT0+i),t.depthBuffer&&!1===t.storeMultisampledDepthBuffer&&$.push(u),e.invalidateFramebuffer(e.READ_FRAMEBUFFER,$))}if(i.bindFramebuffer(e.READ_FRAMEBUFFER,null),i.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),h)for(let t=0;t<n.length;t++){i.bindFramebuffer(e.FRAMEBUFFER,c.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,c.__webglColorRenderbuffer[t]);const s=r.get(n[t]).__webglTexture;i.bindFramebuffer(e.FRAMEBUFFER,c.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,s,0)}i.bindFramebuffer(e.DRAW_FRAMEBUFFER,c.__webglMultisampledFramebuffer)}else if(t.depthBuffer&&!1===t.storeMultisampledDepthBuffer&&l){const i=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,[i])}},this.setupDepthRenderbuffer=j,this.setupFrameBufferTexture=V,this.useMultisampledRTT=q,this.dispose=function(){for(const e of f){const t=e.deref();void 0!==t&&(!0===t.isRenderTarget?N(t):C(t))}f.clear(),h.clear()}}function Gu(e,t){return{convert:function(i,r=""){let n;const s=Qi.getTransfer(r);if(i===ze)return e.UNSIGNED_BYTE;if(i===qe)return e.UNSIGNED_SHORT_4_4_4_4;if(i===Ye)return e.UNSIGNED_SHORT_5_5_5_1;if(i===Ze)return e.UNSIGNED_INT_5_9_9_9_REV;if(i===Qe)return e.UNSIGNED_INT_10F_11F_11F_REV;if(i===Ge)return e.BYTE;if(i===Ve)return e.SHORT;if(i===He)return e.UNSIGNED_SHORT;if(i===We)return e.INT;if(i===je)return e.UNSIGNED_INT;if(i===$e)return e.FLOAT;if(i===Xe)return e.HALF_FLOAT;if(i===Je)return e.ALPHA;if(i===et)return e.RGB;if(i===tt)return e.RGBA;if(i===it)return e.DEPTH_COMPONENT;if(i===rt)return e.DEPTH_STENCIL;if(i===nt)return e.RED;if(i===st)return e.RED_INTEGER;if(i===at)return e.RG;if(i===ot)return e.RG_INTEGER;if(i===ut)return e.RGBA_INTEGER;if(i===ct||i===ht||i===dt||i===pt)if(s===Kt){if(n=t.get("WEBGL_compressed_texture_s3tc_srgb"),null===n)return null;if(i===ct)return n.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===ht)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===dt)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===pt)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(n=t.get("WEBGL_compressed_texture_s3tc"),null===n)return null;if(i===ct)return n.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===ht)return n.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===dt)return n.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===pt)return n.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(i===ft||i===mt||i===gt||i===_t){if(n=t.get("WEBGL_compressed_texture_pvrtc"),null===n)return null;if(i===ft)return n.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===mt)return n.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===gt)return n.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===_t)return n.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(i===vt||i===bt||i===yt||i===xt||i===St||i===Tt||i===Mt){if(n=t.get("WEBGL_compressed_texture_etc"),null===n)return null;if(i===vt||i===bt)return s===Kt?n.COMPRESSED_SRGB8_ETC2:n.COMPRESSED_RGB8_ETC2;if(i===yt)return s===Kt?n.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:n.COMPRESSED_RGBA8_ETC2_EAC;if(i===xt)return n.COMPRESSED_R11_EAC;if(i===St)return n.COMPRESSED_SIGNED_R11_EAC;if(i===Tt)return n.COMPRESSED_RG11_EAC;if(i===Mt)return n.COMPRESSED_SIGNED_RG11_EAC}if(i===Et||i===wt||i===At||i===Rt||i===Ct||i===Nt||i===Pt||i===Lt||i===Dt||i===Ut||i===It||i===Ft||i===Ot||i===Bt){if(n=t.get("WEBGL_compressed_texture_astc"),null===n)return null;if(i===Et)return s===Kt?n.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:n.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===wt)return s===Kt?n.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:n.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===At)return s===Kt?n.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:n.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===Rt)return s===Kt?n.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:n.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===Ct)return s===Kt?n.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:n.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===Nt)return s===Kt?n.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:n.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===Pt)return s===Kt?n.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:n.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===Lt)return s===Kt?n.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:n.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===Dt)return s===Kt?n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:n.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===Ut)return s===Kt?n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:n.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===It)return s===Kt?n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:n.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===Ft)return s===Kt?n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:n.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===Ot)return s===Kt?n.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:n.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===Bt)return s===Kt?n.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:n.COMPRESSED_RGBA_ASTC_12x12_KHR}if(i===kt||i===zt||i===Gt){if(n=t.get("EXT_texture_compression_bptc"),null===n)return null;if(i===kt)return s===Kt?n.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:n.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===zt)return n.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===Gt)return n.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}if(i===Vt||i===Ht||i===Wt||i===jt){if(n=t.get("EXT_texture_compression_rgtc"),null===n)return null;if(i===Vt)return n.COMPRESSED_RED_RGTC1_EXT;if(i===Ht)return n.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===Wt)return n.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===jt)return n.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}return i===Ke?e.UNSIGNED_INT_24_8:void 0!==e[i]?e[i]:null}}}class Vu{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(null===this.texture){const i=new Zs(e.texture);e.depthNear===t.depthNear&&e.depthFar===t.depthFar||(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=i}}getMesh(e){if(null!==this.texture&&null===this.mesh){const t=e.cameras[0].viewport,i=new la({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 ws(new ea(20,20),i)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class Hu extends Ri{constructor(e,t){super();const i=this;let r=null,n=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 Vu,g={},_=t.getContextAttributes();let v=null,b=null;const y=[],x=[],S=new Vi;let T=null,M=null;const E=new za;E.viewport=new ur;const w=new za;w.viewport=new ur;const A=[E,w],R=new eo;let C=null,N=null;function P(e){const t=x.indexOf(e.inputSource);if(-1===t)return;const i=y[t];void 0!==i&&(i.update(e.inputSource,e.frame,l||s),i.dispatchEvent({type:e.type,data:e.inputSource}))}function L(){r.removeEventListener("select",P),r.removeEventListener("selectstart",P),r.removeEventListener("selectend",P),r.removeEventListener("squeeze",P),r.removeEventListener("squeezestart",P),r.removeEventListener("squeezeend",P),r.removeEventListener("end",L),r.removeEventListener("inputsourceschange",D);for(let e=0;e<y.length;e++){const t=x[e];null!==t&&(x[e]=null,y[e].disconnect(t))}C=null,N=null,m.reset();for(const e in g)delete g[e];if(e.setRenderTarget(v),d=null,h=null,c=null,r=null,b=null,F.stop(),i.isPresenting=!1,e.setPixelRatio(T),e.setSize(S.width,S.height,!1),null!==M){const e=M.camera;e.fov=M.fov,e.zoom=M.zoom,e.updateProjectionMatrix(),M=null}i.dispatchEvent({type:"sessionend"})}function D(e){for(let t=0;t<e.removed.length;t++){const i=e.removed[t],r=x.indexOf(i);r>=0&&(x[r]=null,y[r].disconnect(i))}for(let t=0;t<e.added.length;t++){const i=e.added[t];let r=x.indexOf(i);if(-1===r){for(let e=0;e<y.length;e++){if(e>=x.length){x.push(i),r=e;break}if(null===x[e]){x[e]=i,r=e;break}}if(-1===r)break}const n=y[r];n&&n.connect(i)}}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.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(e){let t=y[e];return void 0===t&&(t=new Wr,y[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=y[e];return void 0===t&&(t=new Wr,y[e]=t),t.getGripSpace()},this.getHand=function(e){let t=y[e];return void 0===t&&(t=new Wr,y[e]=t),t.getHandSpace()},this.setFramebufferScaleFactor=function(e){n=e,!0===i.isPresenting&&Ti("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(e){a=e,!0===i.isPresenting&&Ti("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(r,t)),c},this.getFrame=function(){return p},this.getSession=function(){return r},this.setSession=async function(u){if(r=u,null!==r){v=e.getRenderTarget(),r.addEventListener("select",P),r.addEventListener("selectstart",P),r.addEventListener("selectend",P),r.addEventListener("squeeze",P),r.addEventListener("squeezestart",P),r.addEventListener("squeezeend",P),r.addEventListener("end",L),r.addEventListener("inputsourceschange",D),!0!==_.xrCompatible&&await t.makeXRCompatible(),T=e.getPixelRatio(),e.getSize(S);if(f&&"createProjectionLayer"in XRWebGLBinding.prototype){let i=null,s=null,a=null;_.depth&&(a=_.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,i=_.stencil?rt:it,s=_.stencil?Ke:je);const o={colorFormat:t.RGBA8,depthFormat:a,scaleFactor:n};c=this.getBinding(),h=c.createProjectionLayer(o),r.updateRenderState({layers:[h]}),e.setPixelRatio(1),e.setSize(h.textureWidth,h.textureHeight,!1),b=new hr(h.textureWidth,h.textureHeight,{format:tt,type:ze,depthTexture:new Ys(h.textureWidth,h.textureHeight,s,void 0,void 0,void 0,void 0,void 0,void 0,i),stencilBuffer:_.stencil,colorSpace:e.outputColorSpace,samples:_.antialias?4:0,resolveDepthBuffer:!1===h.ignoreDepthValues,resolveStencilBuffer:!1===h.ignoreDepthValues,storeMultisampledDepthBuffer:!1===h.ignoreDepthValues,storeMultisampledStencilBuffer:!1===h.ignoreDepthValues})}else{const i={antialias:_.antialias,alpha:!0,depth:_.depth,stencil:_.stencil,framebufferScaleFactor:n};d=new XRWebGLLayer(r,t,i),r.updateRenderState({baseLayer:d}),e.setPixelRatio(1),e.setSize(d.framebufferWidth,d.framebufferHeight,!1),b=new hr(d.framebufferWidth,d.framebufferHeight,{format:tt,type:ze,colorSpace:e.outputColorSpace,stencilBuffer:_.stencil,resolveDepthBuffer:!1===d.ignoreDepthValues,resolveStencilBuffer:!1===d.ignoreDepthValues,storeMultisampledDepthBuffer:!1===d.ignoreDepthValues,storeMultisampledStencilBuffer:!1===d.ignoreDepthValues})}b.isXRRenderTarget=!0,this.setFoveation(o),l=null,s=await r.requestReferenceSpace(a),F.setContext(r),F.start(),i.isPresenting=!0,i.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(null!==r)return r.environmentBlendMode},this.getDepthTexture=function(){return m.getDepthTexture()},this.updateCamera=function(e){if(null===r)return;let t=e.near,i=e.far;null!==m.texture&&(m.depthNear>0&&(t=m.depthNear),m.depthFar>0&&(i=m.depthFar)),R.near=w.near=E.near=t,R.far=w.far=E.far=i,C===R.near&&N===R.far||(r.updateRenderState({depthNear:R.near,depthFar:R.far}),C=R.near,N=R.far),R.layers.mask=6|e.layers.mask,E.layers.mask=-5&R.layers.mask,w.layers.mask=-3&R.layers.mask;const n=e.parent,s=R.cameras;U(R,n);for(let e=0;e<s.length;e++)U(s[e],n);R.projectionMatrix.copy(E.projectionMatrix),R.projectionMatrixInverse.copy(E.projectionMatrixInverse),null===M&&e.isPerspectiveCamera&&(M={camera:e,fov:e.fov,zoom:e.zoom}),function(e,t,i){null===i?e.matrix.copy(t.matrixWorld):(e.matrix.copy(i.matrixWorld),e.matrix.invert(),e.matrix.multiply(t.matrixWorld));e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(!0),e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse),e.isPerspectiveCamera&&(e.fov=2*Li*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}(e,R,n)},this.getCamera=function(){return R},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(R)},this.getCameraTexture=function(e){return g[e]};let I=null;const F=new co;F.setAnimationLoop(function(t,n){if(u=n.getViewerPose(l||s),p=n,null!==u){const t=u.views;null!==d&&(e.setRenderTargetFramebuffer(b,d.framebuffer),e.setRenderTarget(b));let n=!1;t.length!==R.cameras.length&&(R.cameras.length=0,n=!0);for(let i=0;i<t.length;i++){const r=t[i];let s=null;if(null!==d)s=d.getViewport(r);else{const t=c.getViewSubImage(h,r);s=t.viewport,0===i&&(e.setRenderTargetTextures(b,t.colorTexture,t.depthStencilTexture),e.setRenderTarget(b))}let a=A[i];void 0===a&&(a=new za,a.layers.enable(i),a.viewport=new ur,A[i]=a),a.matrix.fromArray(r.transform.matrix),a.matrix.decompose(a.position,a.quaternion,a.scale),a.projectionMatrix.fromArray(r.projectionMatrix),a.projectionMatrixInverse.copy(a.projectionMatrix).invert(),a.viewport.set(s.x,s.y,s.width,s.height),0===i&&(R.matrix.copy(a.matrix),R.matrix.decompose(R.position,R.quaternion,R.scale)),!0===n&&R.cameras.push(a)}const s=r.enabledFeatures;if(s&&s.includes("depth-sensing")&&"gpu-optimized"==r.depthUsage&&f){c=i.getBinding();const e=c.getDepthInformation(t[0]);e&&e.isValid&&e.texture&&m.init(e,r.renderState)}if(s&&s.includes("camera-access")&&f){e.state.unbindTexture(),c=i.getBinding();for(let e=0;e<t.length;e++){const i=t[e].camera;if(i){let e=g[i];e||(e=new Zs,g[i]=e);const t=c.getCameraImage(i);e.sourceTexture=t}}}}for(let e=0;e<y.length;e++){const t=x[e],i=y[e];null!==t&&void 0!==i&&i.update(t,n,l||s)}I&&I(t,n),n.detectedPlanes&&i.dispatchEvent({type:"planesdetected",data:n}),p=null}),this.setAnimationLoop=function(e){I=e},this.dispose=function(){}}}const Wu=new fr,ju=new Xi;function $u(e,t){function i(e,t){!0===e.matrixAutoUpdate&&e.updateMatrix(),t.value.copy(e.matrix)}function r(e,r){e.opacity.value=r.opacity,r.color&&e.diffuse.value.copy(r.color),r.emissive&&e.emissive.value.copy(r.emissive).multiplyScalar(r.emissiveIntensity),r.map&&(e.map.value=r.map,i(r.map,e.mapTransform)),r.alphaMap&&(e.alphaMap.value=r.alphaMap,i(r.alphaMap,e.alphaMapTransform)),r.bumpMap&&(e.bumpMap.value=r.bumpMap,i(r.bumpMap,e.bumpMapTransform),e.bumpScale.value=r.bumpScale,1===r.side&&(e.bumpScale.value*=-1)),r.normalMap&&(e.normalMap.value=r.normalMap,i(r.normalMap,e.normalMapTransform),e.normalScale.value.copy(r.normalScale),1===r.side&&e.normalScale.value.negate()),r.displacementMap&&(e.displacementMap.value=r.displacementMap,i(r.displacementMap,e.displacementMapTransform),e.displacementScale.value=r.displacementScale,e.displacementBias.value=r.displacementBias),r.emissiveMap&&(e.emissiveMap.value=r.emissiveMap,i(r.emissiveMap,e.emissiveMapTransform)),r.specularMap&&(e.specularMap.value=r.specularMap,i(r.specularMap,e.specularMapTransform)),r.alphaTest>0&&(e.alphaTest.value=r.alphaTest);const n=t.get(r),s=n.envMap,a=n.envMapRotation;s&&(e.envMap.value=s,e.envMapRotation.value.setFromMatrix4(Wu.makeRotationFromEuler(a)).transpose(),s.isCubeTexture&&!1===s.isRenderTargetTexture&&e.envMapRotation.value.premultiply(ju),e.reflectivity.value=r.reflectivity,e.ior.value=r.ior,e.refractionRatio.value=r.refractionRatio),r.lightMap&&(e.lightMap.value=r.lightMap,e.lightMapIntensity.value=r.lightMapIntensity,i(r.lightMap,e.lightMapTransform)),r.aoMap&&(e.aoMap.value=r.aoMap,e.aoMapIntensity.value=r.aoMapIntensity,i(r.aoMap,e.aoMapTransform))}return{refreshFogUniforms:function(t,i){i.color.getRGB(t.fogColor.value,aa(e)),i.isFog?(t.fogNear.value=i.near,t.fogFar.value=i.far):i.isFogExp2&&(t.fogDensity.value=i.density)},refreshMaterialUniforms:function(e,n,s,a,o){n.isNodeMaterial?n.uniformsNeedUpdate=!1:n.isMeshBasicMaterial?r(e,n):n.isMeshLambertMaterial?(r(e,n),n.envMap&&(e.envMapIntensity.value=n.envMapIntensity)):n.isMeshToonMaterial?(r(e,n),function(e,t){t.gradientMap&&(e.gradientMap.value=t.gradientMap)}(e,n)):n.isMeshPhongMaterial?(r(e,n),function(e,t){e.specular.value.copy(t.specular),e.shininess.value=Math.max(t.shininess,1e-4)}(e,n),n.envMap&&(e.envMapIntensity.value=n.envMapIntensity)):n.isMeshStandardMaterial?(r(e,n),function(e,t){e.metalness.value=t.metalness,t.metalnessMap&&(e.metalnessMap.value=t.metalnessMap,i(t.metalnessMap,e.metalnessMapTransform));e.roughness.value=t.roughness,t.roughnessMap&&(e.roughnessMap.value=t.roughnessMap,i(t.roughnessMap,e.roughnessMapTransform));t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)}(e,n),n.isMeshPhysicalMaterial&&function(e,t,r){e.ior.value=t.ior,t.diffuseRoughness>0&&(e.diffuseRoughness.value=t.diffuseRoughness,t.diffuseRoughnessMap&&(e.diffuseRoughnessMap.value=t.diffuseRoughnessMap,i(t.diffuseRoughnessMap,e.diffuseRoughnessMapTransform)));t.sheen>0&&(e.sheenColor.value.copy(t.sheenColor).multiplyScalar(t.sheen),e.sheenRoughness.value=t.sheenRoughness,t.sheenColorMap&&(e.sheenColorMap.value=t.sheenColorMap,i(t.sheenColorMap,e.sheenColorMapTransform)),t.sheenRoughnessMap&&(e.sheenRoughnessMap.value=t.sheenRoughnessMap,i(t.sheenRoughnessMap,e.sheenRoughnessMapTransform)));t.clearcoat>0&&(e.clearcoat.value=t.clearcoat,e.clearcoatRoughness.value=t.clearcoatRoughness,t.clearcoatMap&&(e.clearcoatMap.value=t.clearcoatMap,i(t.clearcoatMap,e.clearcoatMapTransform)),t.clearcoatRoughnessMap&&(e.clearcoatRoughnessMap.value=t.clearcoatRoughnessMap,i(t.clearcoatRoughnessMap,e.clearcoatRoughnessMapTransform)),t.clearcoatNormalMap&&(e.clearcoatNormalMap.value=t.clearcoatNormalMap,i(t.clearcoatNormalMap,e.clearcoatNormalMapTransform),e.clearcoatNormalScale.value.copy(t.clearcoatNormalScale),1===t.side&&e.clearcoatNormalScale.value.negate()));t.dispersion>0&&(e.dispersion.value=t.dispersion);t.retroreflectivity>0&&(e.retroreflectivity.value=t.retroreflectivity);t.iridescence>0&&(e.iridescence.value=t.iridescence,e.iridescenceIOR.value=t.iridescenceIOR,e.iridescenceThicknessMinimum.value=t.iridescenceThicknessMinimum,e.iridescenceThicknessMaximum.value=t.iridescenceThicknessMaximum,t.iridescenceMap&&(e.iridescenceMap.value=t.iridescenceMap,i(t.iridescenceMap,e.iridescenceMapTransform)),t.iridescenceThicknessMap&&(e.iridescenceThicknessMap.value=t.iridescenceThicknessMap,i(t.iridescenceThicknessMap,e.iridescenceThicknessMapTransform)));t.transmission>0&&(e.transmission.value=t.transmission,e.transmissionSamplerMap.value=r.texture,e.transmissionSamplerSize.value.set(r.width,r.height),t.transmissionMap&&(e.transmissionMap.value=t.transmissionMap,i(t.transmissionMap,e.transmissionMapTransform)),e.thickness.value=t.thickness,t.thicknessMap&&(e.thicknessMap.value=t.thicknessMap,i(t.thicknessMap,e.thicknessMapTransform)),e.attenuationDistance.value=t.attenuationDistance,e.attenuationColor.value.copy(t.attenuationColor));t.anisotropy>0&&(e.anisotropyVector.value.set(t.anisotropy*Math.cos(t.anisotropyRotation),t.anisotropy*Math.sin(t.anisotropyRotation)),t.anisotropyMap&&(e.anisotropyMap.value=t.anisotropyMap,i(t.anisotropyMap,e.anisotropyMapTransform)));e.specularIntensity.value=t.specularIntensity,e.specularColor.value.copy(t.specularColor),t.specularColorMap&&(e.specularColorMap.value=t.specularColorMap,i(t.specularColorMap,e.specularColorMapTransform));t.specularIntensityMap&&(e.specularIntensityMap.value=t.specularIntensityMap,i(t.specularIntensityMap,e.specularIntensityMapTransform))}(e,n,o)):n.isMeshMatcapMaterial?(r(e,n),function(e,t){t.matcap&&(e.matcap.value=t.matcap)}(e,n)):n.isMeshDepthMaterial?r(e,n):n.isMeshDistanceMaterial?(r(e,n),function(e,i){const r=t.get(i).light;e.referencePosition.value.setFromMatrixPosition(r.matrixWorld),e.nearDistance.value=r.shadow.camera.near,e.farDistance.value=r.shadow.camera.far}(e,n)):n.isMeshNormalMaterial?r(e,n):n.isLineBasicMaterial?(function(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,t.map&&(e.map.value=t.map,i(t.map,e.mapTransform))}(e,n),n.isLineDashedMaterial&&function(e,t){e.dashSize.value=t.dashSize,e.totalSize.value=t.dashSize+t.gapSize,e.scale.value=t.scale}(e,n)):n.isPointsMaterial?function(e,t,r,n){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.size.value=t.size*r,e.scale.value=.5*n,t.map&&(e.map.value=t.map,i(t.map,e.uvTransform));t.alphaMap&&(e.alphaMap.value=t.alphaMap,i(t.alphaMap,e.alphaMapTransform));t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}(e,n,s,a):n.isSpriteMaterial?function(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.rotation.value=t.rotation,t.map&&(e.map.value=t.map,i(t.map,e.mapTransform));t.alphaMap&&(e.alphaMap.value=t.alphaMap,i(t.alphaMap,e.alphaMapTransform));t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}(e,n):n.isShadowMaterial?(e.color.value.copy(n.color),e.opacity.value=n.opacity):n.isShaderMaterial&&(n.uniformsNeedUpdate=!1)}}}function Xu(e,t,i,r){let n={},s={};function a(t,i,r,n){if(!0===function(e,t,i,r){const n=e.value,s=t+"_"+i;if(Array.isArray(n)){void 0===r[s]&&(r[s]=[]);const e=r[s];let t=!1;for(let i=0;i<n.length;i++)!0===l(n[i],e,i)&&(t=!0);return t}return l(n,r,s)}(t,i,r,n)){const i=t.__offset,r=t.value;if(Array.isArray(r)){let e=0;for(let i=0;i<r.length;i++){const n=r[i],s=u(n,!0);o(n,t.__data,e),e+=s.storage/Float32Array.BYTES_PER_ELEMENT}}else o(r,t.__data,0);e.bufferSubData(e.UNIFORM_BUFFER,i,t.__data)}}function o(e,t,i){"number"==typeof e||"boolean"==typeof e?t[i]=e:e.isMatrix3?(t[i]=e.elements[0],t[i+1]=e.elements[1],t[i+2]=e.elements[2],t[i+3]=0,t[i+4]=e.elements[3],t[i+5]=e.elements[4],t[i+6]=e.elements[5],t[i+7]=0,t[i+8]=e.elements[6],t[i+9]=e.elements[7],t[i+10]=e.elements[8],t[i+11]=0):ArrayBuffer.isView(e)?t.set(e.subarray(0,t.length-i),i):e.toArray(t,i)}function l(e,t,i){if(void 0===t[i])return"number"==typeof e||"boolean"==typeof e?t[i]=e:ArrayBuffer.isView(e)?t[i]=e.slice():t[i]=e.clone(),!0;{const r=t[i];if("number"==typeof e||"boolean"==typeof e){if(r!==e)return t[i]=e,!0}else{if(ArrayBuffer.isView(e))return!0;if(!1===r.equals(e))return r.copy(e),!0}}return!1}function u(e,t){const i={boundary:0,storage:0};return"number"==typeof e||"boolean"==typeof e?(i.boundary=4,i.storage=4):e.isVector2?(i.boundary=8,i.storage=8):e.isVector3||e.isColor?(i.boundary=16,i.storage=12):e.isVector4?(i.boundary=16,i.storage=16):e.isMatrix3?(i.boundary=16,i.storage=48):e.isMatrix4?(i.boundary=16,i.storage=64):e.isTexture?Ti("WebGLRenderer: Texture samplers can not be part of an uniforms group."):ArrayBuffer.isView(e)?(i.boundary=16,i.storage=e.byteLength):Ti("WebGLRenderer: Unsupported uniform value type.",e),!0===t&&(i.boundary=16,i.storage=16*Math.ceil(i.storage/16)),i}function c(t){const i=t.target;i.removeEventListener("dispose",c),e.deleteBuffer(n[i.id]),delete n[i.id],delete s[i.id]}return{bind:function(e,t){const i=t.program;r.uniformBlockBinding(e,i,n[e.id])},update:function(i,o){let l=n[i.id];void 0===l&&(!function(e){const t=e.uniforms;let i=0;const r=16;for(let e=0,n=t.length;e<n;e++){const n=Array.isArray(t[e])?t[e]:[t[e]];for(let s=0,a=n.length;s<a;s++){const a=n[s],o=Array.isArray(a.value)?a.value:[a.value],l=Array.isArray(t[e])||Array.isArray(a.value);let c=i;for(let e=0,t=o.length;e<t;e++){const t=u(o[e],l),n=i%r,s=n%t.boundary,a=n+s;i+=s,0!==a&&r-a<t.storage&&(i+=r-a),0===e&&(c=i),i+=t.storage}const h="int"===a.type?Int32Array:"uint"===a.type?Uint32Array:Float32Array;a.__data=new h((i-c)/Float32Array.BYTES_PER_ELEMENT),a.__offset=c}}const n=i%r;n>0&&(i+=r-n);e.__size=i,e.__cache={}}(i),l=function(t){const i=e.createBuffer(),r=t.__size,n=t.usage;return e.bindBuffer(e.UNIFORM_BUFFER,i),e.bufferData(e.UNIFORM_BUFFER,r,n),e.bindBuffer(e.UNIFORM_BUFFER,null),i}(i),n[i.id]=l,i.addEventListener("dispose",c));const h=o.program;r.updateUBOMapping(i,h);const d=t.render.frame;s[i.id]!==d&&(!function(t){const i=n[t.id],r=t.uniforms,s=t.__cache;e.bindBuffer(e.UNIFORM_BUFFER,i);for(let e=0,t=r.length;e<t;e++){const t=r[e];if(Array.isArray(t))for(let i=0,r=t.length;i<r;i++)a(t[i],e,i,s);else a(t,e,0,s)}e.bindBuffer(e.UNIFORM_BUFFER,null)}(i),s[i.id]=d)},dispose:function(){for(const t in n)e.deleteBuffer(n[t]);n={},s={}}}}ju.set(-1,0,0,0,1,0,0,0,1);const qu=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 Yu=null;const Ku="vertex",Zu="none",Qu="frame",Ju="render",ec="object",tc="readOnly",ic="writeOnly",rc="readWrite",nc=["setup","analyze","generate"],sc=["fragment","vertex","compute"],ac=["x","y","z","w"],oc=[/^StackTrace\.js$/,/^TSLCore\.js$/,/^.*Node\.js$/,/^three\.webgpu.*\.js$/];class lc{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 i=e.match(t);if(!i)return null;const r=i[1]||i[2]||"",n=i[3].split("?")[0],s=parseInt(i[4],10),a=parseInt(i[5],10);return{fn:r,file:n.split("/").pop(),line:s,column:a}}).filter(e=>e&&!oc.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;return`${e}\n${this.stack.map(e=>{const t=`${e.file}:${e.line}:${e.column}`;return e.fn?` at ${e.fn} (${t})`:` at ${t}`}).join("\n")}`}}function uc(e,t=0){let i=3735928559^t,r=1103547991^t;if(Array.isArray(e))for(let t,n=0;n<e.length;n++)t=e[n],i=Math.imul(i^t,2654435761),r=Math.imul(r^t,1597334677);else for(let t,n=0;n<e.length;n++)t=e.charCodeAt(n),i=Math.imul(i^t,2654435761),r=Math.imul(r^t,1597334677);return i=Math.imul(i^i>>>16,2246822507),i^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(i^i>>>13,3266489909),4294967296*(2097151&r)+(i>>>0)}const cc=e=>uc(e),hc=e=>uc(e),dc=(...e)=>uc(e),pc=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]);function fc(e){return pc.get(e)}function mc(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 gc(e){if(!0===e.isDepthTexture)return"float";const t=e.format;let i,r;if(i=t===nt||t===st||t===it||t===rt||t===Je?1:t===at||t===ot?2:t===et||t===lt?3:4,r=e.type===je?"uint":e.type===We?"int":"float",1===i)return r;let n=fc(i);return"float"!==r&&(n=r[0]+n),n}function _c(e,...t){const i=e?e.slice(-4):void 0;return 1===t.length&&("vec2"===i?t=[t[0],t[0]]:"vec3"===i?t=[t[0],t[0],t[0]]:"vec4"===i&&(t=[t[0],t[0],t[0],t[0]])),"color"===e?new Yr(...t):"vec2"===i?new Vi(...t):"vec3"===i?new Wi(...t):"vec4"===i?new ur(...t):"mat2"===i?new oo(...t):"mat3"===i?new Xi(...t):"mat4"===i?new fr(...t):"bool"===e?t[0]||!1:"float"===e||"int"===e||"uint"===e?t[0]||0:"string"===e?t[0]||"":"ArrayBuffer"===e?(r=t[0],Uint8Array.from(atob(r),e=>e.charCodeAt(0)).buffer):null;var r}function vc(e,t){const i={...e,...t};return void 0!==e.overrideNodes&&void 0!==t.overrideNodes&&e.overrideNodes!==t.overrideNodes&&(i.overrideNodes=new Map([...e.overrideNodes,...t.overrideNodes])),i}function bc(e){return void 0!==e[0]&&null!==e[0]&&(e[0].isNode||Object.getPrototypeOf(e[0])!==Object.prototype)}const yc={analyze:"setup",generate:"analyze"};let xc=0;class Sc extends Ri{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=Zu,this.updateBeforeType=Zu,this.updateAfterType=Zu,this.version=0,this.name="",this.global=!1,this.parents=!1,this.assignable=!1,this.isNode=!0,this._inspectorNode=null,this._cacheKey=null,this._uuid=null,this._cacheKeyVersion=0,this.id=xc++,this.stackTrace=null,!0===Sc.captureStackTrace&&(this.stackTrace=new lc)}isCacheable(){return!0}toAssignable(){return this.assignable=!0,this.toStack()}isAssignable(e){return!0!==e.getDataFromNode(this).forceDeclaration&&this.assignable}isAssign(e){return e.getDataFromNode(this).assign}_updateAssignable(e,t,i=this){const r=e.context.nodeLoop;if(void 0===t.stack&&"setup"===e.buildStage)t.stack=e.declareBeforeBlock(this);else if(!0===this.assignable&&r&&"analyze"===e.buildStage&&!1===i.isCacheable(e)&&!1===e.isDeterministic(i)){const i=e.activeStacks.indexOf(t.stack),n=e.activeStacks.indexOf(e.getDataFromNode(r).stack);-1!==i&&n>=i&&(t.forceDeclaration=!0)}}_declaresAssignable(){return!0}_declareVariable(e,t,i,r,n){const s=e.getVarFromNode(this,null,i,void 0,r,!0,n),a=e.getPropertyName(s),o=r?e.generateLetStatement(s.type,a,s.count):e.generateVarStatement(s.type,a,s.count);return e.addLineFlowCode(`${o} = ${t}`,this),a}_isVariable(e,t){return(!0===t.assign||!0===t.forceDeclaration)&&"void"!==this.getNodeType(e)}_buildVariable(e,t,i){const r=this.getNodeType(e),n=e.getVectorType(r);if(void 0===t.propertyName){const i=this.generate.length<2?e.format(this.generate(e)||"",r,n):this.generate(e,n)||"";t.propertyName=this._declareVariable(e,i,n,!1,"variable")}return e.format(t.propertyName,n,i)}_isFunctionScope(){return!1}_checkFlowBlock(e,t){if(void 0!==t.flowBlock){const{guard:i,parent:r}=t.flowBlock,n=void 0!==i&&this._isFunctionScope();let s=e.flowBlock;for(;null!==s&&s!==t.flowBlock&&(!n||s.guard!==i||s.parent!==r);)s=s.parent;null===s&&(t.flowBlock=void 0,t.propertyName=void 0,t.snippet=void 0,t.generated=void 0)}}_setFlowBlock(e,t,i,r){const n=!1===this.isGlobal(e)||e.flow.code.length!==r;!1!==i||void 0===t.propertyName&&void 0===t.snippet||!n||null===e.flowBlock||(t.flowBlock=e.flowBlock)}set needsUpdate(e){!0===e&&this.version++}get uuid(){return null===this._uuid&&(this._uuid=Di()),this._uuid}get type(){return this.constructor.type}onUpdate(e,t){return this.updateType=t,this.update=e.bind(this),this}onFrameUpdate(e){return this.onUpdate(e,Qu)}onRenderUpdate(e){return this.onUpdate(e,Ju)}onObjectUpdate(e){return this.onUpdate(e,ec)}onReference(e){return this.updateReference=e.bind(this),this}updateReference(){return this}isGlobal(){return this.global}getChildren(){const e=this._getChildren(),t=[];for(let i=0;i<e.length;i++)t.push(e[i].childNode);return t}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);const i=Object.getOwnPropertyNames(this);for(let r=0;r<i.length;r++){const n=i[r];if(95===n.charCodeAt(0))continue;const s=this[n];if(!(null===s||"object"!=typeof s&&"function"!=typeof s||e.has(s)))if(!0===Array.isArray(s))for(let e=0;e<s.length;e++){const i=s[e];i&&!0===i.isNode&&t.push({property:n,index:e,childNode:i})}else if(s&&!0===s.isNode)t.push({property:n,childNode:s});else if(s&&Object.getPrototypeOf(s)===Object.prototype)for(const e in s){if(!0===e.startsWith("_"))continue;const i=s[e];i&&!0===i.isNode&&t.push({property:n,index:e,childNode:i})}}return t}getCacheKey(e=!1,t=null){if(!0===(e=e||this.version!==this._cacheKeyVersion)||null===this._cacheKey){null===t&&(t=new Set);const i=[];for(const{property:r,childNode:n}of this._getChildren(t))i.push(cc(r.slice(0,-4)),n.getCacheKey(e,t));this._cacheKey=dc(hc(i),this.customCacheKey()),this._cacheKeyVersion=this.version}return this._cacheKey}customCacheKey(){return this.id}getScope(){return this}getHash(){return String(this.id)}getUpdateType(){return this.updateType}getUpdateBeforeType(){return this.updateBeforeType}getUpdateAfterType(){return this.updateAfterType}getElementType(e){const t=this.getNodeType(e);return e.getElementType(t)}getMemberType(){return"void"}getNodeType(e,t=null){const i=e.getDataFromNode(this);let r;return null!==t?(i.typeFromOutput=i.typeFromOutput||{},r=i.typeFromOutput[t],void 0===r&&(r=this.generateNodeType(e,t),i.typeFromOutput[t]=r)):(r=i.type,void 0===r&&(r=this.generateNodeType(e),i.type=r)),r}generateNodeType(e,t=null){const i=e.getNodeProperties(this);return i.outputNode?i.outputNode.getNodeType(e,t):this.nodeType}getShared(e){const t=this.getHash(e),i=e.getNodeFromHash(t);let r=null;if(i&&i!==this)r=i;else if(e.context.overrideNodes){const t=e.context.overrideNodes.get(this);if(t){const i=e.getDataFromNode(this),n=i.overrides||(i.overrides=new Map);!1===n.has(t)?(n.set(t,null),r=t(e).overrideNode(this,null),n.set(t,r)):r=n.get(t)}}return r||this}getArrayCount(){return null}setup(e){const t=e.getNodeProperties(this);let i=0;for(const e of this.getChildren())t["node"+i++]=e;return t.outputNode||null}analyze(e,t=null){const i=e.increaseUsage(this);if(!0===this.parents){const i=e.getDataFromNode(this,"any");i.stages=i.stages||{},i.stages[e.shaderStage]=i.stages[e.shaderStage]||[],i.stages[e.shaderStage].push(t)}if(1===i){const t=e.getNodeProperties(this);for(const i of Object.values(t))i&&!0===i.isNode&&i.build(e,this)}}generate(e,t){const{outputNode:i}=e.getNodeProperties(this);if(i&&!0===i.isNode)return i.build(e,t)}updateBefore(){Ti("Abstract function.")}updateAfter(){Ti("Abstract function.")}update(){Ti("Abstract function.")}_setupInspector(e){null!==this._inspectorNode&&"setup"===e.buildStage&&e.addNode(this._inspectorNode)}build(e,t=null){this._setupInspector(e);const i=this.getShared(e);if(this!==i)return i.build(e,t);const r=e.getDataFromNode(this);!0===this.assignable&&this._declaresAssignable()&&this._updateAssignable(e,r),r.buildStages=r.buildStages||{setup:!1,analyze:!1,generate:!1},r.buildStages[e.buildStage]=!0;const n=yc[e.buildStage];if(n&&!0!==r.buildStages[n]){const t=e.getBuildStage();e.setBuildStage(n),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 i of Object.values(t))if(i&&!0===i.isNode){if(!0===i.parents){const t=e.getNodeProperties(i);t.parents=t.parents||[],t.parents.push(this)}i.build(e)}e.addSequentialNode(this)}s=t.outputNode}else if("analyze"===a)this.analyze(e,t);else if("generate"===a){this._checkFlowBlock(e,r);const i=void 0!==r.propertyName||void 0!==r.snippet,n=e.flow.code.length,a=this.isCacheable(e)&&!1===e.isReference(t),o=a?e.getVectorType(this.getNodeType(e,t)):null,l=a&&"void"!==o&&"void"!==t&&r.usageCount>1,u=l?o:t;if(!0===this.assignable&&this._declaresAssignable()&&this._isVariable(e,r))s=this._buildVariable(e,r,t);else if(a&&void 0!==r.propertyName)s=e.format(r.propertyName,o,t);else{if(this.generate.length<2){const t=this.getNodeType(e);s=r.snippet,void 0===s&&(void 0===r.generated?(r.generated=!0,s=this.generate(e)||"",r.snippet=s):(Ti("Node: Recursion detected.",this),s="/* Recursion detected. */")),s=e.format(s,t,u)}else s=this.generate(e,u)||"";if(""===s&&null!==u&&"void"!==u&&"OutputType"!==u&&(Mi(`TSL: Invalid generated code, expected a "${u}".`),s=e.generateConst(u)),l){const i=this._declareVariable(e,s,o,!0!==r.assign,"cacheVariable");r.snippet=s,r.propertyName=i,s=e.format(i,o,t)}}this._setFlowBlock(e,r,i,n)}return e.removeChain(this),s}getSerializeChildren(){return this._getChildren()}serialize(e){const t=this.getSerializeChildren(),i={};for(const{property:r,index:n,childNode:s}of t)void 0!==n?(void 0===i[r]&&(i[r]=Number.isInteger(n)?[]:{}),i[r][n]=s.toJSON(e.meta).uuid):i[r]=s.toJSON(e.meta).uuid;Object.keys(i).length>0&&(e.inputNodes=i)}deserialize(e){if(void 0!==e.inputNodes){const t=e.meta.nodes;for(const i in e.inputNodes)if(Array.isArray(e.inputNodes[i])){const r=[];for(const n of e.inputNodes[i])r.push(t[n]);this[i]=r}else if("object"==typeof e.inputNodes[i]){const r={};for(const n in e.inputNodes[i]){const s=e.inputNodes[i][n];r[n]=t[s]}this[i]=r}else{const r=e.inputNodes[i];this[i]=t[r]}}}toJSON(e){const{uuid:t,type:i}=this,r=void 0===e||"string"==typeof e;r&&(e={textures:{},images:{},nodes:{}});let n=e.nodes[t];function s(e){const t=[];for(const i in e){const r=e[i];delete r.metadata,t.push(r)}return t}if(void 0===n&&(n={uuid:t,type:i,meta:e,metadata:{version:4.7,type:"Node",generator:"Node.toJSON"}},!0!==r&&(e.nodes[n.uuid]=n),this.serialize(n),delete n.meta),r){const t=s(e.textures),i=s(e.images),r=s(e.nodes);t.length>0&&(n.textures=t),i.length>0&&(n.images=i),r.length>0&&(n.nodes=r)}return n}}Sc.captureStackTrace=!1;class Tc extends Sc{static get type(){return"ArrayElementNode"}constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}isCacheable(){return!1}getScope(){return this.node.getScope()}generateNodeType(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 Mc extends Sc{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}generateNodeType(e){const t=this.node.getNodeType(e);let i=null;for(const r of this.convertTo.split("|"))null!==i&&e.getTypeLength(t)!==e.getTypeLength(r)||(i=r);return i}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){const i=this.node,r=this.getNodeType(e),n=i.build(e,r);return e.format(n,r,t)}}class Ec extends Sc{static get type(){return"JoinNode"}constructor(e=[],t=null){super(t),this.nodes=e}generateNodeType(e){return null!==this.nodeType?e.getVectorType(this.nodeType):e.getTypeFromLength(this.nodes.reduce((t,i)=>t+e.getTypeLength(i.getNodeType(e)),0))}generate(e,t){const i=this.getNodeType(e),r=e.getTypeLength(i),n=this.nodes,s=e.getComponentType(i),a=[];let o=0;for(const t of n){if(o>=r){Mi(`TSL: Length of parameters exceeds maximum length of function '${i}()' type.`,this.stackTrace);break}let n,l=t.getNodeType(e),u=e.getTypeLength(l);o+u>r&&(Mi(`TSL: Length of '${i}()' data exceeds maximum length of output type.`,this.stackTrace),u=r-o,l=e.getTypeFromLength(u)),o+=u,n=t.build(e,l);if(e.getComponentType(l)!==s){const t=e.getTypeFromLength(u,s);n=e.format(n,l,t)}a.push(n)}const l=`${e.getType(i)}( ${a.join(", ")} )`;return e.format(l,i,t)}}const wc=ac.join("");class Ac extends Sc{static get type(){return"SplitNode"}constructor(e,t="x"){super(),this.node=e,this.components=t,this.isSplitNode=!0}isCacheable(){return!1}getVectorLength(){let e=this.components.length;for(const t of this.components)e=Math.max(ac.indexOf(t)+1,e);return e}getComponentType(e){return e.getComponentType(this.node.getNodeType(e))}generateNodeType(e){return e.getTypeFromLength(this.components.length,this.getComponentType(e))}getScope(){return this.node.getScope()}generate(e,t){const i=this.node,r=e.getTypeLength(i.getNodeType(e));let n=null;if(r>1){let s=null;this.getVectorLength()>=r&&(s=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const a=i.build(e,s);n=this.components.length===r&&this.components===wc.slice(0,this.components.length)?e.format(a,s,t):e.format(`${a}.${this.components}`,this.getNodeType(e),t)}else n=i.build(e,t);return n}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}class Rc extends Sc{static get type(){return"SetNode"}constructor(e,t,i){super(),this.sourceNode=e,this.components=t,this.targetNode=i}generateNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:i,targetNode:r}=this,n=this.getNodeType(e),s=e.getComponentType(r.getNodeType(e)),a=e.getTypeFromLength(i.length,s),o=r.build(e,a),l=t.build(e,n),u=e.getTypeLength(n),c=[];for(let e=0;e<u;e++){const t=ac[e];t===i[0]?(c.push(o),e+=i.length-1):c.push(l+"."+t)}return`${e.getType(n)}( ${c.join(", ")} )`}}class Cc extends Sc{static get type(){return"FlipNode"}constructor(e,t){super(),this.sourceNode=e,this.components=t}generateNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{components:t,sourceNode:i}=this,r=this.getNodeType(e),n=i.build(e),s=e.getVarFromNode(this),a=e.getPropertyName(s);e.addLineFlowCode(a+" = "+n,this);const o=e.getTypeLength(r),l=[];let u=0;for(let e=0;e<o;e++){const i=ac[e];i===t[u]?(l.push("1.0 - "+a+"."+i),u++):l.push(a+"."+i)}return`${e.getType(r)}( ${l.join(", ")} )`}}class Nc extends Sc{static get type(){return"InputNode"}constructor(e,t=null){super(t),this.isInputNode=!0,this.value=e,this.precision=null}isCacheable(){return!1}generateNodeType(){return null===this.nodeType?mc(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=mc(this.value),e.nodeType=this.nodeType,"ArrayBuffer"===e.valueType&&(e.value=function(e){let t="";const i=new Uint8Array(e);for(let e=0;e<i.length;e++)t+=String.fromCharCode(i[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)?_c(e.valueType,...e.value):e.value,this.precision=e.precision||null,this.value&&this.value.fromArray&&(this.value=this.value.fromArray(e.value))}generate(){Ti("Abstract function.")}}const Pc=/float|u?int/;class Lc extends Nc{static get type(){return"ConstNode"}constructor(e,t=null){super(e,t),this.isConstNode=!0,this.isWeak=!1}generateConst(e){return e.generateConst(this.getNodeType(e),this.value)}generate(e,t){const i=this.getNodeType(e);if(Pc.test(i)&&Pc.test(t)){let r=this.value;return"int"===i?r=Math.trunc(r):"uint"===i&&(r=r>=0?Math.trunc(r):0),e.generateConst(t,r)}return e.format(this.generateConst(e),i,t)}serialize(e){super.serialize(e),e.isWeak=this.isWeak}deserialize(e){super.deserialize(e),this.isWeak=!0===e.isWeak}}class Dc extends Sc{static get type(){return"MemberNode"}constructor(e,t){super(),this.structNode=e,this.property=t,this.isMemberNode=!0}isCacheable(){return!1}getScope(){return this.structNode.getScope()}hasMember(e){return(!this.structNode.isMemberNode||!1!==this.structNode.hasMember(e))&&"void"!==this.structNode.getMemberType(e,this.property)}generateNodeType(e){return!1===this.hasMember(e)?"float":this.structNode.getMemberType(e,this.property)}getMemberType(e,t){if(!1===this.hasMember(e))return"float";const i=this.getNodeType(e);return e.getStructTypeNode(i).getMemberType(e,t)}generate(e){if(!1===this.hasMember(e)){Ti(`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 Uc=null;const Ic=new WeakMap,Fc=new Map;function Oc(e,t){if(Fc.has(e))Ti(`TSL: Redefinition of method chaining '${e}'.`);else{if("function"!=typeof t)throw new Error(`THREE.TSL: Node element ${e} is not a function`);Fc.set(e,t),"assign"!==e&&(Sc.prototype[e]=function(...e){return this.isStackNode?this.addToStack(t(...e)):t(this,...e)},Sc.prototype[e+"Assign"]=function(...e){return this.isStackNode?this.assign(e[0],t(...e)):this.assign(t(this,...e))})}}const Bc=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("");Sc.prototype.assign=function(...e){if(!0!==this.isStackNode)return null!==Uc?Uc.assign(this,...e):Mi("TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().",new lc),this;{const t=Fc.get("assign");return this.addToStack(t(...e))}},Sc.prototype.get=function(e){return new Dc(this,e)};const kc={},zc=new WeakMap;function Gc(e){let t=zc.get(e);return void 0===t&&(t={},zc.set(e,t)),t}function Vc(e,t,i){kc[e]=kc[t]=kc[i]={get(){const t=Gc(this);let i=t[e];return void 0===i&&(i=new Ac(this,e),t[e]=i),i},set(t){this[e].assign(dh(t))}};const r=e.toUpperCase(),n=t.toUpperCase(),s=i.toUpperCase();Sc.prototype["set"+r]=Sc.prototype["set"+n]=Sc.prototype["set"+s]=function(t){const i=Bc(e);return new Rc(this,i,dh(t))},Sc.prototype["flip"+r]=Sc.prototype["flip"+n]=Sc.prototype["flip"+s]=function(){const t=Bc(e);return new Cc(this,t)}}const Hc=["x","y","z","w"],Wc=["r","g","b","a"],jc=["s","t","p","q"];for(let e=0;e<4;e++){let t=Hc[e],i=Wc[e],r=jc[e];Vc(t,i,r);for(let n=0;n<4;n++){t=Hc[e]+Hc[n],i=Wc[e]+Wc[n],r=jc[e]+jc[n],Vc(t,i,r);for(let s=0;s<4;s++){t=Hc[e]+Hc[n]+Hc[s],i=Wc[e]+Wc[n]+Wc[s],r=jc[e]+jc[n]+jc[s],Vc(t,i,r);for(let a=0;a<4;a++)t=Hc[e]+Hc[n]+Hc[s]+Hc[a],i=Wc[e]+Wc[n]+Wc[s]+Wc[a],r=jc[e]+jc[n]+jc[s]+jc[a],Vc(t,i,r)}}}for(let e=0;e<32;e++)kc[e]={get(){const t=Gc(this);let i=t[e];return void 0===i&&(i=new Tc(this,new Lc(e,"uint")),t[e]=i),i},set(t){this[e].assign(dh(t))}};Object.defineProperties(Sc.prototype,kc);const $c=function(e,t=null){for(const i in e)e[i]=dh(e[i],t);return e},Xc=function(e,t=null){const i=e.length;for(let r=0;r<i;r++)e[r]=dh(e[r],t);return e},qc=function(e,t=null,i=null,r=null){function n(e){return null!==r&&(Object.assign(e,r),!0===r.assignable&&(e=e.toAssignable())),e}let s,a,o,l=t;function u(t){let i;return i=l?/[a-z]/i.test(l)?l+"()":l:e.type,void 0!==a&&t.length<a?(Mi(`TSL: "${i}" parameter length is less than minimum required.`,new lc),t.concat(new Array(a-t.length).fill(0))):void 0!==o&&t.length>o?(Mi(`TSL: "${i}" parameter length exceeds limit.`,new lc),t.slice(0,o)):t}return null===t?s=(...t)=>n(new e(...fh(u(t)))):null!==i?(i=dh(i),s=(...r)=>n(new e(t,...fh(u(r)),i))):s=(...i)=>n(new e(t,...fh(u(i)))),s.setParameterLength=(...e)=>(1===e.length?a=o=e[0]:2===e.length&&([a,o]=e),s),s.setName=e=>(l=e,s),s},Yc=function(e,...t){return new e(...fh(t))};class Kc extends Sc{constructor(e,t){super(),this.shaderNode=e,this.rawInputs=t,this.isShaderCallNodeInternal=!0}isCacheable(e){return 0===this.getOutputNode(e).nodes.length}generateNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}getElementType(e){return this.getOutputNode(e).getElementType(e)}getMemberType(e,t){return this.getOutputNode(e).getMemberType(e,t)}call(e){const{shaderNode:t,rawInputs:i}=this,r=e.getNodeProperties(t),n=e.getClosestSubBuild(t.subBuilds)||"",s=n||"default";if(r[s])return r[s];const a=e.subBuildFn,o=e.fnCall;e.subBuildFn=n,e.fnCall=this;let l=null;const u=t.layout?e._getLayoutInputs(t,i):null;if(null!==u){const i=t.layout.inputs;if(bc(u)){const t=u;for(let r=0;r<i.length;r++){const i=t[r];i&&i.isNode&&i.build(e)}}else{const t=u[0];for(const r of i){const i=t[r.name];i&&i.isNode&&i.build(e)}}const r=e.buildFunctionNode(t);e.addInclude(r);const n=function(e){let t;ph(e),t=bc(e)?[...e]:e[0];return t}(u);l=r.call(n)}else{let r=Ic.get(e);void 0===r&&(r=new Proxy(e,{get:(e,t,i)=>{let r;return r=Symbol.iterator===t?function*(){yield}:Reflect.get(e,t,i),r}}),Ic.set(e,r));const n=i?function(e){let t=0;return ph(e),new Proxy(e,{get:(i,r,n)=>{let s;if("length"===r)return s=e.length,s;if(Symbol.iterator===r)s=function*(){for(const t of e)yield t};else{if(e.length>0)if(Object.getPrototypeOf(e[0])===Object.prototype){const i=e[0];s=void 0===i[r]?i[t++]:Reflect.get(i,r,n)}else e[0]instanceof Sc&&(s=void 0===e[r]?e[t++]:Reflect.get(e,r,n));else s=Reflect.get(i,r,n);s=dh(s)}return s}})}(i):null,s=Array.isArray(i)?i.length>0:null!==i,a=t.jsFunc,o=s||a.length>1?a(n,r):a(r);l=dh(o)}return e.subBuildFn=a,e.fnCall=o,t.once&&(r[s]=l),l}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}getOutputNode(e){const t=e.getNodeProperties(this),i=e.getSubBuildOutput(this);return t[i]=t[i]||this.setupOutput(e),t[i].subBuild=e.getClosestSubBuild(this),t[i]}generate(e,t){return this.getOutputNode(e).build(e,t)||""}build(e,t=null){this._setupInspector(e);const i=this.getShared(e);if(this!==i)return i.build(e,t);let r=null;const n=e.getBuildStage(),s=e.getNodeProperties(this),a=!0===this.assignable?e.getDataFromNode(this):null;null!==a&&this._updateAssignable(e,a);const o=e.getSubBuildOutput(this),l=this.getOutputNode(e),u=e.fnCall;if(e.fnCall=this,"setup"===n){const t=e.getSubBuildProperty("initialized",this);if(!0!==s[t]&&(s[t]=!0,s[o]=this.getOutputNode(e),s[o].build(e),this.shaderNode.subBuilds))for(const t of e.chaining){const i=e.getDataFromNode(t,"any");i.subBuilds=i.subBuilds||new Set;for(const e of this.shaderNode.subBuilds)i.subBuilds.add(e)}r=s[o]}else if("analyze"===n)null!==a&&!1!==this._isVariable(e,a)&&1!==e.increaseUsage(this)||l.build(e,t);else if("generate"===n)if(null!==a&&this._isVariable(e,a)){this._checkFlowBlock(e,a);const i=void 0!==a.propertyName,n=e.flow.code.length;r=this._buildVariable(e,a,t),this._setFlowBlock(e,a,i,n)}else r=l.build(e,t)||"";return e.fnCall=u,r}}class Zc extends Sc{constructor(e,t){super(t),this.jsFunc=e,this.layout=null,this.global=!0,this.once=!1}isCacheable(){return!1}setLayout(e){return this.layout=e,this}getLayout(){return this.layout}call(e=null){return new Kc(this,e)}setup(){return this.call()}}const Qc=[!1,!0],Jc=[0,1,2,3],eh=[-1,-2],th=[.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],ih=new Map;for(const e of Qc)ih.set(e,new Lc(e));const rh=new Map;for(const e of Jc)rh.set(e,new Lc(e,"uint"));const nh=new Map;for(const e of rh.keys())nh.set(e,new Lc(e,"int"));for(const e of eh)nh.set(e,new Lc(e,"int"));const sh=new Map;for(const e of nh.keys())sh.set(e,new Lc(e));for(const e of th)sh.set(e,new Lc(e));for(const e of th)sh.set(-e,new Lc(-e));const ah={bool:ih,uint:rh,ints:nh,float:sh},oh=new Map(ih),lh=(e,t)=>{if(oh.has(e))return oh.get(e);if(!0===e.isNode)return e;{const i=new Lc(e,t);return i.isWeak=!t&&"number"==typeof e,i}};for(const e of sh.keys())oh.set(e,lh(e));const uh=function(e,t=null){return(...i)=>{for(const t of i)if(void 0===t)return Mi(`TSL: Invalid parameter for the type "${e}".`,new lc),new Lc(0,e);if((0===i.length||!["bool","float","int","uint"].includes(e)&&i.every(e=>{const t=typeof e;return"object"!==t&&"function"!==t}))&&(i=[_c(e,...i)]),1===i.length&&null!==t&&t.has(i[0])){const e=t.get(i[0]);return new Lc(e.value,e.nodeType).toAssignable()}if(1===i.length){const t=i[0],r=lh(t,e);return r.nodeType===e?r===t?new Mc(r,e).toAssignable():oh.get(t)===r?new Lc(r.value,r.nodeType).toAssignable():r.toAssignable():new Mc(r,e).toAssignable()}const r=i.map(e=>lh(e));return new Ec(r,e).toAssignable()}};function ch(e){return e&&e.isNode&&e.traverse(t=>{t.isConstNode&&(e=t.value)}),Boolean(e)}function hh(e,t){return new Zc(e,t)}const dh=(e,t=null)=>function(e,t=null){const i=mc(e);return"node"===i?e:null===t&&("float"===i||"boolean"===i)||i&&"shader"!==i&&"string"!==i?lh(e,t):"shader"===i?e.isFn?e:yh(e):e}(e,t),ph=(e,t=null)=>new $c(e,t),fh=(e,t=null)=>new Xc(e,t),mh=(e,t=null,i=null,r=null)=>new qc(e,t,i,r),gh=(e,...t)=>new Yc(e,...t),_h=(e,t=null,i=null,r={})=>new qc(e,t,i,{...r,assignable:!0});let vh=0;class bh extends Sc{constructor(e,t=null){super();let i=null;null!==t&&("object"==typeof t?i=t.return:("string"==typeof t?i=t:Mi("TSL: Invalid layout type.",new lc),t=null)),this.shaderNode=new hh(e,i),null!==t&&this.setLayout(t),this.isFn=!0}isCacheable(){return!1}setLayout(e){const t=this.shaderNode.nodeType;if("object"!=typeof e.inputs){const i={name:"fn"+vh++,type:t,inputs:[]};for(const t in e)"return"!==t&&i.inputs.push({name:t,type:e[t]});e=i}return this.shaderNode.setLayout(e),this}generateNodeType(e){return this.shaderNode.getNodeType(e)||"float"}call(...e){const t=this.shaderNode.call(e);return"void"===this.shaderNode.nodeType?t.toStack():t.toAssignable()}once(e=null){return this.shaderNode.once=!0,this.shaderNode.subBuilds=e,this}generate(e){const t=this.getNodeType(e);return Mi('TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".',this.stackTrace),e.generateConst(t)}}function yh(e,t=null){const i=new bh(e,t);return new Proxy(()=>{},{apply:(e,t,r)=>i.call(...r),get:(e,t,r)=>Reflect.get(i,t,r),set:(e,t,r,n)=>Reflect.set(i,t,r,n)})}const xh=e=>{Uc=e},Sh=()=>Uc,Th=(...e)=>Uc.If(...e);Oc("toStack",function(e){return Uc&&Uc.addToStack(e),e});const Mh=new uh("color"),Eh=new uh("float",ah.float),wh=new uh("int",ah.ints),Ah=new uh("uint",ah.uint),Rh=new uh("bool",ah.bool),Ch=new uh("vec2"),Nh=new uh("ivec2"),Ph=new uh("uvec2"),Lh=new uh("bvec2"),Dh=new uh("vec3"),Uh=new uh("ivec3"),Ih=new uh("uvec3"),Fh=new uh("bvec3"),Oh=new uh("vec4"),Bh=new uh("ivec4"),kh=new uh("uvec4"),zh=new uh("bvec4"),Gh=new uh("mat2"),Vh=new uh("mat3"),Hh=new uh("mat4");Oc("toColor",Mh),Oc("toFloat",Eh),Oc("toInt",wh),Oc("toUint",Ah),Oc("toBool",Rh),Oc("toVec2",Ch),Oc("toIVec2",Nh),Oc("toUVec2",Ph),Oc("toBVec2",Lh),Oc("toVec3",Dh),Oc("toIVec3",Uh),Oc("toUVec3",Ih),Oc("toBVec3",Fh),Oc("toVec4",Oh),Oc("toIVec4",Bh),Oc("toUVec4",kh),Oc("toBVec4",zh),Oc("toMat2",Gh),Oc("toMat3",Vh),Oc("toMat4",Hh);Oc("element",mh(Tc).setParameterLength(2)),Oc("convert",(e,t)=>new Mc(dh(e),t));class Wh extends Sc{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t,this.isAssignNode=!0}isCacheable(){return!1}generateNodeType(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 i=e.getTypeLength(t.node.getNodeType(e));return ac.join("").slice(0,i)!==t.components}return!1}setup(e){const{targetNode:t,sourceNode:i}=this,r=t.getScope();e.getDataFromNode(r).assign=!0;const n=e.getNodeProperties(this);n.sourceNode=i,n.targetNode=t.context({assign:!0})}generate(e,t){const{targetNode:i,sourceNode:r}=e.getNodeProperties(this),n=this.needsSplitAssign(e),s=i.build(e),a=i.getNodeType(e),o=r.build(e,a),l=r.getNodeType(e),u=e.getDataFromNode(this);let c;if(void 0!==u.propertyName)"void"!==t&&(c=s);else if(n){const r=e.getVarFromNode(this,null,a),n=e.getPropertyName(r);e.addLineFlowCode(`${n} = ${o}`,this);const l=i.node,u=l.node.context({assign:!0}).build(e);for(let t=0;t<l.components.length;t++){const i=l.components[t];e.addLineFlowCode(`${u}.${i} = ${n}[ ${t} ]`,this)}"void"!==t&&(c=s)}else c=`${s} = ${o}`,"void"!==t&&"void"!==l||(e.addLineFlowCode(c,this),"void"!==t&&(c=s));return u.propertyName=s,e.format(c,a,t)}}Oc("assign",mh(Wh).setParameterLength(2));class jh extends Sc{static get type(){return"ArrayNode"}constructor(e,t,i=null){super(e),this.count=t,this.values=i,this.isArrayNode=!0}getArrayCount(){return this.count}generateNodeType(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)}}const $h=(...e)=>{let t;if(1===e.length){const i=e[0].map(e=>dh(e));t=new jh(null,i.length,i)}else{const i=e[0],r=e[1];t=new jh(i,r)}return t};Oc("toArray",(e,t)=>$h(Array(t).fill(e)));class Xh extends Sc{static get type(){return"UniformGroupNode"}constructor(e,t=!1,i=1,r=null){super("string"),this.name=e,this.shared=t,this.order=i,this.updateType=r,this.isUniformGroup=!0}isCacheable(){return!1}update(){this.needsUpdate=!0}serialize(e){super.serialize(e),e.name=this.name,e.version=this.version,e.shared=this.shared}deserialize(e){super.deserialize(e),this.name=e.name,this.version=e.version,this.shared=e.shared}}const qh=(e,t=1,i=null)=>new Xh(e,!1,t,i),Yh=(e,t=0,i=null)=>new Xh(e,!0,t,i),Kh=Yh("render",0,Ju),Zh=qh("object",1,ec);class Qh extends Nc{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=Zh}setName(e){return this.name=e,this}label(e){return Ti('TSL: "label()" has been deprecated. Use "setName()" instead.',new lc),this.setName(e)}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}getSharedNode(e){const t=this.getUniformHash(e);let i=e.getNodeFromHash(t);return void 0===i&&(e.setHashNode(this,t),i=this),i}onUpdate(e,t){return e=e.bind(this),super.onUpdate(t=>{const i=e(t,this);void 0!==i&&(this.value=i)},t)}getInputType(e){let t=super.getInputType(e);return"bool"===t&&(t="uint"),t}generate(e,t){const i=this.getNodeType(e),r=this.getSharedNode(e),n=r.getInputType(e),s=e.getUniformFromNode(r,n,e.shaderStage,this.name||e.context.nodeName),a=e.getPropertyName(s);void 0!==e.context.nodeName&&delete e.context.nodeName;let o=a;if("bool"===i){const t=e.getDataFromNode(this);let r=t.propertyName;if(void 0===r){const s=e.getVarFromNode(this,null,"bool");r=e.getPropertyName(s),t.propertyName=r,o=e.format(a,n,i),e.addLineFlowCode(`${r} = ${o}`,this)}o=r}return e.format(o,i,t)}}const Jh=(e,t)=>{const i=(e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null)(t||e);if(i===e&&(e=_c(i)),e&&!0===e.isNode){let t=e.value;e.traverse(e=>{!0===e.isConstNode&&(t=e.value)}),e=t}return new Qh(e,i)};class ed extends Sc{static get type(){return"PropertyNode"}constructor(e,t=null,i=!1,r=null){super(e),this.name=t,this.varying=i,this.placeholderNode=dh(r),this.isPropertyNode=!0,this.global=!0}isCacheable(){return!1}getNodeType(e){const t=super.getNodeType(e);return"output"===t?e.getOutputType():t}customCacheKey(){return cc(this.type+":"+(this.name||"")+":"+(this.varying?"1":"0"))}getHash(e){return this.name||super.getHash(e)}generate(e){let t;if(!0===this.varying)t=e.getVaryingFromNode(this,this.name),t.needsInterpolation=!0;else if(t=e.getVarFromNode(this,this.name),null!==this.placeholderNode&&!1===e.hasWriteUsage(this)){const i=this.placeholderNode.build(e,this.getNodeType(e));e.addLineFlowCode(`${e.getPropertyName(t)} = ${i}`,this)}return e.getPropertyName(t)}}const td=(e,t,i=null)=>new ed(e,t,!1,i),id=(e,t,i=null)=>new ed(e,t,!0,i),rd=gh(ed,"vec4","DiffuseColor"),nd=gh(ed,"vec3","DiffuseContribution"),sd=gh(ed,"float","DiffuseRoughness"),ad=gh(ed,"vec3","EmissiveColor"),od=gh(ed,"float","Roughness"),ld=gh(ed,"float","Metalness"),ud=gh(ed,"float","Clearcoat"),cd=gh(ed,"float","ClearcoatRoughness"),hd=gh(ed,"vec3","Sheen"),dd=gh(ed,"float","SheenRoughness"),pd=gh(ed,"float","Iridescence"),fd=gh(ed,"float","IridescenceIOR"),md=gh(ed,"float","IridescenceThickness"),gd=gh(ed,"float","AlphaT"),_d=gh(ed,"float","Anisotropy"),vd=gh(ed,"vec3","AnisotropyT"),bd=gh(ed,"vec3","AnisotropyB"),yd=gh(ed,"color","SpecularColor"),xd=gh(ed,"color","SpecularColorBlended"),Sd=gh(ed,"float","SpecularF90"),Td=gh(ed,"float","Shininess"),Md=gh(ed,"output","Output"),Ed=gh(ed,"float","dashSize"),wd=gh(ed,"float","gapSize"),Ad=gh(ed,"float","IOR"),Rd=gh(ed,"float","Transmission"),Cd=gh(ed,"float","Thickness"),Nd=gh(ed,"float","AttenuationDistance"),Pd=gh(ed,"color","AttenuationColor"),Ld=gh(ed,"float","Dispersion"),Dd=gh(ed,"float","Retroreflectivity"),Ud=gh(ed,"float","AmbientOcclusion",!1,1);class Id extends Sc{static get type(){return"FunctionCallNode"}constructor(e=null,t={}){super(),this.functionNode=e,this.parameters=t}setParameters(e){return this.parameters=e,this}getParameters(){return this.parameters}generateNodeType(e){return this.functionNode.getNodeType(e)}getMemberType(e,t){return this.functionNode.getMemberType(e,t)}generate(e){const t=[],i=this.functionNode,r=i.getInputs(e),n=this.parameters,s=(t,i)=>{const r=i.type;let n;return n="pointer"===r?"&"+t.build(e):t.build(e,r),n};if(Array.isArray(n)){if(n.length>r.length)Mi("TSL: The number of provided parameters exceeds the expected number of inputs in 'Fn()'."),n.length=r.length;else if(n.length<r.length)for(Mi("TSL: The number of provided parameters is less than the expected number of inputs in 'Fn()'.");n.length<r.length;)n.push(Eh(0));for(let e=0;e<n.length;e++)t.push(s(n[e],r[e]))}else for(const e of r){const i=n[e.name];void 0!==i?t.push(s(i,e)):(Mi(`TSL: Input '${e.name}' not found in 'Fn()'.`),t.push(s(Eh(0),e)))}return`${i.build(e,"property")}( ${t.join(", ")} )`}}Oc("call",(e,...t)=>(t=t.length>1||t[0]&&!0===t[0].isNode?fh(t):ph(t[0]),new Id(dh(e),t)));const Fd={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class Od extends Sc{static get type(){return"OperatorNode"}constructor(e,t,i,...r){if(super(),r.length>0){let n=new Od(e,t,i);for(let t=0;t<r.length-1;t++)n=new Od(e,n,r[t]);t=n,i=r[r.length-1]}this.op=e,this.aNode=t,this.bNode=i,this.isOperatorNode=!0}getOperatorMethod(e,t){return e.getMethod(Fd[this.op],t)}generateNodeType(e,t=null){const i=this.op,r=this.aNode,n=this.bNode,s=r.getNodeType(e),a=n?n.getNodeType(e):null;if("void"===s||"void"===a)return t||"void";if("~"===i||"&"===i||"|"===i||"^"===i||">>"===i||"<<"===i)return e.getIntegerType(s);if("&&"===i||"||"===i||"^^"===i)return"bool";if("!"===i){const t=e.getTypeLength(s);return t>1?`bvec${t}`:"bool"}if("=="===i||"!="===i||"<"===i||">"===i||"<="===i||">="===i){const t=Math.max(e.getTypeLength(s),e.getTypeLength(a));return t>1?`bvec${t}`:"bool"}if(null===a)return s;{if(e.isMatrix(s)){if(e.isScalar(a))return s;if(e.isVector(a))return e.getVectorFromMatrix(s);if(e.isMatrix(a))return s}else if(e.isMatrix(a)){if(e.isScalar(s))return a;if(e.isVector(s))return e.getVectorFromMatrix(a)}const t=e.getTypeLength(a)>e.getTypeLength(s)?a:s,i=e.getPromotedComponentType(r,n);return e.changeComponentType(t,i)}}generate(e,t){const i=this.op,{aNode:r,bNode:n}=this,s=this.getNodeType(e,t);let a=null,o=null;if("void"!==s)if(a=r.getNodeType(e),o=n?n.getNodeType(e):null,"<"===i||">"===i||"<="===i||">="===i||"=="===i||"!="===i){const t=Math.max(e.getTypeLength(a),e.getTypeLength(o));a=o=e.getTypeFromLength(t,e.getPromotedComponentType(r,n))}else">>"===i||"<<"===i?(a=s,o=e.changeComponentType(o,"uint")):e.isMatrix(a)?e.isScalar(o)?o="float":e.isVector(o)?o=e.getVectorFromMatrix(a):e.isMatrix(o)||(a=o=s):a=e.isMatrix(o)?e.isScalar(a)?"float":e.isVector(a)?e.getVectorFromMatrix(o):o=s:o=s;else a=o=s;const l=r.build(e,a),u=n?n.build(e,o):null,c=e.getFunctionOperator(i);if("void"!==t){const r=e.renderer.coordinateSystem===ui;if("=="===i||"!="===i||"<"===i||">"===i||"<="===i||">="===i)return r&&e.isVector(a)?e.format(`${this.getOperatorMethod(e,t)}( ${l}, ${u} )`,s,t):e.format(`( ${l} ${i} ${u} )`,s,t);if("%"===i)return e.isInteger(o)?e.format(`( ${l} % ${u} )`,s,t):e.format(`${this.getOperatorMethod(e,s)}( ${l}, ${u} )`,s,t);if("!"===i)return r&&e.isVector(a)?e.format(`not( ${l} )`,t):e.format(`( ${i} ${l} )`,a,t);if("~"===i)return e.format(`( ${i} ${l} )`,a,t);if(c)return e.format(`${c}( ${l}, ${u} )`,s,t);if(e.isMatrix(a)&&e.isScalar(o))return e.format(`( ${u} ${i} ${l} )`,s,t);if(e.isScalar(a)&&e.isMatrix(o))return e.format(`${l} ${i} ${u}`,s,t);{let n=`( ${l} ${i} ${u} )`;return!r&&"bool"===s&&e.isVector(a)&&e.isVector(o)&&(n=`all${n}`),e.format(n,s,t)}}if("void"!==a)return c?e.format(`${c}( ${l}, ${u} )`,s,t):e.isMatrix(a)&&e.isScalar(o)?e.format(`${u} ${i} ${l}`,s,t):e.format(`${l} ${i} ${u}`,s,t)}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const Bd=_h(Od,"+").setParameterLength(2,1/0).setName("add"),kd=_h(Od,"-").setParameterLength(2,1/0).setName("sub"),zd=_h(Od,"*").setParameterLength(2,1/0).setName("mul"),Gd=_h(Od,"/").setParameterLength(2,1/0).setName("div"),Vd=_h(Od,"%").setParameterLength(2).setName("mod"),Hd=_h(Od,"==").setParameterLength(2).setName("equal"),Wd=_h(Od,"!=").setParameterLength(2).setName("notEqual"),jd=_h(Od,"<").setParameterLength(2).setName("lessThan"),$d=_h(Od,">").setParameterLength(2).setName("greaterThan"),Xd=_h(Od,"<=").setParameterLength(2).setName("lessThanEqual"),qd=_h(Od,">=").setParameterLength(2).setName("greaterThanEqual"),Yd=_h(Od,"&&").setParameterLength(2,1/0).setName("and"),Kd=_h(Od,"||").setParameterLength(2,1/0).setName("or"),Zd=_h(Od,"!").setParameterLength(1).setName("not"),Qd=_h(Od,"^^").setParameterLength(2).setName("xor"),Jd=_h(Od,"&").setParameterLength(2).setName("bitAnd"),ep=_h(Od,"~").setParameterLength(1).setName("bitNot"),tp=_h(Od,"|").setParameterLength(2).setName("bitOr"),ip=_h(Od,"^").setParameterLength(2).setName("bitXor"),rp=_h(Od,"<<").setParameterLength(2).setName("shiftLeft"),np=_h(Od,">>").setParameterLength(2).setName("shiftRight"),sp=yh(([e])=>(e.addAssign(1),e)),ap=yh(([e])=>(e.subAssign(1),e)),op=yh(([e])=>{const t=wh(e).toConst();return e.addAssign(1),t}),lp=yh(([e])=>{const t=wh(e).toConst();return e.subAssign(1),t});Oc("add",Bd),Oc("sub",kd),Oc("mul",zd),Oc("div",Gd),Oc("mod",Vd),Oc("equal",Hd),Oc("notEqual",Wd),Oc("lessThan",jd),Oc("greaterThan",$d),Oc("lessThanEqual",Xd),Oc("greaterThanEqual",qd),Oc("and",Yd),Oc("or",Kd),Oc("not",Zd),Oc("xor",Qd),Oc("bitAnd",Jd),Oc("bitNot",ep),Oc("bitOr",tp),Oc("bitXor",ip),Oc("shiftLeft",rp),Oc("shiftRight",np),Oc("incrementBefore",sp),Oc("decrementBefore",ap),Oc("increment",op),Oc("decrement",lp);class up extends Sc{static get type(){return"MathNode"}constructor(e,t,i=null,r=null){if(super(),(e===up.MAX||e===up.MIN)&&arguments.length>3){let n=new up(e,t,i);for(let t=3;t<arguments.length-1;t++)n=new up(e,n,arguments[t]);t=n,i=arguments[arguments.length-1],r=null}this.method=e,this.aNode=t,this.bNode=i,this.cNode=r,this.isMathNode=!0}getInputType(e){const t=this.aNode.getNodeType(e),i=this.bNode?this.bNode.getNodeType(e):null,r=this.cNode?this.cNode.getNodeType(e):null,n=e.isMatrix(t)?0:e.getTypeLength(t),s=e.isMatrix(i)?0:e.getTypeLength(i),a=e.isMatrix(r)?0:e.getTypeLength(r);let o;if(o=n>s&&n>a?t:s>a?i:a>n?r:t,e.isMatrix(o))return o;const l=cp.has(this.method)?"float":e.getPromotedComponentType(this.aNode,this.bNode,this.cNode);return e.changeComponentType(o,l)}generateNodeType(e){const t=this.method;return t===up.LENGTH||t===up.DISTANCE||t===up.DOT||t===up.DETERMINANT?"float":t===up.CROSS?"vec3":t===up.ALL||t===up.ANY?"bool":t===up.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):this.getInputType(e)}setup(e){const{aNode:t,bNode:i,method:r}=this;let n=null;if(r===up.ONE_MINUS)n=kd(1,t);else if(r===up.RECIPROCAL)n=Gd(Eh(1),t);else if(r===up.DIFFERENCE)n=kp(kd(t,i));else if(r===up.TRANSFORM_DIRECTION){let r,s;e.isMatrix(t.getNodeType(e))?(r=t,s=i):(r=i,s=t),n=Ep(zd(r,Oh(Dh(s),0)).xyz)}return null!==n?n:super.setup(e)}generate(e,t){if(e.getNodeProperties(this).outputNode)return super.generate(e,t);let i=this.method;const r=this.getNodeType(e),n=this.getInputType(e),s=this.aNode,a=this.bNode,o=this.cNode,l=e.renderer.coordinateSystem;if(i===up.NEGATE)return e.format("( - "+s.build(e,n)+" )",r,t);{const u=[];return i===up.CROSS?u.push(s.build(e,r),a.build(e,r)):l===ui&&i===up.STEP?u.push(s.build(e,1===e.getTypeLength(s.getNodeType(e))?"float":n),a.build(e,n)):l!==ui||i!==up.MIN&&i!==up.MAX?i===up.REFRACT?u.push(s.build(e,n),a.build(e,n),o.build(e,"float")):i===up.MIX?u.push(s.build(e,n),a.build(e,n),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":n)):(l===ci&&i===up.ATAN&&null!==a&&(i="atan2"),"fragment"===e.shaderStage||i!==up.DFDX&&i!==up.DFDY||(Mi(`TSL: '${i}' is not supported in the ${e.shaderStage} stage.`,this.stackTrace),i="/*"+i+"*/"),u.push(s.build(e,n)),null!==a&&u.push(a.build(e,n)),null!==o&&u.push(o.build(e,n))):u.push(s.build(e,n),a.build(e,1===e.getTypeLength(a.getNodeType(e))?e.getComponentType(n):n)),e.format(`${e.getMethod(i,r)}( ${u.join(", ")} )`,r,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}up.ALL="all",up.ANY="any",up.RADIANS="radians",up.DEGREES="degrees",up.EXP="exp",up.EXP2="exp2",up.LOG="log",up.LOG2="log2",up.SQRT="sqrt",up.INVERSE_SQRT="inversesqrt",up.FLOOR="floor",up.CEIL="ceil",up.NORMALIZE="normalize",up.FRACT="fract",up.SIN="sin",up.SINH="sinh",up.COS="cos",up.COSH="cosh",up.TAN="tan",up.TANH="tanh",up.ASIN="asin",up.ASINH="asinh",up.ACOS="acos",up.ACOSH="acosh",up.ATAN="atan",up.ATANH="atanh",up.ABS="abs",up.SIGN="sign",up.LENGTH="length",up.NEGATE="negate",up.ONE_MINUS="oneMinus",up.DFDX="dFdx",up.DFDY="dFdy",up.ROUND="round",up.RECIPROCAL="reciprocal",up.TRUNC="trunc",up.FWIDTH="fwidth",up.TRANSPOSE="transpose",up.DETERMINANT="determinant",up.INVERSE="inverse",up.EQUALS="equals",up.MIN="min",up.MAX="max",up.STEP="step",up.REFLECT="reflect",up.DISTANCE="distance",up.DIFFERENCE="difference",up.DOT="dot",up.CROSS="cross",up.POW="pow",up.TRANSFORM_DIRECTION="transformDirection",up.MIX="mix",up.CLAMP="clamp",up.REFRACT="refract",up.SMOOTHSTEP="smoothstep",up.FACEFORWARD="faceforward";const cp=new Set([up.RADIANS,up.DEGREES,up.EXP,up.EXP2,up.LOG,up.LOG2,up.SQRT,up.INVERSE_SQRT,up.FLOOR,up.CEIL,up.NORMALIZE,up.FRACT,up.SIN,up.SINH,up.COS,up.COSH,up.TAN,up.TANH,up.ASIN,up.ASINH,up.ACOS,up.ACOSH,up.ATAN,up.ATANH,up.LENGTH,up.DFDX,up.DFDY,up.ROUND,up.TRUNC,up.FWIDTH,up.RECIPROCAL,up.STEP,up.REFLECT,up.DISTANCE,up.DOT,up.CROSS,up.POW,up.MIX,up.REFRACT,up.SMOOTHSTEP,up.FACEFORWARD]),hp=Eh(1e-6),dp=Eh(Math.PI),pp=_h(up,up.ALL).setParameterLength(1),fp=_h(up,up.ANY).setParameterLength(1),mp=_h(up,up.RADIANS).setParameterLength(1),gp=_h(up,up.DEGREES).setParameterLength(1),_p=_h(up,up.EXP).setParameterLength(1),vp=_h(up,up.EXP2).setParameterLength(1),bp=_h(up,up.LOG).setParameterLength(1),yp=_h(up,up.LOG2).setParameterLength(1),xp=_h(up,up.SQRT).setParameterLength(1),Sp=_h(up,up.INVERSE_SQRT).setParameterLength(1),Tp=_h(up,up.FLOOR).setParameterLength(1),Mp=_h(up,up.CEIL).setParameterLength(1),Ep=_h(up,up.NORMALIZE).setParameterLength(1),wp=_h(up,up.FRACT).setParameterLength(1),Ap=_h(up,up.SIN).setParameterLength(1),Rp=_h(up,up.SINH).setParameterLength(1),Cp=_h(up,up.COS).setParameterLength(1),Np=_h(up,up.COSH).setParameterLength(1),Pp=_h(up,up.TAN).setParameterLength(1),Lp=_h(up,up.TANH).setParameterLength(1),Dp=_h(up,up.ASIN).setParameterLength(1),Up=_h(up,up.ASINH).setParameterLength(1),Ip=_h(up,up.ACOS).setParameterLength(1),Fp=_h(up,up.ACOSH).setParameterLength(1),Op=_h(up,up.ATAN).setParameterLength(1,2),Bp=_h(up,up.ATANH).setParameterLength(1),kp=_h(up,up.ABS).setParameterLength(1),zp=_h(up,up.SIGN).setParameterLength(1),Gp=_h(up,up.LENGTH).setParameterLength(1),Vp=_h(up,up.NEGATE).setParameterLength(1),Hp=_h(up,up.ONE_MINUS).setParameterLength(1),Wp=_h(up,up.DFDX).setParameterLength(1),jp=_h(up,up.DFDY).setParameterLength(1),$p=_h(up,up.ROUND).setParameterLength(1),Xp=_h(up,up.RECIPROCAL).setParameterLength(1),qp=_h(up,up.TRUNC).setParameterLength(1),Yp=_h(up,up.FWIDTH).setParameterLength(1),Kp=_h(up,up.TRANSPOSE).setParameterLength(1),Zp=_h(up,up.DETERMINANT).setParameterLength(1),Qp=_h(up,up.INVERSE).setParameterLength(1),Jp=_h(up,up.MIN).setParameterLength(2,1/0),ef=_h(up,up.MAX).setParameterLength(2,1/0),tf=_h(up,up.STEP).setParameterLength(2),rf=_h(up,up.REFLECT).setParameterLength(2),nf=_h(up,up.DISTANCE).setParameterLength(2),sf=_h(up,up.DIFFERENCE).setParameterLength(2),af=_h(up,up.DOT).setParameterLength(2),of=_h(up,up.CROSS).setParameterLength(2),lf=_h(up,up.POW).setParameterLength(2),uf=e=>zd(e,e),cf=e=>zd(e,e,e,e),hf=_h(up,up.TRANSFORM_DIRECTION).setParameterLength(2),df=_h(up,up.MIX).setParameterLength(3),pf=(e,t=0,i=1)=>new up(up.CLAMP,dh(e),dh(t),dh(i)),ff=e=>pf(e),mf=_h(up,up.REFRACT).setParameterLength(3),gf=_h(up,up.SMOOTHSTEP).setParameterLength(3),_f=_h(up,up.FACEFORWARD).setParameterLength(3),vf=yh(([e])=>{const t=af(e.xy,Ch(12.9898,78.233)),i=Vd(t,dp);return wp(Ap(i).mul(43758.5453))},{uv:"vec2",return:"float"});Oc("all",pp),Oc("any",fp),Oc("radians",mp),Oc("degrees",gp),Oc("exp",_p),Oc("exp2",vp),Oc("log",bp),Oc("log2",yp),Oc("sqrt",xp),Oc("inverseSqrt",Sp),Oc("floor",Tp),Oc("ceil",Mp),Oc("normalize",Ep),Oc("fract",wp),Oc("sin",Ap),Oc("sinh",Rp),Oc("cos",Cp),Oc("cosh",Np),Oc("tan",Pp),Oc("tanh",Lp),Oc("asin",Dp),Oc("asinh",Up),Oc("acos",Ip),Oc("acosh",Fp),Oc("atan",Op),Oc("atanh",Bp),Oc("abs",kp),Oc("sign",zp),Oc("length",Gp),Oc("lengthSq",e=>af(e,e)),Oc("negate",Vp),Oc("oneMinus",Hp),Oc("dFdx",Wp),Oc("dFdy",jp),Oc("round",$p),Oc("reciprocal",Xp),Oc("trunc",qp),Oc("fwidth",Yp),Oc("min",Jp),Oc("max",ef),Oc("step",(e,t)=>tf(t,e)),Oc("reflect",rf),Oc("distance",nf),Oc("dot",af),Oc("cross",of),Oc("pow",lf),Oc("pow2",uf),Oc("pow3",e=>zd(e,e,e)),Oc("pow4",cf),Oc("transformDirection",hf),Oc("transformNormalByViewMatrix",(e,t)=>Ep(zd(t,Oh(Dh(e),0)).xyz)),Oc("transformNormalByInverseViewMatrix",(e,t)=>Ep(Oh(Dh(e),0).mul(t).xyz)),Oc("mix",(e,t,i)=>df(t,i,e)),Oc("clamp",pf),Oc("refract",mf),Oc("smoothstep",(e,t,i)=>gf(t,i,e)),Oc("faceForward",_f),Oc("difference",sf),Oc("saturate",ff),Oc("cbrt",e=>zd(zp(e),lf(kp(e),1/3))),Oc("transpose",Kp),Oc("determinant",Zp),Oc("inverse",Qp),Oc("rand",vf);class bf extends Error{constructor(e,t=null){super(e),this.name="NodeError",this.stackTrace=t}}class yf extends Sc{static get type(){return"ConditionalNode"}constructor(e,t,i=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=i}isCacheable(){return!1}generateNodeType(e){const{condNode:t,ifNode:i,elseNode:r}=e.getNodeProperties(this);if(void 0===i)return e.flowBuildStage(this,"setup"),this.getNodeType(e);let n=i.getNodeType(e);if(null!==r){const t=r.getNodeType(e);e.getTypeLength(t)>e.getTypeLength(n)&&(n=t)}const s=e.getTypeLength(t.getNodeType(e));return s>1&&!e.isReference(n)&&(1===e.getTypeLength(n)||e.isVector(e.getVectorType(n)))&&(n=e.getTypeFromLength(Math.max(s,e.getTypeLength(n)),e.getComponentType(n))),n}setup(e){const{condNode:t,ifNode:i,elseNode:r}=this,n=e.getNodeProperties(this);n.condNode=t,n.ifNode=i,n.elseNode=r}generate(e,t){const i=this.getNodeType(e),r=e.getDataFromNode(this);if(void 0!==r.propertyName)return e.format(r.propertyName,i,t);const{condNode:n,ifNode:s,elseNode:a}=e.getNodeProperties(this),o=e.currentFunctionNode,l="void"!==t,u=l?td(i).build(e):"";r.propertyName=u;const c=n.getNodeType(e);if(e.getTypeLength(c)>1){const r=e.getVectorType(i);if(e.isReference(i)||!e.isVector(r))throw new bf(`TSL: select() with a vector condition ("${c}") requires scalar or vector values, received "${i}".`,this.stackTrace);let o;o=null!==a?a.build(e,i):e.generateConst(i);const h=e.changeComponentType(i,"bool"),d=n.build(e,h),p=s.build(e,i),f=e.getVectorSelect(d,p,o,i);return l?(e.addFlowCode(`\n${e.tab}${u} = ${f};\n\n`),e.format(u,i,t)):""}const h=n.build(e,"bool");if(e.context.uniformFlow&&null!==a){const r=s.build(e,i),n=a.build(e,i),o=e.getTernary(h,r,n);return e.format(o,i,t)}e.addFlowCode(`\n${e.tab}if ( ${h} ) {\n\n`).addFlowTab();const d=e.getDataFromNode(n),p=d.propertyName===h&&!0!==d.assign?h:void 0,f=e.flowBlock;e.flowBlock={parent:f,guard:p};let m=s.build(e,i);if(e.flowBlock=f,m&&(l?m=u+" = "+m+";":(m="return "+m+";",null===o&&(Ti("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.",this.stackTrace),m="// "+m))),e.removeFlowTab().addFlowCode(e.tab+"\t"+m+"\n\n"+e.tab+"}"),null!==a){e.addFlowCode(" else {\n\n").addFlowTab(),e.flowBlock={parent:f,guard:void 0!==p?"!"+p:void 0};let t=a.build(e,i);e.flowBlock=f,t&&(l?t=u+" = "+t+";":(t="return "+t+";",null===o&&(Ti("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,i,t)}}const xf=mh(yf).setParameterLength(2,3);Oc("select",xf);class Sf extends Sc{static get type(){return"ContextNode"}constructor(e=null,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}isCacheable(){return!1}getScope(){return this.node.getScope()}generateNodeType(e){return this.node.getNodeType(e)}getFlowContextData(){let e={};return this.traverse(t=>{!0===t.isContextNode&&(e=vc(e,t.value))}),e}getMemberType(e,t){return this.node.getMemberType(e,t)}analyze(e){if(1===e.increaseUsage(this)){const t=e.addContext(this.value);this.node.build(e,this),e.setContext(t)}}setup(e){const t=e.addContext(this.value);this.node.build(e),e.setContext(t)}generate(e,t){const i=e.addContext(this.value),r=this.node.build(e,t);return e.setContext(i),r}}const Tf=(e=null,t={})=>{let i=e;return null!==i&&!0===i.isNode||(t=i||t,i=null),new Sf(i,t)},Mf=(e,t)=>Tf(e,{nodeName:t});Oc("context",Tf),Oc("label",function(e,t){return Ti('TSL: "label()" has been deprecated. Use "setName()" instead.'),Mf(e,t)}),Oc("uniformFlow",e=>Tf(e,{uniformFlow:!0})),Oc("setName",Mf),Oc("builtinShadowContext",(e,t,i)=>function(e,t,i=null){return Tf(i,{getShadow:({light:i,shadowColorNode:r})=>t===i?r.mul(e):r})}(t,i,e)),Oc("builtinAOContext",(e,t)=>function(e,t=null){return Tf(t,{getAO:(t,{material:i})=>!0===i.transparent?t:null!==t?t.mul(e):e})}(t,e)),Oc("builtinGIContext",(e,t,i)=>function(e,t,i=null){const r=e.max(.001);return Tf(i,{getAO:(e,{material:t})=>!0===t.transparent?e:null!==e?e.mul(r):r,getGI:(e,{material:i})=>{if(!0===i.transparent)return e;const n=t.div(r);return null!==e?e.add(n):n}})}(t,i,e));class Ef extends Sc{static get type(){return"VarNode"}constructor(e,t=null,i=!1){super(),this.node=e,this.name=t,this.global=!0,this.isVarNode=!0,this.readOnly=i,this.parents=!0,this.assignable=!1}isCacheable(){return!1}setAssignable(e){return this.assignable=e,this}getAssignable(){return this.assignable}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}generateNodeType(e){return this.node.getNodeType(e)}getArrayCount(e){return this.node.getArrayCount(e)}_declaresAssignable(){return!1}_isFunctionScope(){return!1===this.readOnly&&!1===this.assignable}build(e,t=null){this._setupInspector(e);const i=this.getShared(e);if(this!==i)return i.build(e,t);const r=e.getDataFromNode(this);return this._updateAssignable(e,r,this.node),this.assignable&&!0!==r.forceDeclaration&&!0!==r.assign?this.node.build(e,t):super.build(e,t)}generate(e){const{node:t,name:i,readOnly:r}=this,n=this.getNodeType(e);if("void"==n){!0!==this.isAssignable(e)&&Mi('TSL: ".toVar()" can not be used with void type.',this.stackTrace);return t.build(e)}const s=e.getVectorType(n),a=t.build(e,s),o=e.getVarFromNode(this,i,s,void 0,r,this.assignable),l=e.getPropertyName(o);let u=l;if(o.readOnly){const i=t.getArrayCount(e);u=e.isDeterministic(t)?e.generateConstStatement(o.type,l,i):e.generateLetStatement(o.type,l,i)}else o.local&&(u=e.generateVarStatement(o.type,l,o.count));return e.addLineFlowCode(`${u} = ${a}`,this),l}}const wf=mh(Ef);Oc("toVar",(e,t=null)=>wf(e,t).toStack()),Oc("toConst",(e,t=null)=>wf(e,t,!0).toStack());class Af extends Sc{static get type(){return"SubBuild"}constructor(e,t,i=null){super(i),this.node=e,this.name=t,this.isSubBuildNode=!0}isCacheable(){return!1}generateNodeType(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){this._setupInspector(e),e.addSubBuild(this.name);const i=this.node.build(e,...t);return e.removeSubBuild(),i}}const Rf=(e,t,i=null)=>new Af(dh(e),t,i);class Cf extends Sc{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=Rf(e,"VERTEX"),this.name=t,this.isVaryingNode=!0,this.interpolationType=null,this.interpolationSampling=null,this.global=!0}isCacheable(){return!1}setInterpolation(e,t=null){return this.interpolationType=e,this.interpolationSampling=t,this}getHash(e){return this.name||super.getHash(e)}generateNodeType(e){return this.node.getNodeType(e)}setupVarying(e){const t=e.getNodeProperties(this);let i=t.varying;if(void 0===i){const r=this.name,n=this.getNodeType(e),s=this.interpolationType,a=this.interpolationSampling;t.varying=i=e.getVaryingFromNode(this,r,n,s,a),t.node=Rf(this.node,"VERTEX")}return i.needsInterpolation||(i.needsInterpolation="fragment"===e.shaderStage),i}setup(e){if(!0===e.context.inlineVaryings&&"fragment"===e.shaderStage){let t=this.node;for(;!0===t.isSubBuildNode;)t=t.node;if(!0!==t.isIndexNode&&(!0!==t.isAttributeNode||t.getContextAttribute(e)))return this.node}this.setupVarying(e),e.flowNodeFromShaderStage(Ku,this.node)}analyze(e){if(e.getNodeProperties(this).outputNode)return super.analyze(e);this.setupVarying(e),e.flowNodeFromShaderStage(Ku,this.node)}generate(e){const{outputNode:t}=e.getNodeProperties(this);if(t)return t.build(e,this.getNodeType(e));const i=e.getSubBuildProperty("property",e.currentStack),r=e.getNodeProperties(this),n=this.setupVarying(e),s=e.shaderStage===Ku?e.flowBlock:null;if(r[i]!==s){const t=this.getNodeType(e),a=e.getPropertyName(n,Ku);if(e.shaderStage===Ku){const i=r.node.build(e,t);e.addLineFlowCode(`${a} = ${i}`,this)}else e.flowNodeFromShaderStage(Ku,r.node,t,a);r[i]=s}return e.getPropertyName(n)}}const Nf=mh(Cf).setParameterLength(1,2);Oc("toVarying",Nf),Oc("toVertexStage",e=>Nf(e));const Pf=yh(([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),i=e.mul(.0773993808),r=e.lessThanEqual(.04045);return df(t,i,r)},{color:"vec3",return:"vec3"}),Lf=yh(([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),i=e.mul(12.92),r=e.lessThanEqual(.0031308);return df(t,i,r)},{color:"vec3",return:"vec3"}),Df="WorkingColorSpace";class Uf extends Sc{static get type(){return"ColorSpaceNode"}constructor(e,t,i){super("vec4"),this.colorNode=e,this.source=t,this.target=i}resolveColorSpace(e,t){return t===Df?Qi.workingColorSpace:"OutputColorSpace"===t?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){const{colorNode:t}=this,i=this.resolveColorSpace(e,this.source),r=this.resolveColorSpace(e,this.target);let n=t;return!1!==Qi.enabled&&i!==r&&i&&r?(Qi.getTransfer(i)===Kt&&(n=Oh(Pf(n.rgb),n.a)),Qi.getPrimaries(i)!==Qi.getPrimaries(r)&&(n=Oh(Vh(Qi._getMatrix(new Xi,i,r)).mul(n.rgb),n.a)),Qi.getTransfer(r)===Kt&&(n=Oh(Lf(n.rgb),n.a)),n):n}}const If=(e,t)=>new Uf(dh(e),t,Df);Oc("workingToColorSpace",(e,t)=>new Uf(dh(e),Df,t)),Oc("colorSpaceToWorking",If);class Ff extends Tc{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}generateNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),i=this.referenceNode.getNodeType(e),r=this.getNodeType(e);return e.format(t,i,r)}}class Of extends Sc{static get type(){return"ReferenceBaseNode"}constructor(e,t,i=null,r=null){super(),this.property=e,this.uniformType=t,this.object=i,this.count=r,this.properties=e.split("."),this.reference=i,this.node=null,this.group=null,this.updateType=ec}isCacheable(){return!1}setGroup(e){return this.group=e,this}element(e){return new Ff(this,dh(e))}setNodeType(e){const t=Jh(null,e);null!==this.group&&t.setGroup(this.group),this.node=t}generateNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let i=e[t[0]];for(let e=1;e<t.length;e++)i=i[t[e]];return i}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 Bf extends Of{static get type(){return"RendererReferenceNode"}constructor(e,t,i=null){super(e,t,i),this.renderer=i,this.setGroup(Kh)}updateReference(e){return this.reference=null!==this.renderer?this.renderer:e.renderer,this.reference}}const kf=(e,t,i=null)=>new Bf(e,t,i);class zf extends Sc{static get type(){return"ToneMappingNode"}constructor(e,t=Gf,i=null){super("vec3"),this._toneMapping=e,this.exposureNode=t,this.colorNode=i}customCacheKey(){return dc(this._toneMapping)}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup(e){const t=this.colorNode||e.context.color,i=this._toneMapping;if(0===i)return t;let r=null;const n=e.renderer.library.getToneMappingFunction(i);return null!==n?r=Oh(n(t.rgb,this.exposureNode),t.a):(Mi("ToneMappingNode: Unsupported Tone Mapping configuration.",i),r=t),r}}const Gf=kf("toneMappingExposure","float");Oc("toneMapping",(e,t,i)=>((e,t,i)=>new zf(e,dh(t),dh(i)))(t,i,e));const Vf=new WeakMap;function Hf(e,t){let i=Vf.get(e);return void 0===i&&(i=new Qn(e,t),Vf.set(e,i)),i}class Wf extends Nc{static get type(){return"BufferAttributeNode"}constructor(e,t=null,i=0,r=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=i,this.bufferOffset=r,this.usage=ai,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):e&&!0===e.isInterleavedBufferAttribute&&(this.attribute=e,this.usage=e.data.usage)}getHash(e){let t;if(0===this.bufferStride&&0===this.bufferOffset){let i=e.globalCache.getData(this.value);void 0===i&&(i={node:this},e.globalCache.setData(this.value,i)),t=i.node.id}else t=this.id;return String(t)}generateNodeType(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),i=e.getTypeLength(t),r=this.value,n=this.bufferStride||i,s=this.bufferOffset;let a;a=!0===r.isInterleavedBuffer?r:!0===r.isBufferAttribute?Hf(r.array,n):Hf(r,n);const o=new ts(a,i,s);a.setUsage(this.usage),this.attribute=o,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),i=e.context.nodeName;void 0!==i&&delete e.context.nodeName;const r=e.getBufferAttributeFromNode(this,t,i),n=e.getPropertyName(r);let s=null;if("vertex"===e.shaderStage||"compute"===e.shaderStage)this.name=n,s=n;else{let r;i&&(r=i+"Varying");s=Nf(this,r).build(e,t)}return s}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}getObjectAttribute(){return this.attribute}}function jf(e,t=null,i=0,r=0,n=35044,s=!1){return"mat3"===t||null===t&&9===e.itemSize?Vh(new Wf(e,"vec3",9,0).setUsage(n).setInstanced(s),new Wf(e,"vec3",9,3).setUsage(n).setInstanced(s),new Wf(e,"vec3",9,6).setUsage(n).setInstanced(s)):"mat4"===t||null===t&&16===e.itemSize?Hh(new Wf(e,"vec4",16,0).setUsage(n).setInstanced(s),new Wf(e,"vec4",16,4).setUsage(n).setInstanced(s),new Wf(e,"vec4",16,8).setUsage(n).setInstanced(s),new Wf(e,"vec4",16,12).setUsage(n).setInstanced(s)):new Wf(e,t,i,r).setUsage(n)}const $f=(e,t=null,i=0,r=0)=>jf(e,t,i,r),Xf=(e,t=null,i=0,r=0)=>jf(e,t,i,r,ai,!0),qf=(e,t=null,i=0,r=0)=>jf(e,t,i,r,oi,!0);Oc("toAttribute",e=>$f(e.value,e.bufferType));class Yf extends Sc{static get type(){return"IndexNode"}constructor(e){super("uint"),this.scope=e,this.isIndexNode=!0}isCacheable(){return!1}generate(e){const t=this.getNodeType(e),i=this.scope;let r,n;if(i===Yf.VERTEX)r=e.getVertexIndex();else if(i===Yf.INSTANCE)r=e.getInstanceIndex();else if(i===Yf.DRAW)r=e.getDrawIndex();else if(i===Yf.INVOCATION_LOCAL)r=e.getInvocationLocalIndex();else if(i===Yf.INVOCATION_SUBGROUP)r=e.getInvocationSubgroupIndex();else{if(i!==Yf.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+i);r=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)n=r;else{n=Nf(this).build(e,t)}return n}}Yf.VERTEX="vertex",Yf.INSTANCE="instance",Yf.SUBGROUP="subgroup",Yf.INVOCATION_LOCAL="invocationLocal",Yf.INVOCATION_SUBGROUP="invocationSubgroup",Yf.DRAW="draw";const Kf=gh(Yf,Yf.VERTEX),Zf=gh(Yf,Yf.INSTANCE);Yf.SUBGROUP,Yf.INVOCATION_SUBGROUP,Yf.INVOCATION_LOCAL;const Qf=gh(Yf,Yf.DRAW);class Jf extends Sc{static get type(){return"ComputeNode"}constructor(e,t){super("void"),this.isComputeNode=!0,this.computeNode=e,this.workgroupSize=t,this.count=null,this.dispatchSize=null,this.version=1,this.name="",this.onInitFunction=null,this.countNode=null,this.updateBeforeType=Qu}isCacheable(){return!1}setName(e){return this.name=e,this}label(e){return Ti('TSL: "label()" has been deprecated. Use "setName()" instead.',new lc),this.setName(e)}onInit(e){return this.onInitFunction=e,this}getUpdateBeforeType(e){return e.compute!==this?this.updateBeforeType:Zu}updateBefore({renderer:e}){e.compute(this)}setup(e){null!==this.count&&null===this.countNode&&(this.countNode=Jh(this.count,"uint").onObjectUpdate(()=>this.count));const t=this.computeNode.build(e);if(t){e.getNodeProperties(this).outputComputeNode=t.outputNode,t.outputNode=null}return t}generate(e,t){const{shaderStage:i}=e;if("compute"===i){const t=this.computeNode.build(e,"void");if(""!==t&&e.addLineFlowCode(t,this),null!==this.count&&!0===e.allowEarlyReturns){const t=this.countNode.build(e,"uint"),i=Zf.build(e,"uint");e.flow.code=`${e.tab}if ( ${i} >= ${t} ) { return; }\n\n${e.flow.code}`}}else{const i=e.getNodeProperties(this).outputComputeNode;if(i)return i.build(e,t)}}}const em=(e,t=[64])=>{(0===t.length||t.length>3)&&Mi("TSL: compute() workgroupSize must have 1, 2, or 3 elements",new lc);for(let e=0;e<t.length;e++){const i=t[e];("number"!=typeof i||i<=0||!Number.isInteger(i))&&Mi(`TSL: compute() workgroupSize element at index [ ${e} ] must be a positive integer`,new lc)}for(;t.length<3;)t.push(1);return new Jf(dh(e),t)};Oc("compute",(e,t,i)=>{const r=em(e,i);return"number"==typeof t?r.count=t:r.dispatchSize=t,r}),Oc("computeKernel",em);class tm extends Sc{static get type(){return"IsolateNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isIsolateNode=!0}isCacheable(){return!1}generateNodeType(e){const t=e.getCache(),i=e.getCacheFromNode(this,this.parent);e.setCache(i);const r=this.node.getNodeType(e);return e.setCache(t),r}build(e,...t){this._setupInspector(e);const i=e.getCache(),r=e.getCacheFromNode(this,this.parent);e.setCache(r);const n=this.node.build(e,...t);return e.setCache(i),n}setParent(e){return this.parent=e,this}getParent(){return this.parent}}const im=e=>new tm(dh(e));Oc("cache",function(e,t=!0){return Ti('TSL: "cache()" has been deprecated. Use "isolate()" instead.'),im(e).setParent(t)}),Oc("isolate",im);class rm extends Sc{static get type(){return"BypassNode"}constructor(e,t){super(),this.isBypassNode=!0,this.outputNode=e,this.callNode=t}isCacheable(){return!1}generateNodeType(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)}}Oc("bypass",mh(rm).setParameterLength(2));const nm=yh(([e,t,i,r=Eh(0),n=Eh(1),s=Rh(!1)])=>{let a=e.sub(t).div(i.sub(t));return ch(s)&&(a=a.clamp()),a.mul(n.sub(r)).add(r)});Oc("remap",nm),Oc("remapClamp",function(e,t,i,r=Eh(0),n=Eh(1)){return nm(e,t,i,r,n,!0)});class sm extends Sc{static get type(){return"ExpressionNode"}constructor(e="",t="void"){super(t),this.snippet=e}isCacheable(){return!1}generate(e,t){const i=this.getNodeType(e),r=this.snippet;if("void"!==i)return e.format(r,i,t);e.addLineFlowCode(r,this)}}const am=mh(sm).setParameterLength(1,2);Oc("discard",e=>(e?xf(e,am("discard")):am("discard")).toStack());const om=yh(([e])=>Oh(e.rgb.mul(e.a),e.a),{color:"vec4",return:"vec4"}),lm=yh(([e])=>e.a.equal(0).select(Oh(0),Oh(e.rgb.div(e.a),e.a)),{color:"vec4",return:"vec4"});class um extends Sc{static get type(){return"RenderOutputNode"}constructor(e,t,i){super("vec4"),this.colorNode=e,this._toneMapping=t,this.outputColorSpace=i,this.premultipliedAlpha=!0,this.isRenderOutputNode=!0}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup({context:e}){let t=this.colorNode||e.color;t=Oh(t.rgb,t.a.clamp(0,1)),!0===this.premultipliedAlpha&&(t=lm(t));const i=(null!==this._toneMapping?this._toneMapping:e.toneMapping)||0,r=(null!==this.outputColorSpace?this.outputColorSpace:e.outputColorSpace)||$t;return 0!==i&&(t=t.toneMapping(i)),r!==$t&&r!==Qi.workingColorSpace&&(t=t.workingToColorSpace(r)),!0===this.premultipliedAlpha&&(t=om(t)),t}}const cm=(e,t=null,i=null)=>new um(dh(e),t,i);Oc("renderOutput",cm);class hm extends Sc{static get type(){return"DebugNode"}constructor(e,t=null){super(),this.node=e,this.callback=t}generateNodeType(e){return this.node.getNodeType(e)}setup(e){return this.node.build(e)}analyze(e){return this.node.build(e)}generate(e){const t=this.callback,i=this.node.build(e);if(null!==t)t(e,i);else{const t="--- TSL debug - "+e.shaderStage+" shader ---",r="-".repeat(t.length);let n="";n+="// #"+t+"#\n",n+=e.flow.code.replace(/^\t/gm,"")+"\n",n+="/* ... */ "+i+" /* ... */\n",n+="// #"+r+"#\n",xi(n)}return i}}Oc("debug",(e,t=null)=>new hm(dh(e),t).toStack());class dm extends Ri{constructor(){super(),this._renderer=null,this.currentFrame=null,this.isRunning=!1,this.enabled=!0}get nodeFrame(){return this._renderer._nodes.nodeFrame}setRenderer(e){return this._renderer=e,this}getRenderer(){return this._renderer}begin(){this.isRunning=!0}finish(){this.isRunning=!1}inspect(){}computeAsync(){}beginCompute(){}finishCompute(){}beginRender(){}finishRender(){}copyTextureToTexture(){}copyFramebufferToTexture(){}dispose(){!0===this.isRunning&&this.finish(),this.dispatchEvent({type:"dispose"})}}class pm extends Sc{static get type(){return"InspectorNode"}constructor(e,t="",i=null){super(),this.node=e,this.name=t,this.callback=i,this.updateType=Qu,this.isInspectorNode=!0}getName(){return this.name||this.node.name}update(e){const{renderer:t}=e;!0!==t.backend.isWebGPUBackend&&t.inspector.constructor!==dm&&Ei('TSL: ".toInspector()" is only available with WebGPU.'),t.inspector.inspect(this)}generateNodeType(e){return this.node.getNodeType(e)}}Oc("toInspector",function(e,t="",i=null){return(e=dh(e))._inspectorNode=new pm(e,t,i),e});class fm extends Sc{static get type(){return"AttributeNode"}constructor(e,t=null){super(t),this.global=!0,this._attributeName=e}isCacheable(){return!1}getHash(e){return this.getAttributeName(e)}getContextAttribute(e){const t=e.context.getAttribute;return t?t(this.getAttributeName(e),e):null}getShared(e){return this.getContextAttribute(e)||super.getShared(e)}generateNodeType(e){const t=this.getContextAttribute(e);if(t)return t.getNodeType(e);let i=this.nodeType;if(null===i){const t=this.getAttributeName(e);if(e.hasGeometryAttribute(t)){const r=e.geometry.getAttribute(t);i=e.getTypeFromAttribute(r)}else i="float"}return i}setAttributeName(e){return this._attributeName=e,this}getAttributeName(){return this._attributeName}generate(e){const t=this.getAttributeName(e),i=this.getNodeType(e);if(!0===e.hasGeometryAttribute(t)){const r=e.geometry.getAttribute(t),n=e.getTypeFromAttribute(r),s=e.getAttribute(t,n);if("vertex"===e.shaderStage)return e.format(s.name,n,i);return Nf(this).build(e,i)}return Ti(`AttributeNode: Vertex attribute "${t}" not found on geometry.`),e.generateConst(i)}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 mm=(e,t=null)=>new fm(e,t);class gm extends Sf{static get type(){return"OverrideContextNode"}constructor(e,t=null,i=null){const r={overrideNodes:e};"fragment"===i&&(r.inlineVaryings=!0),super(t,r),this.isOverrideContextNode=!0}}function _m(e,t,i){return r=>r.shaderStage===i?t(r):e}Oc("overrideNode",(e,t,i)=>function(e,t=null,i=null){if(t&&t.isNode){const e=t;t=()=>e}return new gm(new Map([[e,t]]),i)}(t,i,e)),Oc("overrideNodes",(e,t,i)=>function(e,t=null,i=null){const r=new Map;for(const[t,n]of e){let e=null;null!==n&&(e="function"==typeof n?n:()=>n,null!==i&&(e=_m(t,e,i))),r.set(t,e)}return new gm(r,t,i)}(t,e,i));class vm extends ed{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getMemberType(e,t){const i=this.getNodeType(e),r=e.getStructTypeNode(i);let n;return null!==r?n=r.getMemberType(e,t):(Mi(`TSL: Member "${t}" not found in struct "${i}".`,new lc),n="float"),n}getHash(){return String(this.id)}generate(){return this.name}}const bm=(e,t)=>{if(!0!==t.assignable)return!1;const i=e.getDataFromNode(t);return!0!==i.forceDeclaration&&!0!==i.assign};class ym extends Sc{static get type(){return"StackNode"}constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this._expressionNode=null,this._currentNode=null,this._nodeDataLibrary=new Map,this.isStackNode=!0}isCacheable(){return!1}getElementType(e){return this.outputNode?this.outputNode.getElementType(e):"void"}generateNodeType(e){return this.outputNode?this.outputNode.getNodeType(e):"void"}getMemberType(e,t){return this.outputNode?this.outputNode.getMemberType(e,t):"void"}addToStack(e,t=-1){if(!0!==e.isNode)return Mi("TSL: Invalid node added to stack.",new lc),this;if(-1===t)if(this._currentNode){let e=this._nodeDataLibrary.get(this._currentNode);void 0===e&&(e={delta:0},this._nodeDataLibrary.set(this._currentNode,e)),e.delta++,t=this.nodes.indexOf(this._currentNode)+e.delta}else t=this.nodes.length;return this.nodes.splice(t,0,e),this}addToStackBefore(e,t=this._currentNode){const i=t?this.nodes.indexOf(t):0;return this.addToStack(e,i)}If(e,t){const i=new hh(t);return this._currentCond=xf(e,i),this.addToStack(this._currentCond)}ElseIf(e,t){const i=new hh(t),r=xf(e,i);return this._currentCond.elseNode=r,this._currentCond=r,this}Else(e){return this._currentCond.elseNode=new hh(e),this}Switch(e){return this._expressionNode=dh(e),this}Case(...e){const t=[];if(e.length>=2)for(let i=0;i<e.length-1;i++)t.push(this._expressionNode.equal(dh(e[i])));else Mi("TSL: Invalid parameter length. Case() requires at least two parameters.",new lc);const i=new hh(e[e.length-1]);let r=t[0];for(let e=1;e<t.length;e++)r=r.or(t[e]);const n=xf(r,i);return null===this._currentCond?(this._currentCond=n,this.addToStack(this._currentCond)):(this._currentCond.elseNode=n,this._currentCond=n,this)}Default(e){return this.Else(e),this}setup(e){const t=e.getNodeProperties(this);let i=0;for(const r of this.getChildren())bm(e,r)||(t["node"+i++]=r);return t.outputNode||null}build(e,...t){this._setupInspector(e);const i=Sh(),r=e.buildStage;xh(this),e.setActiveStack(this);for(let t=0;t<this.nodes.length;t++){const i=this.nodes[t],n=this._currentNode;if(this._currentNode=i,!bm(e,i)){if("setup"===r)i.build(e);else if("analyze"===r)i.build(e,this);else if("generate"===r){const t=e.getDataFromNode(i,"any").stages,r=t&&t[e.shaderStage];if(i.isVarNode&&r&&1===r.length&&r[0]&&r[0].isStackNode)continue;i.build(e,"void")}this._currentNode=n}}let n;if(this.outputNode){const i=this.outputNode.build(e,...t);"generate"===e.buildStage&&"void"===this.outputNode.getNodeType(e)||(n=i)}else n=super.build(e,...t);return xh(i),e.removeActiveStack(this),n}}const xm=mh(ym).setParameterLength(0,1);class Sm extends Yr{constructor(e,t,i,r=1){super(e,t,i),this.a=r}set(e,t,i,r=1){return this.a=r,super.set(e,t,i)}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)}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b,yield this.a}}class Tm extends Sc{static get type(){return"LoopNode"}constructor(e=[]){super("void"),this.params=e}isCacheable(){return!1}getVarName(e){return String.fromCharCode("i".charCodeAt(0)+e)}getProperties(e){const t=e.getNodeProperties(this);if(void 0!==t.stackNode)return t;const i={},r=this._getInternalParams();for(let e=0,t=r.length-1;e<t;e++){const t=r[e],n=!0!==t.isNode&&t.name||this.getVarName(e),s=!0!==t.isNode&&t.type||"int";i[n]=am(n,s)}const n=e.addStack(),s=r[r.length-1](i);t.returnsNode=s.context({nodeLoop:this,nodeBlock:e.createBlock()}),t.stackNode=n;const a=r[0];if(!0!==a.isNode&&"function"==typeof a.update){const e=yh(a.update)(i);t.updateNode=e.context({nodeLoop:this})}return e.removeStack(),t}_getInternalParams(){const e=this.params;return"function"==typeof e[0]?[Rh(!0),e[0]]:e}setup(e){this.getProperties(e)}generate(e){const t=this.getProperties(e),i=this._getInternalParams(),r=t.stackNode;for(let r=0,n=i.length-1;r<n;r++){const n=i[r];let s,a=!1,o=null,l=null,u=null,c=null,h=null,d=null;if(n.isNode?"bool"===n.getNodeType(e)?(a=!0,c="bool",l=n.build(e,c)):(c="int",u=this.getVarName(r),o="0",l=n.build(e,c),h="<"):(c=n.type||"int",u=n.name||this.getVarName(r),o=n.start,l=n.end,h=n.condition,d=n.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 i={start:o,end:l},r=i.start,n=i.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):(Mi("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)+" = "+r}; ${u+" "+h+" "+n}; ${a} )`}e.addFlowCode((0===r?"\n":"")+e.tab+s+" {\n\n").addFlowTab()}const n=e.flowBlock;e.flowBlock={parent:n};const s=r.build(e,"void");t.returnsNode.build(e,"void"),e.flowBlock=n,e.removeFlowTab().addFlowCode("\n"+e.tab+s);for(let t=0,r=i.length-1;t<r;t++)e.addFlowCode((0===t?"":e.tab)+"}\n\n").removeFlowTab();e.addFlowTab()}}const Mm=(...e)=>new Tm(fh(e,"int")).toStack(),Em=new Hn;class wm extends Sc{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=ec,this.uniformNode=new Qh(null)}isCacheable(){return!1}generateNodeType(){const e=this.scope;return e===wm.WORLD_MATRIX?"mat4":e===wm.POSITION||e===wm.VIEW_POSITION||e===wm.DIRECTION||e===wm.SCALE?"vec3":e===wm.RADIUS?"float":void 0}update(e){const t=this.object3d,i=this.uniformNode,r=this.scope;if(r===wm.WORLD_MATRIX)i.value=t.matrixWorld;else if(r===wm.POSITION)i.value=i.value||new Wi,i.value.setFromMatrixPosition(t.matrixWorld);else if(r===wm.SCALE)i.value=i.value||new Wi,i.value.setFromMatrixScale(t.matrixWorld);else if(r===wm.DIRECTION)i.value=i.value||new Wi,t.getWorldDirection(i.value);else if(r===wm.VIEW_POSITION){const r=e.camera;i.value=i.value||new Wi,i.value.setFromMatrixPosition(t.matrixWorld),i.value.applyMatrix4(r.matrixWorldInverse)}else if(r===wm.RADIUS){const r=e.object.geometry;null===r.boundingSphere&&r.computeBoundingSphere(),Em.copy(r.boundingSphere).applyMatrix4(t.matrixWorld),i.value=Em.radius}}generate(e){const t=this.scope;return t===wm.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===wm.POSITION||t===wm.VIEW_POSITION||t===wm.DIRECTION||t===wm.SCALE?this.uniformNode.nodeType="vec3":t===wm.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}}wm.WORLD_MATRIX="worldMatrix",wm.POSITION="position",wm.SCALE="scale",wm.VIEW_POSITION="viewPosition",wm.DIRECTION="direction",wm.RADIUS="radius";class Am extends Sc{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}isCacheable(){return!1}generate(){return this.name}}const Rm=mh(Am).setParameterLength(1);class Cm extends Qh{static get type(){return"BufferNode"}constructor(e,t,i=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=i,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 Nm=(e,t,i)=>new Cm(e,t,i);class Pm extends Tc{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),i=this.getNodeType(e),r=this.node.getPaddedType(e);return e.format(t,r,i)}}class Lm extends Cm{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=null===t?mc(e[0]):t,this.updateType=Ju,this.isArrayBufferNode=!0}generateNodeType(e){return this.getPaddedType(e)}getElementType(){return this.elementType}getPaddedType(e){const t=this.elementType;let i="vec4";return"mat2"===t?i=!0===e.renderer.backend.isWebGLBackend?"vec4":"mat2":!0===/mat/.test(t)?i="mat4":"i"===t.charAt(0)?i="ivec4":"u"===t.charAt(0)&&(i="uvec4"),i}update(){this.updateBuffer()}onUpdate(e,t){return e=e.bind(this),super.onUpdate((t,i)=>{e(t,i),this.updateBuffer()},t)}updateBuffer(){const{array:e,value:t}=this,i=this.elementType;if("float"===i||"int"===i||"uint"===i)for(let i=0;i<e.length;i++){t[4*i]=e[i]}else if("color"===i)for(let i=0;i<e.length;i++){const r=4*i,n=e[i];t[r]=n.r,t[r+1]=n.g,t[r+2]=n.b||0}else if("mat2"===i)for(let i=0;i<e.length;i++){const r=4*i,n=e[i];t[r]=n.elements[0],t[r+1]=n.elements[1],t[r+2]=n.elements[2],t[r+3]=n.elements[3]}else if("mat3"===i)for(let i=0;i<e.length;i++){const r=16*i,n=e[i];t[r]=n.elements[0],t[r+1]=n.elements[1],t[r+2]=n.elements[2],t[r+4]=n.elements[3],t[r+5]=n.elements[4],t[r+6]=n.elements[5],t[r+8]=n.elements[6],t[r+9]=n.elements[7],t[r+10]=n.elements[8],t[r+15]=1}else if("mat4"===i)for(let i=0;i<e.length;i++){const r=16*i,n=e[i];for(let e=0;e<n.elements.length;e++)t[r+e]=n.elements[e]}else for(let i=0;i<e.length;i++){const r=4*i,n=e[i];t[r]=n.x,t[r+1]=n.y,t[r+2]=n.z||0,t[r+3]=n.w||0}}setup(e){const t=this.array.length,i=this.elementType;let r=Float32Array;const n=this.getPaddedType(e),s=e.getTypeLength(n);return"i"===i.charAt(0)&&(r=Int32Array),"u"===i.charAt(0)&&(r=Uint32Array),this.value=new r(t*s),this.bufferCount=t,this.bufferType=n,this.updateBuffer(),super.setup(e)}element(e){return new Pm(this,dh(e))}}const Dm=(e,t)=>new Lm(e,t);let Um,Im;class Fm extends Sc{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this.isViewportNode=!0}isCacheable(){return!1}generateNodeType(){return this.scope===Fm.VIEWPORT?"vec4":"vec2"}update({renderer:e}){const t=e.getRenderTarget();this.scope===Fm.VIEWPORT?null!==t?Im.copy(t.viewport):(e.getViewport(Im),Im.multiplyScalar(e.getPixelRatio())):null!==t?(Um.width=t.width,Um.height=t.height):e.getDrawingBufferSize(Um)}setup(){const e=this.scope;let t=null;t=e===Fm.SIZE?Jh(Um||(Um=new Vi)).setGroup(Kh):e===Fm.VIEWPORT?Jh(Im||(Im=new ur)).setGroup(Kh):Ch(zm.div(km));let i=Zu;return this.scope!==Fm.SIZE&&this.scope!==Fm.VIEWPORT||(i=Ju),this.updateType=i,t}generate(e){if(this.scope===Fm.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const i=e.getNodeProperties(km).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${i}.y - ${t}.y )`}return t}return super.generate(e)}}Fm.COORDINATE="coordinate",Fm.VIEWPORT="viewport",Fm.SIZE="size",Fm.UV="uv";const Om=Jh(1).setGroup(Kh).onRenderUpdate(({renderer:e})=>e.getPixelRatio()),Bm=gh(Fm,Fm.UV),km=gh(Fm,Fm.SIZE),zm=gh(Fm,Fm.COORDINATE),Gm=gh(Fm,Fm.VIEWPORT),Vm=Gm.zw;Gm.xy;const Hm=new WeakMap;function Wm(e,t,i,r){let n=Hm.get(e);void 0===n&&(n=new Map,Hm.set(e,n));const s=i+":"+t.cameras.length;let a=n.get(s);return void 0===a&&(a=r(t),n.set(s,a)),a}let jm=null,$m=null,Xm=null,qm=null,Ym=null,Km=null;const Zm=Jh(0,"uint").setName("u_cameraIndex").setGroup(Yh("cameraIndex")).toVarying("v_cameraIndex"),Qm=Jh("float").setName("cameraNear").setGroup(Kh).onRenderUpdate(({camera:e})=>e.near),Jm=Jh("float").setName("cameraFar").setGroup(Kh).onRenderUpdate(({camera:e})=>e.far),eg=yh(({camera:e,renderer:t})=>{let i;if(e.isArrayCamera&&e.cameras.length>0){const r=Wm(t,e,"cameraProjectionMatrices",e=>{const t=e.cameras.map(e=>e.projectionMatrix);return Dm(t).setGroup(Kh).setName("cameraProjectionMatrices").onRenderUpdate(({camera:e},t)=>{for(let i=0;i<e.cameras.length;i++)t.array[i]=e.cameras[i].projectionMatrix})});i=r.element(e.isMultiViewCamera?Rm("gl_ViewID_OVR"):Zm)}else null===jm&&(jm=Jh(e.projectionMatrix).setName("cameraProjectionMatrix").setGroup(Kh).onRenderUpdate(({camera:e})=>e.projectionMatrix)),i=jm;return i}).once()(),tg=yh(({camera:e,renderer:t})=>{let i;if(e.isArrayCamera&&e.cameras.length>0){const r=Wm(t,e,"cameraProjectionMatricesInverse",e=>{const t=e.cameras.map(e=>e.projectionMatrixInverse);return Dm(t).setGroup(Kh).setName("cameraProjectionMatricesInverse").onRenderUpdate(({camera:e},t)=>{for(let i=0;i<e.cameras.length;i++)t.array[i]=e.cameras[i].projectionMatrixInverse})});i=r.element(e.isMultiViewCamera?Rm("gl_ViewID_OVR"):Zm)}else null===$m&&($m=Jh(e.projectionMatrixInverse).setName("cameraProjectionMatrixInverse").setGroup(Kh).onRenderUpdate(({camera:e})=>e.projectionMatrixInverse)),i=$m;return i}).once()(),ig=yh(({camera:e,renderer:t})=>{let i;if(e.isArrayCamera&&e.cameras.length>0){const r=Wm(t,e,"cameraViewMatrices",e=>{const t=e.cameras.map(e=>e.matrixWorldInverse);return Dm(t).setGroup(Kh).setName("cameraViewMatrices").onRenderUpdate(({camera:e},t)=>{for(let i=0;i<e.cameras.length;i++)t.array[i]=e.cameras[i].matrixWorldInverse})});i=r.element(e.isMultiViewCamera?Rm("gl_ViewID_OVR"):Zm)}else null===Xm&&(Xm=Jh(e.matrixWorldInverse).setName("cameraViewMatrix").setGroup(Kh).onRenderUpdate(({camera:e})=>e.matrixWorldInverse)),i=Xm;return i}).once()(),rg=yh(({camera:e,renderer:t})=>{let i;if(e.isArrayCamera&&e.cameras.length>0){const r=Wm(t,e,"cameraWorldMatrices",e=>{const t=e.cameras.map(e=>e.matrixWorld);return Dm(t).setGroup(Kh).setName("cameraWorldMatrices").onRenderUpdate(({camera:e},t)=>{for(let i=0;i<e.cameras.length;i++)t.array[i]=e.cameras[i].matrixWorld})});i=r.element(e.isMultiViewCamera?Rm("gl_ViewID_OVR"):Zm)}else null===qm&&(qm=Jh(e.matrixWorld).setName("cameraWorldMatrix").setGroup(Kh).onRenderUpdate(({camera:e})=>e.matrixWorld)),i=qm;return i}).once()(),ng=yh(({camera:e,renderer:t})=>{let i;if(e.isArrayCamera&&e.cameras.length>0){const r=Wm(t,e,"cameraPositions",e=>{const t=[];for(let i=0,r=e.cameras.length;i<r;i++)t.push(new Wi);return Dm(t).setGroup(Kh).setName("cameraPositions").onRenderUpdate(({camera:e},t)=>{const i=e.cameras,r=t.array;for(let e=0,t=i.length;e<t;e++)r[e].setFromMatrixPosition(i[e].matrixWorld)})});i=r.element(e.isMultiViewCamera?Rm("gl_ViewID_OVR"):Zm)}else null===Ym&&(Ym=Jh(new Wi).setName("cameraPosition").setGroup(Kh).onRenderUpdate(({camera:e},t)=>t.value.setFromMatrixPosition(e.matrixWorld))),i=Ym;return i}).once()(),sg=yh(({camera:e,renderer:t})=>{let i;if(e.isArrayCamera&&e.cameras.length>0){const r=Wm(t,e,"cameraViewports",e=>{const t=e.cameras.map(e=>e.viewport);return Dm(t,"vec4").setGroup(Kh).setName("cameraViewports").onRenderUpdate(({camera:e},t)=>{for(let i=0;i<e.cameras.length;i++)t.array[i]=e.cameras[i].viewport})});i=r.element(Zm)}else null===Km&&(Km=Oh(0,0,km.x,km.y).toConst("cameraViewport")),i=Km;return i}).once()(),ag=new fr;class og extends wm{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const lg=gh(og,og.WORLD_MATRIX),ug=Jh(new Xi).onObjectUpdate(({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld)),cg=yh(e=>e.context.modelViewMatrix||hg).once()().toVar("modelViewMatrix"),hg=ig.mul(lg),dg=yh(e=>{e.context.isHighPrecisionModelViewMatrix=!0;const t=e.camera;let i;if(t.isArrayCamera&&t.cameras.length>0){const e=[];for(let i=0;i<t.cameras.length;i++)e.push(new fr);const r=Dm(e).onObjectUpdate(({object:e,camera:t},i)=>{const r=t.cameras,n=i.array;for(let t=0,i=r.length;t<i;t++)n[t].multiplyMatrices(r[t].matrixWorldInverse,e.matrixWorld)});i=r.element(t.isMultiViewCamera?Rm("gl_ViewID_OVR"):Zm)}else i=Jh("mat4").onObjectUpdate(({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld));return i}).once()().toVar("highpModelViewMatrix"),pg=yh(e=>{const t=e.context.isHighPrecisionModelViewMatrix,i=e.camera;let r;if(i.isArrayCamera&&i.cameras.length>0){const e=[];for(let t=0;t<i.cameras.length;t++)e.push(new Xi);const t=Dm(e).onObjectUpdate(({object:e,camera:t},i)=>{const r=t.cameras,n=i.array;for(let t=0,i=r.length;t<i;t++)ag.multiplyMatrices(r[t].matrixWorldInverse,e.matrixWorld),n[t].getNormalMatrix(ag)});r=t.element(i.isMultiViewCamera?Rm("gl_ViewID_OVR"):Zm)}else r=Jh("mat3").onObjectUpdate(({object:e,camera:i})=>(!0!==t&&e.modelViewMatrix.multiplyMatrices(i.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix)));return r}).once()().toVar("highpModelNormalViewMatrix"),fg=yh(e=>"fragment"!==e.shaderStage?(Ei("TSL: `clipSpace` is only available in fragment stage."),Oh()):e.context.clipSpace.toVarying("v_clipSpace")).once()(),mg=mm("position","vec3"),gg=mg.toVarying("positionLocal"),_g=mg.toVarying("positionPrevious"),vg=yh(e=>lg.mul(gg).xyz.toVarying(e.getSubBuildProperty("v_positionWorld")),"vec3").once(["POSITION"])(),bg=yh(()=>gg.transformDirection(lg).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection"),"vec3").once(["POSITION"])(),yg=yh(e=>{if("fragment"===e.shaderStage&&e.material.vertexNode){const e=tg.mul(fg);return e.xyz.div(e.w).toVar("positionView")}return e.context.setupPositionView().toVarying("v_positionView")},"vec3").once(["POSITION","VERTEX"])(),xg=yh(e=>{let t;return t=e.camera.isOrthographicCamera?Dh(0,0,1):yg.negate().toVarying("v_positionViewDirection").normalize(),t.toVar("positionViewDirection")},"vec3").once(["POSITION"])(),Sg=(e=0)=>mm("uv"+(e>0?e:""),"vec2"),Tg=yh(([e=bg])=>{const t=e.z.atan(e.x).mul(1/(2*Math.PI)).add(.5),i=e.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5);return Ch(t,i)}),Mg=yh(([e=Sg()])=>{const t=e.x.sub(.5).mul(2*Math.PI),i=e.y.sub(.5).mul(Math.PI),r=i.cos(),n=r.mul(t.cos()),s=i.sin(),a=r.mul(t.sin());return Dh(n,s,a)});class Eg extends Sc{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}isCacheable(){return!1}generate(e){if("fragment"!==e.shaderStage)return"true";const{material:t}=e;return 1===t.side?"false":e.getFrontFacing()}}const wg=Eh(gh(Eg)).mul(2).sub(1),Ag=yh(([e],{material:t})=>{const i=t.side;return 1===i?e=e.mul(-1):2===i&&(e=e.mul(wg)),e}),Rg=mm("normal","vec3"),Cg=yh(e=>!1===e.geometry.hasAttribute("normal")?(Ti('TSL: Vertex attribute "normal" not found on geometry.'),Dh(0,1,0)):Rg,"vec3").once()().toVar("normalLocal"),Ng=yg.dFdx().cross(yg.dFdy()).normalize().toVar("normalFlat"),Pg=yh(e=>{let t;return t=e.isFlatShading()?Ng:Og(Cg).toVarying("v_normalViewGeometry").normalize(),t},"vec3").once()().toVar("normalViewGeometry"),Lg=yh(e=>{let t=Pg.transformNormalByInverseViewMatrix(ig);return!0!==e.isFlatShading()&&(t=t.toVarying("v_normalWorldGeometry")),t.normalize().toVar("normalWorldGeometry")},"vec3").once()(),Dg=yh(e=>{let t;return"NORMAL"===e.subBuildFn||"VERTEX"===e.subBuildFn?(t=Pg,!0!==e.isFlatShading()&&(t=Ag(t))):t=e.context.setupNormal().context({getUV:null,getTextureLevel:null}),t},"vec3").once(["NORMAL","VERTEX"])().toVar("normalView"),Ug=Dg.transformNormalByInverseViewMatrix(ig).toVar("normalWorld"),Ig=yh(({subBuildFn:e,context:t})=>{let i;return i="NORMAL"===e||"VERTEX"===e?Dg:t.setupClearcoatNormal().context({getUV:null,getTextureLevel:null}),i},"vec3").once(["NORMAL","VERTEX"])().toVar("clearcoatNormalView"),Fg=yh(([e,t=lg])=>Vh(t).inverse().transpose().mul(e).normalize());Oc("transformNormal",Fg);const Og=yh(([e],t)=>{const i=t.context.modelNormalViewMatrix;if(i)return e.transformNormalByViewMatrix(i);return ug.mul(e).transformNormalByViewMatrix(ig)}),Bg=yh(()=>{const e=Dh(xg.z,0,xg.x.negate()).normalize(),t=xg.cross(e);return Ch(e.dot(Dg),t.dot(Dg)).mul(.495).add(.5)}).once(["NORMAL","VERTEX"])().toVar("matcapUV");class kg extends Qh{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=Qu}get textureNode(){return this._textureNode}get texture(){return this._textureNode.value}update(){const e=this.texture,t=e.images,i=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(i&&void 0!==i.width){const{width:e,height:t}=i;this.value=Math.log2(Math.max(e,t))}}}const zg=mh(kg).setParameterLength(1),Gg=e=>Dh(e,xp(ff(Eh(1).sub(af(e,e)))));class Vg extends Sc{static get type(){return"RotateNode"}constructor(e,t,i="XYZ"){super(),this.positionNode=e,this.rotationNode=t,this._order=i}customCacheKey(){return cc(this._order)}setOrder(e){return this._order=e,this}getOrder(){return this._order}generateNodeType(e){return this.positionNode.getNodeType(e)}setup(e){const{rotationNode:t,positionNode:i}=this;if("vec2"===this.getNodeType(e)){const e=t.cos(),r=t.sin();return Gh(e,r,r.negate(),e).mul(i)}{const e=t,r=this._order,n={X:Hh(Oh(1,0,0,0),Oh(0,Cp(e.x),Ap(e.x),0),Oh(0,Ap(e.x).negate(),Cp(e.x),0),Oh(0,0,0,1)),Y:Hh(Oh(Cp(e.y),0,Ap(e.y).negate(),0),Oh(0,1,0,0),Oh(Ap(e.y),0,Cp(e.y),0),Oh(0,0,0,1)),Z:Hh(Oh(Cp(e.z),Ap(e.z),0,0),Oh(Ap(e.z).negate(),Cp(e.z),0,0),Oh(0,0,1,0),Oh(0,0,0,1))};return n[r.charAt(0)].mul(n[r.charAt(1)]).mul(n[r.charAt(2)]).mul(Oh(i,1)).xyz}}serialize(e){super.serialize(e),e.order=this._order}deserialize(e){super.deserialize(e),this._order=e.order}}const Hg=mh(Vg).setParameterLength(2,3);class Wg extends Sc{static get type(){return"TextureSizeNode"}constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}isCacheable(){return!1}generate(e){const t=this.textureNode.build(e,"property"),i=null===this.levelNode?"0":this.levelNode.build(e,"int"),r=e.generateTextureSize(this.textureNode.value,t,i);return e.format(r,this.getNodeType(e))}}const jg=mh(Wg).setParameterLength(1,2),$g=new lr;class Xg extends Qh{static get type(){return"TextureNode"}constructor(e=$g,t=null,i=null,r=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=i,this.biasNode=r,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.gatherNode=null,this.offsetNode=null,this.sampler=!0,this.updateMatrix=!1,this.referenceNode=null,this._mergeable=!0,this._value=e,this._matrixUniform=null,this._flipYUniform=null,this._samplerComparison=!1,this.setUpdateMatrix(null===t)}set mergeable(e){this.referenceNode?this.referenceNode.mergeable=e:this._mergeable=e}get mergeable(){return this.referenceNode?this.referenceNode.mergeable:this._mergeable}set value(e){this.referenceNode?this.referenceNode.value=e:this._value=e}get value(){return this.referenceNode?this.referenceNode.value:this._value}getUniformHash(e){return this.referenceNode&&!this.referenceNode.mergeable?this.referenceNode.getHash(e):this._mergeable?this.value.uuid:this.getHash(e)}customCacheKey(){const{type:e,minFilter:t,magFilter:i}=this.value;return dc(this.id,e,t,i)}generateNodeType(){return null!==this.gatherNode?"vec4":gc(this.value)}getInputType(){return"texture"}getDefaultUV(){return Sg(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return this._getMatrixUniform().mul(Dh(e,1)).xy}_getTransformedGradient(e){return this._getMatrixUniform().mul(Dh(e,0)).xy}_getMatrixUniform(){const e=this.getBase();return null===e._matrixUniform&&(e._matrixUniform=Jh(e.value.matrix).onObjectUpdate(()=>{const t=e.value;return!0===t.matrixAutoUpdate&&t.updateMatrix(),t.matrix})),e._matrixUniform}setUpdateMatrix(e){return this.updateMatrix=e,this}setupUV(e,t){if(e.isFlipY()){const e=this.getBase();null===e._flipYUniform&&(e._flipYUniform=Jh(!1).onObjectUpdate(()=>{const t=e.value;return t.image instanceof ImageBitmap&&!0===t.flipY||!0===t.isRenderTargetTexture||!0===t.isFramebufferTexture||!0===t.isDepthTexture})),t=t.toVar(),t=this.sampler?e._flipYUniform.select(t.flipY(),t):e._flipYUniform.select(t.setY(wh(jg(this,this.levelNode).y).sub(wh(t.y)).sub(1)),t)}return t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;const i=this.value;if(!i||!0!==i.isTexture)throw new bf("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().",this.stackTrace);const r=yh(()=>{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),t})();let n=this.levelNode;null===n&&e.context.getTextureLevel&&(n=e.context.getTextureLevel(this));let s=null,a=null;if(null!==this.compareNode)if(e.renderer.hasCompatibility(pi))s=this.compareNode;else{const e=i.compareFunction;null===e||e===Jt||e===ti||e===ii||e===ni?a=this.compareNode:(s=this.compareNode,Ei('TSL: Only "LessCompare", "LessEqualCompare", "GreaterCompare" and "GreaterEqualCompare" are supported for depth texture comparison fallback.'))}let o=this.gradNode;if(null===o&&null===this.uvNode&&null===n&&null===this.biasNode&&!0===this.sampler&&e.context.getTextureGradient){const t=e.context.getTextureGradient(this,e);t&&(o=!0===this.updateMatrix?t.map(e=>this._getTransformedGradient(e)):t)}t.uvNode=r,t.levelNode=n,t.biasNode=this.biasNode,t.compareNode=s,t.compareStepNode=a,t.gradNode=o,t.gatherNode=this.gatherNode,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,i,r,n,s,a,o,l,u,c){const h=this.value;let d;return d=n?e.generateTextureBias(h,t,i,n,s,u):o?e.generateTextureGrad(h,t,i,o,s,u):l?a?e.generateTextureGatherCompare(h,t,i,a,s,u,c):e.generateTextureGather(h,t,i,l,s,u,c):a?e.generateTextureCompare(h,t,i,a,s,u):!1===this.sampler?e.generateTextureLoad(h,t,i,r,s,u):r?e.generateTextureLevel(h,t,i,r,s,u):e.generateTexture(h,t,i,s,u),d}generate(e,t){const i=this.value,r=e.getNodeProperties(this),n=super.generate(e,"property");if("samplerComparison"!==t&&null===r.compareNode||(this.getSharedNode(e)._samplerComparison=!0),/^sampler/.test(t))return n+"_sampler";if(e.isReference(t))return n;{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,gatherNode:f,offsetNode:m}=r,g=this.generateUV(e,t),_=l?l.build(e,"float"):null,v=u?u.build(e,"float"):null,b=d?d.build(e,"int"):null,y=c?c.build(e,"float"):null,x=h?h.build(e,"float"):null,S=p?[p[0].build(e,"vec2"),p[1].build(e,"vec2")]:null,T=f?f.build(e,"int"):null,M=m?this.generateOffset(e,m):null,E=this.getBase()._flipYUniform,w=E?E.build(e,"bool"):null;let A=b;null===A&&i.isArrayTexture&&!0!==this.isTexture3DNode&&(A="0");const R=e.getVarFromNode(this);o=e.getPropertyName(R);let C,N=this.generateSnippet(e,n,g,_,v,A,y,S,T,M,w);if(C=!0===i.isDepthTexture&&null===T?"float":i.type===je?"uvec4":i.type===We?"ivec4":"vec4",N=e.format(N,C,a),null!==x){const t=i.compareFunction;N=t===ii||t===ni?tf(am(N,a),am(x,"float")).build(e,a):tf(am(x,"float"),am(N,a)).build(e,a)}e.addLineFlowCode(`${o} = ${N}`,this),s.snippet=N,s.propertyName=o}let l=o;return e.needsToWorkingColorSpace(i)&&(l=If(am(l,a),i.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=dh(e),t.referenceNode=this.getBase(),t}load(e){return this.sample(e).setSampler(!1)}blur(e){const t=this.clone();t.biasNode=dh(e).mul(zg(t)),t.referenceNode=this.getBase();const i=t.value;return!1===t.generateMipmaps&&(i&&!1===i.generateMipmaps||i.minFilter===Ue||i.magFilter===Ue)&&(Ti("TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),t}level(e){const t=this.clone();return t.levelNode=dh(e),t.referenceNode=this.getBase(),t}size(e){return jg(this,e)}bias(e){const t=this.clone();return t.biasNode=dh(e),t.referenceNode=this.getBase(),t}getBase(){return this.referenceNode?this.referenceNode.getBase():this}compare(e){const t=this.clone();return t.compareNode=dh(e),t.referenceNode=this.getBase(),t}grad(e,t){const i=this.clone();return i.gradNode=[dh(e),dh(t)],i.referenceNode=this.getBase(),i}gather(e=0){const t=this.clone();return t.gatherNode=dh(e),t.referenceNode=this.getBase(),t}isSampleCompare(){return null!==this.compareNode||!0===this._samplerComparison}depth(e){const t=this.clone();return t.depthNode=dh(e),t.referenceNode=this.getBase(),t}offset(e){const t=this.clone();return t.offsetNode=dh(e),t.referenceNode=this.getBase(),t}serialize(e){super.serialize(e),e.value=this.value.toJSON(e.meta).uuid,e.sampler=this.sampler,e.updateMatrix=this.updateMatrix}deserialize(e){super.deserialize(e),this.value=e.meta.textures[e.value],this.sampler=e.sampler,this.updateMatrix=e.updateMatrix}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.gatherNode=this.gatherNode,e.offsetNode=this.offsetNode,e}}const qg=mh(Xg).setParameterLength(1,4).setName("texture"),Yg=(e=$g,t=null,i=null,r=null)=>{let n;return e&&!0===e.isTextureNode?(n=e.clone(),n.referenceNode=e.getBase(),null!==t&&(n.uvNode=dh(t)),null!==i&&(n.levelNode=dh(i)),null!==r&&(n.biasNode=dh(r))):n=qg(e,t,i,r),n},Kg=(...e)=>Yg(...e).setSampler(!1),Zg=new Vi;class Qg extends Xg{static get type(){return"ViewportTextureNode"}constructor(e=Bm,t=null,i=null){let r=null;null===i?(r=new $s,r.minFilter=ke,i=r):r=i,super(i,e,t),this.generateMipmaps=!1,this.defaultFramebuffer=r,this.isOutputTextureNode=!0,this.updateBeforeType=Ju,this._cacheTextures=new WeakMap}getTextureForReference(e=null){let t,i;if(this.referenceNode?(t=this.referenceNode.defaultFramebuffer,i=this.referenceNode._cacheTextures):(t=this.defaultFramebuffer,i=this._cacheTextures),null===e)return t;if(!1===i.has(e)){const r=t.clone();i.set(e,r)}return i.get(e)}updateReference(e){const t=e.renderer,i=t.getRenderTarget(),r=t.getCanvasTarget(),n=i||r;return this.value=this.getTextureForReference(n),this.value}updateBefore(e){const t=e.renderer,i=t.getRenderTarget(),r=t.getCanvasTarget(),n=i||r;null===n?t.getDrawingBufferSize(Zg):n.getDrawingBufferSize?n.getDrawingBufferSize(Zg):Zg.set(n.width,n.height);const s=this.getTextureForReference(n);s.image.width===Zg.width&&s.image.height===Zg.height||(s.image.width=Zg.width,s.image.height=Zg.height,s.needsUpdate=!0);const a=s.generateMipmaps;s.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(s),s.generateMipmaps=a}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const Jg=mh(Qg,null,null,{generateMipmaps:!0}).setParameterLength(0,3),e_=Jg(),t_=(e=Bm,t=null)=>e_.sample(e,t);let i_=null;class r_ extends Qg{static get type(){return"ViewportDepthTextureNode"}constructor(e=Bm,t=null,i=null){null===i&&(null===i_&&(i_=new Ys),i=i_),super(e,t,i)}}const n_=mh(r_).setParameterLength(0,3);class s_ extends Sc{static get type(){return"ViewportDepthNode"}constructor(e,t=null){super("float"),this.scope=e,this.valueNode=t,this.isViewportDepthNode=!0}isCacheable(){return!1}generate(e){const{scope:t}=this;return t===s_.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,i=this.valueNode;let r=null;if(t===s_.DEPTH_BASE)null!==i&&(r=h_().assign(i));else if(t===s_.DEPTH)r=!0!==e.isOrthographicCamera?l_(yg.z,Qm,Jm):a_(yg.z,Qm,Jm);else if(t===s_.LINEAR_DEPTH)if(null!==i)if(!0!==e.isOrthographicCamera){const e=u_(i,Qm,Jm);r=a_(e,Qm,Jm)}else r=i;else r=a_(yg.z,Qm,Jm);return r}}s_.DEPTH_BASE="depthBase",s_.DEPTH="depth",s_.LINEAR_DEPTH="linearDepth";const a_=(e,t,i)=>e.add(t).div(t.sub(i)),o_=yh(([e,t,i],r)=>!0===r.renderer.reversedDepthBuffer?i.sub(t).mul(e).sub(i):t.sub(i).mul(e).sub(t)),l_=(e,t,i)=>t.add(e).mul(i).div(i.sub(t).mul(e)),u_=yh(([e,t,i],r)=>!0===r.renderer.reversedDepthBuffer?t.mul(i).div(t.sub(i).mul(e).sub(t)):t.mul(i).div(i.sub(t).mul(e).sub(i))),c_=(e,t,i)=>{t=t.max(hp).toVar();const r=yp(e.negate().div(t)),n=yp(i.div(t));return r.div(n)},h_=mh(s_,s_.DEPTH_BASE),d_=gh(s_,s_.DEPTH);n_(),d_.assign=e=>h_(e),new fr;const p_=new cr;Bm.flipX(),p_.depthTexture=new Ys(1,1);const f_=new fr,m_=Jh(0).onReference(({material:e})=>e).onObjectUpdate(({material:e})=>e.refractionRatio),g_=Jh(1).onReference(({material:e})=>e).onObjectUpdate(function({material:e,scene:t}){return e.envMap?e.envMapIntensity:t.environmentIntensity}),__=Jh(new fr).onReference(function(e){return e.material}).onObjectUpdate(function({material:e,scene:t}){const i=(null!==t.environment||t.environmentNode&&t.environmentNode.isNode)&&null===e.envMap?t.environmentRotation:e.envMapRotation;return i?f_.makeRotationFromEuler(i).transpose():f_.identity(),f_}),v_=xg.negate().reflect(Dg),b_=xg.negate().refract(Dg,m_),y_=v_.transformDirection(rg).toVar("reflectVector"),x_=b_.transformDirection(rg).toVar("refractVector"),S_=new Xs;class T_ extends Xg{static get type(){return"CubeTextureNode"}constructor(e,t=null,i=null,r=null){super(e,t,i,r),this.isCubeTextureNode=!0}getInputType(){return!0===this.value.isDepthTexture?"cubeDepthTexture":"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===Ae?y_:e.mapping===Re?x_:(Mi('CubeTextureNode: Mapping "%s" not supported.',e.mapping),Dh(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const i=this.value;return e.renderer.coordinateSystem!==ci&&(i.isRenderTargetTexture||i.isDepthTexture)||(t=Dh(t.x.negate(),t.yz)),t}generateUV(e,t){return t.build(e,!0===this.sampler?"vec3":"ivec3")}}const M_=mh(T_).setParameterLength(1,4).setName("cubeTexture"),E_=(e=S_,t=null,i=null,r=null)=>{let n;return e&&!0===e.isCubeTextureNode?(n=e.clone(),n.referenceNode=e,null!==t&&(n.uvNode=dh(t)),null!==i&&(n.levelNode=dh(i)),null!==r&&(n.biasNode=dh(r))):n=M_(e,t,i,r),n};class w_ extends Sc{static get type(){return"ReferenceNode"}constructor(e,t,i=null,r=null){super(),this.property=e,this.uniformType=t,this.object=i,this.count=r,this.properties=e.split("."),this.reference=i,this.node=null,this.group=null,this.name=null,this.updateType=ec}isCacheable(){return!1}element(e){return new Ff(this,dh(e))}setGroup(e){return this.group=e,this}setName(e){return this.name=e,this}label(e){return Ti('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}setNodeType(e){let t=null;null!==this.count?t=Nm(null,e,this.count):Array.isArray(this.getValueFromReference())?(t=Dm(null,e),t.updateType=ec):t="texture"===e?Yg(null):"cubeTexture"===e?E_(null):Jh(null,e),null!==this.group&&t.setGroup(this.group),null!==this.name&&t.setName(this.name),this.node=t}generateNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let i=e[t[0]];for(let e=1;e<t.length;e++)i=i[t[e]];return i}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 A_=(e,t,i)=>new w_(e,t,i),R_=(e,t,i,r)=>new w_(e,t,r,i);class C_ extends w_{static get type(){return"MaterialReferenceNode"}constructor(e,t,i=null){super(e,t,i),this.material=i,this.isMaterialReferenceNode=!0}updateReference(e){return this.reference=null!==this.material?this.material:e.material,this.reference}}const N_=(e,t,i=null)=>new C_(e,t,i),P_=Sg(),L_=yg.dFdx(),D_=yg.dFdy(),U_=P_.dFdx(),I_=P_.dFdy(),F_=Dg,O_=D_.cross(F_),B_=F_.cross(L_),k_=O_.mul(U_.x).add(B_.mul(I_.x)),z_=O_.mul(U_.y).add(B_.mul(I_.y)),G_=k_.dot(k_).max(z_.dot(z_)),V_=G_.equal(0).select(0,G_.inverseSqrt()),H_=k_.mul(V_).toVar("tangentViewFrame"),W_=z_.mul(V_).toVar("bitangentViewFrame"),j_=mm("tangent","vec4"),$_=j_.xyz.toVar("tangentLocal"),X_=yh(e=>{let t;return t="VERTEX"===e.subBuildFn||e.geometry.hasAttribute("tangent")?cg.mul(Oh($_,0)).xyz.toVarying("v_tangentView").normalize():H_,!0!==e.isFlatShading()&&(t=Ag(t)),t},"vec3").once(["NORMAL","VERTEX"])().toVar("tangentView"),q_=yh(([e,t],i)=>{let r=e.mul(j_.w).xyz;return"NORMAL"===i.subBuildFn&&!0!==i.isFlatShading()&&(r=r.toVarying(t)),r}).once(["NORMAL"]),Y_=Vh(X_,yh(e=>{let t;return t="VERTEX"===e.subBuildFn||e.geometry.hasAttribute("tangent")?q_(Dg.cross(X_),"v_bitangentView").normalize():W_,!0!==e.isFlatShading()&&(t=Ag(t)),t},"vec3").once(["NORMAL","VERTEX"])().toVar("bitangentView"),Dg).toVar("TBNViewMatrix"),K_=yh(()=>{let e=bd.cross(xg);return e=e.cross(bd).normalize(),e=df(e,Dg,_d.mul(od.oneMinus()).oneMinus().pow2().pow2()).normalize(),e}).once()();class Z_ extends Sc{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:i,unpackNormalMode:r}=this;let n=this.node.mul(2).sub(1);if(0===t?"rg"===r?n=Gg(n.xy):"ga"===r?n=Gg(n.yw):""!==r&&Mi(`THREE.NodeMaterial: Unexpected unpack normal mode: ${r}`):""!==r&&Mi(`THREE.NodeMaterial: Normal map type '${t}' is not compatible with unpack normal mode '${r}'`),null!==i){let t=i;!0===e.isFlatShading()&&(t=Ag(t)),n=Dh(n.xy.mul(t),n.z)}let s=null;return 1===t?s=Og(n):0===t?s=Y_.mul(n).normalize():(Mi(`NodeMaterial: Unsupported normal map type: ${t}`),s=Dg),s}}const Q_=mh(Z_).setParameterLength(1,2),J_=yh(({textureNode:e,bumpScale:t})=>{const i=t=>e.isolate().context({getUV:e=>t(e.uvNode||Sg()),forceUVContext:!0}),r=Eh(i(e=>e));return Ch(Eh(i(e=>e.add(e.dFdx()))).sub(r),Eh(i(e=>e.add(e.dFdy()))).sub(r)).mul(t)}),ev=yh(e=>{const{surf_pos:t,surf_norm:i,dHdxy:r}=e,n=t.dFdx().normalize(),s=i,a=t.dFdy().normalize().cross(s),o=s.cross(n),l=n.dot(a).mul(wg),u=l.sign().mul(r.x.mul(a).add(r.y.mul(o)));return l.abs().mul(i).sub(u).normalize()});class tv extends Sc{static get type(){return"BumpMapNode"}constructor(e,t=null,i=Dg){super("vec3"),this.textureNode=e,this.scaleNode=t,this.normalNode=i}setup(e){if(!0===e.material.wireframe)return this.normalNode;const t=null!==this.scaleNode?this.scaleNode:1,i=J_({textureNode:this.textureNode,bumpScale:t});return ev({surf_pos:yg,surf_norm:this.normalNode,dHdxy:i})}}const iv=mh(tv).setParameterLength(1,3),rv=new Map;class nv extends Sc{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}isCacheable(){return!1}getCache(e,t){let i=rv.get(e);return void 0===i&&(i=N_(e,t),rv.set(e,i)),i}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,i=this.scope;let r=null;if(i===nv.COLOR){const e=void 0!==t.color?this.getColor(i):Dh();r=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(i===nv.OPACITY){const e=this.getFloat(i);r=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(i===nv.SPECULAR_STRENGTH)r=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:Eh(1);else if(i===nv.SPECULAR_INTENSITY){const e=this.getFloat(i);r=t.specularIntensityMap&&!0===t.specularIntensityMap.isTexture?e.mul(this.getTexture(i).a):e}else if(i===nv.SPECULAR_COLOR){const e=this.getColor(i);r=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(i).rgb):e}else if(i===nv.ROUGHNESS){const e=this.getFloat(i);r=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(i).g):e}else if(i===nv.DIFFUSE_ROUGHNESS){const e=this.getFloat(i);r=t.diffuseRoughnessMap&&!0===t.diffuseRoughnessMap.isTexture?e.mul(this.getTexture(i).r):e}else if(i===nv.METALNESS){const e=this.getFloat(i);r=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(i).b):e}else if(i===nv.EMISSIVE){const e=this.getFloat("emissiveIntensity"),n=this.getColor(i).mul(e);r=t.emissiveMap&&!0===t.emissiveMap.isTexture?n.mul(this.getTexture(i)):n}else if(i===nv.NORMAL)t.normalMap?(r=Q_(this.getTexture("normal"),this.getCache("normalScale","vec2")),r.normalMapType=t.normalMapType,t.normalMap.format!=at&&t.normalMap.format!=Wt&&t.normalMap.format!=Tt||(r.unpackNormalMode="rg")):r=t.bumpMap?iv(this.getTexture("bump").r,this.getFloat("bumpScale")):Dg;else if(i===nv.CLEARCOAT){const e=this.getFloat(i);r=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(i).r):e}else if(i===nv.CLEARCOAT_ROUGHNESS){const e=this.getFloat(i);r=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(i).g):e}else if(i===nv.CLEARCOAT_NORMAL)r=t.clearcoatNormalMap?Q_(this.getTexture(i),this.getCache(i+"Scale","vec2")):Dg;else if(i===nv.SHEEN){const e=this.getColor("sheenColor").mul(this.getFloat("sheen"));r=t.sheenColorMap&&!0===t.sheenColorMap.isTexture?e.mul(this.getTexture("sheenColor").rgb):e}else if(i===nv.SHEEN_ROUGHNESS){const e=this.getFloat(i);r=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(i).a):e,r=r.clamp(1e-4,1)}else if(i===nv.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(i);r=Gh(Wv.x,Wv.y,Wv.y.negate(),Wv.x).mul(e.rg.mul(2).sub(Ch(1)).normalize().mul(e.b))}else r=Wv;else if(i===nv.IRIDESCENCE_THICKNESS){const e=this.getFloat("iridescenceThicknessMaximum");if(t.iridescenceThicknessMap){const t=this.getFloat("iridescenceThicknessMinimum");r=e.sub(t).mul(this.getTexture(i).g).add(t)}else r=e}else if(i===nv.TRANSMISSION){const e=this.getFloat(i);r=t.transmissionMap?e.mul(this.getTexture(i).r):e}else if(i===nv.THICKNESS){const e=this.getFloat(i);r=t.thicknessMap?e.mul(this.getTexture(i).g):e}else if(i===nv.IOR)r=this.getFloat(i);else if(i===nv.LIGHT_MAP)r=t.lightMap?this.getTexture(i).rgb.mul(this.getFloat("lightMapIntensity")):Dh(0);else if(i===nv.AO)r=t.aoMap?this.getTexture(i).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1):Eh(1);else if(i===nv.LINE_DASH_OFFSET)r=t.dashOffset?this.getFloat(i):Eh(0);else{const t=this.getNodeType(e);r=this.getCache(i,t)}return r}}nv.ALPHA_TEST="alphaTest",nv.COLOR="color",nv.OPACITY="opacity",nv.SHININESS="shininess",nv.SPECULAR="specular",nv.SPECULAR_STRENGTH="specularStrength",nv.SPECULAR_INTENSITY="specularIntensity",nv.SPECULAR_COLOR="specularColor",nv.REFLECTIVITY="reflectivity",nv.ROUGHNESS="roughness",nv.DIFFUSE_ROUGHNESS="diffuseRoughness",nv.METALNESS="metalness",nv.NORMAL="normal",nv.CLEARCOAT="clearcoat",nv.CLEARCOAT_ROUGHNESS="clearcoatRoughness",nv.CLEARCOAT_NORMAL="clearcoatNormal",nv.EMISSIVE="emissive",nv.ROTATION="rotation",nv.SHEEN="sheen",nv.SHEEN_ROUGHNESS="sheenRoughness",nv.ANISOTROPY="anisotropy",nv.IRIDESCENCE="iridescence",nv.IRIDESCENCE_IOR="iridescenceIOR",nv.IRIDESCENCE_THICKNESS="iridescenceThickness",nv.IOR="ior",nv.TRANSMISSION="transmission",nv.THICKNESS="thickness",nv.ATTENUATION_DISTANCE="attenuationDistance",nv.ATTENUATION_COLOR="attenuationColor",nv.LINE_SCALE="scale",nv.LINE_DASH_SIZE="dashSize",nv.LINE_GAP_SIZE="gapSize",nv.LINE_WIDTH="linewidth",nv.LINE_DASH_OFFSET="dashOffset",nv.POINT_SIZE="size",nv.DISPERSION="dispersion",nv.RETROREFLECTIVITY="retroreflectivity",nv.LIGHT_MAP="light",nv.AO="ao";const sv=gh(nv,nv.ALPHA_TEST),av=gh(nv,nv.COLOR),ov=gh(nv,nv.SHININESS),lv=gh(nv,nv.EMISSIVE),uv=gh(nv,nv.OPACITY),cv=gh(nv,nv.SPECULAR),hv=gh(nv,nv.SPECULAR_INTENSITY),dv=gh(nv,nv.SPECULAR_COLOR),pv=gh(nv,nv.SPECULAR_STRENGTH),fv=gh(nv,nv.REFLECTIVITY),mv=gh(nv,nv.ROUGHNESS),gv=gh(nv,nv.DIFFUSE_ROUGHNESS),_v=gh(nv,nv.METALNESS),vv=gh(nv,nv.NORMAL),bv=gh(nv,nv.CLEARCOAT),yv=gh(nv,nv.CLEARCOAT_ROUGHNESS),xv=gh(nv,nv.CLEARCOAT_NORMAL),Sv=gh(nv,nv.ROTATION),Tv=gh(nv,nv.SHEEN),Mv=gh(nv,nv.SHEEN_ROUGHNESS),Ev=gh(nv,nv.ANISOTROPY),wv=gh(nv,nv.IRIDESCENCE),Av=gh(nv,nv.IRIDESCENCE_IOR),Rv=gh(nv,nv.IRIDESCENCE_THICKNESS),Cv=gh(nv,nv.TRANSMISSION),Nv=gh(nv,nv.THICKNESS),Pv=gh(nv,nv.IOR),Lv=gh(nv,nv.ATTENUATION_DISTANCE),Dv=gh(nv,nv.ATTENUATION_COLOR),Uv=gh(nv,nv.LINE_SCALE),Iv=gh(nv,nv.LINE_DASH_SIZE),Fv=gh(nv,nv.LINE_GAP_SIZE),Ov=gh(nv,nv.LINE_WIDTH),Bv=gh(nv,nv.LINE_DASH_OFFSET),kv=gh(nv,nv.POINT_SIZE),zv=gh(nv,nv.DISPERSION),Gv=gh(nv,nv.RETROREFLECTIVITY),Vv=gh(nv,nv.LIGHT_MAP),Hv=gh(nv,nv.AO),Wv=Jh(new Vi).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))}),jv=yh(e=>e.context.setupModelViewProjection(),"vec4").once()().toVarying("v_modelViewProjection");class $v extends Sc{static get type(){return"EventNode"}constructor(e,t){super("void"),this.eventType=e,this.callback=t,e===$v.OBJECT?this.updateType=ec:e===$v.MATERIAL?this.updateType=Ju:e===$v.FRAME?this.updateType=Qu:e===$v.AFTER_OBJECT?this.updateAfterType=ec:e===$v.BEFORE_OBJECT?this.updateBeforeType=ec:e===$v.BEFORE_MATERIAL?this.updateBeforeType=Ju:e===$v.BEFORE_FRAME&&(this.updateBeforeType=Qu)}isCacheable(){return!1}setup(e){const{eventType:t,callback:i}=this;if(t===$v.BEFORE_RENDER_PIPELINE){const t=e.context.onBeforePipelineCallbacks;t&&t.push(i)}else if(t===$v.AFTER_RENDER_PIPELINE){const t=e.context.onAfterPipelineCallbacks;t&&t.push(i)}return super.setup(e)}update(e){this.callback(e)}updateBefore(e){this.callback(e)}updateAfter(e){this.callback(e)}}$v.OBJECT="object",$v.MATERIAL="material",$v.FRAME="frame",$v.AFTER_OBJECT="afterObject",$v.BEFORE_OBJECT="beforeObject",$v.BEFORE_MATERIAL="beforeMaterial",$v.BEFORE_FRAME="beforeFrame",$v.BEFORE_RENDER_PIPELINE="beforeRenderPipeline",$v.AFTER_RENDER_PIPELINE="afterRenderPipeline";const Xv=(e,t)=>new $v(e,t).toStack(),qv=e=>Xv($v.OBJECT,e),Yv=e=>Xv($v.AFTER_OBJECT,e);class Kv extends Tc{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 i=this.storageBufferNode.structTypeNode;return i?i.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 i;const r=e.isContextAssign();if(i=!1===e.isAvailable("storageBuffer")?!0!==this.node.isPBO||!0===r||!this.node.value.isInstancedBufferAttribute&&"compute"===e.shaderStage?this.node.build(e):e.generatePBO(this):super.generate(e),!0!==r){const r=this.getNodeType(e);i=e.format(i,r,t)}return i}}const Zv=mh(Kv).setParameterLength(2);class Qv extends Cm{static get type(){return"StorageBufferNode"}constructor(e,t=null,i=0){let r,n=null;t&&t.isStructTypeNode?(r="struct",n=t,(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(i=e.count)):null===t&&(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)?(r=fc(e.itemSize),i=e.count):r=t,super(e,r,i),this.isStorageBufferNode=!0,this.structTypeNode=n,this.access=rc,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){let t;if(0===this.bufferCount){let i=e.globalCache.getData(this.value);void 0===i&&(i={node:this},e.globalCache.setData(this.value,i)),t=i.node.id}else t=this.id;return String(t)}getInputType(){return this.value.isIndirectStorageBufferAttribute?"indirectStorageBuffer":"storageBuffer"}element(e){return Zv(this,e)}setPBO(e){return this.isPBO=e,this}getPBO(){return this.isPBO}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(tc)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return null===this._attribute&&(this._attribute=$f(this.value),this._varying=Nf(this._attribute)),{attribute:this._attribute,varying:this._varying}}generateNodeType(e){return null!==this.structTypeNode?this.structTypeNode.getNodeType(e):super.generateNodeType(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:i}=this.getAttributeData(),r=i.build(e);return e.registerTransform(r,t),e.format(r,t.getNodeType(e),this.getNodeType(e))}}const Jv=(e,t=null,i=0)=>new Qv(e,t,i),eb=new WeakMap;function tb(e,t,i){let r=eb.get(e);return void 0===r&&(r=[],eb.set(e,r)),r[i]||(r[i]=new ts(e,function(e){return/float|int|uint|bool/.test(e)?1:/vec2/.test(e)?2:/vec3/.test(e)?3:/vec4/.test(e)||/mat2/.test(e)?4:/mat3/.test(e)?9:/mat4/.test(e)?16:void Mi(`TSL: Unsupported type: ${e}`,new lc)}(t),i))}class ib extends Wf{static get type(){return"ReferenceBufferAttributeNode"}constructor(e,t,i=0,r=0){super(null,t,i,r),this.referenceNode=e,this.isReferenceBufferAttributeNode=!0}getHash(){return String(this.id)}getObjectAttribute(e){const t=this.referenceNode.getAttribute(e);return t&&0!==this.bufferStride?tb(t,this.bufferType,this.bufferOffset):t}setup(e){this.attribute=this.getObjectAttribute(e.object)}}class rb extends Sc{static get type(){return"ReferenceAttributeNode"}constructor(e,t=null,i=null){super(t),this.property=e,this.properties=e.split("."),this.object=i}getValueFromReference(e){let t=e;for(const e of this.properties){if(null==t)break;t=t[e]}return t}getAttribute(e){return this.getValueFromReference(null!==this.object?this.object:e)}generateNodeType(e){if(null!==this.nodeType)return this.nodeType;const t=this.getAttribute(e.object);return t?e.getTypeFromAttribute(t):"float"}setup(e){const t=this.getAttribute(e.object);if(!t)throw new Error(`THREE.ReferenceAttributeNode: Attribute "${this.property}" not found.`);const i=this.getNodeType(e);if(!0===t.isStorageBufferAttribute||!0===t.isStorageInstancedBufferAttribute){const e=!0===t.isStorageInstancedBufferAttribute?Zf:Kf;return Jv(t,i,Math.max(t.count,1)).onObjectUpdate(({object:e})=>this.getAttribute(e)).element(e)}return"mat4"===i?Hh(...[0,4,8,12].map(e=>new ib(this,"vec4",16,e))):"mat3"===i?Vh(...[0,3,6].map(e=>new ib(this,"vec3",9,e))):new ib(this,i)}}const nb=(e,t=null,i=null)=>new rb(e,t,i),sb=new WeakMap,ab=new WeakMap;function ob(e,t){let i;const r=Math.max(t.count,1);if(!0===t.isStorageInstancedBufferAttribute)i=Jv(t,"mat4",r).element(Zf);else{if(16*r*4<=e.getUniformBufferLimit())i=Nm(t.array,"mat4",r).element(Zf);else{const e=t.usage===oi?qf:Xf,r=[0,4,8,12].map(i=>e(new ts(t,4,i)));i=Hh(...r)}}return i}function lb({target:e}){sb.get(e).previousInstanceMatrix.dispose()}function ub(e){const t=e.instanceMatrix;let i=ab.get(e);return void 0!==i&&i.count===t.count||(void 0===i?e.addEventListener("dispose",cb):i.dispose(),i=t.clone(),ab.set(e,i)),i}function cb({target:e}){e.removeEventListener("dispose",cb),ab.get(e).dispose(),ab.delete(e)}class hb extends rb{static get type(){return"PreviousInstanceMatrixNode"}constructor(){super("previousInstanceMatrix","mat4")}getValueFromReference(e){return ub(e)}}function db(e,t,i){const r=t.mul(gg).xyz;if(gg.assign(r),null!==i&&_g.assign(i.mul(_g).xyz),e.hasGeometryAttribute("normal")){const e=Fg(Cg,t);Cg.assign(e)}}const pb=id("vec3","vInstanceColor"),fb=yh(([e,t=null],i)=>{const r=t&&!0===t.isStorageInstancedBufferAttribute,n=ob(i,e);let s=null;if(t)if(r)s=Jv(t,"vec3",Math.max(t.count,1)).element(Zf);else{const e=t.usage===oi?qf:Xf;s=Dh(e(t))}let a=null;if(i.needsPreviousData()){const t=i.object;Yv(({object:t})=>{const{previousInstanceMatrix:i}=sb.get(t);i.array.set(e.array),i.version=e.version}),a=function(e,t,i){let r=sb.get(e);if(void 0===r){const n=t.clone();r={previousInstanceMatrix:n,node:ob(i,n)},sb.set(e,r),e.addEventListener("dispose",lb)}return r.node}(t,e,i)}db(i,n,a),null!==s&&pb.assign(s)},"void"),mb=yh(([e],t)=>{if(function(e,t){if(!0!==t.renderer.isRenderer)return!1;const i=1+(null!==e.instanceColor?1:0)+(t.needsPreviousData()?1:0);return Object.keys(e.geometry.attributes).length+i<=8}(e,t)){let i=null;t.needsPreviousData()&&(Yv(({object:e})=>{const t=ub(e);t.array.set(e.instanceMatrix.array),t.version=e.instanceMatrix.version}),i=new hb),db(t,nb("instanceMatrix","mat4"),i),null!==e.instanceColor&&pb.assign(nb("instanceColor","vec3"))}else t.objectSpecific=!0,fb(e.instanceMatrix,e.instanceColor)},"void"),gb=yh(([e,t])=>{const i=wh(jg(Kg(e),0).x).toConst(),r=wh(t),n=r.mod(i).toConst(),s=r.div(i).toConst();return Kg(e,Nh(n,s))}),_b=yh(([e,t])=>{const i=wh(jg(Kg(e),0).x).toConst(),r=wh(t).mod(i).toConst(),n=wh(t).div(i).toConst();return Kg(e,Nh(r,n)).x});function vb(e,t){const i=wh(jg(Kg(e),0).x).toConst(),r=Eh(t).mul(4).toInt().toConst(),n=r.mod(i).toConst(),s=r.div(i).toConst();return Hh(Kg(e,Nh(n,s)),Kg(e,Nh(n.add(1),s)),Kg(e,Nh(n.add(2),s)),Kg(e,Nh(n.add(3),s)))}function bb(e){let t=e._previousMatricesTexture;if(null===t){const{image:i,format:r,type:n,version:s}=e._matricesTexture;t=new Rs(i.data.slice(),i.width,i.height,r,n),t.version=s,e._previousMatricesTexture=t}return t}const yb=id("vec4","vBatchColor"),xb=id("uint","vBatchIndirectId"),Sb=yh(([e],t)=>{const i=null===t.getDrawIndex()?Zf:Qf,r=_b(e._indirectTexture,wh(i));xb.assign(r);const n=vb(e._matricesTexture,r),s=e._colorsTexture;if(null!==s){const e=gb(s,r);yb.assign(e)}const a=Vh(n);if(gg.assign(n.mul(gg)),t.needsPreviousData()){Yv(({object:e})=>{const t=bb(e),i=e._matricesTexture;t.version!==i.version&&(t.image.data.set(i.image.data),t.version=i.version)});const t=vb(bb(e),r);_g.assign(t.mul(_g).xyz)}const o=Cg.div(Dh(a[0].dot(a[0]),a[1].dot(a[1]),a[2].dot(a[2]))),l=a.mul(o).xyz;Cg.assign(l),t.hasGeometryAttribute("tangent")&&$_.mulAssign(a);const u=!0===t.renderer.backend.isWebGPUBackend?"merged":"multiDraw";qv(({object:e,camera:t,material:i})=>{e._updateDrawParameters(t,e.geometry,i,u)})},"void"),Tb=new WeakMap;function Mb(e){return{element:t=>{const i=wh(jg(e).x).toConst(),r=wh(t).mul(4).toConst(),n=r.div(i).toConst(),s=r.sub(n.mul(i)).toConst();return Hh(e.load(Nh(s,n)),e.load(Nh(s.add(1),n)),e.load(Nh(s.add(2),n)),e.load(Nh(s.add(3),n)))}}}function Eb(e,t,i,r,n,s){const a=e.element(n.x),o=e.element(n.y),l=e.element(n.z),u=e.element(n.w),c=i.mul(t),h=Bd(a.mul(s.x).mul(c),o.mul(s.y).mul(c),l.mul(s.z).mul(c),u.mul(s.w).mul(c));return r.mul(h).xyz}function wb(e){if(null===e.previousBoneMatrices&&(e.update(),e.previousBoneMatrices=new Float32Array(e.boneMatrices)),null===e.previousBoneTexture&&null!==e.boneTexture){const{width:t,height:i}=e.boneTexture.image;e.previousBoneTexture=new Rs(e.previousBoneMatrices,t,i,tt,$e),e.previousBoneTexture.needsUpdate=!0}}const Ab=yh(([e],t)=>{const i=mm("skinIndex","uvec4"),r=mm("skinWeight","vec4"),n=A_("bindMatrix","mat4"),s=A_("bindMatrixInverse","mat4"),a=function(e,t){let i;if(16*t.bones.length*4<=e.getUniformBufferLimit())i=R_("skeleton.boneMatrices","mat4",t.bones.length);else{null===t.boneTexture&&t.computeBoneTexture();const e=Yg(t.boneTexture);qv(({object:t})=>{const i=t.skeleton;null===i.boneTexture&&i.computeBoneTexture(),e.value=i.boneTexture}),i=Mb(e)}return i}(t,e.skeleton),o=t.needsPreviousData();if(qv(({object:e,frameId:t})=>{const i=e.skeleton;o&&wb(i),Tb.get(i)!==t&&(Tb.set(i,t),null!==i.previousBoneMatrices&&(i.previousBoneMatrices.set(i.boneMatrices),null!==i.previousBoneTexture&&(i.previousBoneTexture.needsUpdate=!0)),i.update())}),o){const a=function(e,t){let i;if(wb(t),16*t.bones.length*4<=e.getUniformBufferLimit())i=R_("skeleton.previousBoneMatrices","mat4",t.bones.length);else{const e=Yg(t.previousBoneTexture);qv(({object:t})=>{e.value=t.skeleton.previousBoneTexture}),i=Mb(e)}return i}(t,e.skeleton),o=Eb(a,_g,n,s,i,r);_g.assign(o)}const l=Eb(a,gg,n,s,i,r);if(gg.assign(l),t.hasGeometryAttribute("normal")){const{skinNormal:e,skinTangent:o}=function(e,t,i,r,n,s,a){const o=e.element(s.x),l=e.element(s.y),u=e.element(s.z),c=e.element(s.w);let h=Bd(a.x.mul(o),a.y.mul(l),a.z.mul(u),a.w.mul(c));h=n.mul(h).mul(r);const d=Vh(h);return{skinNormal:d.mul(t),skinTangent:d.mul(i)}}(a,Cg,$_,n,s,i,r);Cg.assign(e),t.hasGeometryAttribute("tangent")&&$_.assign(o)}},"void"),Rb=new WeakMap,Cb=new ur,Nb=new WeakMap,Pb=yh(({bufferMap:e,influence:t,stride:i,width:r,depth:n,offset:s})=>{const a=wh(Kf).mul(i).add(s),o=a.div(r),l=a.sub(o.mul(r));return Kg(e,Nh(l,o)).depth(n).mul(t)}),Lb=Jh(1).onObjectUpdate(({object:e})=>e.geometry.morphTargetsRelative?1:1-e.morphTargetInfluences.reduce((e,t)=>e+t,0)),Db=td("vec4","morphColorSum"),Ub=yh(([e],{geometry:t})=>4===t.morphAttributes.color[0].itemSize?Nf(e.mul(Lb).add(Db)):Nf(Oh(e.rgb.mul(Lb).add(Db.rgb),e.a)));const Ib=yh(([e],t)=>{const{geometry:i}=e,r=void 0!==i.morphAttributes.position,n=i.hasAttribute("normal")&&void 0!==i.morphAttributes.normal,s=!0===t.material.vertexColors&&void 0!==i.morphAttributes.color,a=!0===s&&4===i.morphAttributes.color[0].itemSize,o=i.morphAttributes.position||i.morphAttributes.normal||i.morphAttributes.color,l=void 0!==o?o.length:0;if(0===l)return;e.morphTexture&&(t.objectSpecific=!0);let u=Nb.get(e);void 0!==u&&u.count===l||(u={influences:e.morphTargetInfluences?Dm(e.morphTargetInfluences,"float"):null,count:l},Nb.set(e,u));const{influences:c}=u,{texture:h,stride:d,size:p}=function(e){const t=void 0!==e.morphAttributes.position,i=void 0!==e.morphAttributes.normal,r=void 0!==e.morphAttributes.color,n=e.morphAttributes.position||e.morphAttributes.normal||e.morphAttributes.color,s=void 0!==n?n.length:0;let a=Rb.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===i&&(c=2),!0===r&&(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 dr(f,h,d,s);m.type=$e,m.needsUpdate=!0;const g=4*c;for(let v=0;v<s;v++){const b=o[v],y=l[v],x=u[v],S=h*d*4*v;for(let T=0;T<b.count;T++){const M=T*g;!0===t&&(Cb.fromBufferAttribute(b,T),f[S+M+0]=Cb.x,f[S+M+1]=Cb.y,f[S+M+2]=Cb.z,f[S+M+3]=0),!0===i&&(Cb.fromBufferAttribute(y,T),f[S+M+4]=Cb.x,f[S+M+5]=Cb.y,f[S+M+6]=Cb.z,f[S+M+7]=0),!0===r&&(Cb.fromBufferAttribute(x,T),f[S+M+8]=Cb.x,f[S+M+9]=Cb.y,f[S+M+10]=Cb.z,f[S+M+11]=4===x.itemSize?Cb.w:1)}}function _(){m.dispose(),Rb.delete(e),e.removeEventListener("dispose",_)}a={count:s,texture:m,stride:c,size:new Vi(h,d)},Rb.set(e,a),e.addEventListener("dispose",_)}return a}(i);!0===r&&gg.mulAssign(Lb),!0===n&&Cg.mulAssign(Lb),!0===s&&Db.assign(0);const f=wh(p.width);Mm(l,({i:t})=>{const i=Eh(0).toVar();e.count>1&&null!==e.morphTexture&&void 0!==e.morphTexture?i.assign(Kg(e.morphTexture,Nh(wh(t).add(1),wh(Zf))).r):i.assign(c.element(t).toVar()),Th(i.notEqual(0),()=>{if(!0===r&&gg.addAssign(Pb({bufferMap:h,influence:i,stride:d,width:f,depth:t,offset:wh(0)}).xyz),!0===n&&Cg.addAssign(Pb({bufferMap:h,influence:i,stride:d,width:f,depth:t,offset:wh(1)}).xyz),!0===s){const e=Pb({bufferMap:h,influence:i,stride:d,width:f,depth:t,offset:wh(2)});!0===a?Db.addAssign(e):Db.rgb.addAssign(e.rgb)}})}),qv(({object:e})=>{const{influences:t}=u;t&&(t.array=e.morphTargetInfluences,t.update())})},"void");class Fb extends Sc{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}isCacheable(){return!1}}class Ob extends Fb{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class Bb extends Sf{static get type(){return"LightingContextNode"}constructor(e,t=null,i=[],r=null,n=null){super(e),this.lightingModel=t,this.materialLightings=i,this.backdropNode=r,this.backdropAlphaNode=n,this._value=null}getContext(){const{materialLightings:e,backdropNode:t,backdropAlphaNode:i}=this,r={directDiffuse:Dh().toVar("directDiffuse"),directSpecular:Dh().toVar("directSpecular"),indirectDiffuse:Dh().toVar("indirectDiffuse"),indirectSpecular:Dh().toVar("indirectSpecular")};return{radiance:Dh().toVar("radiance"),irradiance:Dh().toVar("irradiance"),iblIrradiance:Dh().toVar("iblIrradiance"),ambientOcclusion:Eh(1).toVar("ambientOcclusion"),reflectedLight:r,materialLightings:e,backdrop:t,backdropAlpha:i}}setup(e){return this.value=this._value||(this._value=this.getContext()),this.value.lightingModel=this.lightingModel||e.context.lightingModel,super.setup(e)}}const kb=mh(Bb);class zb extends Fb{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}class Gb extends Sc{static get type(){return"ClippingNode"}constructor(e=Gb.DEFAULT){super(),this.scope=e}isCacheable(){return!1}setup(e){super.setup(e);const t=e.clippingContext,{intersectionPlanes:i,unionPlanes:r}=t;return this.hardwareClipping=e.hardwareClipping,this.position=!0===e.camera.isArrayCamera?rg.mul(Oh(yg,1)).xyz:yg,this.scope===Gb.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(i,r):this.scope===Gb.HARDWARE?this.setupHardwareClipping(r,e):this.setupDefault(i,r)}setupAlphaToCoverage(e,t){return yh(()=>{const i=Eh().toVar("distanceToPlane"),r=Eh().toVar("distanceToGradient"),n=Eh(1).toVar("clipOpacity"),s=t.length;if(!1===this.hardwareClipping&&s>0){const e=Dm(t).setGroup(Kh);Mm(s,({i:t})=>{const s=e.element(t);i.assign(this.position.dot(s.xyz).negate().add(s.w)),r.assign(i.fwidth().div(2)),n.mulAssign(gf(r.negate(),r,i))})}const a=e.length;if(a>0){const t=Dm(e).setGroup(Kh),s=Eh(1).toVar("intersectionClipOpacity");Mm(a,({i:e})=>{const n=t.element(e);i.assign(this.position.dot(n.xyz).negate().add(n.w)),r.assign(i.fwidth().div(2)),s.mulAssign(gf(r.negate(),r,i).oneMinus())}),n.mulAssign(s.oneMinus())}rd.a.mulAssign(n),rd.a.equal(0).discard()})()}setupDefault(e,t){return yh(()=>{const i=t.length;if(!1===this.hardwareClipping&&i>0){const e=Dm(t).setGroup(Kh);Mm(i,({i:t})=>{const i=e.element(t);this.position.dot(i.xyz).greaterThan(i.w).discard()})}const r=e.length;if(r>0){const t=Dm(e).setGroup(Kh),i=Rh(!0).toVar("clipped");Mm(r,({i:e})=>{const r=t.element(e);i.assign(this.position.dot(r.xyz).greaterThan(r.w).and(i))}),i.discard()}})()}setupHardwareClipping(e,t){const i=e.length;return t.enableHardwareClipping(i),yh(()=>{const r=Dm(e).setGroup(Kh),n=Rm(t.getClipDistance());Mm(i,({i:e})=>{const t=r.element(e),i=this.position.dot(t.xyz).sub(t.w).negate();n.element(e).assign(i)})})()}}Gb.ALPHA_TO_COVERAGE="alphaToCoverage",Gb.DEFAULT="default",Gb.HARDWARE="hardware";const Vb=["alphaMap","alphaTest","anisotropy","anisotropyMap","anisotropyRotation","aoMap","aoMapIntensity","attenuationColor","attenuationDistance","bumpMap","bumpScale","clearcoat","clearcoatMap","clearcoatNormalMap","clearcoatNormalScale","clearcoatRoughness","clearcoatRoughnessMap","color","dashOffset","dashSize","diffuseRoughness","diffuseRoughnessMap","dispersion","displacementBias","displacementMap","displacementScale","emissive","emissiveIntensity","emissiveMap","envMap","envMapIntensity","envMapRotation","gapSize","gradientMap","ior","iridescence","iridescenceIOR","iridescenceMap","iridescenceThicknessMap","iridescenceThicknessMaximum","iridescenceThicknessMinimum","lightMap","lightMapIntensity","linewidth","map","matcap","metalness","metalnessMap","normalMap","normalScale","opacity","reflectivity","refractionRatio","retroreflectivity","rotation","roughness","roughnessMap","scale","sheen","sheenColor","sheenColorMap","sheenRoughness","sheenRoughnessMap","shininess","size","specular","specularColor","specularColorMap","specularIntensity","specularIntensityMap","specularMap","steps","thickness","thicknessMap","transmission","transmissionMap","wireframe"],Hb=new WeakMap,Wb=new WeakMap,jb=new WeakMap,$b=new WeakMap,Xb=new WeakMap;class qb{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=!0===e.object.isSkinnedMesh,this.refreshUniforms=Vb,this.renderId=0}firstInitialization(e){return!1===this.renderObjects.has(e)&&(this.getRenderObjectData(e),!0)}hasDynamicInstancing(e){return!0===e.isInstancedMesh&&(e.instanceMatrix.usage===oi||null!==e.instanceColor&&e.instanceColor.usage===oi)}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:i,object:r}=e;t={geometryId:i.id,geometryVersion:this.getGeometryData(i)._version,materialVersion:this.getMaterialData(e.material)._version,attributesDisposeVersion:e._geometries.attributes.disposeVersion,worldMatrix:r.matrixWorld.clone()},r.center&&(t.center=r.center.clone()),r.morphTargetInfluences&&(t.morphTargetInfluences=r.morphTargetInfluences.slice()),!0===r.isInstancedMesh&&(t.instanceMatrix=r.instanceMatrix,t.instanceMatrixVersion=r.instanceMatrix.version,t.instanceColor=r.instanceColor,t.instanceColorVersion=null!==r.instanceColor?r.instanceColor.version:null,t.morphTextureVersion=null!==r.morphTexture?r.morphTexture.version:null),!0===r.isBatchedMesh&&(t.matricesTextureVersion=r._matricesTexture.version,t.colorsTextureVersion=null!==r._colorsTexture?r._colorsTexture.version:null,t.indirectTextureVersion=r._indirectTexture.version),null!==e.bundle&&(t.version=e.bundle.version),t.outputTarget=this.getOutputTarget(e.renderer),t.outputTargetVersion=this.getOutputTargetData(t.outputTarget,e.context)._version;const{environment:n,environmentIntensity:s,environmentRotation:a}=e.scene;t.environmentIntensity=s,t.environmentRotation=a.clone(),t.environmentVersion=null!==n?this.getTextureData(n)._version:null,t.lights=this.getLightsData(e.lightsNode.getBuiltinLights(),[]),this.renderObjects.set(e,t)}return t}getOutputTarget(e){const t=e.getRenderTarget();return null!==t?t:e.getOutputRenderTarget()||e.getCanvasTarget()}getOutputTargetData(e,t){const{width:i,height:r}=t;let n=Xb.get(e);return void 0===n?(n={_version:0,width:i,height:r},Xb.set(e,n)):n.width===i&&n.height===r||(n.width=i,n.height=r,n._version++),n}getAttributesData(e){const t={};for(const i in e){const r=e[i];t[i]={id:r.isInterleavedBufferAttribute?r.data.uuid:r.id,version:r.isInterleavedBufferAttribute?r.data.version:r.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||e.context.getGI)}getGeometryData(e){let t=jb.get(e);return void 0===t&&(t={_renderId:-1,_version:0,attributes:this.getAttributesData(e.attributes),indexId:e.index?e.index.id:null,indexVersion:e.index?e.index.version:null,drawRange:{start:e.drawRange.start,count:e.drawRange.count}},e.addEventListener("dispose",()=>{t._version++}),jb.set(e,t)),t}getTextureData(e){let t=$b.get(e);if(void 0===t){t={_version:0};const i=()=>{t._version++};null!==e.renderTarget?e.renderTarget.addEventListener("dispose",i):e.addEventListener("dispose",i),$b.set(e,t)}return t}getTextureTransformData(e){return{offset:e.offset.clone(),repeat:e.repeat.clone(),center:e.center.clone(),rotation:e.rotation,matrix:e.matrix.clone()}}equalsTextureTransform(e,t){return!0===t.matrixAutoUpdate?e.rotation===t.rotation&&e.offset.equals(t.offset)&&e.repeat.equals(t.repeat)&&e.center.equals(t.center):e.matrix.equals(t.matrix)}getMaterialData(e){let t=Wb.get(e);if(void 0===t){t={_renderId:-1,_version:0};for(const i of this.refreshUniforms){const r=e[i];void 0!==r&&(null===r?t[i]=null:"object"==typeof r&&void 0!==r.clone?!0===r.isTexture?t[i]={id:r.id,version:0,cacheVersion:this.getTextureData(r)._version,transform:this.getTextureTransformData(r)}:t[i]=r.clone():t[i]=r)}Wb.set(e,t)}return t}equals(e,t,i){const{object:r,material:n,geometry:s}=e,a=this.getRenderObjectData(e);if(!0!==a.worldMatrix.equals(r.matrixWorld))return a.worldMatrix.copy(r.matrixWorld),!1;const o=this.getMaterialData(e.material);if(o._renderId!==i){o._renderId=i;let e=!1;for(const t in o){const i=o[t],r=n[t];if("_renderId"!==t&&"_version"!==t)if(null===i||null==r)i!==(void 0===r?null:r)&&(null==r?o[t]=null:!0===r.isTexture?o[t]={id:r.id,version:r.version,cacheVersion:this.getTextureData(r)._version,transform:this.getTextureTransformData(r)}:"object"==typeof r&&void 0!==r.clone?o[t]=r.clone():o[t]=r,e=!0);else if(void 0!==i.equals)!1===i.equals(r)&&(i.copy(r),e=!0);else if(!0===r.isTexture){const t=this.getTextureData(r);i.id===r.id&&i.version===r.version&&i.cacheVersion===t._version&&!1!==this.equalsTextureTransform(i.transform,r)||(i.id=r.id,i.version=r.version,i.cacheVersion=t._version,i.transform.offset.copy(r.offset),i.transform.repeat.copy(r.repeat),i.transform.center.copy(r.center),i.transform.rotation=r.rotation,i.transform.matrix.copy(r.matrix),e=!0)}else i!==r&&(o[t]=r,e=!0)}!0===e&&o._version++}if(a.materialVersion!==o._version)return a.materialVersion=o._version,!1;const l=this.getOutputTargetData(a.outputTarget,e.context);if(a.outputTargetVersion!==l._version)return a.outputTargetVersion=l._version,!1;if(a.geometryId!==s.id)return a.geometryId=s.id,a.geometryVersion=this.getGeometryData(s)._version,!1;const u=this.getGeometryData(e.geometry);if(u._renderId!==i){u._renderId=i;let e=!1;const t=s.attributes,r=u.attributes;let n=0,a=0;for(const e in t)n++;for(const i in r){a++;const n=r[i],s=t[i];if(void 0===s){delete r[i],e=!0;continue}const o=s.isInterleavedBufferAttribute?s.data.uuid:s.id,l=s.isInterleavedBufferAttribute?s.data.version:s.version;n.id===o&&n.version===l||(n.id=o,n.version=l,e=!0)}a!==n&&(u.attributes=this.getAttributesData(t),e=!0);const o=s.index,l=o?o.id:null,c=o?o.version:null;u.indexId===l&&u.indexVersion===c||(u.indexId=l,u.indexVersion=c,e=!0),u.drawRange.start===s.drawRange.start&&u.drawRange.count===s.drawRange.count||(u.drawRange.start=s.drawRange.start,u.drawRange.count=s.drawRange.count,e=!0),!0===e&&u._version++}if(a.geometryVersion!==u._version)return a.geometryVersion=u._version,!1;if(a.morphTargetInfluences){let e=!1;for(let t=0;t<a.morphTargetInfluences.length;t++)a.morphTargetInfluences[t]!==r.morphTargetInfluences[t]&&(a.morphTargetInfluences[t]=r.morphTargetInfluences[t],e=!0);if(e)return!1}if(!0===r.isInstancedMesh){const e=null!==r.instanceColor?r.instanceColor.version:null,t=null!==r.morphTexture?r.morphTexture.version:null;if(a.instanceMatrix!==r.instanceMatrix||a.instanceMatrixVersion!==r.instanceMatrix.version||a.instanceColor!==r.instanceColor||a.instanceColorVersion!==e||a.morphTextureVersion!==t)return a.instanceMatrix=r.instanceMatrix,a.instanceMatrixVersion=r.instanceMatrix.version,a.instanceColor=r.instanceColor,a.instanceColorVersion=e,a.morphTextureVersion=t,!1}if(!0===r.isBatchedMesh){const e=null!==r._colorsTexture?r._colorsTexture.version:null;if(a.matricesTextureVersion!==r._matricesTexture.version||a.colorsTextureVersion!==e||a.indirectTextureVersion!==r._indirectTexture.version)return a.matricesTextureVersion=r._matricesTexture.version,a.colorsTextureVersion=e,a.indirectTextureVersion=r._indirectTexture.version,!1}if(a.lights)for(let e=0;e<t.length;e++){const i=a.lights[e],r=t[e];if(i.map!==r.map||i.cacheVersion!==r.cacheVersion||i.shadowMapWidth!==r.shadowMapWidth||i.shadowMapHeight!==r.shadowMapHeight)return i.map=r.map,i.cacheVersion=r.cacheVersion,i.shadowMapWidth=r.shadowMapWidth,i.shadowMapHeight=r.shadowMapHeight,!1}const c=e.scene;if(null!==c.environment&&null===n.envMap){const e=this.getTextureData(c.environment)._version;if(a.environmentIntensity!==c.environmentIntensity||!1===a.environmentRotation.equals(c.environmentRotation)||a.environmentVersion!==e)return a.environmentIntensity=c.environmentIntensity,a.environmentRotation.copy(c.environmentRotation),a.environmentVersion=e,!1}return a.center&&!1===a.center.equals(r.center)?(a.center.copy(r.center),!1):(null!==e.bundle&&(a.version=e.bundle.version),!0)}getLightsData(e,t){t.length=0;for(const i of e){let e=null;!0===i.isSpotLight&&null!==i.map&&(e={map:i.map.version,cacheVersion:this.getTextureData(i.map)._version}),!0===i.castShadow&&void 0!==i.shadow&&(null===e&&(e={}),e.shadowMapWidth=i.shadow.mapSize.width,e.shadowMapHeight=i.shadow.mapSize.height),null!==e&&t.push(e)}return t}getLights(e,t){let i=Hb.get(e);return void 0===i&&(i={renderId:-1,lightsData:[]},Hb.set(e,i)),i.renderId===t||(i.renderId=t,this.getLightsData(e.getBuiltinLights(),i.lightsData)),i.lightsData}hasDisposedAttributes(e,t){const i=e._geometries.attributes;for(const t of e.getVertexBuffers())if(!1===i.has(t))return!0;const r=e.getIndex();return null!==r&&!1===i.has(r)||(t.attributesDisposeVersion=i.disposeVersion,!1)}needsRefresh(e,t){if(this.hasNode||this.hasAnimation||this.hasDynamicInstancing(e.object)||this.firstInitialization(e)||this.needsVelocity(t.renderer))return gi;const{renderId:i}=t;let r=fi;this.renderId!==i&&(this.renderId=i,r=mi);const n=this.getRenderObjectData(e),s=this.getOutputTarget(t.renderer);n.outputTarget!==s&&(n.outputTarget=s,r=gi);const a=e._geometries.attributes;n.attributesDisposeVersion!==a.disposeVersion&&this.hasDisposedAttributes(e,n)&&(r=gi);const o=!0===e.object.static,l=null!==e.bundle&&!0===e.bundle.static&&n.version===e.bundle.version;if(o||l)return r;const u=this.getLights(e.lightsNode,i);return!1===this.equals(e,u,i)&&(r=gi),r}}const Yb=yh(([e])=>wp(zd(1e4,Ap(zd(17,e.x).add(zd(.1,e.y)))).mul(Bd(.1,kp(Ap(zd(13,e.y).add(e.x)))))),{value:"vec2",return:"float"}),Kb=yh(([e])=>Yb(Ch(Yb(e.xy),e.z)),{value:"vec3",return:"float"}),Zb=yh(([e])=>{const t=ef(Gp(Wp(e.xyz)),Gp(jp(e.xyz))),i=Eh(1).div(Eh(.05).mul(t)).toVar("pixScale"),r=Ch(vp(Tp(yp(i))),vp(Mp(yp(i)))),n=Ch(Kb(Tp(r.x.mul(e.xyz))),Kb(Tp(r.y.mul(e.xyz)))),s=wp(yp(i)),a=Bd(zd(s.oneMinus(),n.x),zd(s,n.y)),o=Jp(s,s.oneMinus()),l=Dh(a.mul(a).div(zd(2,o).mul(kd(1,o))),a.sub(zd(.5,o)).div(kd(1,o)),kd(1,kd(1,a).mul(kd(1,a)).div(zd(2,o).mul(kd(1,o))))),u=a.lessThan(o.oneMinus()).select(a.lessThan(o).select(l.x,l.y),l.z);return pf(u,1e-6,1)},{position:"vec3",return:"float"});class Qb extends fm{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 i;return i=!0===e.hasGeometryAttribute(t)?super.generate(e):e.generateConst(this.nodeType,new ur(1,1,1,1)),i}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}class Jb extends os{static get type(){return"NodeMaterial"}get type(){return this.constructor.type}set type(e){}constructor(){super(),this.isNodeMaterial=!0,this.fog=!0,this.lights=!1,this.lightsNode=null,this.envNode=null,this.aoNode=null,this.colorNode=null,this.normalNode=null,this.opacityNode=null,this.backdropNode=null,this.backdropAlphaNode=null,this.alphaTestNode=null,this.maskNode=null,this.maskShadowNode=null,this.positionNode=null,this.geometryNode=null,this.depthNode=null,this.receivedShadowPositionNode=null,this.castShadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null,this.contextNode=null}_getNodeChildren(){const e=[];for(const t of Object.getOwnPropertyNames(this)){if(!0===t.startsWith("_"))continue;const i=this[t];i&&!0===i.isNode&&e.push({property:t,childNode:i})}return e}customProgramCacheKey(){const e=[];for(const{property:t,childNode:i}of this._getNodeChildren())e.push(cc(t.slice(0,-4)),i.getCacheKey(!0));return this.type+hc(e)}build(e){this.setup(e)}setupObserver(e){return new qb(e)}setup(e){e.context.setupNormal=()=>Rf(this.setupNormal(e),"NORMAL","vec3"),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);const t=e.renderer,i=t.getRenderTarget();e.addStack();const r=this.setupVertex(e),n=Rf(this.vertexNode||r,"VERTEX");let s;e.context.clipSpace=n,e.stack.outputNode=n,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!==i?!0===i.depthBuffer&&this.setupDepth(e):!0===t.depth&&this.setupDepth(e)),null===this.fragmentNode){this.setupDiffuseColor(e),this.setupAmbientOcclusion(e),this.setupVariants(e);const r=this.setupLighting(e);null!==a&&e.stack.addToStack(a);const n=Oh(r,rd.a).max(0);s=this.setupOutput(e,n),Md.assign(s);const o=null!==this.outputNode;if(o&&(s=this.outputNode),e.context.getOutput&&(s=e.context.getOutput(s,e)),null!==i){const e=t.getMRT(),i=this.mrtNode;null!==e?(o&&Md.assign(s),s=e,null!==i&&(s=e.merge(i))):null!==i&&(s=i)}}else{let t=this.fragmentNode;!0!==t.isOutputStructNode&&(t=t.convert(e.getOutputType())),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:i}=e.clippingContext;let r=null;if(t.length>0||i.length>0){const t=e.renderer.currentSamples;this.alphaToCoverage&&t>1?r=new Gb(Gb.ALPHA_TO_COVERAGE):e.stack.addToStack(new Gb)}return r}setupHardwareClipping(e){if(e.hardwareClipping=!1,null===e.clippingContext)return;const t=e.clippingContext.unionPlanes.length;t>0&&t<=8&&e.isAvailable("clipDistance")&&(e.stack.addToStack(new Gb(Gb.HARDWARE)),e.hardwareClipping=!0)}setupDepth(e){const{renderer:t,camera:i}=e;let r=this.depthNode;if(null===r){const e=t.getMRT();e&&e.has("depth")?r=e.get("depth"):!0===t.logarithmicDepthBuffer&&(r=!0!==i.isOrthographicCamera?c_(yg.z,Qm,Jm):a_(yg.z,Qm,Jm))}null!==r&&d_.assign(r).toStack()}setupPositionView(){return cg.mul(gg).xyz}setupModelViewProjection(){return eg.mul(yg)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.position=e.removeStack(),jv}setupPosition(e){const{object:t,geometry:i}=e;if((i.morphAttributes.position||i.morphAttributes.normal||i.morphAttributes.color)&&Ib(t),!0===t.isSkinnedMesh&&Ab(t),this.displacementMap){const e=N_("displacementMap","texture"),t=N_("displacementScale","float"),i=N_("displacementBias","float");gg.addAssign(Cg.normalize().mul(e.x.mul(t).add(i)))}return t.isBatchedMesh&&Sb(t),t.isInstancedMesh&&t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&mb(t),null!==this.positionNode&&gg.assign(Rf(this.positionNode,"POSITION","vec3")),gg}setupDiffuseColor(e){const{object:t,geometry:i}=e;null!==this.maskNode&&Rh(this.maskNode).not().discard();let r=this.colorNode?Oh(this.colorNode):av,n=null;!0===this.vertexColors&&i.hasAttribute("color")&&(n=((e=0)=>new Qb(e))()),t.instanceColor&&(n=null!==n?n.mul(pb):pb),t.isBatchedMesh&&t._colorsTexture&&(n=null!==n?n.mul(yb):yb),!0===this.vertexColors&&void 0!==i.morphAttributes.color&&(n=Ub(Oh(null!==n?n:1))),null!==n&&(r=r.mul(n)),rd.assign(r);const s=this.opacityNode?Eh(this.opacityNode):uv;rd.a.assign(rd.a.mul(s));let a=null;(null!==this.alphaTestNode||this.alphaTest>0)&&(a=null!==this.alphaTestNode?Eh(this.alphaTestNode):sv,!0===this.alphaToCoverage?(rd.a=gf(a,a.add(Yp(rd.a)),rd.a),rd.a.lessThanEqual(0).discard()):rd.a.lessThanEqual(a).discard()),!0===this.alphaHash&&rd.a.lessThan(Zb(gg)).discard(),e.isOpaque()&&rd.a.assign(1)}setupVariants(){}setupOutgoingLight(){return!0===this.lights?Dh(0):rd.rgb}setupNormal(){return this.normalNode?Dh(this.normalNode):vv}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?N_("envMap","cubeTexture"):N_("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new zb(Vv)),t}setupMaterialLightings(e){const t=[],i=this.setupEnvironment(e);i&&i.isLightingNode&&t.push(i);const r=this.setupLightMap(e);if(r&&r.isLightingNode&&t.push(r),e.context.ambientOcclusion&&t.push(new Ob(e.context.ambientOcclusion)),e.context.getGI){const i=e.context.getGI(null,e);null!==i&&t.push(new zb(i))}return t}setupAmbientOcclusion(e){let t=this.aoNode;null===t&&e.material.aoMap&&(t=Hv),e.context.getAO&&(t=e.context.getAO(t,e)),null!==t&&(Ud.assign(t),e.context.ambientOcclusion=Ud)}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:i,backdropAlphaNode:r,emissiveNode:n}=this,s=!0===this.lights&&e.renderer.lighting.enabled,a=s||null!==this.lightsNode,o=s?this.setupMaterialLightings(e):[],l=a?this.lightsNode||e.lightsNode:null;let u=this.setupOutgoingLight(e);if(l&&(o.length>0||l.getScope().hasLights)){const t=this.setupLightingModel(e)||null;u=kb(l,t,o,i,r)}else null!==i&&(u=Dh(null!==r?df(u,i,r):i));return(n&&!0===n.isNode||t.emissive&&!0===t.emissive.isColor)&&(ad.assign(Dh(n||lv)),u=u.add(ad)),u}setupFog(e,t){const i=e.fogNode;return i&&(Md.assign(t),t=Oh(i.toVar())),t}setupPremultipliedAlpha(e,t){return om(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 i=e[t];void 0===this[t]&&(this[t]=i,i&&i.clone&&(this[t]=i.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 i=os.prototype.toJSON.call(this,e);i.inputNodes={};for(const{property:t,childNode:r}of this._getNodeChildren())i.inputNodes[t]=r.toJSON(e).uuid;function r(e){const t=[];for(const i in e){const r=e[i];delete r.metadata,t.push(r)}return t}if(t){const t=r(e.textures),n=r(e.images),s=r(e.nodes);t.length>0&&(i.textures=t),n.length>0&&(i.images=n),s.length>0&&(i.nodes=s)}return i}copy(e){for(let t=Object.getPrototypeOf(this);t!==Object.prototype;t=Object.getPrototypeOf(t)){const i=Object.getOwnPropertyDescriptors(t);for(const t in i)if(void 0!==i[t].set&&void 0!==e[t]){const i=e[t];this[t]&&void 0!==this[t].copy?this[t].copy(i):this[t]=i}}for(const t in this)if(!/^(?:is[A-Z]|_)|^(?:id|uuid|version|type|userData|clippingPlanes)$/.test(t)&&void 0!==this[t]&&void 0!==e[t]){const i=e[t];this[t]&&void 0!==this[t].copy?this[t].copy(i):this[t]=i}return this.clippingPlanes=e.clippingPlanes?e.clippingPlanes.map(e=>e.clone()):null,this.userData=JSON.parse(JSON.stringify(e.userData)),this}}const ey=new ja(-1,1,1,-1,0,1);class ty extends Zn{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new kn([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new kn(t,2))}}const iy=new ty,ry=Oh($h([-1,-1,3]).element(Kf),$h([3,-1,-1]).element(Kf),0,1);class ny extends ws{constructor(e){super(iy,e),this.camera=ey,this.isQuadMesh=!0}async renderAsync(e){Ei('QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await e.init(),e.render(this,ey)}render(e){const t=this.material.vertexNode;this.material.vertexNode=ry,e.render(this,ey),this.material.vertexNode=t}}function sy(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 Yr),t.clearAlpha=e.getClearAlpha(),t.autoClear=e.autoClear,t.autoClearColor=e.autoClearColor,t.autoClearDepth=e.autoClearDepth,t.autoClearStencil=e.autoClearStencil,t.opaque=e.opaque,t.transparent=e.transparent,t.scissorTest=e.getScissorTest(),t}(e,t),e.setMRT(null),e.setRenderObjectFunction(null),e.setClearColor(0,1),e.autoClear=!0,e.autoClearColor=!0,e.autoClearDepth=!0,e.autoClearStencil=!0,e.opaque=!0,e.transparent=!0,t}const ay=yh(([e])=>wp(Eh(52.9829189).mul(wp(af(e,Ch(.06711056,.00583715))))),{position:"vec2",return:"float"}),oy=yh(([e,t,i])=>{const r=Eh(2.399963229728653),n=xp(Eh(e).add(.5).div(Eh(t))),s=Eh(e).mul(r).add(i);return Ch(Cp(s),Ap(s)).mul(n)},{sampleIndex:"int",samplesCount:"int",phi:"float",return:"vec2"}),ly=1/6,uy=e=>{const t=(e=>zd(ly,zd(e,zd(e,e.negate().add(3)).sub(3)).add(1)))(e),i=(e=>zd(ly,zd(e,zd(e,zd(3,e).sub(6))).add(4)))(e),r=(e=>zd(ly,zd(e,zd(e,zd(-3,e).add(3)).add(3)).add(1)))(e),n=(e=>zd(ly,lf(e,3)))(e),s=t.add(i),a=r.add(n);return{g0:s,g1:a,h0:Bd(-1,i.div(s)),h1:Bd(1,n.div(a))}},cy=(e,t,i,r,n,s)=>{const a=Ch(i.x,t.y),o=Ch(t.x,i.y),l=r.y.mul(Bd(r.x.mul(e.sample(t).level(s)),n.x.mul(e.sample(a).level(s)))),u=n.y.mul(Bd(r.x.mul(e.sample(o).level(s)),n.x.mul(e.sample(i).level(s))));return l.add(u)},hy=yh(([e,t])=>{const i=Ch(e.size(wh(t))),r=Ch(e.size(wh(t.add(1)))),n=Oh(i,r),s=Gd(1,n),a=e.uvNode.xyxy.mul(n).add(.5),o=Tp(a),l=wp(a),{g0:u,g1:c,h0:h,h1:d}=uy(l),p=o.add(h).sub(.5).mul(s),f=o.add(d).sub(.5).mul(s),m=cy(e,p.xy,f.xy,u.xy,c.xy,Tp(t)),g=cy(e,p.zw,f.zw,u.zw,c.zw,Mp(t));return wp(t).mix(m,g)}),dy=new fr,py=Jh(0).setGroup(Kh).onRenderUpdate(({scene:e})=>e.backgroundBlurriness),fy=Jh(1).setGroup(Kh).onRenderUpdate(({scene:e})=>e.backgroundIntensity),my=Jh(new fr).setGroup(Kh).onRenderUpdate(({scene:e})=>{const t=e.background;return null!==t&&t.isTexture&&300!==t.mapping||e.backgroundNode&&e.backgroundNode.isNode?dy.makeRotationFromEuler(e.backgroundRotation).transpose():dy.identity(),dy}),gy=yh(([e,t])=>e.mul(t).clamp(),{color:"vec3",exposure:"float",return:"vec3"}),_y=yh(([e,t])=>(e=e.mul(t)).div(e.add(1)).clamp(),{color:"vec3",exposure:"float",return:"vec3"}),vy=yh(([e,t])=>{const i=(e=(e=e.mul(t)).sub(.004).max(0)).mul(e.mul(6.2).add(.5)),r=e.mul(e.mul(6.2).add(1.7)).add(.06);return i.div(r).pow(2.2)},{color:"vec3",exposure:"float",return:"vec3"}),by=yh(([e])=>{const t=e.mul(e.add(.0245786)).sub(90537e-9),i=e.mul(e.mul(.983729).add(.432951)).add(.238081);return t.div(i)},{color:"vec3",return:"vec3"}),yy=yh(([e,t])=>{const i=Vh(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),r=Vh(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=i.mul(e),e=by(e),(e=r.mul(e)).clamp()},{color:"vec3",exposure:"float",return:"vec3"}),xy=Vh(Dh(1.6605,-.1246,-.0182),Dh(-.5876,1.1329,-.1006),Dh(-.0728,-.0083,1.1187)),Sy=Vh(Dh(.6274,.0691,.0164),Dh(.3293,.9195,.088),Dh(.0433,.0113,.8956)),Ty=yh(([e])=>{const t=Dh(e).toVar(),i=Dh(t.mul(t)).toVar(),r=Dh(i.mul(i)).toVar();return Eh(15.5).mul(r.mul(i)).sub(zd(40.14,r.mul(t))).add(zd(31.96,r).sub(zd(6.868,i.mul(t))).add(zd(.4298,i).add(zd(.1191,t).sub(.00232))))},{x:"vec3",return:"vec3"}),My=yh(([e,t])=>{const i=Dh(e).toVar(),r=Vh(Dh(.856627153315983,.137318972929847,.11189821299995),Dh(.0951212405381588,.761241990602591,.0767994186031903),Dh(.0482516061458583,.101439036467562,.811302368396859)),n=Vh(Dh(1.1271005818144368,-.1413297634984383,-.14132976349843826),Dh(-.11060664309660323,1.157823702216272,-.11060664309660294),Dh(-.016493938717834573,-.016493938717834257,1.2519364065950405)),s=Eh(-12.47393),a=Eh(4.026069);return i.mulAssign(t),i.assign(Sy.mul(i)),i.assign(r.mul(i)),i.assign(ef(i,1e-10)),i.assign(yp(i)),i.assign(i.sub(s).div(a.sub(s))),i.assign(pf(i,0,1)),i.assign(Ty(i)),i.assign(n.mul(i)),i.assign(lf(ef(Dh(0),i),Dh(2.2))),i.assign(xy.mul(i)),i.assign(pf(i,0,1)),i},{color:"vec3",exposure:"float",return:"vec3"}),Ey=yh(([e,t])=>{const i=Eh(.76),r=Eh(.15);e=e.mul(t);const n=Jp(e.r,Jp(e.g,e.b)),s=xf(n.lessThan(.08),n.sub(zd(6.25,n.mul(n))),.04);e.subAssign(s);const a=ef(e.r,ef(e.g,e.b));Th(a.lessThan(i),()=>e);const o=kd(1,i),l=kd(1,o.mul(o).div(a.add(o.sub(i))));e.mulAssign(l.div(a));const u=kd(1,Gd(1,r.mul(a.sub(l)).add(1)));return df(e,Dh(l),u)},{color:"vec3",exposure:"float",return:"vec3"});class wy extends Sc{static get type(){return"CodeNode"}constructor(e="",t=[],i=""){super("code"),this.isCodeNode=!0,this.global=!0,this.code=e,this.includes=t,this.language=i}isCacheable(){return!1}setIncludes(e){return this.includes=e,this}getIncludes(){return this.includes}generate(e){const t=this.getIncludes(e);for(const i of t)i.build(e,"void");const i=e.getCodeFromNode(this,this.getNodeType(e));return i.code=this.code,i.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 Ay extends wy{static get type(){return"FunctionNode"}constructor(e="",t=[],i=""){super(e,t,i)}generateNodeType(e){return this.getNodeFunction(e).type}getMemberType(e,t){const i=this.getNodeType(e);return e.getStructTypeNode(i).getMemberType(e,t)}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){const t=e.getDataFromNode(this);let i=t.nodeFunction;return void 0===i&&(i=e.parser.parseFunction(this.code),t.nodeFunction=i),i}generate(e,t){const i=this.getNodeFunction(e),r=e.getDataFromNode(this),n=i.type;let s=r.functionPropertyName;if(void 0===s){super.generate(e);const t=i.name,a=e.getCodeFromNode(this,n);""!==t&&(a.name=t,e.registerDeclaration(a)),s=e.getPropertyName(a),a.code=i.getCode(s)+"\n",r.functionPropertyName=s}return"property"===t?s:e.format(`${s}()`,n,t)}}function Ry(e){let t;const i=e.context.getViewZ;return void 0!==i&&(t=i(this)),(t||yg.z).negate()}const Cy=yh(([e,t],i)=>{const r=Ry(i);return gf(e,t,r)}),Ny=yh(([e],t)=>{const i=Ry(t);return e.mul(e,i,i).negate().exp().oneMinus()}),Py=yh(([e,t])=>Oh(t.toFloat().mix(Md.rgb,e.toVec3()),Md.a));let Ly;function Dy(e){Ly=Ly||new WeakMap;let t=Ly.get(e);return void 0===t&&Ly.set(e,t={}),t}function Uy(e){const t=Dy(e);return t.shadowMatrix||(t.shadowMatrix=Jh("mat4").setGroup(Kh).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 Iy(e){const t=Dy(e);return t.position||(t.position=Jh(new Wi).setGroup(Kh).onRenderUpdate((t,i)=>i.value.setFromMatrixPosition(e.matrixWorld)))}function Fy(e){const t=Dy(e);return t.viewPosition||(t.viewPosition=yh(({camera:i})=>i.isArrayCamera&&i.cameras.length>0?ig.mul(Oh(Iy(e),1)).xyz:t.viewPositionUniform||(t.viewPositionUniform=Jh(new Wi).setGroup(Kh).onRenderUpdate(({camera:t},i)=>{i.value=i.value||new Wi,i.value.setFromMatrixPosition(e.matrixWorld),i.value.applyMatrix4(t.matrixWorldInverse)}))).once()())}const Oy=e=>ig.transformDirection(Iy(e).sub(function(e){const t=Dy(e);return t.targetPosition||(t.targetPosition=Jh(new Wi).setGroup(Kh).onRenderUpdate((t,i)=>i.value.setFromMatrixPosition(e.target.matrixWorld)))}(e))),By=td("vec3","totalDiffuse"),ky=td("vec3","totalSpecular"),zy=td("vec3","outgoingLight"),Gy=(e,t)=>{for(const i of t)if(i.isAnalyticLightNode&&i.light.id===e)return i;return null},Vy=new WeakMap,Hy=[];class Wy extends Sc{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=By,this.totalSpecularNode=ky,this.outgoingLightNode=zy,this._lights=[],this.global=!0}isCacheable(){return!1}customCacheKey(){const e=this.getBuiltinLights();for(let t=0;t<e.length;t++){const i=e[t];if(Hy.push(i.id),Hy.push(i.castShadow?1:0),!0===i.castShadow){const e=Vy.get(i),t=e?e.version:0;Hy.push(t)}if(!0===i.isSpotLight){const e=null!==i.map?i.map.id:-1,t=i.colorNode?i.colorNode.getCacheKey():-1;Hy.push(e,t)}}const t=hc(Hy);return Hy.length=0,t}getHash(e){const t=e.getDataFromNode(this);if(void 0===t.lightNodesHash){const i=this.setupLightsNode(e);t.lightNodes=i;const r=[];for(const e of i)r.push(e.getHash());t.lightNodesHash="lights-"+r.join(",")}return t.lightNodesHash}setupLightsNode(e){const t=[],i=e.getDataFromNode(this).lightNodes||null,r=(e=>e.sort((e,t)=>e.id-t.id))([...e.context.materialLightings,...this.getBuiltinLights()]);for(const e of r)if(e.isNode)t.push(e);else{let r=null;if(null!==i&&(r=Gy(e.id,i)),null===r){const t=e._lightNode;if(void 0===t){Ti(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}!1===Vy.has(e)&&Vy.set(e,new t(e)),r=Vy.get(e)}t.push(r)}return t}setupDirectLight(e,t,i){const{lightingModel:r,reflectedLight:n}=e.context;r.direct({...i,lightNode:t,reflectedLight:n},e)}setupDirectRectAreaLight(e,t,i){const{lightingModel:r,reflectedLight:n}=e.context;r.directRectArea({...i,lightNode:t,reflectedLight:n},e)}setupLights(e,t){for(const i of t)i.build(e);void 0!==e.context.lightProbeIrradiance&&e.context.irradiance.addAssign(e.context.lightProbeIrradiance)}getLightNodes(e){const t=e.getDataFromNode(this);return void 0===t.lightNodes&&(t.lightNodes=this.setupLightsNode(e)),t.lightNodes}setup(e){const t=e.lightsNode;e.lightsNode=this;let i=this.outgoingLightNode;const r=e.context,n=r.lightingModel;if(n){const{totalDiffuseNode:t,totalSpecularNode:s}=this;r.outgoingLight=i,e.addStack(),n.start(e);const{backdrop:a,backdropAlpha:o}=r,{directDiffuse:l,directSpecular:u,indirectDiffuse:c,indirectSpecular:h}=r.reflectedLight;let d=l.add(c);null!==a&&(d=Dh(null!==o?o.mix(d,a):a)),t.assign(d),s.assign(u.add(h)),i.assign(t.add(s)),n.finish(e),i=i.bypass(e.removeStack())}return e.lightsNode=t,i}setLights(e){return this._lights=e,this}getLights(){return this._lights}getBuiltinLights(){return this._lights}get hasLights(){return this._lights.length>0}}class jy{constructor(){this.weakMaps={}}_getWeakMap(e){const t=e.length;let i=this.weakMaps[t];return void 0===i&&(i=new WeakMap,this.weakMaps[t]=i),i}get(e){let t=this._getWeakMap(e);for(let i=0;i<e.length-1;i++)if(t=t.get(e[i]),void 0===t)return;return t.get(e[e.length-1])}set(e,t){let i=this._getWeakMap(e);for(let t=0;t<e.length-1;t++){const r=e[t];!1===i.has(r)&&i.set(r,new WeakMap),i=i.get(r)}return i.set(e[e.length-1],t),this}delete(e){let t=this._getWeakMap(e);for(let i=0;i<e.length-1;i++)if(t=t.get(e[i]),void 0===t)return!1;return t.delete(e[e.length-1])}}const $y=new WeakMap,Xy=new jy,qy=[];class Yy extends Sc{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=Ju,this.isShadowBaseNode=!0}isCacheable(){return!1}getShadowMaterial(){return(e=>{let t=$y.get(e);return void 0===t&&(t=new Jb,t.colorNode=Oh(0,0,0,1),t.isShadowPassMaterial=!0,t.name="ShadowMaterial",t.blending=0,t.fog=!1,$y.set(e,t)),t})(this.light)}disposeShadowMaterial(){(e=>{const t=$y.get(e);void 0!==t&&(t.dispose(),$y.delete(e))})(this.light)}getShadowRenderObjectFunction(e,t=this.light.shadow){return((e,t,i)=>{qy[0]=e,qy[1]=t;let r=Xy.get(qy);return void 0!==r&&r.shadowType===i||(r=(r,n,s,a,o,l,u,c,h)=>{(!0===r.castShadow||r.receiveShadow&&3===i)&&(r.onBeforeShadow(e,r,s,t.camera,a,n.overrideMaterial,l),e.renderObject(r,n,s,a,o,l,u,c,h),r.onAfterShadow(e,r,s,t.camera,a,n.overrideMaterial,l))},r.shadowType=i,Xy.set(qy,r)),qy[0]=null,qy[1]=null,r})(e,t,e.shadowMap.type)}setupShadowPosition({context:e,material:t}){Ky.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||vg)}}const Ky=td("vec3","shadowPositionWorld"),Zy=new WeakMap;const Qy=yh(({depthTexture:e,shadowCoord:t,depthLayer:i})=>{let r=Yg(e,t.xy).setName("t_basic");return e.isArrayTexture&&(r=r.depth(i)),r.compare(t.z)}),Jy=yh(({depthTexture:e,shadowCoord:t,shadow:i,depthLayer:r})=>{const n=(t,i)=>{let n=Yg(e,t);return e.isArrayTexture&&(n=n.depth(r)),n.compare(i)},{mapSize:s,radius:a}=function(e){let t=Zy.get(e);return void 0===t&&(t={mapSize:A_("mapSize","vec2",e).setGroup(Kh),radius:A_("radius","float",e).setGroup(Kh)},Zy.set(e,t)),t}(i),o=Ch(1).div(s),l=a.mul(o),u=ay(zm.xy).mul(6.28318530718);return Bd(n(t.xy.add(oy(0,5,u).mul(l)),t.z),n(t.xy.add(oy(1,5,u).mul(l)),t.z),n(t.xy.add(oy(2,5,u).mul(l)),t.z),n(t.xy.add(oy(3,5,u).mul(l)),t.z),n(t.xy.add(oy(4,5,u).mul(l)),t.z)).mul(.2)}),ex=yh(({depthTexture:e,shadowCoord:t,depthLayer:i},r)=>{let n=Yg(e).sample(t.xy);e.isArrayTexture&&(n=n.depth(i)),n=n.rg;const s=n.x,a=ef(1e-7,n.y.mul(n.y)),o=r.renderer.reversedDepthBuffer?tf(s,t.z):tf(t.z,s),l=Eh(1).toVar();return Th(o.notEqual(1),()=>{const e=t.z.sub(s);let i=a.div(a.add(e.mul(e)));i=pf(kd(i,.3).div(.65)),l.assign(ef(o,i))}),l}),tx=yh(({samples:e,radius:t,size:i,shadowPass:r,depthLayer:n})=>{const s=Eh(0).toVar("meanVertical"),a=Eh(0).toVar("squareMeanVertical"),o=e.lessThanEqual(Eh(1)).select(Eh(0),Eh(2).div(e.sub(1))),l=e.lessThanEqual(Eh(1)).select(Eh(0),Eh(-1));Mm({start:wh(0),end:wh(e),type:"int",condition:"<"},({i:e})=>{const u=l.add(Eh(e).mul(o));let c=r.sample(Bd(zm.xy,Ch(0,u).mul(t)).div(i));r.value.isArrayTexture&&(c=c.depth(n)),c=c.x,s.addAssign(c),a.addAssign(c.mul(c))}),s.divAssign(e),a.divAssign(e);const u=xp(a.sub(s.mul(s)).max(0));return Ch(s,u)}),ix=yh(({samples:e,radius:t,size:i,shadowPass:r,depthLayer:n})=>{const s=Eh(0).toVar("meanHorizontal"),a=Eh(0).toVar("squareMeanHorizontal"),o=e.lessThanEqual(Eh(1)).select(Eh(0),Eh(2).div(e.sub(1))),l=e.lessThanEqual(Eh(1)).select(Eh(0),Eh(-1));Mm({start:wh(0),end:wh(e),type:"int",condition:"<"},({i:e})=>{const u=l.add(Eh(e).mul(o));let c=r.sample(Bd(zm.xy,Ch(u,0).mul(t)).div(i));r.value.isArrayTexture&&(c=c.depth(n)),s.addAssign(c.x),a.addAssign(Bd(c.y.mul(c.y),c.x.mul(c.x)))}),s.divAssign(e),a.divAssign(e);const u=xp(a.sub(s.mul(s)).max(0));return Ch(s,u)}),rx=[Qy,Jy,null,ex];let nx;const sx=new ny;class ax extends Yy{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:i,shadowCoord:r,shadow:n,depthLayer:s}){const a=r.x.greaterThanEqual(0).and(r.x.lessThanEqual(1)).and(r.y.greaterThanEqual(0)).and(r.y.lessThanEqual(1)).and(r.z.lessThanEqual(1)),o=t({depthTexture:i,shadowCoord:r,shadow:n,depthLayer:s});return a.select(o,Eh(1))}setupShadowCoord(e,t){const{shadow:i}=this,{renderer:r}=e,n=i.biasNode||A_("bias","float",i).setGroup(Kh);let s,a=t;if(i.camera.isOrthographicCamera||!0!==r.logarithmicDepthBuffer)a=a.xyz.div(a.w),s=a.z;else{const e=a.w;a=a.xy.div(e);const t=A_("near","float",i.camera).setGroup(Kh),r=A_("far","float",i.camera).setGroup(Kh);s=c_(e.negate(),t,r)}return a=Dh(a.x,a.y.oneMinus(),r.reversedDepthBuffer?s.sub(n):s.add(n)),a}getShadowFilterFn(e){return rx[e]}setupRenderTarget(e,t){const i=new Ys(e.mapSize.width,e.mapSize.height);i.name="ShadowDepthTexture",i.compareFunction=t.renderer.reversedDepthBuffer?ni:ti;const r=t.createRenderTarget(e.mapSize.width,e.mapSize.height);return r.texture.name="ShadowMap",r.texture.type=e.mapType,r.depthTexture=i,{shadowMap:r,depthTexture:i}}setupShadow(e){const{renderer:t,camera:i}=e,{light:r,shadow:n}=this,{depthTexture:s,shadowMap:a}=this.setupRenderTarget(n,e),o=t.shadowMap.type,l=t.hasCompatibility(pi);if(1===o&&l?(s.minFilter=Oe,s.magFilter=Oe):(s.minFilter=Ue,s.magFilter=Ue),n.camera.coordinateSystem=i.coordinateSystem,n.camera._reversedDepth=t.reversedDepthBuffer,n.camera.updateProjectionMatrix(),3===o&&!0!==n.isPointLightShadow){s.compareFunction=null,a.depth>1?(a._vsmShadowMapVertical||(a._vsmShadowMapVertical=e.createRenderTarget(n.mapSize.width,n.mapSize.height,{format:at,type:Xe,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapVertical.texture.name="VSMVertical"),this.vsmShadowMapVertical=a._vsmShadowMapVertical,a._vsmShadowMapHorizontal||(a._vsmShadowMapHorizontal=e.createRenderTarget(n.mapSize.width,n.mapSize.height,{format:at,type:Xe,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapHorizontal.texture.name="VSMHorizontal"),this.vsmShadowMapHorizontal=a._vsmShadowMapHorizontal):(this.vsmShadowMapVertical=e.createRenderTarget(n.mapSize.width,n.mapSize.height,{format:at,type:Xe,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(n.mapSize.width,n.mapSize.height,{format:at,type:Xe,depthBuffer:!1}));let t=Yg(s);s.isArrayTexture&&(t=t.depth(this.depthLayer));let i=Yg(this.vsmShadowMapVertical.texture);s.isArrayTexture&&(i=i.depth(this.depthLayer));const r=A_("blurSamples","float",n).setGroup(Kh),o=A_("radius","float",n).setGroup(Kh),l=A_("mapSize","vec2",n).setGroup(Kh),u=Tf(e.getSharedContext());let c=this.vsmMaterialVertical||(this.vsmMaterialVertical=new Jb);c.contextNode=u,c.fragmentNode=tx({samples:r,radius:o,size:l,shadowPass:t,depthLayer:this.depthLayer}),c.name="VSMVertical",c=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new Jb),c.contextNode=u,c.fragmentNode=ix({samples:r,radius:o,size:l,shadowPass:i,depthLayer:this.depthLayer}),c.name="VSMHorizontal"}const u=A_("intensity","float",n).setGroup(Kh),c=A_("normalBias","float",n).setGroup(Kh),h=Uy(r),d=Ug.mul(c);let p;if(!t.highPrecision||e.material.receivedShadowPositionNode||e.context.shadowPositionWorld)p=h.mul(Ky.add(d));else{p=Jh("mat4").onObjectUpdate(({object:e},t)=>t.value.multiplyMatrices(h.value,e.matrixWorld)).mul(gg).add(h.mul(Oh(d,0)))}const f=this.setupShadowCoord(e,p),m=n.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(null===m)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const g=3===o&&!0!==n.isPointLightShadow?this.vsmShadowMapHorizontal.texture:s,_=this.setupShadowFilter(e,{filterFn:m,shadowTexture:a.texture,depthTexture:g,shadowCoord:f,shadow:n,depthLayer:this.depthLayer});let v,b;!0===t.shadowMap.transmitted&&(a.texture.isCubeTexture?v=E_(a.texture,f.xyz):(v=Yg(a.texture,f),s.isArrayTexture&&(v=v.depth(this.depthLayer)))),b=v?df(1,_.rgb.mix(v,1),u.mul(v.a)).toVar():df(1,_,u).toVar(),this.shadowMap=a,this.shadow.map=a,this.shadow.needsUpdate=!0;const y=`${this.light.type} Shadow [ ${this.light.name||"ID: "+this.light.id} ]`;return v&&v.toInspector(`${y} / Color`,()=>this.shadowMap.texture.isCubeTexture?E_(this.shadowMap.texture,Mg()):Yg(this.shadowMap.texture)),b.toInspector(`${y} / Depth`,()=>{const e=A_("near","float",this.shadow.camera),t=A_("far","float",this.shadow.camera);let i,r;return i=this.shadowMap.texture.isCubeTexture?E_(this.shadowMap.depthTexture,Mg()).r:Yg(this.shadowMap.depthTexture).r,r=this.shadow.camera.isPerspectiveCamera?u_(i,e,t):o_(i,e,t),r=a_(r,e,t),r.oneMinus()})}setup(e){if(!1!==e.renderer.shadowMap.enabled)return yh(()=>{const t=e.renderer.shadowMap.type;this._currentShadowType!==t&&(this._reset(),this._node=null);let i=this._node;return this.setupShadowPosition(e),null===i&&(this._node=i=this.setupShadow(e),this._currentShadowType=t),e.material.receivedShadowNode&&(i=e.material.receivedShadowNode(i)),i})()}renderShadow(e){const{shadow:t,shadowMap:i,light:r}=this,{renderer:n,scene:s}=e;t.updateMatrices(r),i.setSize(t.mapSize.width,t.mapSize.height,i.depth);const a=s.name;s.name=`Shadow Map [ ${r.name||"ID: "+r.id} ]`,n.render(s,t.camera),s.name=a}updateShadow(e){const{shadowMap:t,shadow:i}=this,{renderer:r,scene:n,camera:s}=e,a=r.shadowMap.type,o=i.camera.layers.mask;4294967294&i.camera.layers.mask||(i.camera.layers.mask=s.layers.mask);const l=r.getRenderObjectFunction();nx=function(e,t,i){return i=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,i=sy(e,i)),i}(r,n,nx),n.overrideMaterial=this.getShadowMaterial(),r.setRenderObjectFunction(this.getShadowRenderObjectFunction(r,this.shadow||this.light.shadow)),r.setClearColor(0,0),r.setRenderTarget(t);const u=n.matrixWorldAutoUpdate;n.matrixWorldAutoUpdate=!1,this.renderShadow(e),n.matrixWorldAutoUpdate=u,r.setRenderObjectFunction(l),3===a&&!0!==i.isPointLightShadow&&this.vsmPass(r),i.camera.layers.mask=o,function(e,t,i){!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.autoClearColor=t.autoClearColor,e.autoClearDepth=t.autoClearDepth,e.autoClearStencil=t.autoClearStencil,e.opaque=t.opaque,e.transparent=t.transparent,e.setScissorTest(t.scissorTest)}(e,i),function(e,t){e.background=t.background,e.backgroundNode=t.backgroundNode,e.overrideMaterial=t.overrideMaterial}(t,i)}(r,n,nx)}vsmPass(e){const{shadow:t}=this,i=this.shadowMap.depth;this.vsmShadowMapVertical.setSize(t.mapSize.width,t.mapSize.height,i),this.vsmShadowMapHorizontal.setSize(t.mapSize.width,t.mapSize.height,i),e.setRenderTarget(this.vsmShadowMapVertical),sx.material=this.vsmMaterialVertical,sx.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),sx.material=this.vsmMaterialHorizontal,sx.render(e)}dispose(){this._reset(),super.dispose()}_reset(){this._currentShadowType=null,this.disposeShadowMaterial(),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){if(null!==e.renderer._precompilationState)return;const{shadow:t}=this;let i=t.needsUpdate||t.autoUpdate;i&&(this._cameraFrameId.get(e.camera)===e.frameId&&(i=!1),this._cameraFrameId.set(e.camera,e.frameId)),i&&(this.updateShadow(e),t.needsUpdate=!1)}}const ox=new Yr,lx=new fr,ux=new Wi,cx=new Wi,hx=[new Wi(-1,0,0),new Wi(1,0,0),new Wi(0,1,0),new Wi(0,-1,0),new Wi(0,0,1),new Wi(0,0,-1)],dx=[new Wi(0,1,0),new Wi(0,1,0),new Wi(0,0,-1),new Wi(0,0,1),new Wi(0,1,0),new Wi(0,1,0)],px=[new Wi(1,0,0),new Wi(-1,0,0),new Wi(0,1,0),new Wi(0,-1,0),new Wi(0,0,1),new Wi(0,0,-1)],fx=[new Wi(0,-1,0),new Wi(0,-1,0),new Wi(0,0,1),new Wi(0,0,-1),new Wi(0,-1,0),new Wi(0,-1,0)],mx=(e,t,i,r,n)=>{const{reversedDepthBuffer:s,logarithmicDepthBuffer:a}=n;if(!0===a)return n=>c_(n.mul(e).negate(),t,i).add(r);const o=i.sub(t),l=t.mul(i).div(o.mul(e));let u,c;return!0===s?(u=t.div(o).add(r).negate().toConst(),c=l.toConst()):(u=i.div(o).add(r).toConst(),c=l.negate().toConst()),e=>u.add(c.div(e))},gx=yh(({depthTexture:e,bd3D:t,dp:i})=>E_(e,t).compare(i)),_x=yh(({depthTexture:e,bd3D:t,distance:i,shadow:r},n)=>{const s=A_("radius","float",r).setGroup(Kh),a=A_("mapSize","vec2",r).setGroup(Kh),o=A_("near","float",r.camera).setGroup(Kh),l=A_("far","float",r.camera).setGroup(Kh),u=A_("bias","float",r).setGroup(Kh),c=s.div(a.x).toConst(),h=kp(t),d=Ep(of(t,h.x.greaterThan(h.z).select(Dh(0,1,0),Dh(1,0,0)))).toConst(),p=of(t,d).toConst(),f=ay(zm.xy).mul(6.28318530718).toConst(),m=mx(i,o,l,u,n.renderer),g=Eh(0).toVar();return Mm(5,({i:i})=>{const r=oy(i,5,f),n=t.add(d.mul(r.x).add(p.mul(r.y)).mul(c)).toConst(),s=kp(n).toConst(),a=ef(s.x,s.y,s.z).toConst();g.addAssign(E_(e,n).compare(m(a)))}),g.mul(.2)}),vx=yh(({filterFn:e,depthTexture:t,shadowCoord:i,shadow:r},n)=>{const s=i.xyz.toConst(),a=s.abs().toConst(),o=a.x.max(a.y).max(a.z),l=Jh("float").setGroup(Kh).onRenderUpdate(()=>r.camera.near),u=Jh("float").setGroup(Kh).onRenderUpdate(()=>r.camera.far),c=A_("bias","float",r).setGroup(Kh),h=Eh(1).toVar();return Th(o.sub(u).lessThanEqual(0).and(o.sub(l).greaterThanEqual(0)),()=>{const i=s.normalize(),a=s.length(),d=mx(a,l,u,c,n.renderer)(o.div(a));h.assign(e({depthTexture:t,bd3D:i,dp:d,distance:a,shadow:r}))}),h});class bx extends ax{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return 0===e?gx:_x}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,depthTexture:i,shadowCoord:r,shadow:n}){return vx({filterFn:t,depthTexture:i,shadowCoord:r,shadow:n})}setupRenderTarget(e,t){const i=new Ks(e.mapSize.width);i.name="PointShadowDepthTexture",i.compareFunction=t.renderer.reversedDepthBuffer?ni:ti;const r=t.createCubeRenderTarget(e.mapSize.width);return r.texture.name="PointShadowMap",r.depthTexture=i,{shadowMap:r,depthTexture:i}}renderShadow(e){const{shadow:t,shadowMap:i,light:r}=this,{renderer:n,scene:s}=e,a=t.camera,o=t.matrix,l=n.coordinateSystem===ci,u=l?hx:px,c=l?dx:fx;i.setSize(t.mapSize.width,t.mapSize.width);const h=n.autoClear,d=n.getClearColor(ox),p=n.getClearAlpha();n.autoClear=!1,n.setClearColor(t.clearColor,t.clearAlpha);for(let e=0;e<6;e++){n.setRenderTarget(i,e),n.clear();const l=r.distance||a.far;l!==a.far&&(a.far=l,a.updateProjectionMatrix()),ux.setFromMatrixPosition(r.matrixWorld),a.position.copy(ux),cx.copy(a.position),cx.add(u[e]),a.up.copy(c[e]),a.lookAt(cx),a.updateMatrixWorld(),o.makeTranslation(-ux.x,-ux.y,-ux.z),lx.multiplyMatrices(a.projectionMatrix,a.matrixWorldInverse),t._frustum.setFromProjectionMatrix(lx,a.coordinateSystem,a.reversedDepth);const h=s.name;s.name=`Point Light Shadow [ ${r.name||"ID: "+r.id} ] - Face ${e+1}`,n.render(s,a),s.name=h}n.autoClear=h,n.setClearColor(d,p)}}class yx extends Fb{static get type(){return"AnalyticLightNode"}constructor(e=null){super(),this.light=e,this.color=new Yr,this.colorNode=e&&e.colorNode||Jh(this.color).setGroup(Kh),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=Qu,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,this.colorNode=this.baseColorNode,this.baseColorNode=null,this.needsUpdate=!0)}getHash(){return this.light.uuid}getLightVector(e){return Fy(this.light).sub(e.context.positionView||yg)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return((e,t)=>new ax(e,t))(this.light)}setupShadow(e){const{renderer:t}=e;if(!1===t.shadowMap.enabled)return;let i=this.shadowColorNode;if(null===i){const e=this.light.shadow.shadowNode;let t;t=void 0!==e?dh(e):this.setupShadowNode(),this.shadowNode=t,this.shadowColorNode=i=this.colorNode.mul(t),this.baseColorNode=this.colorNode}e.context.getShadow&&(i=e.context.getShadow(this,e)),this.colorNode=i}setup(e){this.colorNode=this.baseColorNode||this.colorNode,this.light.castShadow?e.object.receiveShadow&&this.setupShadow(e):null!==this.shadowNode&&this.disposeShadow();const t=this.setupDirect(e),i=this.setupDirectRectArea(e);t&&e.lightsNode.setupDirectLight(e,this,t),i&&e.lightsNode.setupDirectRectAreaLight(e,this,i)}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}const xx=yh(({lightDistance:e,cutoffDistance:t,decayExponent:i})=>{const r=e.pow(i).max(.01).reciprocal();return t.greaterThan(0).select(r.mul(e.div(t).pow4().oneMinus().clamp().pow2()),r)},{lightDistance:"float",cutoffDistance:"float",decayExponent:"float",return:"float"});class Sx extends yx{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=Jh(0).setGroup(Kh),this.decayExponentNode=Jh(2).setGroup(Kh)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return((e,t)=>new bx(e,t))(this.light)}setupDirect(e){return(({color:e,lightVector:t,cutoffDistance:i,decayExponent:r})=>{const n=t.normalize(),s=t.length(),a=xx({lightDistance:s,cutoffDistance:i,decayExponent:r});return{lightDirection:n,lightColor:e.mul(a)}})({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}const Tx=yh(({SAMPLES:e,sigma:t,direction:i,envMap:r})=>{const n=Dh(i).toVar(),s=xf(kp(n.z).lessThan(.999),Dh(0,0,1),Dh(1,0,0)),a=Ep(of(s,n)).toVar(),o=of(n,a).toVar(),l=Jp(t.mul(3),Math.PI),u=_p(l.mul(l).mul(-.5).div(t.mul(t))).oneMinus().toVar(),c=Dh(0).toVar(),h=Eh(0).toVar();return Mm({start:wh(0),end:e},({i:i})=>{const s=Eh(i).add(.5).div(Eh(e)),l=t.mul(xp(bp(s.mul(u).oneMinus()).mul(-2))).toVar(),d=Eh(i).mul(2.399963229728653).toVar(),p=a.mul(Cp(d)).add(o.mul(Ap(d))),f=n.mul(Cp(l)).add(p.mul(Ap(l))),m=Ap(l).div(l).toVar();c.addAssign(r.sample(f).level(0).rgb.mul(m)),h.addAssign(m)}),Oh(c.div(h),1)}),Mx=yh(([e])=>{const t=Ah(e).toVar();return t.assign(t.shiftLeft(Ah(16)).bitOr(t.shiftRight(Ah(16)))),t.assign(t.bitAnd(Ah(1431655765)).shiftLeft(Ah(1)).bitOr(t.bitAnd(Ah(2863311530)).shiftRight(Ah(1)))),t.assign(t.bitAnd(Ah(858993459)).shiftLeft(Ah(2)).bitOr(t.bitAnd(Ah(3435973836)).shiftRight(Ah(2)))),t.assign(t.bitAnd(Ah(252645135)).shiftLeft(Ah(4)).bitOr(t.bitAnd(Ah(4042322160)).shiftRight(Ah(4)))),t.assign(t.bitAnd(Ah(16711935)).shiftLeft(Ah(8)).bitOr(t.bitAnd(Ah(4278255360)).shiftRight(Ah(8)))),Eh(t).mul(2.3283064365386963e-10)}),Ex=yh(([e,t])=>Ch(Eh(e).div(Eh(t)),Mx(e))),wx=yh(({roughness:e,lodBias:t,envMap:i,direction:r,GGX_SAMPLES:n})=>{const s=Dh(r).toVar(),a=Dh(0).toVar();return Th(e.lessThan(.001),()=>{a.assign(i.sample(s).level(0).rgb)}).Else(()=>{const r=e.mul(e).toConst(),o=r.mul(r).toConst(),l=xf(kp(s.z).lessThan(.999),Dh(0,0,1),Dh(1,0,0)),u=Ep(of(l,s)).toVar(),c=of(s,u).toVar(),h=Eh(0).toVar();Mm({start:Ah(0),end:n},({i:e})=>{const l=Ex(e,n),d=Eh(1).div(l.x.oneMinus().add(o.mul(l.x))).toConst(),p=l.x.oneMinus().sub(o.mul(l.x)).mul(d).toConst();Th(p.greaterThan(0),()=>{const e=l.y.mul(2*Math.PI).toConst(),n=r.mul(2).mul(xp(l.x.mul(l.x.oneMinus()))).mul(d).toConst(),f=s.mul(p).add(u.mul(Cp(e)).add(c.mul(Ap(e))).mul(n)).toConst(),m=o.mul(d),g=ef(yp(m).add(t),0);a.addAssign(i.sample(f).level(g).rgb.mul(p)),h.addAssign(p)})}),a.divAssign(h)}),Oh(a,1)}),Ax=yh(({roughness:e,sourceLod:t,sourceSize:i,envMap:r,direction:n})=>{const s=Dh(n).toVar(),a=e.mul(e).toConst(),o=a.mul(a).toConst(),l=Eh(2).div(Eh(i)).toConst(),u=Dh(0).toVar(),c=Eh(0).toVar();return Mm({start:wh(0),end:wh(3),name:"face"},({face:e})=>{Mm({start:wh(0),end:i,name:"y"},({y:n})=>{Mm({start:wh(0),end:i,name:"x"},({x:i})=>{const a=Ch(i,n).add(.5).mul(l).sub(1).toConst(),h=xf(e.equal(0),Dh(1,a),xf(e.equal(1),Dh(a.x,1,a.y),Dh(a,1))).toVar(),d=Sp(af(a,a).add(1)).toConst(),p=af(s,h).toVar();h.mulAssign(xf(p.lessThan(0),-1,1)),p.assign(kp(p).mul(d));const f=o.add(1).add(o.sub(1).mul(p)),m=p.mul(d).mul(d).mul(d).div(f.mul(f)).toConst();u.addAssign(r.sample(h).level(t).rgb.mul(m)),c.addAssign(m)})})}),Oh(u.div(c),1)});class Rx extends cr{constructor(e=1,t={}){super(e,e,t),this.isCubeRenderTarget=!0;const i={width:e,height:e,depth:1},r=[i,i,i,i,i,i];this.texture=new Xs(r),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){const i=t.minFilter,r=t.generateMipmaps;t.generateMipmaps=!0,this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const n=new Qs(5,5,5),s=Tg(bg),a=new Jb;a.colorNode=Yg(t,s,0),a.side=1,a.blending=0;const o=new ws(n,a),l=new Zr;l.add(o),t.minFilter===ke&&(t.minFilter=Oe);const u=new Ja(1,10,this),c=e.getMRT();return e.setMRT(null),u.update(e,l),e.setMRT(c),t.minFilter=i,t.generateMipmaps=r,o.geometry.dispose(),o.material.dispose(),this}clear(e,t=!0,i=!0,r=!0){const n=e.getRenderTarget();for(let n=0;n<6;n++)e.setRenderTarget(this,n),e.clear(t,i,r);e.setRenderTarget(n)}}const Cx=new Wi,Nx=new Yr,Px=new WeakMap;class Lx{constructor(e){this._renderer=e,this._cubeSize=0,this._sourceTarget=null,this._cubeCamera=new Ja(1,10,null),this._boxMesh=new ws(new Qs(5,5,5),null),this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null,this._integrationMaterial=null}fromScene(e,t=0,i=.1,r=100,n={}){const{size:s=256,position:a=Cx,renderTarget:o=null}=n,l=this._renderer;if(this._setSize(s),!1===l.hasInitialized())throw new Error('THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Use "await renderer.init();" before using this method.');const u=o||this._allocateTarget(),c=this._getSourceTarget(!0);t>0&&(c.texture.mipmapsAutoUpdate=!1);const h=l.autoClear,d=l.autoClearColor,p=l.autoClearDepth,f=l.autoClearStencil,m=e.background;l.autoClear=!0,l.autoClearColor=!0,l.autoClearDepth=!0,l.autoClearStencil=!0,null===m&&(e.background=l.getClearColor(Nx));const g=new Ja(i,r,c);return g.position.copy(a),g.update(l,e),l.autoClear=h,l.autoClearColor=d,l.autoClearDepth=p,l.autoClearStencil=f,e.background=m,t>0&&(c.texture.mipmapsAutoUpdate=!0,this._blur(u,t)),this._applyPMREM(u),u}async fromSceneAsync(e,t=0,i=.1,r=100,n={}){return Ei('PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this.fromScene(e,t,i,r,n)}fromEquirectangular(e,t=null){if(!1===this._renderer.hasInitialized())throw new Error('THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Use "await renderer.init();" before using this method.');return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return Ei('PMREMGenerator: ".fromEquirectangularAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}fromCubemap(e,t=null){if(!1===this._renderer.hasInitialized())throw new Error('THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Use "await renderer.init();" before using this method.');return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return Ei('PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=Ix(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=Fx(),await this._compileMaterial(this._equirectMaterial))}dispose(){null!==this._sourceTarget&&this._sourceTarget.dispose(),null!==this._cubemapMaterial&&this._cubemapMaterial.dispose(),null!==this._equirectMaterial&&this._equirectMaterial.dispose(),null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._ggxMaterial&&this._ggxMaterial.dispose(),null!==this._integrationMaterial&&this._integrationMaterial.dispose(),this._boxMesh.geometry.dispose()}static lodToRoughness(e,t){return t>0?1-Math.sqrt(1-e/t):0}_setSize(e){this._cubeSize=Math.max(256,Oi(e))}_fromTexture(e,t){e.mapping===Ae||e.mapping===Re?this._setSize(0===e.image.length?256:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4);const i=t||this._allocateTarget();return this._textureToCubemap(e),this._applyPMREM(i),i}_allocateTarget(){const e=this._cubeSize,t=Dx(e,!1,!1),i=Math.log2(e)-3;for(let r=0;r<=i;r++)t.texture.mipmaps.push({width:e>>r,height:e>>r});return t.texture.name="PMREM",t.texture.isPMREMTexture=!0,t}_getSourceTarget(e=!1){const t=this._cubeSize,i=this._sourceTarget;return(null===i||i.width!==t||e&&!1===i.depthBuffer)&&(null!==i&&i.dispose(),this._sourceTarget=Dx(t,!0,e)),this._sourceTarget}async _compileMaterial(e){this._boxMesh.material=e,await this._renderer.compile(this._boxMesh,this._cubeCamera.children[0])}_renderCube(e,t,i){const r=this._boxMesh,n=this._cubeCamera;r.material=i,n.renderTarget=e,n.activeMipmapLevel=t,n.update(this._renderer,r)}_textureToCubemap(e){let t;e.mapping===Ae||e.mapping===Re?(null===this._cubemapMaterial&&(this._cubemapMaterial=Ix()),t=this._cubemapMaterial):(null===this._equirectMaterial&&(this._equirectMaterial=Fx()),t=this._equirectMaterial),Px.get(t).envMap.value=e,this._renderCube(this._getSourceTarget(),0,t)}_applyPMREM(e){null===this._ggxMaterial&&(this._ggxMaterial=function(){const e={envMap:E_(),roughness:Jh(0),lodBias:Jh(0)};return Ux("ggx",e,wx({...e,direction:bg,GGX_SAMPLES:Ah(256)}))}(),this._integrationMaterial=function(){const e={envMap:E_(),roughness:Jh(0),sourceLod:Jh(0),sourceSize:Jh(16,"int")};return Ux("integration",e,Ax({...e,direction:bg}))}());const t=this._cubeSize,i=e.texture.mipmaps.length-1,r=Px.get(this._ggxMaterial);r.envMap.value=this._sourceTarget.texture;const n=Px.get(this._integrationMaterial);n.envMap.value=this._sourceTarget.texture,n.sourceLod.value=Math.log2(t/16);for(let s=0;s<=i;s++){const a=Lx.lodToRoughness(s,i);if(s>i-3)n.roughness.value=a,this._renderCube(e,s,this._integrationMaterial);else{const i=a>0?Math.log2(t)+.5*Math.log2(6/(256*Math.pow(a,4)))+.5:0;r.roughness.value=a,r.lodBias.value=i,this._renderCube(e,s,this._ggxMaterial)}}}_blur(e,t){null===this._blurMaterial&&(this._blurMaterial=function(){const e={envMap:E_(),sigma:Jh(0)};return Ux("blur",e,Tx({...e,direction:bg,SAMPLES:wh(20)}))}());const i=this._blurMaterial,r=Px.get(i),n=this._sourceTarget;r.sigma.value=Math.min(t,Math.PI)/Math.SQRT2,r.envMap.value=n.texture,this._renderCube(e,0,i),r.envMap.value=e.texture,this._renderCube(n,0,i)}}function Dx(e,t,i){return new Rx(e,{minFilter:ke,generateMipmaps:t,type:Xe,colorSpace:qt,depthBuffer:i})}function Ux(e,t,i){const r=new Jb;return r.name=`PMREM_${e}`,r.fragmentNode=i,r.side=1,r.blending=0,r.depthTest=!1,r.depthWrite=!1,Px.set(r,t),r}function Ix(){const e={envMap:E_()};return Ux("cubemap",e,e.envMap.sample(bg))}function Fx(){const e={envMap:Yg()},t=yh(()=>{const t=bg,i=t.dFdx().mul(.25).toConst(),r=t.dFdy().mul(.25).toConst(),n=e.envMap.sample(Tg(t.sub(i).sub(r).normalize())).level(0).rgb.add(e.envMap.sample(Tg(t.add(i).sub(r).normalize())).level(0).rgb).add(e.envMap.sample(Tg(t.sub(i).add(r).normalize())).level(0).rgb).add(e.envMap.sample(Tg(t.add(i).add(r).normalize())).level(0).rgb);return Oh(n.mul(.25),1)})();return Ux("equirect",e,t)}const Ox=new WeakMap;function Bx(e,t,i){const r=function(e){let t=Ox.get(e);void 0===t&&(t=new WeakMap,Ox.set(e,t));return t}(t);let n=r.get(e);if((void 0!==n?n.texture.pmremVersion:-1)!==e.pmremVersion){const t=e.image;if(e.isCubeTexture){if(!function(e){if(null==e)return!1;let t=0;const i=6;for(let r=0;r<i;r++)void 0!==e[r]&&t++;return t===i}(t))return null;n=i.fromCubemap(e,n)}else{if(!function(e){return null!=e&&e.height>0}(t))return null;n=i.fromEquirectangular(e,n)}if(n.texture.pmremVersion=e.pmremVersion,!1===r.has(e)){const t=()=>{e.removeEventListener("dispose",t);const i=r.get(e);void 0!==i&&(i.texture.pmremVersion=-1,i.dispose(),r.delete(e))};e.addEventListener("dispose",t)}r.set(e,n)}return n.texture}class kx extends Sc{static get type(){return"PMREMNode"}constructor(e,t=null,i=null){super("vec3"),this._value=e,this._pmrem=null,this.uvNode=t,this.levelNode=i,this._generator=null;const r=new Xs;r.isRenderTargetTexture=!0,this._texture=E_(r),this._maxLod=Jh(0),this._size=Jh(0),this.updateBeforeType=Ju}set value(e){this._value=e,this._pmrem=null}get value(){return this._value}updateFromTexture(e){const t=e.isCompressedCubeTexture?e.image[0].mipmaps:e.mipmaps;this._texture.value=e,this._maxLod.value=t.length-1,this._size.value=t[0].width}updateBefore(e){let t=this._pmrem;const i=t?t.pmremVersion:-1,r=this._value;i!==r.pmremVersion&&(!0===r.isPMREMTexture?t=r:(null===this._generator&&(this._generator=new Lx(e.renderer)),t=Bx(r,e.renderer,this._generator)),null!==t&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this,e));let i=this.levelNode;return null===i&&e.context.getTextureLevel&&(i=e.context.getTextureLevel(this)),this._texture.sample(__.mul(t)).level(((e,t)=>(e=Eh(e).clamp(),Eh(t).mul(e).mul(Eh(2).sub(e))))(i,this._maxLod)).rgb}dispose(){super.dispose(),null!==this._generator&&this._generator.dispose()}}const zx=mh(kx).setParameterLength(1,3),Gx=1e-7,Vx=.5-2/(3*Math.PI),Hx=2/3-28/(15*Math.PI),Wx=yh(({mu:e,roughness:t,A:i})=>{const r=e.oneMinus(),n=r.mul(r.mul(r.mul(r.mul(.0714429953).sub(.332181442)).add(.491881867)).add(.0571085289));return i.mul(t.mul(n).add(1))},{mu:"float",roughness:"float",A:"float",return:"float"}),jx=yh(({lightDirection:e,diffuseColor:t,roughness:i,normalView:r=Dg,viewDirection:n=xg})=>{const s=t.clamp(),a=r.dot(e).clamp(),o=r.dot(n).clamp(),l=e.dot(n).sub(a.mul(o)),u=l.greaterThan(0).select(l.div(a.max(o).max(Gx)),l),c=i.mul(Vx).add(1).reciprocal(),h=s.mul(1/Math.PI,c,i.mul(u).add(1)),d=c.mul(i.mul(Hx).add(1)),p=Wx({mu:o,roughness:i,A:c}),f=Wx({mu:a,roughness:i,A:c}),m=s.mul(s,d).div(s.mul(d.oneMinus()).oneMinus().max(Gx)).mul(1/Math.PI,p.oneMinus().max(Gx),f.oneMinus().max(Gx)).div(d.oneMinus().max(Gx)),g=h.add(m);return i.lessThanEqual(Gx).select(s.mul(1/Math.PI),g)}),$x=yh(({diffuseColor:e,roughness:t,dotNV:i})=>{const r=e.clamp(),n=t.mul(Vx).add(1).reciprocal(),s=Wx({mu:i.clamp(),roughness:t,A:n}),a=n.mul(t.mul(Hx).add(1)),o=r.mul(r,a).div(r.mul(a.oneMinus()).oneMinus().max(Gx)),l=r.mul(s).add(o.mul(s.oneMinus()));return t.lessThanEqual(Gx).select(r,l)},{diffuseColor:"vec3",roughness:"float",dotNV:"float",return:"vec3"}),Xx=yh(({f0:e,f90:t,dotVH:i})=>{const r=i.mul(-5.55473).sub(6.98316).mul(i).exp2();return e.mul(r.oneMinus()).add(t.mul(r))}),qx=yh(({alpha:e,dotNL:t,dotNV:i})=>{const r=e.pow2(),n=t.mul(r.add(r.oneMinus().mul(i.pow2())).sqrt()),s=i.mul(r.add(r.oneMinus().mul(t.pow2())).sqrt());return Gd(.5,n.add(s).max(hp))},{alpha:"float",dotNL:"float",dotNV:"float",return:"float"}),Yx=yh(({alphaT:e,alphaB:t,dotTV:i,dotBV:r,dotTL:n,dotBL:s,dotNV:a,dotNL:o})=>{const l=o.mul(Dh(e.mul(i),t.mul(r),a).length()),u=a.mul(Dh(e.mul(n),t.mul(s),o).length());return Gd(.5,l.add(u).max(hp))},{alphaT:"float",alphaB:"float",dotTV:"float",dotBV:"float",dotTL:"float",dotBL:"float",dotNV:"float",dotNL:"float",return:"float"}),Kx=yh(({alpha:e,dotNH:t})=>{const i=e.pow2(),r=t.pow2().mul(i.oneMinus()).oneMinus();return i.div(r.pow2()).mul(1/Math.PI)},{alpha:"float",dotNH:"float",return:"float"}),Zx=Eh(1/Math.PI),Qx=yh(({alphaT:e,alphaB:t,dotNH:i,dotTH:r,dotBH:n})=>{const s=e.mul(t),a=Dh(t.mul(r),e.mul(n),s.mul(i)),o=a.dot(a),l=s.div(o);return Zx.mul(s.mul(l.pow2()))},{alphaT:"float",alphaB:"float",dotNH:"float",dotTH:"float",dotBH:"float",return:"float"}),Jx=yh(({lightDirection:e,f0:t,f90:i,roughness:r,f:n,normalView:s=Dg,viewDirection:a=xg,USE_IRIDESCENCE:o,USE_ANISOTROPY:l})=>{const u=r.max(.045).pow2(),c=e.add(a).normalize(),h=s.dot(e).clamp(),d=s.dot(a).clamp(),p=s.dot(c).clamp(),f=a.dot(c).clamp();let m,g,_=Xx({f0:t,f90:i,dotVH:f});if(ch(o)&&(_=pd.mix(_,n)),ch(l)){const t=vd.dot(e),i=vd.dot(a),r=vd.dot(c),n=bd.dot(e),s=bd.dot(a),o=bd.dot(c),l=gd.max(u);m=Yx({alphaT:l,alphaB:u,dotTV:i,dotBV:s,dotTL:t,dotBL:n,dotNV:d,dotNL:h}),g=Qx({alphaT:l,alphaB:u,dotNH:p,dotTH:r,dotBH:o})}else m=qx({alpha:u,dotNL:h,dotNV:d}),g=Kx({alpha:u,dotNH:p});return _.mul(m).mul(g)}),eS=yh(e=>e.diffuseColor.mul(1/Math.PI)),tS=yh(({roughness:e,dotNH:t})=>{const i=e.pow2(),r=Eh(1).div(i),n=t.pow2().oneMinus().max(.0078125);return Eh(2).add(r).mul(n.pow(r.mul(.5))).div(2*Math.PI)},{roughness:"float",dotNH:"float",return:"float"}),iS=yh(({dotNV:e,dotNL:t})=>Eh(1).div(Eh(4).mul(t.add(e).sub(t.mul(e)))).clamp(),{dotNV:"float",dotNL:"float",return:"float"}),rS=yh(({lightDirection:e})=>{const t=e.add(xg).normalize(),i=Dg.dot(e).clamp(),r=Dg.dot(xg).clamp(),n=Dg.dot(t).clamp(),s=tS({roughness:dd,dotNH:n}),a=iS({dotNV:r,dotNL:i});return hd.mul(s).mul(a)}),nS=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 sS=null;const aS=yh(({roughness:e,dotNV:t})=>{null===sS&&(sS=new Rs(nS,16,16,at,Xe),sS.name="DFG_LUT",sS.minFilter=Oe,sS.magFilter=Oe,sS.wrapS=Le,sS.wrapT=Le,sS.generateMipmaps=!1,sS.needsUpdate=!0);const i=Ch(e,t);return Yg(sS,i).rg}),oS=yh(e=>{const{dotNV:t,specularColor:i,specularF90:r,roughness:n}=e,s=aS({dotNV:t,roughness:n});return i.mul(s.x).add(r.mul(s.y))}),lS=yh(({f:e,f90:t,dotVH:i})=>{const r=i.oneMinus().saturate(),n=r.mul(r),s=r.mul(n,n).clamp(0,.9999);return e.sub(Dh(t).mul(s)).div(s.oneMinus())},{f:"vec3",f90:"float",dotVH:"float",return:"vec3"}),uS=yh(({N:e,V:t,roughness:i})=>{const r=e.dot(t).saturate(),n=Ch(i,r.oneMinus().sqrt());return n.assign(n.mul(.984375).add(.0078125)),n},{N:"vec3",V:"vec3",roughness:"float",return:"vec2"}),cS=yh(({f:e})=>{const t=e.length();return ef(t.mul(t).add(e.z).div(t.add(1)),0)},{f:"vec3",return:"float"}),hS=yh(({v1:e,v2:t})=>{const i=e.dot(t),r=i.abs().toVar(),n=r.mul(.0145206).add(.4965155).mul(r).add(.8543985).toVar(),s=r.add(4.1616724).mul(r).add(3.417594).toVar(),a=n.div(s),o=i.greaterThan(0).select(a,ef(i.mul(i).oneMinus(),1e-7).inverseSqrt().mul(.5).sub(a));return e.cross(t).mul(o)},{v1:"vec3",v2:"vec3",return:"vec3"}),dS=yh(({N:e,V:t,P:i,mInv:r,p0:n,p1:s,p2:a,p3:o})=>{const l=s.sub(n).toVar(),u=o.sub(n).toVar(),c=l.cross(u),h=Dh().toVar();return Th(c.dot(i.sub(n)).greaterThanEqual(0),()=>{const l=t.sub(e.mul(t.dot(e))).normalize(),u=e.cross(l).negate(),c=r.mul(Vh(l,u,e).transpose()).toVar(),d=c.mul(n.sub(i)).normalize().toVar(),p=c.mul(s.sub(i)).normalize().toVar(),f=c.mul(a.sub(i)).normalize().toVar(),m=c.mul(o.sub(i)).normalize().toVar(),g=Dh(0).toVar();g.addAssign(hS({v1:d,v2:p})),g.addAssign(hS({v1:p,v2:f})),g.addAssign(hS({v1:f,v2:m})),g.addAssign(hS({v1:m,v2:d})),h.assign(Dh(cS({f:g})))}),h},{N:"vec3",V:"vec3",P:"vec3",mInv:"mat3",p0:"vec3",p1:"vec3",p2:"vec3",p3:"vec3",return:"vec3"}),pS=yh(e=>{if(!1===e.geometry.hasAttribute("normal"))return Eh(0);const t=Pg.dFdx().abs().max(Pg.dFdy().abs());return t.x.max(t.y).max(t.z)}),fS=yh(e=>{const{roughness:t}=e,i=pS();let r=t.max(.045);return r=r.add(i),r=r.min(1),r}),mS=yh(([e,t])=>{const i=e.x,r=e.y,n=e.z;let s=t.element(0).mul(.886227);return s=s.add(t.element(1).mul(1.023328).mul(r)),s=s.add(t.element(2).mul(1.023328).mul(n)),s=s.add(t.element(3).mul(1.023328).mul(i)),s=s.add(t.element(4).mul(.858086).mul(i).mul(r)),s=s.add(t.element(5).mul(.858086).mul(r).mul(n)),s=s.add(t.element(6).mul(n.mul(n).mul(.743125).sub(.247708))),s=s.add(t.element(7).mul(.858086).mul(i).mul(n)),s=s.add(t.element(8).mul(.429043).mul(zd(i,i).sub(zd(r,r)))),s}),gS=new Ws;class _S extends Jb{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(gS),this.setValues(e)}}const vS=new ba;class bS extends Jb{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(vS),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?Eh(this.offsetNode):Bv,t=this.dashScaleNode?Eh(this.dashScaleNode):Uv,i=this.dashSizeNode?Eh(this.dashSizeNode):Iv,r=this.gapSizeNode?Eh(this.gapSizeNode):Fv;Ed.assign(i),wd.assign(r);const n=Nf(mm("lineDistance").mul(t));(e?n.add(e):n).mod(Ed.add(wd)).greaterThan(Ed).discard()}}const yS=id("vec3","worldStart"),xS=id("vec3","worldEnd"),SS=id("float","lineDistance"),TS=id("vec4","worldPos"),MS=yh(({start:e,end:t})=>{const i=eg.element(2).element(2),r=eg.element(3).element(2);return i.greaterThan(0).select(r.negate().div(i.add(1)),r.mul(-.5).div(i)).sub(e.z).div(t.z.sub(e.z))},{start:"vec4",end:"vec4",return:"float"}),ES=yh(({p1:e,p2:t,p3:i,p4:r})=>{const n=e.sub(i),s=r.sub(i),a=t.sub(e),o=n.dot(s),l=s.dot(a),u=n.dot(a),c=s.dot(s),h=a.dot(a).mul(c).sub(l.mul(l)),d=o.mul(l).sub(u.mul(c)).div(h).clamp(),p=o.add(l.mul(d)).div(c).clamp();return Ch(d,p)},{p1:"vec3",p2:"vec3",p3:"vec3",p4:"vec3",return:"vec2"});yh(({material:e})=>{const t=e._useDash,i=e._useWorldUnits,r=mm("instanceStart"),n=mm("instanceEnd"),s=Oh(cg.mul(Oh(r,1))).toVar("start"),a=Oh(cg.mul(Oh(n,1))).toVar("end");let o,l;t&&(o=Eh(mm("instanceDistanceStart")).toVar("distanceStart"),l=Eh(mm("instanceDistanceEnd")).toVar("distanceEnd")),i&&(yS.assign(s.xyz),xS.assign(a.xyz));const u=Gm.z.div(Gm.w),c=eg.element(2).element(3).equal(-1);if(Th(c,()=>{Th(s.z.lessThan(0).and(a.z.greaterThan(0)),()=>{const e=MS({start:s,end:a});a.assign(Oh(df(s.xyz,a.xyz,e),a.w)),t&&l.assign(df(o,l,e))}).ElseIf(a.z.lessThan(0).and(s.z.greaterThanEqual(0)),()=>{const e=MS({start:a,end:s});s.assign(Oh(df(a.xyz,s.xyz,e),s.w)),t&&o.assign(df(l,o,e))})}),t){const t=e.dashScaleNode?Eh(e.dashScaleNode):Uv,i=e.offsetNode?Eh(e.offsetNode):Bv;let r=mg.y.lessThan(.5).select(t.mul(o),t.mul(l));r=r.add(i),SS.assign(r)}const h=eg.mul(s),d=eg.mul(a),p=h.xyz.div(h.w),f=d.xyz.div(d.w),m=f.xy.sub(p.xy).toVar();m.x.assign(m.x.mul(u)),m.assign(m.normalize());const g=Oh().toVar();if(i){const e=a.xyz.sub(s.xyz).normalize(),i=c.select(df(s.xyz,a.xyz,.5).normalize(),Dh(0,0,-1)),r=e.cross(i).normalize(),n=e.cross(r);TS.assign(mg.y.lessThan(.5).select(s,a));const o=Ov.mul(.5);TS.addAssign(Oh(mg.x.lessThan(0).select(r.mul(o),r.mul(o).negate()),0)),t||(TS.addAssign(Oh(mg.y.lessThan(.5).select(e.mul(o).negate(),e.mul(o)),0)),TS.addAssign(Oh(n.mul(o),0)),Th(mg.y.greaterThan(1).or(mg.y.lessThan(0)),()=>{TS.subAssign(Oh(n.mul(2).mul(o),0))})),g.assign(eg.mul(TS));const l=Dh().toVar();l.assign(mg.y.lessThan(.5).select(p,f)),Th(g.w.greaterThan(0),()=>{g.z.assign(l.z.mul(g.w))})}else{const e=Ch(m.y,m.x.negate()).toVar("offset");m.x.assign(m.x.div(u)),e.x.assign(e.x.div(u)),e.assign(mg.x.lessThan(0).select(e.negate(),e)),Th(mg.y.lessThan(0),()=>{e.assign(e.sub(m))}).ElseIf(mg.y.greaterThan(1),()=>{e.assign(e.add(m))}),e.assign(e.mul(Ov)),e.assign(e.div(Gm.w.div(Om))),g.assign(mg.y.lessThan(.5).select(h,d)),e.assign(e.mul(g.w)),g.assign(g.add(Oh(e,0,0)))}return g})(),yh(({material:e,renderer:t})=>{const i=e._useAlphaToCoverage,r=e._useDash,n=e._useWorldUnits,s=Sg();if(r){const t=e.dashSizeNode?Eh(e.dashSizeNode):Iv,i=e.gapSizeNode?Eh(e.gapSizeNode):Fv;Ed.assign(t),wd.assign(i),s.y.lessThan(-1).or(s.y.greaterThan(1)).discard(),SS.mod(Ed.add(wd)).greaterThan(Ed).discard()}const a=Eh(1).toVar("alpha");if(n){const e=Eh().toVar(),n=eg.element(2).element(3).notEqual(-1).toConst();Th(n,()=>{const t=xS.xy.sub(yS.xy),i=TS.xy.sub(yS.xy).dot(t).div(t.dot(t)).clamp();e.assign(yS.xy.add(t.mul(i)).sub(TS.xy).length())}).Else(()=>{const t=TS.xyz.normalize().mul(1e5),i=xS.sub(yS),r=ES({p1:yS,p2:xS,p3:Dh(0,0,0),p4:t}),n=yS.add(i.mul(r.x)),s=t.mul(r.y),a=n.sub(s);e.assign(a.length())});const s=e.div(Ov);if(!r)if(i&&t.currentSamples>0){const e=s.fwidth();a.assign(gf(e.negate().add(.5),e.add(.5),s).oneMinus())}else s.greaterThan(.5).discard()}else if(i&&t.currentSamples>0){const e=s.x,t=s.y.greaterThan(0).select(s.y.sub(1),s.y.add(1)),i=e.mul(e).add(t.mul(t)),r=Eh(i.fwidth()).toVar("dlen");Th(s.y.abs().greaterThan(1),()=>{a.assign(gf(r.oneMinus(),r.add(1),i).oneMinus())})}else Th(s.y.abs().greaterThan(1),()=>{const e=s.x,t=s.y.greaterThan(0).select(s.y.sub(1),s.y.add(1));e.mul(e).add(t.mul(t)).greaterThan(1).discard()});return a})();const wS=new fa;class AS extends Jb{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(wS),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?Eh(this.opacityNode):uv;rd.assign(If(Oh(dh(Dg).mul(.5).add(.5),e),Xt))}}const RS=new WeakMap;class CS extends Sc{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=E_(null);const t=new Xs;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=Ju}updateBefore(e){const{renderer:t,material:i}=e,r=this.envNode;if(r.isTextureNode||r.isMaterialReferenceNode){const e=r.isTextureNode?r.value:i[r.property];if(e&&e.isTexture){const i=e.mapping;if(i===Ce||i===Ne){if(RS.has(e)){const t=RS.get(e);PS(t,e.mapping),this._cubeTexture=t}else{const i=e.image;if(function(e){return null!=e&&e.height>0}(i)){const r=new Rx(i.height);r.fromEquirectangularTexture(t,e),PS(r.texture,e.mapping),this._cubeTexture=r.texture,RS.set(e,r.texture),e.addEventListener("dispose",NS)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function NS(e){const t=e.target;t.removeEventListener("dispose",NS);const i=RS.get(t);void 0!==i&&(RS.delete(t),i.dispose())}function PS(e,t){t===Ce?e.mapping=Ae:t===Ne&&(e.mapping=Re)}const LS=mh(CS).setParameterLength(1);class DS extends Fb{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=LS(this.envNode).context({getUV:e=>__.mul(e.uvNode||e.getDefaultUV()),forceUVContext:!0})}}class US extends Fb{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=Eh(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class IS{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class FS extends IS{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,i=e.reflectedLight,r=e.irradianceLightMap;i.indirectDiffuse.assign(Oh(0)),r?i.indirectDiffuse.addAssign(r):i.indirectDiffuse.addAssign(Oh(1,1,1,0)),i.indirectDiffuse.mulAssign(t),i.indirectDiffuse.mulAssign(rd.rgb)}finish(e){const{material:t,context:i}=e,r=i.outgoingLight,n=e.context.environment;if(n)switch(t.combine){case 0:r.rgb.assign(df(r.rgb,r.rgb.mul(n.rgb),pv.mul(fv)));break;case 1:r.rgb.assign(df(r.rgb,n.rgb,pv.mul(fv)));break;case 2:r.rgb.addAssign(n.rgb.mul(pv.mul(fv)));break;default:Ti("BasicLightingModel: Unsupported .combine value:",t.combine)}}}const OS=new fs;class BS extends Jb{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(OS),this.setValues(e)}setupNormal(){return Ag(Pg)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new DS(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new US(Vv)),t}setupOutgoingLight(){return rd.rgb}setupLightingModel(){return new FS}}const kS=yh(({dotNH:e})=>Td.mul(Eh(.5)).add(1).mul(Eh(1/Math.PI)).mul(e.pow(Td))),zS=yh(({lightDirection:e})=>{const t=e.add(xg).normalize(),i=Dg.dot(t).clamp(),r=xg.dot(t).clamp(),n=Xx({f0:yd,f90:1,dotVH:r}),s=Eh(.25),a=kS({dotNH:i});return n.mul(s).mul(a)});class GS extends FS{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:i}){const r=Dg.dot(e).clamp().mul(t);i.directDiffuse.addAssign(r.mul(eS({diffuseColor:rd.rgb}))),!0===this.specular&&i.directSpecular.addAssign(r.mul(zS({lightDirection:e})).mul(pv))}indirect(e){const{ambientOcclusion:t,irradiance:i,reflectedLight:r}=e.context;r.indirectDiffuse.addAssign(i.mul(eS({diffuseColor:rd}))),r.indirectDiffuse.mulAssign(t)}}const VS=new ma;class HS extends Jb{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.emissiveNode=null,this.setDefaultValues(VS),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new DS(t):null}setupLightingModel(){return new GS(!1)}}const WS=new da;class jS extends Jb{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.emissiveNode=null,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(WS),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new DS(t):null}setupLightingModel(){return new GS}setupVariants(){const e=(this.shininessNode?Eh(this.shininessNode):ov).max(1e-4);Td.assign(e);const t=this.specularNode||cv;yd.assign(t)}}const $S=yh(([e,t,i,r,n])=>{const s=Dh(mf(t.negate(),Ep(e),Gd(1,r))),a=Dh(Gp(n[0].xyz),Gp(n[1].xyz),Gp(n[2].xyz));return Ep(s).mul(i.mul(a))},{n:"vec3",v:"vec3",thickness:"float",ior:"float",modelMatrix:"mat4",return:"vec3"}),XS=yh(([e,t])=>e.mul(pf(t.mul(2).sub(2),0,1)),{roughness:"float",ior:"float",return:"float"}),qS=Jg(),YS=t_(),KS=yh(([e,t,i],{material:r})=>{const n=(1===r.side?qS:YS).sample(e.mul(sg.zw).add(sg.xy).div(km)),s=yp(sg.z).mul(XS(t,i));return hy(n,s)}),ZS=yh(([e,t,i])=>(Th(i.notEqual(0),()=>{const r=bp(t).negate().div(i);return _p(r.negate().mul(e))}),Dh(1)),{transmissionDistance:"float",attenuationColor:"vec3",attenuationDistance:"float",return:"vec3"}),QS=yh(([e,t,i,r,n,s,a,o,l,u,c,h,d,p,f])=>{let m,g;if(f){m=Oh().toVar(),g=Dh().toVar();const n=c.sub(1).mul(f.mul(.025)),s=Dh(c.sub(n),c,c.add(n));Mm({start:0,end:3},({i:n})=>{const c=s.element(n),f=$S(e,t,h,c,o),_=a.add(f),v=u.mul(l.mul(Oh(_,1))),b=Ch(v.xy.div(v.w)).toVar();b.addAssign(1),b.divAssign(2),b.assign(Ch(b.x,b.y.oneMinus()));const y=KS(b,i,c);m.element(n).assign(y.element(n)),m.a.addAssign(y.a),g.element(n).assign(r.element(n).mul(ZS(Gp(f),d,p).element(n)))}),m.a.divAssign(3)}else{const n=$S(e,t,h,c,o),s=a.add(n),f=u.mul(l.mul(Oh(s,1))),_=Ch(f.xy.div(f.w)).toVar();_.addAssign(1),_.divAssign(2),_.assign(Ch(_.x,_.y.oneMinus())),m=KS(_,i,c),g=r.mul(ZS(Gp(n),d,p))}const _=g.rgb.mul(m.rgb),v=e.dot(t).clamp(),b=Dh(oS({dotNV:v,specularColor:n,specularF90:s,roughness:i})),y=g.r.add(g.g,g.b).div(3);return Oh(b.oneMinus().mul(_),m.a.oneMinus().mul(y).oneMinus())}),JS=Vh(3.2404542,-1.5371385,-.4985314,-.969266,1.8760108,.041556,.0556434,-.2040259,1.0572252),eT=(e,t)=>e.sub(t).div(e.add(t)).pow2(),tT=yh(({outsideIOR:e,eta2:t,cosTheta1:i,thinFilmThickness:r,baseF0:n})=>{const s=df(e,t,gf(0,.03,r)),a=e.div(s).pow2().mul(i.pow2().oneMinus()).oneMinus();Th(a.lessThan(0),()=>Dh(1));const o=a.sqrt(),l=eT(s,e),u=Xx({f0:l,f90:1,dotVH:i}),c=u.oneMinus(),h=s.lessThan(e).select(Math.PI,0),d=Eh(Math.PI).sub(h),p=(e=>{const t=e.sqrt();return Dh(1).add(t).div(Dh(1).sub(t))})(n.clamp(0,.9999)),f=eT(p,s.toVec3()),m=Xx({f0:f,f90:1,dotVH:o}),g=Dh(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(r,o,2),v=Dh(d).add(g),b=u.mul(m).clamp(1e-5,.9999),y=b.sqrt(),x=c.pow2().mul(m).div(Dh(1).sub(b)),S=u.add(x).toVar(),T=x.sub(c).toVar();return Mm({start:1,end:2,condition:"<=",name:"m"},({m:e})=>{T.mulAssign(y);const t=((e,t)=>{const i=e.mul(2*Math.PI*1e-9),r=Dh(54856e-17,44201e-17,52481e-17),n=Dh(1681e3,1795300,2208400),s=Dh(43278e5,93046e5,66121e5),a=Eh(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(i.mul(2239900).add(t.x).cos()).mul(i.pow2().mul(-45282e5).exp());let o=r.mul(s.mul(2*Math.PI).sqrt()).mul(n.mul(i).add(t).cos()).mul(i.pow2().negate().mul(s).exp());return o=Dh(o.x.add(a),o.y,o.z).div(1.0685e-7),JS.mul(o)})(Eh(e).mul(_),Eh(e).mul(v)).mul(2);S.addAssign(T.mul(t))}),S.max(Dh(0))},{outsideIOR:"float",eta2:"float",cosTheta1:"float",thinFilmThickness:"float",baseF0:"vec3",return:"vec3"}),iT=yh(({normal:e,viewDir:t,roughness:i})=>{const r=e.dot(t).saturate(),n=i.mul(i),s=i.add(.1).reciprocal(),a=Eh(-1.9362).add(i.mul(1.0678)).add(n.mul(.4573)).sub(s.mul(.8469)),o=Eh(-.6014).add(i.mul(.5538)).sub(n.mul(.467)).sub(s.mul(.1255));return a.mul(r).add(o).exp().saturate()},{normal:"vec3",viewDir:"vec3",roughness:"float",return:"float"}),rT=Dh(.04),nT=Eh(1);class sT extends IS{constructor(e=!1,t=!1,i=!1,r=!1,n=!1,s=!1,a=!1,o=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=i,this.anisotropy=r,this.transmission=n,this.dispersion=s,this.retroreflection=a,this.diffuseRoughness=o,this.clearcoatRadiance=null,this.clearcoatSpecularDirect=null,this.clearcoatSpecularIndirect=null,this.sheenSpecularDirect=null,this.sheenSpecularIndirect=null,this.iridescenceFresnel=null,this.iridescenceF0Dielectric=null,this.iridescenceF0Metallic=null,this.dfg=null,this.eonDirectionalAlbedo=null,this.multiScatteringCompensation=null,this.singleScatteringDielectric=null,this.multiScatteringDielectric=null}start(e){if(!0===this.clearcoat&&(this.clearcoatRadiance=Dh().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=Dh().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=Dh().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=Dh().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=Dh().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=Dg.dot(xg).clamp(),t=tT({outsideIOR:Eh(1),eta2:fd,cosTheta1:e,thinFilmThickness:md,baseF0:yd}),i=tT({outsideIOR:Eh(1),eta2:fd,cosTheta1:e,thinFilmThickness:md,baseF0:rd.rgb});this.iridescenceFresnel=df(t,i,ld),this.iridescenceF0Dielectric=lS({f:t,f90:1,dotVH:e}),this.iridescenceF0Metallic=lS({f:i,f90:1,dotVH:e})}if(!0===this.transmission){const t=vg,i=ng.sub(vg).normalize(),r=Ug,n=e.context;n.backdrop=QS(r,i,od,nd,xd,Sd,t,lg,ig,eg,Ad,Cd,Pd,Nd,this.dispersion?Ld:null),n.backdropAlpha=Rd,rd.a.mulAssign(df(1,n.backdrop.a,Rd))}const t=Dg.dot(xg).clamp();this.dfg=aS({roughness:od,dotNV:t}).toConst("dfg");const i=this.dfg.x.add(this.dfg.y);this.multiScatteringCompensation=xd.mul(i.reciprocal().sub(1)).add(1).toConst("multiScatteringCompensation"),this.singleScatteringDielectric=Dh().toVar("singleScatteringDielectric"),this.multiScatteringDielectric=Dh().toVar("multiScatteringDielectric"),this.computeMultiscattering(this.singleScatteringDielectric,this.multiScatteringDielectric,Sd,yd,this.iridescenceF0Dielectric),!0===this.diffuseRoughness&&(this.eonDirectionalAlbedo=$x({diffuseColor:rd.rgb,roughness:sd,dotNV:t})),super.start(e)}computeMultiscattering(e,t,i,r,n=null){const s=this.dfg,a=n?pd.mix(r,n):r,o=a.mul(s.x).add(i.mul(s.y)),l=s.x.add(s.y).oneMinus(),u=a.add(a.oneMinus().mul(.047619)),c=o.mul(u).div(l.mul(u).oneMinus());e.addAssign(o),t.addAssign(c.mul(l))}direct({lightDirection:e,lightColor:t,reflectedLight:i}){const r=Dg.dot(e).clamp().mul(t).toVar();if(!0===this.sheen){this.sheenSpecularDirect.addAssign(r.mul(rS({lightDirection:e})));const t=iT({normal:Dg,viewDir:xg,roughness:dd}),i=iT({normal:Dg,viewDir:e,roughness:dd}),n=hd.r.max(hd.g).max(hd.b).mul(t.max(i)).oneMinus();r.mulAssign(n)}if(!0===this.clearcoat){const i=Ig.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(i.mul(Jx({lightDirection:e,f0:rT,f90:nT,roughness:cd,normalView:Ig})))}const n=e.add(xg).normalize(),s=xg.dot(n).clamp();let a=Xx({f0:yd,f90:Sd,dotVH:s}),o=Jx({lightDirection:e,f0:xd,f90:Sd,roughness:od,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy});if(!0===this.retroreflection){const t=xg.negate().reflect(Dg),i=e.add(t).normalize(),r=t.dot(i).clamp(),n=Xx({f0:yd,f90:Sd,dotVH:r}),s=Jx({lightDirection:e,viewDirection:t,f0:xd,f90:Sd,roughness:od,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy});a=df(a,n,Dd.clamp()),o=df(o,s,Dd.clamp())}const l=this.diffuseRoughness?jx({lightDirection:e,diffuseColor:rd.rgb,roughness:sd}).mul(ld.oneMinus()):eS({diffuseColor:nd});i.directDiffuse.addAssign(r.mul(l).mul(a.oneMinus())),i.directSpecular.addAssign(r.mul(o).mul(this.multiScatteringCompensation))}directRectArea({lightColor:e,lightPosition:t,halfWidth:i,halfHeight:r,reflectedLight:n,ltc_1:s,ltc_2:a}){const o=t.add(i).sub(r),l=t.sub(i).sub(r),u=t.sub(i).add(r),c=t.add(i).add(r),h=Dg,d=xg,p=yg.toVar(),f=uS({N:h,V:d,roughness:od}),m=s.sample(f).toVar(),g=a.sample(f).toVar(),_=Vh(Dh(m.x,0,m.y),Dh(0,1,0),Dh(m.z,0,m.w)).toVar(),v=xd.mul(g.x).add(Sd.sub(xd).mul(g.y)).toVar();if(n.directSpecular.addAssign(e.mul(v).mul(dS({N:h,V:d,P:p,mInv:_,p0:o,p1:l,p2:u,p3:c}))),n.directDiffuse.addAssign(e.mul(nd).mul(dS({N:h,V:d,P:p,mInv:Vh(1,0,0,0,1,0,0,0,1),p0:o,p1:l,p2:u,p3:c}))),!0===this.clearcoat){const t=Ig,i=uS({N:t,V:d,roughness:cd}),r=s.sample(i),n=a.sample(i),h=Vh(Dh(r.x,0,r.y),Dh(0,1,0),Dh(r.z,0,r.w)),f=rT.mul(n.x).add(nT.sub(rT).mul(n.y));this.clearcoatSpecularDirect.addAssign(e.mul(f).mul(dS({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:i}=e.context,r=this.singleScatteringDielectric,n=this.multiScatteringDielectric,s=this.diffuseRoughness?this.eonDirectionalAlbedo.mul(ld.oneMinus(),1/Math.PI):eS({diffuseColor:nd}),a=t.mul(s).mul(r.add(n).oneMinus()).toVar();if(!0===this.sheen){const e=iT({normal:Dg,viewDir:xg,roughness:dd});this.sheenSpecularIndirect.addAssign(t.mul(hd,e,1/Math.PI));const i=hd.r.max(hd.g).max(hd.b).mul(e).oneMinus();a.mulAssign(i)}i.indirectDiffuse.addAssign(a)}indirectSpecular(e){const{radiance:t,iblIrradiance:i,reflectedLight:r}=e.context;if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(i.mul(hd,iT({normal:Dg,viewDir:xg,roughness:dd}),1/Math.PI)),!0===this.clearcoat){const e=Ig.dot(xg).clamp(),t=oS({dotNV:e,specularColor:rT,specularF90:nT,roughness:cd});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const n=this.singleScatteringDielectric,s=this.multiScatteringDielectric,a=Dh().toVar("singleScatteringMetallic"),o=Dh().toVar("multiScatteringMetallic");this.computeMultiscattering(a,o,Sd,rd.rgb,this.iridescenceF0Metallic);const l=df(n,a,ld),u=df(s,o,ld),c=n.add(s),h=(this.diffuseRoughness?this.eonDirectionalAlbedo.mul(ld.oneMinus()):nd).mul(c.oneMinus()),d=i.mul(1/Math.PI),p=t.mul(l).add(u.mul(d)).toVar(),f=h.mul(d).toVar();if(!0===this.sheen){const e=iT({normal:Dg,viewDir:xg,roughness:dd}),t=hd.r.max(hd.g).max(hd.b).mul(e).oneMinus();p.mulAssign(t),f.mulAssign(t)}r.indirectSpecular.addAssign(p),r.indirectDiffuse.addAssign(f)}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:i}=e.context,r=Dg.dot(xg).clamp().add(t),n=od.mul(-16).oneMinus().negate().exp2(),s=t.sub(r.pow(n).oneMinus()).clamp();!0===this.clearcoat&&this.clearcoatSpecularIndirect.mulAssign(t),!0===this.sheen&&this.sheenSpecularIndirect.mulAssign(t),i.indirectDiffuse.mulAssign(t),i.indirectSpecular.mulAssign(s)}finish({context:e}){const{outgoingLight:t}=e;if(!0===this.clearcoat){const e=Ig.dot(xg).clamp(),i=Xx({dotVH:e,f0:rT,f90:nT}),r=t.mul(ud.mul(i).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(ud));t.assign(r)}if(!0===this.sheen){const e=t.add(this.sheenSpecularDirect,this.sheenSpecularIndirect);t.assign(e)}}}const aT=new WeakMap;class oT extends Fb{static get type(){return"EnvironmentNode"}constructor(e=null){super(),this.envNode=e,this._pmremNode=null}setup(e){const{material:t}=e;let i=this.envNode;if(i.isTextureNode||i.isMaterialReferenceNode){const t=this._getPMREMNodeCache(e.renderer);let r=t.get(i);void 0===r&&(r=zx(this._getEnvTexture(e)),t.set(i,r)),this._pmremNode=r,this.updateBeforeType=i.isMaterialReferenceNode?ec:Ju,i=r}const r=!0===t.useAnisotropy||t.anisotropy>0?K_:Dg;let n=im(i.context(lT(od,r)).mul(g_));if(!0===t.useRetroreflection||t.retroreflectivity>0){const e=im(i.context(uT(od,r)).mul(g_));n=Dd.clamp().mix(n,e)}const s=i.context(cT(Ug)).mul(Math.PI).mul(g_),a=im(s);e.context.radiance.addAssign(n),e.context.iblIrradiance.addAssign(a);const o=e.context.lightingModel.clearcoatRadiance;if(o){const e=i.context(lT(cd,Ig)).mul(g_),t=im(e);o.addAssign(t)}}updateBefore(e){const t=this._getEnvTexture(e);t&&this._pmremNode.value!==t&&(this._pmremNode.value=t,this._pmremNode.updateBefore(e))}_getEnvTexture(e){const t=this.envNode;return t.isMaterialReferenceNode?(t.updateReference(e),t.getValueFromReference()):t.value}_getPMREMNodeCache(e){let t=aT.get(e);return void 0===t&&(t=new WeakMap,aT.set(e,t)),t}}const lT=(e,t)=>{let i=null;return{getUV:()=>(null===i&&(i=xg.negate().reflect(t),i=cf(e).mix(i,t).normalize(),i=i.transformDirection(rg)),i),getTextureLevel:()=>e}},uT=(e,t)=>{let i=null;return{getUV:()=>(null===i&&(i=cf(e).mix(xg,t).normalize(),i=i.transformDirection(rg)),i),getTextureLevel:()=>e}},cT=e=>({getUV:()=>e,getTextureLevel:()=>Eh(1)}),hT=new ca;class dT extends Jb{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(hT),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new oT(t):null}setupLightingModel(){return new sT}setupSpecular(){const e=df(Dh(.04),rd.rgb,ld);yd.assign(Dh(.04)),xd.assign(e),Sd.assign(1)}setupVariants(){const e=this.metalnessNode?Eh(this.metalnessNode):_v;ld.assign(e);let t=this.roughnessNode?Eh(this.roughnessNode):mv;t=fS({roughness:t}),od.assign(t),this.setupSpecular(),nd.assign(rd.rgb.mul(e.oneMinus()))}}const pT=new ha;class fT extends dT{static get type(){return"MeshPhysicalNodeMaterial"}constructor(e){super(),this.isMeshPhysicalNodeMaterial=!0,this.clearcoatNode=null,this.clearcoatRoughnessNode=null,this.diffuseRoughnessNode=null,this.clearcoatNormalNode=null,this.sheenNode=null,this.sheenRoughnessNode=null,this.iridescenceNode=null,this.iridescenceIORNode=null,this.iridescenceThicknessNode=null,this.specularIntensityNode=null,this.specularColorNode=null,this.iorNode=null,this.transmissionNode=null,this.thicknessNode=null,this.attenuationDistanceNode=null,this.attenuationColorNode=null,this.dispersionNode=null,this.retroreflectivityNode=null,this.anisotropyNode=null,this.setDefaultValues(pT),this.setValues(e)}get useClearcoat(){return this.clearcoat>0||null!==this.clearcoatNode}get useDiffuseRoughness(){return this.diffuseRoughness>0||null!==this.diffuseRoughnessNode}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}get useRetroreflection(){return this.retroreflectivity>0||null!==this.retroreflectivityNode}setupSpecular(){const e=this.iorNode?Eh(this.iorNode):Pv,t=this.specularColorNode?Dh(this.specularColorNode):dv,i=this.specularIntensityNode?Eh(this.specularIntensityNode):hv;Ad.assign(e),yd.assign(Jp(uf(Ad.sub(1).div(Ad.add(1))).mul(t),Dh(1)).mul(i)),xd.assign(df(yd,rd.rgb,ld)),Sd.assign(df(i,1,ld))}setupLightingModel(){return new sT(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion,this.useRetroreflection,this.useDiffuseRoughness)}setupVariants(e){if(super.setupVariants(e),this.useDiffuseRoughness){const e=this.diffuseRoughnessNode?Eh(this.diffuseRoughnessNode):gv;sd.assign(e.clamp())}if(this.useClearcoat){const e=this.clearcoatNode?Eh(this.clearcoatNode):bv,t=this.clearcoatRoughnessNode?Eh(this.clearcoatRoughnessNode):yv;ud.assign(e),cd.assign(fS({roughness:t}))}if(this.useSheen){const e=this.sheenNode?Dh(this.sheenNode):Tv,t=this.sheenRoughnessNode?Eh(this.sheenRoughnessNode):Mv;hd.assign(e),dd.assign(t)}if(this.useRetroreflection){const e=this.retroreflectivityNode?Eh(this.retroreflectivityNode):Gv;Dd.assign(e)}if(this.useIridescence){const e=this.iridescenceNode?Eh(this.iridescenceNode):wv,t=this.iridescenceIORNode?Eh(this.iridescenceIORNode):Av,i=this.iridescenceThicknessNode?Eh(this.iridescenceThicknessNode):Rv;pd.assign(e),fd.assign(t),md.assign(i)}if(this.useAnisotropy){const e=(this.anisotropyNode?Ch(this.anisotropyNode):Ev).toVar();_d.assign(e.length()),Th(_d.equal(0),()=>{e.assign(Ch(1,0))}).Else(()=>{e.divAssign(Ch(_d)),_d.assign(_d.saturate())}),gd.assign(_d.pow2().mix(od.pow2(),1)),vd.assign(Y_[0].mul(e.x).add(Y_[1].mul(e.y))),bd.assign(Y_[1].mul(e.x).sub(Y_[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?Eh(this.transmissionNode):Cv,t=this.thicknessNode?Eh(this.thicknessNode):Nv,i=this.attenuationDistanceNode?Eh(this.attenuationDistanceNode):Lv,r=this.attenuationColorNode?Dh(this.attenuationColorNode):Dv;if(Rd.assign(e),Cd.assign(t),Nd.assign(i),Pd.assign(r),this.useDispersion){const e=this.dispersionNode?Eh(this.dispersionNode):zv;Ld.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?Dh(this.clearcoatNormalNode):xv}setup(e){e.context.setupClearcoatNormal=()=>Rf(this.setupClearcoatNormal(e),"NORMAL","vec3"),super.setup(e)}}const mT=yh(({normal:e,lightDirection:t,builder:i})=>{const r=e.dot(t),n=Ch(r.mul(.5).add(.5),0);if(i.material.gradientMap){const e=N_("gradientMap","texture").context({getUV:()=>n});return Dh(e.r)}{const e=n.fwidth().mul(.5);return df(Dh(.7),Dh(1),gf(Eh(.7).sub(e.x),Eh(.7).add(e.x),n.x))}});class gT extends IS{direct({lightDirection:e,lightColor:t,reflectedLight:i},r){const n=mT({normal:Dg,lightDirection:e,builder:r}).mul(t);i.directDiffuse.addAssign(n.mul(eS({diffuseColor:rd.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:i,reflectedLight:r}=e.context;r.indirectDiffuse.addAssign(i.mul(eS({diffuseColor:rd}))),r.indirectDiffuse.mulAssign(t)}}const _T=new pa;class vT extends Jb{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.emissiveNode=null,this.setDefaultValues(_T),this.setValues(e)}setupLightingModel(){return new gT}}const bT=new va;class yT extends Jb{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(bT),this.setValues(e)}setupVariants(e){const t=Bg;let i;i=e.material.matcap?N_("matcap","texture").context({getUV:()=>t}):Dh(df(.2,.8,t.y)),rd.rgb.mulAssign(i.rgb)}}const xT=new ls;class ST extends Jb{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(xT),this.setValues(e)}setupPositionView(e){const{object:t,camera:i}=e,{positionNode:r,rotationNode:n,scaleNode:s,sizeAttenuation:a}=this,o=cg.mul(Dh(r||0));let l=Ch(lg[0].xyz.length(),lg[1].xyz.length());null!==s&&(l=l.mul(Ch(s))),!0!==i.isOrthographicCamera&&!1===a&&(l=l.mul(o.z.negate()));let u=mg.xy;if(t.center&&!0===t.center.isVector2){const e=((e,t,i)=>new Of(e,t,i))("center","vec2");u=u.sub(e.sub(.5))}u=u.mul(l);const c=Eh(n||Sv),h=Hg(u,c);return Oh(o.xy.add(h),o.zw)}get sizeAttenuation(){return this._useSizeAttenuation}set sizeAttenuation(e){this._useSizeAttenuation!==e&&(this._useSizeAttenuation=e,this.needsUpdate=!0)}}const TT=new js,MT=new Vi;class ET extends ST{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(TT),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return cg.mul(Dh(e||gg)).xyz}setupVertexSprite(e){const{material:t,camera:i}=e,{rotationNode:r,scaleNode:n,sizeNode:s,sizeAttenuation:a}=this;let o=super.setupVertex(e);if(!0!==t.isNodeMaterial)return o;let l=null!==s?Ch(s):kv;l=l.mul(Om),!0!==i.isOrthographicCamera&&!0===a&&(l=l.mul(wT.div(yg.z.negate()))),n&&n.isNode&&(l=l.mul(Ch(n)));let u=mg.xy;if(r&&r.isNode){const e=Eh(r);u=Hg(u,e)}return u=u.mul(l),u=u.div(Vm.div(2)),u=u.mul(o.w),o=o.add(Oh(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 wT=Jh(1).setGroup(Kh).onRenderUpdate(function({renderer:e}){const t=e.getSize(MT);this.value=.5*t.y});class AT extends IS{constructor(){super(),this.shadowNode=Eh(1).toVar("shadowMask")}direct({lightNode:e}){null!==e.shadowNode&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){rd.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(rd.rgb)}}const RT=new ia;class CT extends Jb{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(RT),this.setValues(e)}setupLightingModel(){return new AT}}td("vec3"),td("float"),td("vec3");class NT{constructor(e,t,i){this.renderer=e,this.nodes=t,this.info=i,this._context="undefined"!=typeof self?self:null,this._animationLoop=null,this._requestId=null}start(){if(null!==this._requestId)return;const e=(t,i)=>{this._requestId=this._context.requestAnimationFrame(e),this.renderer._inspector.isRunning&&this.renderer._inspector.finish(),!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,i)};e()}stop(){this.renderer._inspector.isRunning&&this.renderer._inspector.finish(),null!==this._context&&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(),this._animationLoop=null}}let PT=0;const LT=new WeakMap,DT=[0,0,0,0,0],UT=["side","blending","combine","normalMapType"];function IT(e){return null==e?"-":!0===e.isStorageInstancedBufferAttribute?"s":"a"}class FT{constructor(e,t,i,r,n,s,a,o,l,u){this.id=PT++,this._nodes=e,this._geometries=t,this.renderer=i,this.object=r,this.material=n,this.scene=s,this.camera=a,this.lightsNode=o,this.context=l,this.geometry=r.geometry,this.geometryVersion=0,this.version=n.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.initialGeometryCacheKey=this.getGeometryCacheKey(),this._nodeBuilderState=null,this._bindings=null,this._monitor=null,this._sourceMaterial=i._currentSourceMaterial,this.sourceMaterialVersion=null!==this._sourceMaterial?this._sourceMaterial.version:0,this.onDispose=null,this.isRenderObject=!0,this.onMaterialDispose=()=>{this.dispose()},this.onGeometryDispose=()=>{this._geometries.deleteNodeAttributes(this),this._geometries.deleteVertexState(this),this.attributes=null,this.attributesId=null},this.onObjectDispose=()=>{this.dispose()},this.onLightsNodeDispose=()=>{this.dispose()},this.object.addEventListener("dispose",this.onObjectDispose),this.material.addEventListener("dispose",this.onMaterialDispose),this.geometry.addEventListener("dispose",this.onGeometryDispose),this.lightsNode.addEventListener("dispose",this.onLightsNodeDispose),null!==this._sourceMaterial&&this._sourceMaterial.addEventListener("dispose",this.onMaterialDispose)}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.getNodeBuilderState().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(this.renderer._bindings,this.context))}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 null!==this._sourceMaterial?[this.object,this.material,this.context,this.lightsNode,this._sourceMaterial]:[this.object,this.material,this.context,this.lightsNode]}setGeometry(e){this.geometry.removeEventListener("dispose",this.onGeometryDispose),this.geometry=e,this.geometry.addEventListener("dispose",this.onGeometryDispose),this.attributes=null,this.attributesId=null,this.geometryVersion++}getAttributes(){if(null!==this.attributes)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,i=[],r=new Set,n={};for(const s of e){let e;if(s.node&&s.node.attribute?e=s.node.getObjectAttribute(this.object):(e=t.getAttribute(s.name),void 0!==e&&(e.isInterleavedBufferAttribute?n[s.name]=e.data.uuid:n[s.name]=e.id)),void 0===e)continue;i.push(e);const a=e.isInterleavedBufferAttribute?e.data:e;r.add(a)}return this.attributes=i,this.attributesId=n,this.vertexBuffers=Array.from(r.values()),i}getVertexBuffers(){return null===this.vertexBuffers&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){const{object:e,material:t,geometry:i,group:r,drawRange:n}=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===i.isInstancedBufferGeometry?l=i.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=n.start*u,h=(n.start+n.count)*u;null!==r&&(c=Math.max(c,r.start*u),h=Math.min(h,(r.start+r.count)*u));const d=i.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 i of Object.keys(e.attributes).sort()){const r=e.attributes[i];t+=i+",",r.itemSize&&(t+=r.itemSize+","),r.normalized&&(t+="n,")}for(const i of Object.keys(e.morphAttributes).sort()){const r=e.morphAttributes[i];t+="morph-"+i+",";for(let e=0,i=r.length;e<i;e++){t+=r[e].id+","}}return t}getMaterialCacheKey(){const{object:e,material:t,renderer:i,scene:r}=this;let n=this._nodes.getCustomProgramCacheKey(t,r);for(const e of function(e){const t=Object.keys(e);let i=LT.get(e.constructor);if(void 0===i){i=[];let t=Object.getPrototypeOf(e);for(;t;){const e=Object.getOwnPropertyDescriptors(t);for(const t in e){const r=e[t];r&&"function"==typeof r.get&&i.push(t)}t=Object.getPrototypeOf(t)}LT.set(e.constructor,i)}for(let e=0;e<i.length;e++)t.push(i[e]);return t}(t)){if(/^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData|iridescenceThicknessRange)$/.test(e))continue;const r=t[e];let s;if(null!==r){const t=typeof r;"number"===t?s=UT.includes(e)?String(r):0!==r?"1":"0":"object"===t?(s="{",r.isTexture&&(s+=r.mapping,s+=r.channel,!0===i.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);n+=s+","}if(n+=this.clippingContextCacheKey+",",e.geometry&&(n+=this.getGeometryCacheKey()),e.skeleton&&(n+=e.skeleton.bones.length+","),e.isBatchedMesh&&(n+=e._matricesTexture.uuid+",",null!==e._colorsTexture&&(n+=e._colorsTexture.uuid+",")),e.isInstancedMesh){const{instanceMatrix:t,instanceColor:i,morphTexture:r}=e;n+=IT(t)+IT(i)+(null!==r?"m":"")+","}else e.count>1&&(n+=e.uuid+",");return n+=this.context.stateKey+",",n+=e.receiveShadow+",",cc(n)}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 i=this.geometry.getAttribute(t);if(void 0===i)return!0;const r=i.isInterleavedBufferAttribute?i.data.uuid:i.id;if(e[t]!==r)return!0}for(const{node:e}of this.getNodeBuilderState().nodeAttributes)if(e&&e.attribute){const t=e.getObjectAttribute(this.object);if(t&&!1===this.attributes.includes(t))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)),DT[0]=e,DT[1]=this.camera.isArrayCamera?this.camera.cameras.length:0,DT[2]=this.object.receiveShadow?1:0,DT[3]=this.renderer.contextNode.id,DT[4]=this.renderer.contextNode.version,hc(DT)}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.object.removeEventListener("dispose",this.onObjectDispose),this.material.removeEventListener("dispose",this.onMaterialDispose),this.geometry.removeEventListener("dispose",this.onGeometryDispose),this.lightsNode.removeEventListener("dispose",this.onLightsNodeDispose),null!==this._sourceMaterial&&this._sourceMaterial.removeEventListener("dispose",this.onMaterialDispose),this.onDispose()}}const OT=[null,null,null,null],BT=[null,null,null,null,null];class kT{constructor(e,t,i,r,n,s){this.renderer=e,this.nodes=t,this.geometries=i,this.pipelines=r,this.bindings=n,this.info=s,this._chainMaps={},this._renderObjects=new Set}get(e,t,i,r,n,s,a,o){const l=this.getChainMap(o),u=this.renderer._currentSourceMaterial,c=null!==u?u.version:0,h=null!==u?BT:OT;h[0]=e,h[1]=t,h[2]=s,h[3]=n,null!==u&&(h[4]=u);let d=l.get(h);if(void 0===d)d=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,i,r,n,s,a,o),l.set(h,d);else{let l=!1;d.camera=r,d.updateClipping(a),d.needsGeometryUpdate&&(d.setGeometry(e.geometry),d.initialGeometryCacheKey!==d.getGeometryCacheKey()&&(l=!0)),(d.version!==t.version||d.sourceMaterialVersion!==c||d.needsUpdate||l)&&(d.initialCacheKey!==d.getCacheKey()?(d.dispose(),d=this.get(e,t,i,r,n,s,a,o)):(d.version=t.version,d.sourceMaterialVersion=c))}return h[0]=null,h[1]=null,h[2]=null,h[3]=null,null!==u&&(h[4]=null),d}getChainMap(e="default"){return this._chainMaps[e]||(this._chainMaps[e]=new jy)}dispose(){for(const e of this._renderObjects)e.dispose();this._renderObjects.clear(),this._chainMaps={}}createRenderObject(e,t,i,r,n,s,a,o,l,u,c){const h=this.getChainMap(c),d=new FT(e,t,i,r,n,s,a,o,l,u);return d.onDispose=()=>{this.geometries.deleteVertexState(d),this.pipelines.delete(d),this.bindings.deleteForRender(d),this.nodes.delete(d),h.delete(d.getChainArray()),this._renderObjects.delete(d)},this._renderObjects.add(d),d}}class zT{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 GT=1,VT=2,HT=3,WT=4,jT=16;let $T=0;class XT extends zT{constructor(e,t){super(),this.backend=e,this.info=t,this._tracked=new Set,this._registry=new FinalizationRegistry(e=>this._tracked.delete(e)),this.disposeVersion=0}delete(e){const t=super.delete(e);return null!==t&&(this.disposeVersion++,!0===e.isBufferAttribute&&(e.removeEventListener("dispose",t.onDispose),this._tracked.delete(t.ref),this._registry.unregister(t.ref)),this.backend.destroyAttribute(e),this.info.destroyAttribute(e)),t}update(e,t){const i=this.get(e);void 0===i.version?(t===GT?(this.backend.createAttribute(e),this.info.createAttribute(e)):t===VT?(this.backend.createIndexAttribute(e),this.info.createIndexAttribute(e)):t===HT?(this.backend.createStorageAttribute(e),this.info.createStorageAttribute(e)):t===WT&&(this.backend.createIndirectStorageAttribute(e),this.info.createIndirectStorageAttribute(e)),i.version=e.version,i.generation=$T++,!0===e.isBufferAttribute&&(i.onDispose=()=>{this.delete(e)},e.addEventListener("dispose",i.onDispose),i.ref=new WeakRef(e),this._tracked.add(i.ref),this._registry.register(e,i.ref,i.ref))):(i.version<e.version||e.usage===oi)&&(this.backend.updateAttribute(e),i.version=e.version)}dispose(){for(const e of this._tracked){const t=e.deref();void 0!==t&&!1!==this.has(t)&&this.delete(t)}this._tracked.clear(),super.dispose()}}function qT(e){return null!==e.index?e.index.version:e.attributes.position.version}function YT(e){return null!==e.index?e.index.id:e.attributes.position.id}function KT(e){const t=e.index,i=e.attributes.position,r=null!==t?t.array.length:i.array.length/3-1,n=new(i.count>=65535?On:Fn)(6*Math.ceil(r/3),1),s=n.array;if(null!==t){const e=t.array;for(let t=0,i=0;t<r;t+=3){const r=e[t+0],n=e[t+1],a=e[t+2];s[i++]=r,s[i++]=n,s[i++]=n,s[i++]=a,s[i++]=a,s[i++]=r}}else for(let e=0,t=0;e<r;e+=3){const i=e+0,r=e+1,n=e+2;s[t++]=i,s[t++]=r,s[t++]=r,s[t++]=n,s[t++]=n,s[t++]=i}return n.version=qT(e),n.__id=YT(e),n}class ZT extends zT{constructor(e,t,i){super(),this.backend=e,this.attributes=t,this.info=i,this.wireframes=new WeakMap,this.attributeCall=new WeakMap,this._tracked=new Set,this._registry=new FinalizationRegistry(e=>this._tracked.delete(e))}has(e){return super.has(e)&&!0===this.get(e).initialized}updateForRender(e){const t=e.geometry;!1===this.has(t)&&this.initGeometry(t),this.updateAttributes(e)}initGeometry(e){const t=this.get(e);t.initialized=!0,this.info.memory.geometries++,t.onDispose=()=>{this.info.memory.geometries--;const i=e.index;null!==i&&this.attributes.delete(i);for(const t of Object.values(e.attributes))this.attributes.delete(this.backend.getBufferAttribute(t));const r=this.wireframes.get(e);void 0!==r&&this.attributes.delete(r),e.removeEventListener("dispose",t.onDispose),this._tracked.delete(t.ref),this._registry.unregister(t.ref),this.delete(e)},e.addEventListener("dispose",t.onDispose),t.ref=new WeakRef(e),this._tracked.add(t.ref),this._registry.register(e,t.ref,t.ref)}updateAttributes(e){const t=e.getAttributes();for(const e of t)e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute?this.updateAttribute(e,HT):this.updateAttribute(e,GT);const i=this.getIndex(e);null!==i&&this.updateAttribute(i,VT);const r=e.geometry.indirect;null!==r&&this.updateAttribute(r,WT)}updateAttribute(e,t){const i=this.info.render.calls,r=this.backend.getBufferAttribute(e);this.attributeCall.get(r)!==i&&(this.attributes.update(r,t),this.attributeCall.set(r,i))}getIndirect(e){return e.geometry.indirect}getIndirectOffset(e){return e.geometry.indirectOffset}getIndex(e){const{geometry:t,material:i}=e;let r=t.index;if(!0===i.wireframe){const e=this.wireframes;let i=e.get(t);void 0===i?(i=KT(t),e.set(t,i)):i.version===qT(t)&&i.__id===YT(t)||(this.attributes.delete(i),i=KT(t),e.set(t,i)),r=i}return r}deleteNodeAttributes(e){const t=new Set(Object.values(e.geometry.attributes));for(const i of e.getAttributes())!1===t.has(i)&&this.attributes.delete(this.backend.getBufferAttribute(i))}deleteVertexState(e){this.backend.deleteVertexState(e)}dispose(){for(const e of this._tracked){const t=e.deref();if(void 0===t)continue;this.get(t).onDispose()}this._tracked.clear(),super.dispose()}}class QT{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,frameCalls:0,drawCalls:0,triangles:0,points:0,lines:0,timestamp:0},this.compute={calls:0,frameCalls:0,timestamp:0},this.memory={attributes:0,attributesSize:0,geometries:0,indexAttributes:0,indexAttributesSize:0,indirectStorageAttributes:0,indirectStorageAttributesSize:0,programs:0,programsSize:0,readbackBuffers:0,readbackBuffersSize:0,renderTargets:0,storageAttributes:0,storageAttributesSize:0,textures:0,texturesSize:0,uniformBuffers:0,uniformBuffersSize:0,total:0},this.memoryMap=new WeakMap}update(e,t,i){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=i*(t/3):e.isPoints?this.render.points+=i*t:e.isLineSegments?this.render.lines+=i*(t/2):e.isLine?this.render.lines+=i*(t-1):Mi("WebGPUInfo: Unknown object type.")}reset(){this.render.drawCalls=0,this.render.frameCalls=0,this.compute.frameCalls=0,this.render.triangles=0,this.render.points=0,this.render.lines=0}dispose(){this.reset(),this.calls=0,this.render.calls=0,this.compute.calls=0,this.render.timestamp=0,this.compute.timestamp=0;for(const e in this.memory)this.memory[e]=0;this.memoryMap=new WeakMap}createTexture(e){const t=this._getTextureMemorySize(e);this.memoryMap.set(e,t),this.memory.textures++,this.memory.total+=t,this.memory.texturesSize+=t}destroyTexture(e){const t=this.memoryMap.get(e)||0;this.memoryMap.delete(e),this.memory.textures--,this.memory.total-=t,this.memory.texturesSize-=t}_createAttribute(e,t){const i=this._getAttributeMemorySize(e);this.memoryMap.set(e,{size:i,type:t}),this.memory[t]++,this.memory.total+=i,this.memory[t+"Size"]+=i}createAttribute(e){this._createAttribute(e,"attributes")}createIndexAttribute(e){this._createAttribute(e,"indexAttributes")}createStorageAttribute(e){this._createAttribute(e,"storageAttributes")}createIndirectStorageAttribute(e){this._createAttribute(e,"indirectStorageAttributes")}destroyAttribute(e){const t=this.memoryMap.get(e);t&&(this.memoryMap.delete(e),this.memory[t.type]--,this.memory.total-=t.size,this.memory[t.type+"Size"]-=t.size)}createReadbackBuffer(e){const t=e.maxByteLength;this.memoryMap.set(e,{size:t,type:"readbackBuffers"}),this.memory.readbackBuffers++,this.memory.total+=t,this.memory.readbackBuffersSize+=t}destroyReadbackBuffer(e){const{size:t}=this.memoryMap.get(e);this.memoryMap.delete(e),this.memory.readbackBuffers--,this.memory.total-=t,this.memory.readbackBuffersSize-=t}createUniformBuffer(e){const t=e.byteLength;this.memoryMap.set(e,{size:t,type:"uniformBuffers"}),this.memory.uniformBuffers++,this.memory.total+=t,this.memory.uniformBuffersSize+=t}destroyUniformBuffer(e){const t=this.memoryMap.get(e);t&&(this.memoryMap.delete(e),this.memory.uniformBuffers--,this.memory.total-=t.size,this.memory.uniformBuffersSize-=t.size)}createProgram(e){const t=e.code.length;this.memoryMap.set(e,t),this.memory.programs++,this.memory.total+=t,this.memory.programsSize+=t}destroyProgram(e){const t=this.memoryMap.get(e)||0;this.memoryMap.delete(e),this.memory.programs--,this.memory.total-=t,this.memory.programsSize-=t}_getTextureMemorySize(e){if(e.isCompressedTexture)return 1;let t=1;e.type===Ge||e.type===ze?t=1:e.type===Ve||e.type===He||e.type===Xe?t=2:e.type!==We&&e.type!==je&&e.type!==$e||(t=4);let i=4;e.format===Je||e.format===nt||e.format===st||e.format===it||e.format===rt?i=1:e.format===at||e.format===ot?i=2:e.format!==et&&e.format!==lt||(i=3);let r=t*i;e.type===qe||e.type===Ye?r=2:e.type!==Ke&&e.type!==Ze&&e.type!==Qe||(r=4);const n=e.width||1,s=e.height||1,a=e.isCubeTexture?6:e.depth||1;let o=n*s*a*r;const l=e.mipmaps;if(l.length>0){let e=0;for(let t=0;t<l.length;t++){const i=l[t];if(i.data)e+=i.data.byteLength;else{e+=(i.width||Math.max(1,n>>t))*(i.height||Math.max(1,s>>t))*a*r}}o+=e}else e.generateMipmaps&&(o*=1.333);return Math.round(o)}_getAttributeMemorySize(e){return e.isInterleavedBufferAttribute&&(e=e.data),e.array?e.array.byteLength:e.count&&e.itemSize?e.count*e.itemSize*4:0}}class JT{constructor(e){this.cacheKey=e,this.usedTimes=0}}class eM extends JT{constructor(e,t,i){super(e),this.vertexProgram=t,this.fragmentProgram=i}}class tM extends JT{constructor(e,t,i=null,r=null){super(e),this.computeProgram=t,this.transforms=i,this.attributes=r,this.isComputePipeline=!0}}let iM=0;class rM{constructor(e,t,i){this.id=iM++,this.code=e,this.stage=t,this.name=i,this.usedTimes=0}}class nM extends zT{constructor(e,t,i){super(),this.backend=e,this.nodes=t,this.info=i,this.bindings=null,this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}getForCompute(e,t,i=null){const{backend:r}=this,n=this.get(e);if(this._needsComputeUpdate(e)){const s=n.pipeline;s&&(s.usedTimes--,s.computeProgram.usedTimes--);const a=this.nodes.getForCompute(e);let o=this.programs.compute.get(a.computeShader);void 0===o&&(o=new rM(a.computeShader,"compute",e.name),this.programs.compute.set(a.computeShader,o),r.createProgram(o),this.info.createProgram(o));const l=this._getComputeCacheKey(e,o);let u=this.caches.get(l);void 0===u&&(u=this._getComputePipeline(e,o,l,t,i)),u.usedTimes++,o.usedTimes++,s&&(0===s.usedTimes&&this._releasePipeline(s),0===s.computeProgram.usedTimes&&this._releaseProgram(s.computeProgram)),n.version=e.version,n.pipeline=u}return n.pipeline}getForRender(e,t=null){const{backend:i}=this,r=this.get(e);if(this._needsRenderUpdate(e)){const n=r.pipeline;n&&(n.usedTimes--,n.vertexProgram.usedTimes--,n.fragmentProgram.usedTimes--);const s=e.getNodeBuilderState(),a=e.material?e.material.name:"";let o=this.programs.vertex.get(s.vertexShader);void 0===o&&(o=new rM(s.vertexShader,"vertex",a),this.programs.vertex.set(s.vertexShader,o),i.createProgram(o),this.info.createProgram(o));let l=this.programs.fragment.get(s.fragmentShader);void 0===l&&(l=new rM(s.fragmentShader,"fragment",a),this.programs.fragment.set(s.fragmentShader,l),i.createProgram(l),this.info.createProgram(l));const u=this._getRenderCacheKey(e,o,l);let c=this.caches.get(u);void 0===c?c=this._getRenderPipeline(e,o,l,u,t):e.pipeline=c,c.usedTimes++,o.usedTimes++,l.usedTimes++,n&&(0===n.usedTimes&&this._releasePipeline(n),0===n.vertexProgram.usedTimes&&this._releaseProgram(n.vertexProgram),0===n.fragmentProgram.usedTimes&&this._releaseProgram(n.fragmentProgram)),r.pipeline=c}return r.pipeline}isReady(e){const t=this.get(e).pipeline;if(void 0===t)return!1;const i=this.backend.get(t);return void 0!==i.pipeline&&null!==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,i,r,n){i=i||this._getComputeCacheKey(e,t);let s=this.caches.get(i);if(void 0===s){const{transforms:a,nodeAttributes:o}=this.nodes.getForCompute(e);s=new tM(i,t,a,o),this.caches.set(i,s),this.backend.createComputePipeline(s,r,n)}return s}_getRenderPipeline(e,t,i,r,n){r=r||this._getRenderCacheKey(e,t,i);let s=this.caches.get(r);return void 0===s&&(s=new eM(r,t,i),this.caches.set(r,s),e.pipeline=s,this.backend.createRenderPipeline(e,n)),s}_getComputeCacheKey(e,t){return e.id+","+t.id}_getRenderCacheKey(e,t,i){return t.id+","+i.id+","+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.backend.destroyPipeline(e),this.caches.delete(e.cacheKey)}_releaseProgram(e){const t=e.code,i=e.stage;this.programs[i].delete(t),this.backend.destroyProgram(e),this.info.destroyProgram(e)}_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)}}const sM=[];class aM extends zT{constructor(e,t,i,r,n,s){super(),this.backend=e,this.textures=i,this.pipelines=n,this.attributes=r,this.nodes=t,this.info=s,this._sharedBindGroups=new WeakMap,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings(),i=this.get(e);return!0!==i.initialized&&(this._createBindings(t),i.initialized=!0),t}getForCompute(e){const t=this.nodes.getForCompute(e).bindings,i=this.get(e);return!0===i.initialized&&i.bindings===t||(void 0!==i.bindings&&this._destroyBindings(i.bindings),this._createBindings(t),i.initialized=!0,i.bindings=t),t}getSharedBindGroup(e,t=null){if(null===t){const e=this.backend.renderer;t=e._currentRenderContext||e}let i="";for(const t of e.bindings)if(t.isNodeUniformsGroup){t.uniforms.sort((e,t)=>e.nodeUniform.node.id-t.nodeUniform.node.id);for(const e of t.uniforms)i+=e.nodeUniform.node.id+","}else i+=t.nodeUniform.id+",";const r=cc(i);let n=this._sharedBindGroups.get(t);void 0===n&&(n=new Map,this._sharedBindGroups.set(t,n));let s=n.get(r);if(void 0===s){s=this.has(e)?e.clone():e,n.set(r,s);const i=this.get(s);i.renderContext=t,i.cacheKey=r}return s}updateForCompute(e){this._updateBindings(this.getForCompute(e))}updateForRender(e){this._updateBindings(this.getForRender(e))}updateSharedForRender(e){const t=this.getForRender(e);for(const e of t)for(const t of e.bindings)if((!0===t.isNodeUniformsGroup||!0===t.isNodeUniformBuffer)&&!0===t.groupNode.shared){if(!1===this.nodes.updateGroup(t))continue;t.update()&&this.backend.updateBinding(t),t.updateRanges.length>0&&t.clearUpdateRanges()}}deleteForCompute(e){const t=this.get(e).bindings||this.nodes.getForCompute(e).bindings;this._destroyBindings(t),this.delete(e)}deleteForRender(e){const t=e.getBindings();this._destroyBindings(t),this.delete(e)}_createBindings(e){for(const t of e){const i=this.get(t);if(void 0===i.bindGroup){for(const e of t.bindings)if(e.isUniformBuffer)this.backend.createUniformBuffer(e),this.info.createUniformBuffer(e);else if(e.isSampledTexture)e.generation=this.textures.updateTexture(e.texture);else if(e.isSampler)e.samplerKey=this.textures.updateSampler(e);else if(e.isStorageBuffer){const t=e.attribute,i=t.isIndirectStorageBufferAttribute?WT:HT;this.attributes.update(t,i)}this.backend.createBindings(t,e,""),i.bindGroup=t,i.usedTimes=1}else i.usedTimes++}}_destroyBindings(e){for(const t of e){const e=this.get(t);if(e.usedTimes--,0===e.usedTimes){for(const e of t.bindings)if(e.isUniformBuffer)this.backend.destroyUniformBuffer(e),this.info.destroyUniformBuffer(e),e.release();else if(e.isSampler){if(!0!==e.isSampledTexture)this.backend.destroySampler(e);else if(null!==e.texture){const i=this.textures.get(e.texture);void 0!==i.bindGroups&&i.bindGroups.delete(t)}e.release()}if(void 0!==e.cacheKey){this._sharedBindGroups.get(e.renderContext).delete(e.cacheKey)}this.backend.deleteBindGroupData(t),this.delete(t)}}}_updateBindings(e){for(const t of e)this._update(t,e)}_update(e,t){const{backend:i}=this;let r=!1,n=!0,s=0,a=0;for(const t of e.bindings){if(!1!==this.nodes.updateGroup(t)){if(t.isStorageBuffer){const e=t.attribute,n=e.isIndirectStorageBufferAttribute?WT:HT,o=i.get(t);this.attributes.update(e,n);const l=this.attributes.get(e).generation;o.attribute===e&&o.generation===l||(o.attribute=e,o.generation=l,r=!0),sM[s++]=e.id,a+=l}if(t.isUniformBuffer){t.update()&&i.updateBinding(t)}else if(t.isSampledTexture){const o=t.update(),l=t.texture,u=this.textures.get(l);if(o){const i=this.textures.updateTexture(l);t.generation!==i&&(t.generation=i,r=!0),u.bindGroups.add(e)}if(void 0!==i.get(l).externalTexture||u.isDefaultTexture?n=!1:(sM[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);t.samplerKey!==e&&(t.samplerKey=e,r=!0)}}t.isBuffer&&t.updateRanges.length>0&&t.clearUpdateRanges()}}if(!0===r){sM.length=s;const i=n?sM.join(","):"";this.backend.updateBindings(e,t,i,a)}}}const oM=Object.freeze([]);function lM(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 uM(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 cM(e){return(e.transmission>0||e.transmissionNode&&e.transmissionNode.isNode)&&2===e.side&&!1===e.forceSinglePass}class hM{constructor(e,t,i){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparentDoublePass=[],this.transparent=[],this.bundles=[],this.lighting=e,this.lightsNode=e.getNode(t),this.lightsArray=[],this.scene=t,this.camera=i,this.occlusionQueryCount=0,this.frameId=-1,this._lastOcclusionObject=null}begin(){return this.renderItemsIndex=0,this.opaque.length=0,this.transparentDoublePass.length=0,this.transparent.length=0,this.bundles.length=0,this.lightsArray.length=0,this.occlusionQueryCount=0,this}getNextRenderItem(e,t,i,r,n,s,a){let o=this.renderItems[this.renderItemsIndex];return void 0===o?(o={id:e.id,object:e,geometry:t,material:i,groupOrder:r,renderOrder:e.renderOrder,z:n,group:s,clippingContext:a},this.renderItems[this.renderItemsIndex]=o):(o.id=e.id,o.object=e,o.geometry=t,o.material=i,o.groupOrder=r,o.renderOrder=e.renderOrder,o.z=n,o.group=s,o.clippingContext=a),this.renderItemsIndex++,o}push(e,t,i,r,n,s,a){!0===this.camera.reversedDepth&&(n=-n);const o=this.getNextRenderItem(e,t,i,r,n,s,a);!0===e.occlusionTest&&this._lastOcclusionObject!==e&&(this.occlusionQueryCount++,this._lastOcclusionObject=e),!0===i.transparent||i.transmission>0||i.transmissionNode&&i.transmissionNode.isNode||i.backdropNode&&i.backdropNode.isNode?(cM(i)&&this.transparentDoublePass.push(o),this.transparent.push(o)):this.opaque.push(o)}unshift(e,t,i,r,n,s,a){const o=this.getNextRenderItem(e,t,i,r,n,s,a);!0===i.transparent||i.transmission>0||i.transmissionNode&&i.transmissionNode.isNode||i.backdropNode&&i.backdropNode.isNode?(cM(i)&&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||lM),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||uM),this.transparent.length>1&&this.transparent.sort(t||uM)}finish(){this.lightsNode.setLights(this.lighting.enabled?this.lightsArray:oM);for(let e=this.renderItemsIndex,t=this.renderItems.length;e<t;e++){const t=this.renderItems[e];if(null===t.id)break;dM(t)}this._lastOcclusionObject=null}clear(){for(let e=0,t=this.renderItems.length;e<t;e++){const t=this.renderItems[e];if(null===t.id)break;dM(t)}this.opaque.length=0,this.transparentDoublePass.length=0,this.transparent.length=0,this.bundles.length=0}}function dM(e){e.id=null,e.object=null,e.geometry=null,e.material=null,e.groupOrder=null,e.renderOrder=null,e.z=null,e.group=null,e.clippingContext=null}const pM=[];class fM{constructor(){this.lists=new jy,this._activeLists=new Set,this._frameId=-1}get(e,t,i){const r=this.lists;pM[0]=e,pM[1]=t,pM[2]=i;let n=r.get(pM);return void 0===n&&(n=new hM(i,e,t),r.set(pM,n)),pM[0]=null,pM[1]=null,pM[2]=null,n.frameId=this._frameId,this._activeLists.add(n),n}update(e){if(e!==this._frameId){this._frameId=e;for(const t of this._activeLists)e-t.frameId>10&&(t.clear(),this._activeLists.delete(t))}}dispose(){this.lists=new jy,this._activeLists.clear(),this._frameId=-1}}let mM=0;class gM{constructor(){this.id=mM++,this.stateKey="",this.frustumArray=null,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 ur,this.scissor=!1,this.scissorValue=new ur,this.renderTarget=null,this.textures=null,this.depthTexture=null,this.activeCubeFace=0,this.activeMipmapLevel=0,this.sampleCount=1,this.width=0,this.height=0,this.occlusionQueryCount=0,this.clippingContext=null,this.camera=null,this.fullscreenPass=!1,this.isRenderContext=!0}getCacheKey(){return _M(this)}}function _M(e){const{textures:t,activeCubeFace:i,activeMipmapLevel:r}=e,n=[i,r];for(const e of t)n.push(e.id);return hc(n)}class vM{constructor(e){this.renderer=e,this._renderContexts={}}get(e=null,t=null,i=0,r=null){let n;if(null===e)n="default";else{const t=e.texture?.format,i=e.texture?.type;n=`${e.textures.length}:${t}:${i}:${e.samples}:${e.depthBuffer}:${e.stencilBuffer}`}const s=n+"-"+(null!==t?t.id:"default")+"-"+(!0===r?.isOrthographicCamera?"orthographic":"perspective"),a=s+"-"+i;let o=this._renderContexts[a];return void 0===o&&(o=new gM,o.mrt=t,o.stateKey=s,this._renderContexts[a]=o),null!==e&&(o.sampleCount=0===e.samples?1:e.samples),o.clearDepthValue=this.renderer.getClearDepth(),o.clearStencilValue=this.renderer.getClearStencil(),o}dispose(){this._renderContexts={}}}const bM=new Wi;function yM(e){return!0===e.isCompressedCubeTexture?e.image[0].mipmaps:e.mipmaps}class xM extends zT{constructor(e,t,i){super(),this.renderer=e,this.backend=t,this.info=i,this._htmlTextures=new Set,this._tracked=new Set,this._registry=new FinalizationRegistry(e=>this._tracked.delete(e))}dispose(){for(const e of this._tracked){const t=e.deref();void 0!==t&&!1!==this.has(t)&&(!0===t.isRenderTarget?this._destroyRenderTarget(t):this._destroyTexture(t))}this._tracked.clear(),this._htmlTextures.clear(),super.dispose()}updateRenderTarget(e,t=0){const i=this.get(e),r=0===e.samples?1:e.samples,n=i.depthTextureMips||(i.depthTextureMips={}),s=e.textures,a=this.getSize(s.length>0?s[0]:e.depthTexture),o=a.width>>t,l=a.height>>t;let u=e.depthTexture||n[t];const c=!0===e.depthBuffer||!0===e.stencilBuffer;let h=!1;const d=void 0!==u&&void 0!==u.image&&u.image.depth>1,p=a.depth>1&&(e.useArrayDepthTexture||e.multiview||d);void 0===u&&c&&(u=new Ys,u.format=e.stencilBuffer?rt:it,u.type=!0===this.renderer.reversedDepthBuffer?$e:e.stencilBuffer?Ke:je,u.image.width=o,u.image.height=l,u.image.depth=a.depth,u.renderTarget=e,n[t]=u),u&&(u.isArrayTexture=p),i.width===a.width&&a.height===i.height||(h=!0,u&&u.renderTarget===e&&(u.needsUpdate=!0,u.image.width=o,u.image.height=l,u.image.depth=p?a.depth:1)),i.width=a.width,i.height=a.height,i.textures=s,i.depthTexture=u||null,i.depth=e.depthBuffer,i.stencil=e.stencilBuffer,i.renderTarget=e,i.sampleCount!==r&&(h=!0,u&&u.renderTarget===e&&(u.needsUpdate=!0),i.sampleCount=r),!0!==i.initialized&&(i.initialized=!0,this.info.memory.renderTargets++,i.onDispose=()=>{this._destroyRenderTarget(e)},e.addEventListener("dispose",i.onDispose),i.ref=new WeakRef(e),this._tracked.add(i.ref),this._registry.register(e,i.ref,i.ref));const f={sampleCount:r};if(!0!==e.isXRRenderTarget){for(let e=0;e<s.length;e++){const t=s[e];h&&(t.needsUpdate=!0),this.updateTexture(t,f)}u&&this.updateTexture(u,f)}}updateTexture(e,t={}){const i=this.get(e);if(!0===i.initialized&&i.version===e.version)return i.generation;const r=e.isRenderTargetTexture||e.isDepthTexture?e.renderTarget:null;if(null!==r&&!0!==this.get(r).initialized)return this.updateRenderTarget(r),i.generation;const n=e.isRenderTargetTexture||e.isDepthTexture||e.isFramebufferTexture,s=this.backend;if(n&&!0===i.initialized&&s.destroyTexture(e),e.isFramebufferTexture){const t=this.renderer.getRenderTarget();e.type=t?t.texture.type:ze}if(e.isHTMLTexture&&e.image){const t=this.renderer.domElement;if("requestPaint"in t){if(t.hasAttribute("layoutsubtree")||t.setAttribute("layoutsubtree","true"),e.image.parentNode!==t&&t.appendChild(e.image),0===this._htmlTextures.size){const e=this._htmlTextures;t.onpaint=t=>{const i=t&&t.changedElements;for(const t of e)i&&!i.includes(t.image)||(t.needsUpdate=!0)}}this._htmlTextures.add(e)}}const{width:a,height:o,depth:l}=this.getSize(e);if(t.width=a,t.height=o,t.depth=l,t.needsMipmaps=this.needsMipmaps(e),t.levels=t.needsMipmaps?this.getMipLevels(e,a,o):1,e.isCubeTexture&&e.mipmaps.length>0&&!n&&t.levels++,n||!0===e.isStorageTexture||!0===e.isExternalTexture)s.createTexture(e,t),i.generation=e.version;else if(e.version>0){const r=e.image;if(void 0===r)Ti("Renderer: Texture marked for update but image is undefined.");else if(!1===r.complete)Ti("Renderer: Texture marked for update but image is incomplete.");else{if(e.images){const i=[];for(const t of e.images)i.push(t);t.images=i}else t.image=r;void 0!==i.isDefaultTexture&&!0!==i.isDefaultTexture||(s.createTexture(e,t),i.isDefaultTexture=!1,i.generation=e.version),!0===e.source.dataReady&&(s.updateTexture(e,t),e.clearUpdateRanges()),t.needsMipmaps&&0===yM(e).length&&!0===e.mipmapsAutoUpdate&&s.generateMipmaps(e),e.onUpdate&&e.onUpdate(e)}}else s.createDefaultTexture(e),i.isDefaultTexture=!0,i.generation=e.version;return!0!==i.initialized&&(i.initialized=!0,i.generation=e.version,i.bindGroups=new Set,this.info.createTexture(e),e.isVideoTexture&&!0===Qi.enabled&&Qi.getTransfer(e.colorSpace)!==Kt&&Ti("WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace."),!0!==e.isRenderTargetTexture&&(i.onDispose=()=>{this._destroyTexture(e)},e.addEventListener("dispose",i.onDispose)),i.ref=new WeakRef(e),this._tracked.add(i.ref),this._registry.register(e,i.ref,i.ref)),i.version=e.version,i.generation}updateSampler(e){return this.backend.updateSampler(e)}getSize(e,t=bM){let i=e.images?e.images[0]:e.image;return!0===e.isCompressedCubeTexture&&(i=i[0]),i?(void 0!==i.image&&(i=i.image),e.isHTMLTexture?(t.width=i.offsetWidth||1,t.height=i.offsetHeight||1,t.depth=1):"undefined"!=typeof HTMLVideoElement&&i instanceof HTMLVideoElement?(t.width=i.videoWidth||1,t.height=i.videoHeight||1,t.depth=1):"undefined"!=typeof VideoFrame&&i instanceof VideoFrame?(t.width=i.displayWidth||1,t.height=i.displayHeight||1,t.depth=1):(t.width=i.width||1,t.height=i.height||1,t.depth=e.isCubeTexture?6:i.depth||1)):t.width=t.height=t.depth=1,t}getMipLevels(e,t,i){let r;const n=yM(e);return r=n.length>0?n.length:!0===e.isCompressedTexture?1:Math.floor(Math.log2(Math.max(t,i)))+1,r}needsMipmaps(e){return!0===e.generateMipmaps||yM(e).length>0}_destroyRenderTarget(e){if(!0===this.has(e)){const t=this.get(e),i=t.textures,r=t.depthTexture;e.removeEventListener("dispose",t.onDispose),this._tracked.delete(t.ref),this._registry.unregister(t.ref);for(let e=0;e<i.length;e++)this._destroyTexture(i[e]);r&&r.renderTarget===e&&this._destroyTexture(r),this.delete(e),this.backend.delete(e),this.info.memory.renderTargets--}}_destroyTexture(e){if(!0===this.has(e)){const t=this.get(e);e.removeEventListener("dispose",t.onDispose),this._tracked.delete(t.ref),this._registry.unregister(t.ref);const i=t.isDefaultTexture;if(this.backend.destroyTexture(e,i),t.bindGroups)for(const i of t.bindGroups){const t=this.backend.get(i);t.groups=void 0,t.versions=void 0;for(const t of i.bindings)t.isSampler&&t.texture===e&&(!0!==t.isSampledTexture&&this.backend.destroySampler(t),t.reset(),t.release())}this._htmlTextures.delete(e),this.delete(e),this.info.destroyTexture(e)}}}const SM=new Sm;class TM extends zT{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,i){const r=this.renderer,n=this.nodes.getBackgroundNode(e)||e.background;let s=!1;if(null===n)r._clearColor.getRGB(SM),SM.a=r._clearColor.a;else if(!0===n.isColor)n.getRGB(SM),SM.a=1,s=!0;else if(!0===n.isNode){const o=this.get(e),l=n;SM.copy(r._clearColor);let u=o.backgroundMesh;if(void 0===u){const h=Oh(l).mul(fy).context({getUV:()=>my.mul(Lg),getTextureLevel:()=>py}),d=eg.element(3).element(3).equal(1),p=Gd(1,eg.element(1).element(1)).mul(3),f=d.select(gg.mul(p),gg),m=cg.mul(Oh(f,0));let g=eg.mul(Oh(m.xyz,1));g=g.setZ(g.w);const _=new Jb;function v(){n.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 ws(new ta(1,32,32),_),u.frustumCulled=!1,u.name="Background.mesh",n.addEventListener("dispose",v)}const c=l.getCacheKey();o.backgroundCacheKey!==c&&(o.backgroundMeshNode.node=Oh(l).mul(fy),o.backgroundMeshNode.needsUpdate=!0,u.material.needsUpdate=!0,o.backgroundCacheKey=c),t.unshift(u,u.geometry,u.material,0,0,null,null)}else Mi("Renderer: Unsupported background configuration.",n);const a=r.xr.getEnvironmentBlendMode();if("additive"===a?SM.set(0,0,0,1):"alpha-blend"===a&&SM.set(0,0,0,0),!0===r.autoClear||!0===s){const b=i.clearColorValue;b.r=SM.r,b.g=SM.g,b.b=SM.b,b.a=SM.a,!0!==r.backend.isWebGLBackend&&!0!==r.alpha||(b.r*=b.a,b.g*=b.a,b.b*=b.a),i.depthClearValue=r.getClearDepth(),i.stencilClearValue=r.getClearStencil(),i.clearColor=!0===r.autoClearColor,i.clearDepth=!0===r.autoClearDepth,i.clearStencil=!0===r.autoClearStencil}else i.clearColor=!1,i.clearDepth=!1,i.clearStencil=!1}}let MM=0;class EM{constructor(e="",t=[]){this.name=e,this.bindings=t,this.id=MM++}clone(){return new EM(this.name,this.bindings.map(e=>e.clone()))}}class wM{constructor(e,t,i,r,n,s,a,o,l,u,c=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=i,this.transforms=c,this.nodeAttributes=r,this.bindings=n,this.updateNodes=s,this.updateBeforeNodes=a,this.updateAfterNodes=o,this.observer=l,this.hardwareClipping=u,this.usedTimes=0}createBindings(e,t){const i=[];for(const r of this.bindings){if(!0!==r.bindings[0].groupNode.shared){const e=new EM(r.name,[]);i.push(e);for(const t of r.bindings)e.bindings.push(t.clone())}else i.push(e.getSharedBindGroup(r,t))}return i}}class AM{constructor(e,t,i=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=i}}class RM{constructor(e,t,i){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=i}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 CM{constructor(e,t,i=!1,r=null,n=!1){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=i,this.local=n,this.count=r}}class NM extends CM{constructor(e,t,i=null,r=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=i,this.interpolationSampling=r}}class PM{constructor(e,t,i=""){this.name=e,this.type=t,this.code=i,Object.defineProperty(this,"isNodeCode",{value:!0})}}let LM=0;class DM{constructor(e=null){this.id=LM++,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 UM{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class IM{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 FM extends IM{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class OM extends IM{constructor(e,t=new Vi){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class BM extends IM{constructor(e,t=new Wi){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class kM extends IM{constructor(e,t=new ur){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class zM extends IM{constructor(e,t=new Yr){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class GM extends IM{constructor(e,t=new oo){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class VM extends IM{constructor(e,t=new Xi){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class HM extends IM{constructor(e,t=new fr){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class WM extends FM{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class jM extends OM{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class $M extends BM{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class XM extends kM{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class qM extends zM{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class YM extends GM{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class KM extends VM{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class ZM extends HM{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}let QM=0;const JM=new WeakMap,eE=new WeakMap,tE=(e,t)=>{const i={[Symbol.iterator](){let e=0;const t=Object.values(this);return{next:()=>({value:t[e],done:e++>=t.length})}}};return e.inputs.forEach((e,r)=>{i[e.name]=t[r]}),i},iE=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),rE=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0"),nE={bool:0,uint:1,int:2,float:3};class sE{constructor(){this.properties=void 0,this.type=void 0,this.typeFromOutput=void 0,this.buildStages=void 0,this.usageCount=void 0,this.readUsageCount=void 0,this.writeUsageCount=void 0,this.stack=void 0,this.stages=void 0,this.snippet=void 0,this.propertyName=void 0,this.generated=void 0,this.flowBlock=void 0,this.assign=void 0,this.forceDeclaration=void 0,this.variable=void 0,this.cacheVariable=void 0,this.uniform=void 0,this.subBuilds=void 0,this.subBuildsCache=void 0}}const aE=new Map,oE=new Map,lE=new Map,uE=new Map,cE=new Map,hE=e=>{if(e.writeUsageCount>0)return!0;if(void 0!==e.subBuildsCache)for(const t in e.subBuildsCache)if(hE(e.subBuildsCache[t]))return!0;return!1},dE=(e,t)=>{for(const i in e)if("nodeBlock"!==i&&"nodeLoop"!==i&&e[i]!==t[i])return!0;return!1};class pE{constructor(e,t,i){this.object=e,this.material=e&&e.material||null,this.geometry=e&&e.geometry||null,this.compute=null,this.renderer=t,this.parser=i,this.scene=null,this.camera=null,this.nodes=new Set,this.sequentialNodes=new Set,this.updateNodes=[],this.updateBeforeNodes=[],this.updateAfterNodes=[],this.hashNodes={},this.observer=null,this.lightsNode=null,this.environmentNode=null,this.fogNode=null,this.clippingContext=null,this.hardwareClipping=!1,this.objectSpecific=!1,this.vertexShader=null,this.fragmentShader=null,this.computeShader=null,this.flowNodes={vertex:[],fragment:[],compute:[]},this.flowCode={vertex:"",fragment:"",compute:""},this.uniforms={vertex:[],fragment:[],compute:[],index:0},this.structs={vertex:[],fragment:[],compute:[],index:0},this.types={vertex:[],fragment:[],compute:[],index:0},this.bindings={vertex:{},fragment:{},compute:{}},this.bindingsIndexes={},this.bindGroups=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.declarations={},this.flow={code:""},this.chaining=[],this.stack=xm(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new DM,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null,this.subBuildLayers=[],this.activeStacks=[],this.subBuildFn=null,this.fnCall=null,this.flowBlock=null,Object.defineProperty(this,"id",{value:QM++})}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,i){return new cr(e,t,i)}createCubeRenderTarget(e,t){return new Rx(e,t)}includes(e){return this.nodes.has(e)}getOutputType(e=0){const t=this.renderer.getRenderTarget();return null!==t&&void 0!==t.textures[e]?gc(t.textures[e]):"vec4"}getOutputStructName(){}_getBindGroup(e,t){const i=t[0].groupNode;let r=i.shared;if(r)for(let e=1;e<t.length;e++)i!==t[e].groupNode&&(r=!1);let n=new EM(e,t);return r&&void 0!==this.renderer._bindings&&(n=this.renderer._bindings.getSharedBindGroup(n)),n}getBindGroupArray(e,t){const i=this.bindings[t];let r=i[e];return void 0===r&&(void 0===this.bindingsIndexes[e]&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),i[e]=r=[]),r}getBindings(){let e=this.bindGroups;if(null===e){const t={},i=this.bindings;for(const e of sc)for(const r in i[e]){const n=i[e][r],s=t[r]||(t[r]=[]);for(const e of n)!1===s.includes(e)&&s.push(e)}e=[];for(const i in t){const r=t[i],n=this._getBindGroup(i,r);e.push(n)}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 i=e[t];this.bindingsIndexes[i.name].group=t}}setHashNode(e,t){this.hashNodes[t]=e}addNode(e){!1===this.nodes.has(e)&&(this.nodes.add(e),this.setHashNode(e,e.getHash(this)))}addSequentialNode(e){const t=e.updateBeforeType,i=e.updateAfterType;t===Zu&&i===Zu||this.sequentialNodes.add(e)}buildUpdateNodes(){for(const e of this.nodes){e.updateType!==Zu&&this.updateNodes.push(e)}for(const e of this.sequentialNodes){const t=e.updateBeforeType,i=e.updateAfterType;t!==Zu&&this.updateBeforeNodes.push(e),i!==Zu&&this.updateAfterNodes.push(e)}}get currentNode(){return this.chaining[this.chaining.length-1]}get renderPipeline(){return this.context.renderPipeline}isFilteredTexture(e){return e.magFilter===Oe||e.magFilter===Be||e.magFilter===Fe||e.magFilter===ke||e.minFilter===Oe||e.minFilter===Be||e.minFilter===Fe||e.minFilter===ke}getUniformBufferLimit(){return this.renderer.backend.capabilities.getUniformBufferLimit()}addChain(e){this.chaining.push(e)}removeChain(e){if(this.chaining.pop()!==e)throw new Error("THREE.NodeBuilder: Invalid node chaining!")}getMethod(e){return e}getTernary(){return null}getVectorSelect(e,t,i){return this.getTernary(e,t,i)}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(vc(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.getGI,delete e.getShadow,delete e.nodeLoop,delete e.nodeBlock,e}setCache(e){this.cache=e}getCache(){return this.cache}getCacheFromNode(e,t=!0){const i=this.getDataFromNode(e);return void 0===i.cache&&(i.cache=new DM(t?this.getCache():null)),i.cache}isAvailable(){return!1}getVertexIndex(){Ti("Abstract function.")}getInstanceIndex(){Ti("Abstract function.")}getDrawIndex(){Ti("Abstract function.")}getFrontFacing(){Ti("Abstract function.")}getFragCoord(){Ti("Abstract function.")}getSubgroupSize(){Ti("Abstract function.")}getInvocationSubgroupIndex(){Ti("Abstract function.")}getSubgroupIndex(){Ti("Abstract function.")}enableSubGroups(){Ti("Abstract function.")}enableShaderF16(){Ti("Abstract function.")}enableDualSourceBlending(){Ti("Abstract function.")}isFlipY(){return!1}isContextAssign(){return!0===this.context.assign}increaseUsage(e){const t=this.getDataFromNode(e);return t.usageCount=void 0===t.usageCount?1:t.usageCount+1,this.isContextAssign()?t.writeUsageCount=void 0===t.writeUsageCount?1:t.writeUsageCount+1:t.readUsageCount=void 0===t.readUsageCount?1:t.readUsageCount+1,t.usageCount}hasWriteUsage(e){const t=e.getShared(this),i=(t.isGlobal(this)?this.globalCache:this.cache).getData(t);if(void 0!==i)for(const e in i)if(hE(i[e]))return!0;return!1}generateTexture(){Ti("Abstract function.")}generateTextureLod(){Ti("Abstract function.")}generateTextureSize(){Ti("Abstract function.")}generateArrayDeclaration(e,t){return this.getType(e)+"[ "+t+" ]"}generateArray(e,t,i=null){let r=this.generateArrayDeclaration(e,t)+"( ";for(let n=0;n<t;n++){const s=i?i[n]:null;r+=null!==s?s.build(this,e):this.generateConst(e),n<t-1&&(r+=", ")}return r+=" )",r}generateStruct(e,t,i=null){const r=[];for(const e of t){const{name:t,type:n}=e;i&&i[t]&&i[t].isNode?r.push(i[t].build(this,n)):r.push(this.generateConst(n))}return e+"( "+r.join(", ")+" )"}generateConst(e,t=null){if(null===t&&("float"===e||"int"===e||"uint"===e?t=0:"bool"===e?t=!1:"color"===e?t=new Yr:"vec2"===e||"uvec2"===e||"ivec2"===e||"bvec2"===e?t=new Vi:"vec3"===e||"uvec3"===e||"ivec3"===e||"bvec3"===e?t=new Wi:"vec4"!==e&&"uvec4"!==e&&"ivec4"!==e&&"bvec4"!==e||(t=new ur)),"float"===e)return rE(t);if("int"===e)return`${Math.trunc(t)}`;if("uint"===e)return t>=0?`${Math.trunc(t)}u`:"0u";if("bool"===e)return t?"true":"false";if("color"===e)return`${this.getType("vec3")}( ${rE(t.r)}, ${rE(t.g)}, ${rE(t.b)} )`;const i=this.getTypeLength(e),r=this.getComponentType(e),n=e=>this.generateConst(r,e);if(2===i)return`${this.getType(e)}( ${n(t.x)}, ${n(t.y)} )`;if(3===i)return`${this.getType(e)}( ${n(t.x)}, ${n(t.y)}, ${n(t.z)} )`;if(4===i&&"mat2"!==e)return`${this.getType(e)}( ${n(t.x)}, ${n(t.y)}, ${n(t.z)}, ${n(t.w)} )`;if(i>=4&&t&&(t.isMatrix2||t.isMatrix3||t.isMatrix4))return`${this.getType(e)}( ${t.elements.map(n).join(", ")} )`;if(i>4)return`${this.getType(e)}()`;throw new Error(`THREE.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 i=this.attributes;for(const t of i)if(t.name===e)return t;const r=new AM(e,t);return this.registerDeclaration(r),i.push(r),r}getPropertyName(e){return e.name}isScalar(e){return"float"===e||"bool"===e||"int"===e||"uint"===e}isReservedKeyword(){return!1}isVector(e){let t=lE.get(e);return void 0===t&&lE.set(e,t=/vec\d/.test(e)),t}isMatrix(e){let t=uE.get(e);return void 0===t&&uE.set(e,t=/mat\d/.test(e)),t}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;return!0===e.isDepthTexture?"float":t===We?"int":t===je?"uint":"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;let t=aE.get(e);if(void 0===t){const i=/(b|i|u|)(vec|mat)([2-4])/.exec(e);t=null===i?null:"b"===i[1]?"bool":"i"===i[1]?"int":"u"===i[1]?"uint":"float",aE.set(e,t)}return t}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 i=fc(e);const r="float"===t?"":t[0];return!0===/mat2/.test(t)&&(i=i.replace("vec","mat")),r+i}getTypeFromArray(e){return iE.get(e.constructor)}isInteger(e){let t=cE.get(e);return void 0===t&&cE.set(e,t=/int|uint|(i|u)vec/.test(e)),t}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const i=t.array,r=e.itemSize,n=e.normalized;let s;return e instanceof Bn||!0===n||(s=this.getTypeFromArray(i)),this.getTypeFromLength(r,s)}getTypeLength(e){const t=this.getVectorType(e);let i=oE.get(t);return void 0===i&&(i=this._getTypeLength(t),oE.set(t,i)),i}_getTypeLength(e){const t=e,i=/vec([2-4])/.exec(t);return null!==i?Number(i[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)}getPromotedComponentType(...e){let t=null,i=!1,r=!0,n=!0;for(const s of e)if(null!==s)if(!0===s.isWeak){const e=Math.trunc(s.value);i=!0,r=r&&e>=0&&e<=4294967295,n=n&&e>=-2147483648&&e<=2147483647}else{const e=this.getComponentType(s.getNodeType(this));(null===t||nE[e]>nE[t])&&(t=e)}return null===t||"bool"===t&&i?"float":"uint"===t&&!1===r?n?"int":"float":"int"===t&&!1===n?"float":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("THREE.NodeBuilder: Invalid active stack removal.");this.activeStacks.pop()}getActiveStack(){return this.activeStacks[this.activeStacks.length-1]}getBaseStack(){return this.activeStacks[0]}createBlock(){const e=this.getActiveStack();return{parent:this.context.nodeBlock||null,context:this.context,stack:e,node:void 0!==e?e._currentNode:void 0}}declareBeforeBlock(e){if(null!==this.flowBlock)return;let t;for(let e=this.context.nodeBlock;e&&(!1!==this.activeStacks.includes(e.stack)&&!dE(this.context,e.context));e=e.parent)t=e;return void 0===t||this.activeStacks.some(t=>t.nodes.includes(e))?void 0:(t.stack.addToStackBefore(e,t.node),t.stack)}addStack(){this.stack=xm(this.stack);const e=Sh();return this.stacks.push(e),xh(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,xh(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,i=null){let r=(i=null===i?e.isGlobal(this)?this.globalCache:this.cache:i).getData(e);void 0===r&&(r={},i.setData(e,r)),void 0===r[t]&&(r[t]=new sE);let n=r[t];if(0===this.subBuildLayers.length)return n;const s=r.any?r.any.subBuilds:null,a=this.getClosestSubBuild(s);return a&&(void 0===n.subBuildsCache&&(n.subBuildsCache={}),n=n.subBuildsCache[a]||(n.subBuildsCache[a]=new sE),n.subBuilds=s),n}getNodeProperties(e,t="any"){const i=this.getDataFromNode(e,t);return i.properties||(i.properties={outputNode:null})}getBufferAttributeFromNode(e,t,i=null){const r=this.getDataFromNode(e,"vertex");let n=r.bufferAttribute;if(void 0===n){const s=this.uniforms.index++;null===i&&(i="nodeAttribute"+s),n=new AM(i,t,e),this.bufferAttributes.push(n),r.bufferAttribute=n}return n}getStructTypeNode(e,t=this.shaderStage){return this.types[t][e]||null}getStructTypeFromNode(e,t,i=null,r=this.shaderStage){const n=this.getDataFromNode(e,r,this.globalCache);let s=n.structType;if(void 0===s){const a=this.structs.index++;null===i&&(i="StructType"+a),s=new UM(i,t),this.structs[r].push(s),this.types[r][i]=e,n.structType=s}return s}getOutputStructTypeFromNode(e,t){const i=this.getStructTypeFromNode(e,t,"OutputType","fragment");return i.output=!0,i}getUniformFromNode(e,t,i=this.shaderStage,r=null){const n=this.getDataFromNode(e,i,this.globalCache);let s=n.uniform;if(void 0===s){const a=this.uniforms.index++;s=new RM(r||"nodeUniform"+a,t,e),this.uniforms[i].push(s),this.registerDeclaration(s),n.uniform=s}return s}getVarFromNode(e,t=null,i=e.getNodeType(this),r=this.shaderStage,n=!1,s=!1,a="variable"){const o=this.getDataFromNode(e,r),l=this.getSubBuildProperty(a,o.subBuilds);let u=o[l];if(void 0===u){const c=n?"_const":"_var",h=this.vars[r]||(this.vars[r]=[]),d=this.vars[c]||(this.vars[c]=0);null===t&&(t=(n?"nodeConst":"nodeVar")+d,this.vars[c]++),l!==a&&(t=this.getSubBuildProperty(t,o.subBuilds));const p=e.getArrayCount(this);u=new CM(t,i,n,p,s),n||s||h.push(u),this.registerDeclaration(u),o[l]=u}return u}isDeterministic(e){if(e.isVarNode&&e.assignable&&(e=e.node),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,i=e.getNodeType(this),r=null,n=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 NM(t,i,r,n),e.push(o),this.registerDeclaration(o),s[a]=o}return o}registerDeclaration(e){const t=this.shaderStage,i=this.declarations[t]||(this.declarations[t]={}),r=this.renderer.debug.diagnostics.keywords,n=e.name;let s=n,a=this.getDeclarationName(e),o=1;for(;r&&this.isReservedKeyword(s)||void 0!==i[a];)s=n+"_"+o++,e.name=s,a=this.getDeclarationName(e);s!==n&&Ti(`TSL: Declaration name '${n}' of '${e.type}' is a reserved keyword or already in use. Renamed to '${s}'.`),i[a]=e}getDeclarationName(e){return this.getPropertyName(e)}getCodeFromNode(e,t,i=this.shaderStage){const r=this.getDataFromNode(e);let n=r.code;if(void 0===n){const e=this.codes[i]||(this.codes[i]=[]),s=e.length;n=new PM("nodeCode"+s,t),e.push(n),r.code=n}return n}addLineFlowCode(e){return""===e||(!1===(e=this.tab+e).trimEnd().endsWith(";")&&(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),i=this.flowChildNode(e,t);return this.flowsData.set(e,i),i}addInclude(e){null!==this.currentFunctionNode&&!1===this.currentFunctionNode.includes.includes(e)&&this.currentFunctionNode.includes.push(e)}buildFunctionNode(e){const t=this.renderer.backend;let i=JM.get(t);void 0===i&&(i=new WeakMap,JM.set(t,i));let r=i.get(e);if(void 0===r){r=new Ay;const t=this.currentFunctionNode;this.currentFunctionNode=r,r.code=this.buildFunctionCode(e),this.currentFunctionNode=t,i.set(e,r)}return r}flowShaderNode(e){const t=e.layout,i=tE(t,t.inputs.map(e=>new vm(e.type,e.name)));e.layout=null;const r=e.call(i),n=this.flowStagesNode(r,t.type);return e.layout=t,n}_getLayoutInputs(e,t){const i=e.layout.inputs,r=null!==t&&t.length>0?t[0]:null,n=null!=r&&!1===bc(t)?r:null,s=i.map((e,i)=>null!==n?void 0!==n[e.name]:null!==t&&void 0!==t[i]);if(s.every(Boolean))return null!==t?t:[];if(e.once)return null;let a=eE.get(e);void 0===a&&(a=new Map,eE.set(e,a));const o=s.map(Number).join("");let l=a.get(o);if(void 0===l&&(l=this._resolveLayoutDefaults(e,s),a.set(o,l)),null===l)return null;if(null!==n){const e={...n};return i.forEach((t,i)=>{!1===s[i]&&(e[t.name]=l[i])}),[e]}return s.map((e,i)=>e?t[i]:l[i])}_resolveLayoutDefaults(e,t){const i=e.layout,r=i.inputs.map(e=>new vm(e.type,e.name)),n=this._getLayoutCallGraph(e,tE(i,r)),s=this._getLayoutCallGraph(e,tE(i,r.map((e,i)=>t[i]?e:void 0))),a=new Map;r.forEach((e,i)=>{!1===t[i]&&a.set(e,i)});const o=[],l=new Map,u=(e,t)=>{if(e===t)return!0;if(!e||!t||!0!==e.isNode||!0!==t.isNode)return!1;const i=a.get(e);if(void 0!==i)return void 0===o[i]&&(o[i]=t),o[i]===t;if(l.has(e))return l.get(e)===t;if(e.constructor!==t.constructor)return!1;l.set(e,t);const r=[...e.getChildren()],n=[...t.getChildren()];if(r.length!==n.length)return!1;for(let e=0;e<r.length;e++)if(!1===u(r[e],n[e]))return!1;return!0},c=s.nodes.length-n.nodes.length;if(c<0)return null;if(l.set(n,s),!1===u(n.outputNode,s.outputNode))return null;for(let e=0;e<n.nodes.length;e++)if(!1===u(n.nodes[e],s.nodes[c+e]))return null;const h=new Set(r);for(const e of a.values()){const t=o[e];if(void 0===t)return null;const i=[t],r=new Set;for(;i.length>0;){const e=i.pop();if(h.has(e))return null;if(!r.has(e)){r.add(e);for(const t of e.getChildren())i.push(t)}}}return o}_getLayoutCallGraph(e,t){const i=e.layout;let r;e.layout=null,this.addStack();try{this.stack.outputNode=e.call(t).call(this)}finally{r=this.removeStack(),e.layout=i}return r}flowBuildStage(e,t,i=null){const r=this.getBuildStage();this.setBuildStage(t);const n=e.build(this,i);return this.setBuildStage(r),n}flowStagesNode(e,t=null){const i=this.flow,r=this.vars,n=this.declarations,s=this.cache,a=this.buildStage,o=this.stack,l=this.flowBlock,u={code:""};this.flow=u,this.vars={},this.declarations={},this.cache=new DM,this.stack=xm(),this.flowBlock=null;for(const i of nc)this.setBuildStage(i),u.result=e.build(this,t);return u.vars=this.getVars(this.shaderStage),this.flow=i,this.vars=r,this.declarations=n,this.cache=s,this.stack=o,this.flowBlock=l,this.setBuildStage(a),u}getFunctionOperator(){return null}buildFunctionCode(){Ti("Abstract function.")}flowChildNode(e,t=null){const i=this.flow,r={code:""};return this.flow=r,r.result=e.build(this,t),this.flow=i,r}flowNodeFromShaderStage(e,t,i=null,r=null){const n=this.tab,s=this.cache,a=this.shaderStage,o=this.context,l=this.flowBlock;this.setShaderStage(e);const u={...this.context};delete u.nodeBlock,this.flowBlock=null,this.cache=this.globalCache,this.tab="\t",this.context=u;let c=null;if("generate"===this.buildStage){const n=this.flowChildNode(t,i);null!==r&&(n.code+=`${this.tab+r} = ${n.result};\n`),this.flowCode[e]=this.flowCode[e]+n.code,c=n}else c=t.build(this);return this.setShaderStage(a),this.cache=s,this.tab=n,this.context=o,this.flowBlock=l,c}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){Ti("Abstract function.")}getVaryings(){Ti("Abstract function.")}getVar(e,t,i=null){return`${null!==i?this.generateArrayDeclaration(e,i):this.getType(e)} ${t}`}generateConstStatement(e,t,i=null){return`const ${this.getVar(e,t,i)}`}generateVarStatement(e,t,i=null){return this.getVar(e,t,i)}generateLetStatement(e,t,i=null){return this.generateVarStatement(e,t,i)}getVars(e,t=!1){const i=[],r=this.vars[e];if(void 0!==r)for(const e of r)i.push(`${this.getVar(e.type,e.name,e.count)};`);return i.join(t?"\n":"\n\t")}getUniforms(){Ti("Abstract function.")}getCodes(e){const t=this.codes[e];let i="";if(void 0!==t)for(const e of t)i+=e.code+"\n";return i}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(){Ti("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 i=this.subBuildLayers;for(let e=t.length-1;e>=0;e--){const r=t[e];if(i.includes(r))return r}return null}getSubBuildOutput(e){return this.getSubBuildProperty("outputNode",e)}getSubBuildProperty(e="",t=null){let i,r;return i=null!==t?this.getClosestSubBuild(t):this.subBuildFn,r=i?e?i+"_"+e:i:e,r}prebuild(){const{renderer:e,material:t}=this;if(!0===e.contextNode.isContextNode?this.addContext(e.contextNode.getFlowContextData()):Mi('NodeBuilder: "renderer.contextNode" must be an instance of `context()`.'),t&&t.contextNode&&(!0===t.contextNode.isContextNode?this.addContext(t.contextNode.getFlowContextData()):Mi('NodeBuilder: "material.contextNode" must be an instance of `context()`.')),null!==t){let i=e.library.fromMaterial(t);null===i&&(Mi(`NodeBuilder: Material "${t.type}" is not compatible.`),i=new Jb),i.build(this)}else this.addFlow("compute",this.compute)}build(){this.prebuild();for(const e of nc){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(const t of sc){this.setShaderStage(t);const i=this.flowNodes[t];for(const t of i)"generate"===e?this.flowNode(t):t.build(this)}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}async buildAsync(e=wi){this.prebuild();for(const t of nc){this.setBuildStage(t),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(const i of sc){this.setShaderStage(i);const r=this.flowNodes[i];for(const e of r)"generate"===t?this.flowNode(e):e.build(this);await e()}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getNodeUniform(e,t){if("float"===t||"int"===t||"uint"===t)return new WM(e);if("vec2"===t||"ivec2"===t||"uvec2"===t)return new jM(e);if("vec3"===t||"ivec3"===t||"uvec3"===t)return new $M(e);if("vec4"===t||"ivec4"===t||"uvec4"===t)return new XM(e);if("color"===t)return new qM(e);if("mat2"===t)return new YM(e);if("mat3"===t)return new KM(e);if("mat4"===t)return new ZM(e);throw new Error(`THREE.NodeBuilder: Uniform "${t}" not implemented.`)}format(e,t,i){if((t=this.getVectorType(t))===(i=this.getVectorType(i))||null===i||this.isReference(i))return e;const r=this.getTypeLength(t),n=this.getTypeLength(i);if(16===r&&9===n)return`${this.getType(i)}( ${e}[ 0 ].xyz, ${e}[ 1 ].xyz, ${e}[ 2 ].xyz )`;if(9===r&&4===n)return`${this.getType(i)}( ${e}[ 0 ].xy, ${e}[ 1 ].xy )`;if(r>4)return e;if(n>4||0===n)return e;if(r===n)return`${this.getType(i)}( ${e} )`;if(r>n)return e="bool"===i?`all( ${e} )`:`${e}.${"xyz".slice(0,n)}`,this.format(e,this.getTypeFromLength(n,this.getComponentType(t)),i);if(4===n&&r>1){const r=this.getComponentType(i),n=this.getTypeFromLength(3,r);return`${this.getType(i)}( ${this.format(e,t,n)}, ${this.generateConst(r,"bool"===r||1)} )`}if(2===r){const r=this.getComponentType(i),n=this.getTypeFromLength(2,r);return`${this.getType(i)}( ${this.format(e,t,n)}, ${this.generateConst(r,"bool"!==r&&0)} )`}return 1===r&&n>1&&t!==this.getComponentType(i)&&(e=`${this.getType(this.getComponentType(i))}( ${e} )`),`${this.getType(i)}( ${e} )`}getSignature(){return`// Three.js r${N} - Node System\n`}needsPreviousData(){const e=this.renderer.getMRT();return null!==e&&e.has("velocity")}}class fE{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.updateMap=new WeakMap,this.updateBeforeMap=new WeakMap,this.updateAfterMap=new WeakMap,this.renderer=null,this.material=null,this.camera=null,this.object=null,this.scene=null,this.compute=null}_getMaps(e,t){let i=e.get(t);return void 0===i&&(i={renderId:0,frameId:0},e.set(t,i)),i}updateBeforeNode(e){const t=e.getUpdateBeforeType(this),i=e.updateReference(this);if(t===Qu){const t=this._getMaps(this.updateBeforeMap,i);if(t.frameId!==this.frameId){const i=t.frameId;t.frameId=this.frameId,!1===e.updateBefore(this)&&(t.frameId=i)}}else if(t===Ju){const t=this._getMaps(this.updateBeforeMap,i);if(t.renderId!==this.renderId){const i=t.renderId;t.renderId=this.renderId,!1===e.updateBefore(this)&&(t.renderId=i)}}else t===ec&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(this),i=e.updateReference(this);if(t===Qu){const t=this._getMaps(this.updateAfterMap,i);t.frameId!==this.frameId&&!1!==e.updateAfter(this)&&(t.frameId=this.frameId)}else if(t===Ju){const t=this._getMaps(this.updateAfterMap,i);t.renderId!==this.renderId&&!1!==e.updateAfter(this)&&(t.renderId=this.renderId)}else t===ec&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(this),i=e.updateReference(this);if(t===Qu){const t=this._getMaps(this.updateMap,i);t.frameId!==this.frameId&&!1!==e.update(this)&&(t.frameId=this.frameId)}else if(t===Ju){const t=this._getMaps(this.updateMap,i);t.renderId!==this.renderId&&!1!==e.update(this)&&(t.renderId=this.renderId)}else t===ec&&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 mE{constructor(e,t,i=null,r="",n=!1){this.type=e,this.name=t,this.count=i,this.qualifier=r,this.isConst=n}}mE.isNodeFunctionInput=!0;class gE extends yx{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class _E extends yx{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:Oy(this.light),lightColor:e}}}class vE extends yx{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=Iy(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=Jh(new Yr).setGroup(Kh)}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:i,lightDirectionNode:r}=this,n=Ug.dot(r).mul(.5).add(.5),s=df(i,t,n);e.context.irradiance.addAssign(s)}}class bE extends yx{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=Jh(0).setGroup(Kh),this.penumbraCosNode=Jh(0).setGroup(Kh),this.cutoffDistanceNode=Jh(0).setGroup(Kh),this.decayExponentNode=Jh(0).setGroup(Kh),this.colorNode=Jh(this.color).setGroup(Kh)}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:i,penumbraCosNode:r}=this;return gf(i,r,t)}getLightCoord(e){const t=e.getNodeProperties(this);let i=t.projectionUV;return void 0===i&&(i=function(e,t=vg){const i=Uy(e).mul(t);return i.xyz.div(i.w)}(this.light,e.context.positionWorld),t.projectionUV=i),i}setupDirect(e){const{colorNode:t,cutoffDistanceNode:i,decayExponentNode:r,light:n}=this,s=this.getLightVector(e),a=s.normalize(),o=a.dot(Oy(n)),l=this.getSpotAttenuation(e,o),u=s.length(),c=xx({lightDistance:u,cutoffDistance:i,decayExponent:r});let h,d,p=t.mul(l).mul(c);if(n.colorNode?(d=this.getLightCoord(e),h=n.colorNode(d)):n.map&&(d=this.getLightCoord(e),h=Yg(n.map,d.xy).onRenderUpdate(()=>n.map)),h){p=d.mul(2).sub(1).abs().lessThan(1).all().select(p.mul(h),p)}return{lightColor:p,lightDirection:a}}}class yE extends bE{static get type(){return"IESSpotLightNode"}constructor(e=null){super(e),this._iesTextureNode=null}getSpotAttenuation(e,t){const i=this.light.iesMap;let r=null;if(i&&!0===i.isTexture){const n=this.getLightCoord(e).sub(.5);this._iesTextureNode=Yg(i);const s=Eh(.5).div(Ch(jg(this._iesTextureNode))),a=nm(Op(n.y,n.x),-Math.PI,Math.PI).add(s.y),o=nm(t.acos(),0,Math.PI,s.x,Eh(1).sub(s.x));r=this._iesTextureNode.sample(Ch(o,a)).level(0).r}else r=super.getSpotAttenuation(e,t);return r}update(e){super.update(e),null!==this._iesTextureNode&&this.light.iesMap&&(this._iesTextureNode.value=this.light.iesMap)}}class xE extends yx{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let e=0;e<9;e++)t.push(new Wi);this.lightProbe=Dm(t).setGroup(Kh)}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=mS(Ug,this.lightProbe);e.context.irradiance.addAssign(t)}}const SE=yh(([e,t])=>{const i=e.abs().sub(t);return Gp(ef(i,0)).add(Jp(ef(i.x,i.y),0))},{p:"vec2",b:"vec2",return:"float"});class TE extends bE{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=Eh(0),i=this.penumbraCosNode,r=Uy(this.light).mul(e.context.positionWorld||vg);return Th(r.w.greaterThan(0),()=>{const e=r.xyz.div(r.w),n=SE(e.xy.sub(Ch(.5)),Ch(.5)),s=Gd(-1,kd(1,Ip(i)).sub(1));t.assign(ff(n.mul(-2).mul(s)))}),t}}const ME=new fr;let EE=null;class wE extends yx{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=Jh(new Wi).setGroup(Kh),this.halfWidth=Jh(new Wi).setGroup(Kh),this.updateType=Ju}update(e){super.update(e);const{light:t}=this;ME.extractRotation(t.matrixWorld),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(ME),this.halfHeight.value.applyMatrix4(ME)}setupDirectRectArea(e){let t,i;e.isAvailable("float32Filterable")?(t=Yg(EE.LTC_FLOAT_1),i=Yg(EE.LTC_FLOAT_2)):(t=Yg(EE.LTC_HALF_1),i=Yg(EE.LTC_HALF_2));const{colorNode:r,light:n}=this;return{lightColor:r,lightPosition:Fy(n),halfWidth:ig.mul(Oh(this.halfWidth,0)).xyz,halfHeight:ig.mul(Oh(this.halfHeight,0)).xyz,ltc_1:t,ltc_2:i}}static setLTC(e){EE=e}}class AE{parseFunction(){Ti("Abstract function.")}}class RE{constructor(e,t,i="",r=""){this.type=e,this.inputs=t,this.name=i,this.precision=r}getCode(){Ti("Abstract function.")}}RE.isNodeFunction=!0;const CE=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,NE=/[a-z_0-9]+/gi,PE="#pragma main";class LE extends RE{constructor(e){const{type:t,inputs:i,name:r,precision:n,inputsCode:s,blockCode:a,headerCode:o}=(e=>{const t=(e=e.trim()).indexOf(PE),i=(-1!==t?e.slice(t+12):e).replace(/^(?:\s*\/\/[^\r\n]*|\s*\/\*[\s\S]*?\*\/|\s*)+/,""),r=i.match(CE);if(null!==r&&5===r.length){const n=r[4],s=[];let a=null;for(;null!==(a=NE.exec(n));)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 i=s[l++][0];let r=Number.parseInt(s[l][0]);!1===Number.isNaN(r)?l++:r=null;const n=s[l++][0];o.push(new mE(i,n,r,t,e))}const u=i.substring(r[0].length),c=void 0!==r[3]?r[3]:"";return{type:r[2],inputs:o,name:c,precision:void 0!==r[1]?r[1]:"",inputsCode:n,blockCode:u,headerCode:-1!==t?e.slice(0,t):""}}throw new Error("THREE.FunctionNode: Function is not a GLSL code.")})(e);super(t,i,r,n),this.inputsCode=s,this.blockCode=a,this.headerCode=o}getCode(e=this.name){let t;const i=this.blockCode;if(""!==i){const{type:r,inputsCode:n,headerCode:s,precision:a}=this;let o=`${r} ${e} ( ${n.trim()} )`;""!==a&&(o=`${a} ${o}`),t=s+o+i}else t="";return t}}class DE extends AE{parseFunction(e){return new LE(e)}}const UE=[],IE=[],FE=Jh(0,"int").setGroup(Kh);class OE extends zT{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new fE,this.nodeBuilderCache=new Map,this.callHashCache=new jy,this.groupsData=new jy,this._buildQueue=[],this._buildInProgress=!1,this.cacheLib={}}updateGroup(e){const t=e.groupNode;if(t.updateType===ec)return!0;UE[0]=t,UE[1]=e;let i=this.groupsData.get(UE);return void 0===i&&this.groupsData.set(UE,i={}),UE[0]=null,UE[1]=null,i.version!==t.version&&(i.version=t.version,!0)}getForRenderCacheKey(e){return e.initialCacheKey}_createNodeBuilder(e,t){const i=this.backend.createNodeBuilder(e.object,this.renderer),r=this.renderer.debug.onNodeBuilderCreated;return null!==r&&r(i,e),i.scene=e.scene,i.material=t,i.camera=e.camera,i.context.material=t,i.lightsNode=e.lightsNode,i.environmentNode=this.getEnvironmentNode(e.scene),i.fogNode=this.getFogNode(e.scene),i.clippingContext=e.clippingContext,this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview&&i.enableMultiview(),i}_reportBuildError(e){let t=e.stackTrace;!t&&e.stack&&(t=new lc(e.stack)),Mi("TSL: "+e,t)}getForRender(e,t=null){const i=this.get(e);let r=i.nodeBuilderState;if(void 0===r){const{nodeBuilderCache:n}=this,s=this.getForRenderCacheKey(e);if(r=n.get(s),void 0===r){const a=async()=>{let i=this._createNodeBuilder(e,e.material);try{null!==t?await i.buildAsync(t):i.build()}catch(r){i=this._createNodeBuilder(e,new Jb),null!==t?await i.buildAsync(t):i.build(),this._reportBuildError(r)}return i};if(null!==t)return a().then(e=>(r=this._createNodeBuilderState(e),!1===e.objectSpecific&&n.set(s,r),r.usedTimes++,i.nodeBuilderState=r,r));{let t=this._createNodeBuilder(e,e.material);try{t.build()}catch(i){t=this._createNodeBuilder(e,new Jb),t.build(),this._reportBuildError(i)}r=this._createNodeBuilderState(t),!1===t.objectSpecific&&n.set(s,r)}}r.usedTimes++,i.nodeBuilderState=r}return r}getForRenderAsync(e,t=wi){const i=this.getForRender(e,t);return i.then?i:Promise.resolve(i)}getForRenderDeferred(e){const t=this.get(e);if(void 0!==t.nodeBuilderState)return t.nodeBuilderState;const i=this.getForRenderCacheKey(e),r=this.nodeBuilderCache.get(i);return void 0!==r?(r.usedTimes++,t.nodeBuilderState=r,r):(!0!==t.pendingBuild&&(t.pendingBuild=!0,this._buildQueue.push(()=>this.getForRenderAsync(e).then(()=>{t.pendingBuild=!1})),this._processBuildQueue()),null)}_processBuildQueue(){if(this._buildInProgress||0===this._buildQueue.length)return;this._buildInProgress=!0;this._buildQueue.shift()().then(()=>{this._buildInProgress=!1,this._processBuildQueue()})}delete(e){if(e.isRenderObject){const t=this.get(e).nodeBuilderState;void 0!==t&&(t.usedTimes--,0===t.usedTimes&&this.nodeBuilderCache.delete(this.getForRenderCacheKey(e)))}return super.delete(e)}getForCompute(e,t=!1,i=wi){const r=this.get(e);let n=r.nodeBuilderState;if(void 0===n||r.version!==e.version){const s=this.backend.createNodeBuilder(null,this.renderer);s.compute=e;const a=this.renderer.debug.onNodeBuilderCreated;if(null!==a&&a(s,e),t)return s.buildAsync(i).then(()=>(n=this._createNodeBuilderState(s),r.nodeBuilderState=n,r.version=e.version,n));s.build(),n=this._createNodeBuilderState(s),r.nodeBuilderState=n,r.version=e.version}return n}getForComputeAsync(e,t=wi){const i=this.getForCompute(e,!0,t);return i.then?i:Promise.resolve(i)}_createNodeBuilderState(e){return new wM(e.vertexShader,e.fragmentShader,e.computeShader,e.getAttributesArray(),e.getBindings(),e.updateNodes,e.updateBeforeNodes,e.updateAfterNodes,e.observer,e.hardwareClipping,e.transforms)}getEnvironmentNode(e){if(!1===this.renderer.lighting.enabled)return null;this.updateEnvironment(e);let t=null;if(e.environmentNode&&e.environmentNode.isNode)t=e.environmentNode;else{const i=this.get(e);i.environmentNode&&(t=i.environmentNode)}return t}getBackgroundNode(e){this.updateBackground(e);let t=null;if(e.backgroundNode&&e.backgroundNode.isNode)t=e.backgroundNode;else{const i=this.get(e);i.backgroundNode&&(t=i.backgroundNode)}return t}getFogNode(e){return this.updateFog(e),e.fogNode||this.get(e).fogNode||null}getCustomProgramCacheKey(e,t){if(e===t.overrideMaterial)return e.customProgramCacheKey();{const t=this.get(e);return t.cacheKeyVersion!==e.version&&(t.cacheKeyVersion=e.version,t.cacheKey=e.customProgramCacheKey()),t.cacheKey}}getCacheKey(e,t){UE[0]=e,UE[1]=t;const i=this.renderer.info.calls,r=this.callHashCache.get(UE)||{};if(r.callId!==i){if(IE.push(this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview?1:0),IE.push(this.renderer.lighting.enabled?1:0),this.renderer.lighting.enabled){IE.push(t.getCacheKey(!0)),IE.push(this.renderer.shadowMap.enabled?1:0),IE.push(this.renderer.shadowMap.type);const i=this.getEnvironmentNode(e);i&&IE.push(i.getCacheKey())}const n=this.getFogNode(e);n&&IE.push(n.getCacheKey()),r.callId=i,r.cacheKey=hc(IE),this.callHashCache.set(UE,r),IE.length=0}return UE[0]=null,UE[1]=null,r.cacheKey}get isToneMappingState(){return!this.renderer.getRenderTarget()}updateBackground(e){const t=this.get(e),i=e.background;if(i){const r=0===e.backgroundBlurriness&&t.backgroundBlurriness>0||e.backgroundBlurriness>0&&0===t.backgroundBlurriness;if(t.background!==i||r){const n=this.getCacheNode("background",i,()=>{if(!0===i.isCubeTexture||i.mapping===Ce||i.mapping===Ne){if(e.backgroundBlurriness>0||!0===i.isPMREMTexture)return zx(i);{let e;return e=!0===i.isCubeTexture?E_(i):Yg(i),LS(e)}}if(!0===i.isTexture)return Yg(i,Bm.flipY()).setUpdateMatrix(!0);!0!==i.isColor&&Mi("WebGPUNodes: Unsupported background configuration.",i)},r);t.backgroundNode=n,t.background=i,t.backgroundBlurriness=e.backgroundBlurriness}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}getCacheNode(e,t,i,r=!1){const n=this.cacheLib[e]||(this.cacheLib[e]=new WeakMap);let s=n.get(t);if(void 0===s||r){if(void 0===s&&!0===t.isTexture){const e=()=>{t.removeEventListener("dispose",e);const i=n.get(t);void 0!==i&&(n.delete(t),i.dispose())};t.addEventListener("dispose",e)}s=i(),n.set(t,s)}return s}updateFog(e){const t=this.get(e),i=e.fog;if(i){if(t.fog!==i){const e=this.getCacheNode("fog",i,()=>{if(i.isFogExp2){const e=A_("color","color",i).setGroup(Kh),t=A_("density","float",i).setGroup(Kh);return Py(e,Ny(t))}if(i.isFog){const e=A_("color","color",i).setGroup(Kh),t=A_("near","float",i).setGroup(Kh),r=A_("far","float",i).setGroup(Kh);return Py(e,Cy(t,r))}Mi("Renderer: Unsupported fog configuration.",i)});t.fogNode=e,t.fog=i}}else delete t.fogNode,delete t.fog}updateEnvironment(e){const t=this.get(e),i=e.environment;if(i){if(t.environment!==i){const e=this.getCacheNode("environment",i,()=>!0===i.isCubeTexture?E_(i):!0===i.isTexture?Yg(i):void Mi("Nodes: Unsupported environment configuration.",i));t.environmentNode=e,t.environment=i}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,i=null,r=null,n=null,s=null){const a=this.nodeFrame;return a.renderer=e,a.scene=t,a.object=i,a.camera=r,a.material=n,a.compute=s,a}getNodeFrameForRender(e){return this.getNodeFrame(e.renderer,e.scene,e.object,e.camera,e.material)}getNodeFrameForCompute(e){return this.getNodeFrame(this.renderer,null,null,null,null,e)}getOutputCacheKey(){const e=this.renderer;return e.toneMapping+","+e.currentColorSpace+","+e.xr.isPresenting}getOutputNode(e){const t=this.renderer;let i;return i=e.isArrayTexture?this.backend.isWebGLBackend?Yg(e,Bm).depth(Rm("gl_ViewID_OVR")).renderOutput(t.toneMapping,t.currentColorSpace):Yg(e,Bm).depth(FE).renderOutput(t.toneMapping,t.currentColorSpace):Yg(e,Bm).renderOutput(t.toneMapping,t.currentColorSpace),i}setOutputLayerIndex(e){FE.value=e}updateBefore(e){const t=e.getNodeBuilderState();for(const i of t.updateBeforeNodes)this.getNodeFrameForRender(e).updateBeforeNode(i)}updateAfter(e){const t=e.getNodeBuilderState();for(const i of t.updateAfterNodes)this.getNodeFrameForRender(e).updateAfterNode(i)}updateBeforeForCompute(e){const t=this.getForCompute(e);for(const i of t.updateBeforeNodes)this.getNodeFrameForCompute(e).updateBeforeNode(i)}updateAfterForCompute(e){const t=this.getForCompute(e);for(const i of t.updateAfterNodes)this.getNodeFrameForCompute(e).updateAfterNode(i)}updateForCompute(e){const t=this.getNodeFrame(),i=this.getForCompute(e);for(const e of i.updateNodes)t.updateNode(e)}updateForRender(e){const t=this.getNodeFrameForRender(e),i=e.getNodeBuilderState();for(const e of i.updateNodes)t.updateNode(e)}needsRefresh(e){const t=this.getNodeFrameForRender(e);return e.getMonitor().needsRefresh(e,t)}dispose(){super.dispose(),this.nodeFrame=new fE,this.nodeBuilderCache=new Map,this.cacheLib={}}}const BE=new ss;let kE=0;class zE{constructor(e=null){this.id=kE++,this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewMatrix=new fr,this.viewNormalMatrix=new Xi,this.clippingGroupContexts=new WeakMap,this.intersectionPlanes=[],this.unionPlanes=[],this.parentVersion=null,null!==e&&(this.viewMatrix=e.viewMatrix,this.viewNormalMatrix=e.viewNormalMatrix,this.clippingGroupContexts=e.clippingGroupContexts,this.shadowPass=e.shadowPass)}projectPlanes(e,t,i){const r=e.length;for(let n=0;n<r;n++){BE.copy(e[n]).applyMatrix4(this.viewMatrix,this.viewNormalMatrix);const r=t[i+n],s=BE.normal;r.x=-s.x,r.y=-s.y,r.z=-s.z,r.w=BE.constant}}updateGlobal(e,t){this.shadowPass=null!==e.overrideMaterial&&e.overrideMaterial.isShadowPassMaterial,!0===t.isArrayCamera?this.viewMatrix.identity():this.viewMatrix.copy(t.matrixWorldInverse),this.viewNormalMatrix.getNormalMatrix(this.viewMatrix)}update(e,t){let i=!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 r=t.clippingPlanes,n=r.length;let s,a;if(this.clipIntersection?(s=this.intersectionPlanes,a=e.intersectionPlanes.length):(s=this.unionPlanes,a=e.unionPlanes.length),s.length!==a+n){s.length=a+n;for(let e=0;e<n;e++)s[a+e]=new ur;i=!0}this.projectPlanes(r,s,a),i&&(this.version++,this.cacheKey=`${this.id}:${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 zE(this),this.clippingGroupContexts.set(e,t)),t.update(this,e),t}get unionClippingCount(){return this.unionPlanes.length}}class GE{constructor(e,t,i){this.bundleGroup=e,this.camera=t,this.renderContext=i}}const VE=[];class HE{constructor(){this.bundles=new jy}get(e,t,i){const r=this.bundles;VE[0]=e,VE[1]=t,VE[2]=i;let n=r.get(VE);return void 0===n&&(n=new GE(e,t,i),r.set(VE,n)),VE[0]=null,VE[1]=null,VE[2]=null,n}dispose(){this.bundles=new jy}}class WE{constructor(){this.materialNodes=new Map,this.toneMappingNodes=new Map}fromMaterial(e){if(e.isNodeMaterial)return e;let t=null;const i=this.getMaterialNodeClass(e.type);if(null!==i){t=new i;for(const i in e)t[i]=e[i]}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 Ei('NodeLibrary: "getLightNodeClass()" has been deprecated. Use "Light.registerNode()" to assign light node classes instead.'),e.prototype._lightNode||null}addLight(e,t){Ei('NodeLibrary: "addLight()" has been deprecated. Use "Light.registerNode()" instead.'),t.registerNode(e)}addType(e,t,i){if(i.has(t))Ti(`Redefinition of node ${t}`);else{if("function"!=typeof e)throw new Error(`THREE.NodeLibrary: Node class ${e.name} is not a class.`);if("function"==typeof t||"object"==typeof t)throw new Error(`THREE.NodeLibrary: Base class ${t} is not a class.`);i.set(t,e)}}}const jE=new Wy;class $E{constructor(){this.enabled=!0,this._cache=[],this._lightsNodeMap=new WeakMap,this._tracked=new Set,this._registry=new FinalizationRegistry(e=>this._tracked.delete(e))}createNode(e=[]){return(new Wy).setLights(e)}getNode(e){if(!0!==e.isScene&&!0!==e.isGroup)return jE;let t=this._lightsNodeMap.get(e);return void 0===t&&(t=this.createNode(),this._lightsNodeMap.set(e,t),this._track(t)),t}_track(e){const t=new WeakRef(e);this._tracked.add(t),this._registry.register(e,t,t)}beginRender(e){this._cache.push(this.getNode(e).getLights())}finishRender(e){this.getNode(e).setLights(this._cache.pop())}dispose(){for(const e of this._tracked){const t=e.deref();void 0!==t&&(this._registry.unregister(e),t.dispose())}this._tracked.clear()}}class XE extends cr{constructor(e=1,t=1,i={}){super(e,t,i),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 qE=new WeakMap;class YE extends Ri{constructor(e,t=!1){super(),this.enabled=!1,this.isPresenting=!1,this.cameraAutoUpdate=!0,this._renderer=e,this._cameraL=new za,this._cameraL.viewport=new ur,this._cameraL.matrixWorldAutoUpdate=!1,this._cameraR=new za,this._cameraR.viewport=new ur,this._cameraR.matrixWorldAutoUpdate=!1,this._cameras=[this._cameraL,this._cameraR],this._cameraXR=new eo,this._currentDepthNear=null,this._currentDepthFar=null,this._controllers=[],this._controllerInputSources=[],this._xrRenderTarget=null,this._layers=[],this._sessionUsesLayers=!1,this._supportsGlBinding="undefined"!=typeof XRWebGLBinding,this._supportsWebGPUBinding=void 0!==globalThis.XRGPUBinding,this._createXRLayer=ew.bind(this),this._gl=null,this._currentAnimationContext=null,this._currentAnimationLoop=null,this._currentPixelRatio=null,this._currentSize=new Vi,this._currentCameraSettings=null,this._onSessionEvent=ZE.bind(this),this._onSessionEnd=QE.bind(this),this._onInputSourcesChange=JE.bind(this),this._onAnimationFrame=tw.bind(this),this._referenceSpace=null,this._referenceSpaceType="local-floor",this._customReferenceSpace=null,this._framebufferScaleFactor=1,this._foveation=1,this._session=null,this._glBaseLayer=null,this._glBinding=null,this._webgpuBinding=null,this._glProjLayer=null,this._xrFrame=null,this._supportsLayers=this._supportsGlBinding&&"createProjectionLayer"in XRWebGLBinding.prototype,this._useMultiviewIfPossible=t,this._useMultiview=!1}getController(e){return this._getController(e).getTargetRaySpace()}getControllerGrip(e){return this._getController(e).getGripSpace()}getHand(e){return this._getController(e).getHandSpace()}getFoveation(){return this._foveation}setFoveation(e){this._foveation=e,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&&Ti("XRManager: Cannot change framebuffer scale while presenting.")}getReferenceSpaceType(){return this._referenceSpaceType}setReferenceSpaceType(e){this._referenceSpaceType=e,!0===this.isPresenting&&Ti("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}getBaseLayer(){return null!==this._glProjLayer?this._glProjLayer:this._glBaseLayer}getBinding(){return null===this._glBinding&&this._supportsGlBinding&&(this._glBinding=new XRWebGLBinding(this._session,this._gl)),this._glBinding}foveateBoundTexture(e){if(null===e||!0!==e.isPostProcessingRenderTarget)return;if(!0!==this.isPresenting)return;if(null===this._glProjLayer)return;const t=this._renderer.backend;if(void 0===t||!0!==t.isWebGLBackend)return;if(null===t.state)return;const i=this._renderer.getOutputRenderTarget();if(null===i||!0!==i.isXRRenderTarget)return;const r=this.getBinding();if(null===r||"function"!=typeof r.foveateBoundTexture)return;this._renderer._textures.updateRenderTarget(e);const{textureGPU:n,glTextureType:s}=t.get(e.texture);if(void 0!==n&&void 0!==s&&e._xrFoveationTextureGPU!==n){e._xrFoveationTextureGPU=n,t.state.bindTexture(s,n);try{r.foveateBoundTexture(s,this.getFoveation())}catch(e){Ei(`XRManager: Unable to foveate bound XR post-processing texture. ${e.name}: ${e.message}`)}finally{t.state.unbindTexture()}}}getWebGPUBinding(){return null===this._webgpuBinding&&this._supportsWebGPUBinding&&(this._webgpuBinding=new globalThis.XRGPUBinding(this._session,this._renderer.backend.device)),this._webgpuBinding}_isWebGPUSession(){return!0===this._renderer.backend.isWebGPUBackend&&null!==this._session&&this._session.enabledFeatures.includes("webgpu")}_validateWebGPUSession(){if(!0===this._renderer.backend.isWebGPUBackend&&!1===this._session.enabledFeatures.includes("webgpu"))throw new Error('THREE.XRManager: WebGPU XR sessions require the "webgpu" session feature. Use VRButtonGPU/XRButton with "webgpu" enabled or use a WebGL backend.')}async _initWebGPUSession(e){const t=this.getWebGPUBinding(),i=t.createProjectionLayer({colorFormat:t.getPreferredColorFormat()});this._glProjLayer=i,e.updateRenderState({layers:[i]}),this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType()),this._xrRenderTarget=new cr(i.textureWidth,i.textureHeight,{depth:2,minFilter:Oe,magFilter:Oe,depthBuffer:!0,multiview:!1,useArrayDepthTexture:!0,storeMultisampledColorBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,samples:this._renderer.samples}),this._xrRenderTarget.texture.isArrayTexture=!0,!0===this._useMultiviewIfPossible&&Ei("THREE.XRManager: WebGPU XR does not support multiview yet. Disabling multiview for this XR session."),this._useMultiview=!1}_disposeWebGPUSession(){const e=this._renderer,t=e.backend,i=this._xrRenderTarget;if(null!==i&&!0===t.isWebGPUBackend){e._renderContexts&&e._renderContexts.dispose&&e._renderContexts.dispose(),i.dispose();for(const e of i.textures)t.has(e)&&t.destroyTexture(e);t.delete(i)}}_getWebGPUViewData(e){const t=this.getWebGPUBinding(),i={colorTexture:null,viewDescriptors:[],viewports:[]};for(let r=0;r<e.length;r++){const n=t.getViewSubImage(this._glProjLayer,e[r]);null===i.colorTexture&&(i.colorTexture=n.colorTexture),i.viewports.push(n.viewport),n.getViewDescriptor&&i.viewDescriptors.push(n.getViewDescriptor())}return i}getFrame(){return this._xrFrame}useMultiview(){return this._useMultiview}createQuadLayer(e,t,i,r,n,s,a,o={}){const l=new ea(e,t),u=new XE(n,s,{format:tt,type:ze,depthTexture:new Ys(n,s,o.stencil?Ke:je,void 0,void 0,void 0,void 0,void 0,void 0,o.stencil?rt:it),stencilBuffer:o.stencil,samples:o.samples??this._renderer.samples,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledColorBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1}),c=new fs({color:16777215,side:0});c.map=u.texture,c.map.offset.y=1,c.map.repeat.y=-1;const h=new ws(l,c);h.position.copy(i),h.quaternion.copy(r);const d={type:"quad",width:e,height:t,translation:i,quaternion:r,pixelwidth:n,pixelheight:s,samples:u.samples,plane:h,material:c,rendercall:a,renderTarget:u};if(this._layers.push(d),null!==this._session){d.plane.material=new fs({color:16777215,side:0}),d.plane.material.blending=5,d.plane.material.blendEquation=H,d.plane.material.blendSrc=q,d.plane.material.blendDst=q,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,i,r,n,s,a,o,l={}){const u=new Js(e,e,e*t/i,64,64,!0,Math.PI-t/2,t),c=new XE(s,a,{format:tt,type:ze,depthTexture:new Ys(s,a,l.stencil?Ke:je,void 0,void 0,void 0,void 0,void 0,void 0,l.stencil?rt:it),stencilBuffer:l.stencil,samples:l.samples??this._renderer.samples,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledColorBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1}),h=new fs({color:16777215,side:1});h.map=c.texture,h.map.offset.y=1,h.map.repeat.y=-1;const d=new ws(u,h);d.position.copy(r),d.quaternion.copy(n);const p={type:"cylinder",radius:e,centralAngle:t,aspectratio:i,translation:r,quaternion:n,pixelwidth:s,pixelheight:a,samples:c.samples,plane:d,material:h,rendercall:o,renderTarget:c};if(this._layers.push(p),null!==this._session){p.plane.material=new fs({color:16777215,side:1}),p.plane.material.blending=5,p.plane.material.blendEquation=H,p.plane.material.blendSrc=q,p.plane.material.blendDst=q,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 Wi,t=new Hi,i=this._renderer,r=this.isPresenting;this.isPresenting=!1;const n=new Vi;i.getSize(n);const s=i.getRenderTarget();for(const r of this._layers){r.renderTarget.isXRRenderTarget=null!==this._session,r.renderTarget._hasExternalTextures=r.renderTarget.isXRRenderTarget;const n=i.contextNode;let s;if(r.renderTarget.isXRRenderTarget&&this._sessionUsesLayers){r.xrlayer.transform=new XRRigidTransform(r.plane.getWorldPosition(e),r.plane.getWorldQuaternion(t));const a=this._glBinding.getSubImage(r.xrlayer,this._xrFrame);i.backend.setXRRenderTargetTextures(r.renderTarget,a.colorTexture,void 0),i._setXRLayerSize(r.renderTarget.width,r.renderTarget.height),s=qE.get(n),void 0===s&&(s=Tf({getOutput:(e,t)=>{const r=cm(e,i.toneMapping,i.outputColorSpace);return r.premultipliedAlpha=t.material.premultipliedAlpha,r},...n.getFlowContextData()}),qE.set(n,s))}else s=n;i.contextNode=s,i.setRenderTarget(r.renderTarget),r.rendercall(),i.contextNode=n}i.setRenderTarget(s),i._setXRLayerSize(n.x,n.y),this.isPresenting=r}getSession(){return this._session}async setSession(e){const t=this._renderer;!1===t.initialized&&await t.init(),this._gl=t.getContext();const i=this._gl;if(this._session=e,null!==e){if(e.addEventListener("select",this._onSessionEvent),e.addEventListener("selectstart",this._onSessionEvent),e.addEventListener("selectend",this._onSessionEvent),e.addEventListener("squeeze",this._onSessionEvent),e.addEventListener("squeezestart",this._onSessionEvent),e.addEventListener("squeezeend",this._onSessionEvent),e.addEventListener("end",this._onSessionEnd),e.addEventListener("inputsourceschange",this._onInputSourcesChange),this._validateWebGPUSession(),this._currentPixelRatio=t.getPixelRatio(),t.getSize(this._currentSize),this._currentAnimationContext=t._animation.getContext(),this._currentAnimationLoop=t._animation.getAnimationLoop(),t._animation.stop(),this._isWebGPUSession())await this._initWebGPUSession(e);else if(!0===this._supportsLayers){let r=null,n=null,s=null;const a=i.getContextAttributes();await t.backend.makeXRCompatible(),this.setFoveation(this.getFoveation()),t.depth&&(s=t.stencil?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT24,r=t.stencil?rt:it,n=t.stencil?Ke:je);const o={colorFormat:i.RGBA8,depthFormat:s,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 Ys(l.textureWidth,l.textureHeight,n,void 0,void 0,void 0,void 0,void 0,void 0,r,c);if(this._xrRenderTarget=new XE(l.textureWidth,l.textureHeight,{format:tt,type:ze,colorSpace:t.outputColorSpace,depthTexture:h,stencilBuffer:t.stencil,samples:a.antialias?4:0,resolveDepthBuffer:!1===l.ignoreDepthValues,resolveStencilBuffer:!1===l.ignoreDepthValues,storeMultisampledColorBuffer:!1,storeMultisampledDepthBuffer:!1===l.ignoreDepthValues,storeMultisampledStencilBuffer:!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 fs({color:16777215,side:"cylinder"===e.type?1:0}),e.plane.material.blending=5,e.plane.material.blendEquation=H,e.plane.material.blendSrc=q,e.plane.material.blendDst=q,e.xrlayer=this._createXRLayer(e),u.unshift(e.xrlayer);e.updateRenderState({layers:u})}else{await t.backend.makeXRCompatible(),this.setFoveation(this.getFoveation());const r={antialias:t.currentSamples>0,alpha:!0,depth:t.depth,stencil:t.stencil,framebufferScaleFactor:this.getFramebufferScaleFactor()},n=new XRWebGLLayer(e,i,r);this._glBaseLayer=n,e.updateRenderState({baseLayer:n}),t.setPixelRatio(1),t._setXRLayerSize(n.framebufferWidth,n.framebufferHeight),this._xrRenderTarget=new XE(n.framebufferWidth,n.framebufferHeight,{format:tt,type:ze,colorSpace:t.outputColorSpace,stencilBuffer:t.stencil}),this._xrRenderTarget._isOpaqueFramebuffer=!0,this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType())}t._animation.setAnimationLoop(this._onAnimationFrame),t._animation.setContext(e),t._animation.start(),this.isPresenting=!0,this.dispatchEvent({type:"sessionstart"})}}updateCamera(e){const t=this._session;if(null===t)return;const i=e.near,r=e.far,n=this._cameraXR,s=this._cameraL,a=this._cameraR;n.near=a.near=s.near=i,n.far=a.far=s.far=r,n.isMultiViewCamera=this._useMultiview,this._currentDepthNear===n.near&&this._currentDepthFar===n.far||(t.updateRenderState({depthNear:n.near,depthFar:n.far}),this._currentDepthNear=n.near,this._currentDepthFar=n.far),n.layers.mask=6|e.layers.mask,s.layers.mask=-5&n.layers.mask,a.layers.mask=-3&n.layers.mask;const o=e.parent,l=n.cameras;KE(n,o);for(let e=0;e<l.length;e++)KE(l[e],o);n.projectionMatrix.copy(s.projectionMatrix),n.projectionMatrixInverse.copy(s.projectionMatrixInverse),null===this._currentCameraSettings&&e.isPerspectiveCamera&&(this._currentCameraSettings={camera:e,fov:e.fov,zoom:e.zoom}),function(e,t,i){null===i?e.matrix.copy(t.matrixWorld):(e.matrix.copy(i.matrixWorld),e.matrix.invert(),e.matrix.multiply(t.matrixWorld));e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(!0),e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse),e.isPerspectiveCamera&&(e.fov=2*Li*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}(e,n,o)}_getController(e){let t=this._controllers[e];return void 0===t&&(t=new Wr,this._controllers[e]=t),t}}function KE(e,t){null===t?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}function ZE(e){const t=this._controllerInputSources.indexOf(e.inputSource);if(-1===t)return;const i=this._controllers[t];if(void 0!==i){const t=this.getReferenceSpace();i.update(e.inputSource,e.frame,t),i.dispatchEvent({type:e.type,data:e.inputSource})}}function QE(){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._disposeWebGPUSession(),this._session=null,this._xrRenderTarget=null,this._glBinding=null,this._webgpuBinding=null,this._glBaseLayer=null,this._glProjLayer=null,!0===this._sessionUsesLayers)for(const e of this._layers)e.renderTarget=new XE(e.pixelwidth,e.pixelheight,{format:tt,type:ze,depthTexture:new Ys(e.pixelwidth,e.pixelheight,e.stencilBuffer?Ke:je,void 0,void 0,void 0,void 0,void 0,void 0,e.stencilBuffer?rt:it),stencilBuffer:e.stencilBuffer,samples:e.samples,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledColorBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1}),e.renderTarget.isXRRenderTarget=!1,e.plane.material=e.material,e.material.map=e.renderTarget.texture,e.material.map.offset.y=1,e.material.map.repeat.y=-1,delete e.xrlayer;if(this.isPresenting=!1,this._useMultiview=!1,t._animation.stop(),t._animation.setAnimationLoop(this._currentAnimationLoop),t._animation.setContext(this._currentAnimationContext),t._animation.start(),t.setPixelRatio(this._currentPixelRatio),t.setSize(this._currentSize.width,this._currentSize.height,!1),null!==this._currentCameraSettings){const e=this._currentCameraSettings.camera;e.fov=this._currentCameraSettings.fov,e.zoom=this._currentCameraSettings.zoom,e.updateProjectionMatrix(),this._currentCameraSettings=null}this.dispatchEvent({type:"sessionend"})}function JE(e){const t=this._controllers,i=this._controllerInputSources;for(let r=0;r<e.removed.length;r++){const n=e.removed[r],s=i.indexOf(n);s>=0&&(i[s]=null,t[s].disconnect(n))}for(let r=0;r<e.added.length;r++){const n=e.added[r];let s=i.indexOf(n);if(-1===s){for(let e=0;e<t.length;e++){if(e>=i.length){i.push(n),s=e;break}if(null===i[e]){i[e]=n,s=e;break}}if(-1===s)break}const a=t[s];a&&a.connect(n)}}function ew(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 tw(e,t){if(void 0===t)return;const i=this._cameraXR,r=this._renderer,n=r.backend,s=this._glBaseLayer,a=this.getReferenceSpace(),o=t.getViewerPose(a);if(this._xrFrame=t,null!==o){const e=o.views,t=this._isWebGPUSession()?this._getWebGPUViewData(e):null;null!==this._glBaseLayer&&null===t&&n.setXRTarget(s.framebuffer);let a=!1;e.length!==i.cameras.length&&(i.cameras.length=0,a=!0);for(let r=0;r<e.length;r++){const o=e[r];let l;if(null!==t)l=t.viewports[r];else if(!0===this._supportsLayers){const e=this._glBinding.getViewSubImage(this._glProjLayer,o);l=e.viewport,0===r&&n.setXRRenderTargetTextures(this._xrRenderTarget,e.colorTexture,this._glProjLayer.ignoreDepthValues&&!this._useMultiview?void 0:e.depthStencilTexture)}else l=s.getViewport(o);let u=this._cameras[r];void 0===u&&(u=new za,u.layers.enable(r),u.viewport=new ur,u.matrixWorldAutoUpdate=!1,this._cameras[r]=u),u.matrix.fromArray(o.transform.matrix),u.matrix.decompose(u.position,u.quaternion,u.scale),u.projectionMatrix.fromArray(o.projectionMatrix),u.projectionMatrixInverse.copy(u.projectionMatrix).invert(),u.viewport.set(l.x,l.y,l.width,l.height),0===r&&(i.matrix.copy(u.matrix),i.matrix.decompose(i.position,i.quaternion,i.scale)),!0===a&&i.cameras.push(u)}null!==t&&null!==t.colorTexture&&n.setXRRenderTargetTextures(this._xrRenderTarget,t.colorTexture,t.viewDescriptors),r.setOutputRenderTarget(this._xrRenderTarget);const l=r._getFrameBufferTarget();null!==t&&(this._xrRenderTarget.samples=null===l?r.samples:0,this._xrRenderTarget.depthBuffer=null===l),r.xr.foveateBoundTexture(l)}for(let e=0;e<this._controllers.length;e++){const i=this._controllerInputSources[e],r=this._controllers[e];null!==i&&void 0!==r&&r.update(i,t,a)}this._currentAnimationLoop&&this._currentAnimationLoop(e,t),t.detectedPlanes&&this.dispatchEvent({type:"planesdetected",data:t}),this._xrFrame=null}class iw extends Ri{constructor(e){super(),this.domElement=e,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new ur(0,0,this._width,this._height),this._scissor=new ur(0,0,this._width,this._height),this._scissorTest=!1,this.colorTexture=new $s,this.depthTexture=new Ys}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,i){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this._pixelRatio=i,this.domElement.width=Math.floor(e*i),this.domElement.height=Math.floor(t*i),this.setViewport(0,0,e,t),this._dispatchResize())}setSize(e,t,i=!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===i&&(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,i,r){const n=this._scissor;e.isVector4?n.copy(e):n.set(e,t,i,r)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,i,r,n=0,s=1){const a=this._viewport;e.isVector4?a.copy(e):a.set(e,t,i,r),a.minDepth=n,a.maxDepth=s}_dispatchResize(){this.dispatchEvent({type:"resize"})}dispose(){this.dispatchEvent({type:"dispose"})}}const rw=new ur;class nw{constructor(){this.renderer=null,this._frustum=new Gs,this._frustumArray=null,this._projScreenMatrix=new fr,this._bundleDepth=0}prepareAsync(){}dispose(){}begin(e,t){this._projScreenMatrix.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),e.isArrayCamera?(null===t.frustumArray&&(t.frustumArray=new Hs),t.frustumArray.setFromArrayCamera(e),this._frustumArray=t.frustumArray):this._frustum.setFromProjectionMatrix(this._projScreenMatrix,e.coordinateSystem,e.reversedDepth)}beginRenderList(e){e.begin()}finishRenderList(e){e.finish()}isCulled(e,t){if(!e.frustumCulled||this._bundleDepth>0)return!1;const i=t.isArrayCamera?this._frustumArray:this._frustum;return!e.intersectsFrustum(i)}pushRenderItem(e,t,i,r,n,s,a,o){e.push(t,i,r,n,s,a,o)}project(e,t,i,r,n){if(!1===e.visible)return;const s=this.renderer;if(e.layers.test(t.layers))if(e.isGroup)i=e.renderOrder,e.isClippingGroup&&e.enabled&&(n=n.getGroupContext(e));else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)r.pushLight(e);else if(e.isSprite){if(!1===this.isCulled(e,t)){!0===s.sortObjects&&rw.setFromMatrixPosition(e.matrixWorld).applyMatrix4(this._projScreenMatrix);const{geometry:t,material:a}=e;a.visible&&this.pushRenderItem(r,e,t,a,i,rw.z,null,n)}}else if(e.isLineLoop)Mi("Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.");else if((e.isMesh||e.isLine||e.isPoints)&&!1===this.isCulled(e,t)){const{geometry:t,material:a}=e;if(!0===s.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),rw.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(this._projScreenMatrix)),Array.isArray(a)){const s=t.groups;for(let o=0,l=s.length;o<l;o++){const l=s[o],u=a[l.materialIndex];u&&u.visible&&this.pushRenderItem(r,e,t,u,i,rw.z,l,n)}}else a.visible&&this.pushRenderItem(r,e,t,a,i,rw.z,null,n)}if(!0===e.isBundleGroup&&void 0!==s.backend.beginBundle){const a=r;r=s._renderLists.get(e,t,s.lighting);const o=s._bundles.get(e,t,s._currentRenderContext),l=s.backend.get(o);if(s._bundleNeedsUpdate(e,l)){this.beginRenderList(r),void 0===l.renderObjects?l.renderObjects=[]:l.renderObjects.length=0;const s=e.children;this._bundleDepth++;for(let e=0,a=s.length;e<a;e++)this.project(s[e],t,i,r,n);this._bundleDepth--,this.finishRenderList(r)}return void a.pushBundle({bundleGroup:e,camera:t,renderList:r})}const a=e.children;for(let e=0,s=a.length;e<s;e++)this.project(a[e],t,i,r,n)}}const sw=new Zr,aw=new Vi,ow=new ur,lw=new ur,uw={[z]:1,[G]:0,[V]:2};class cw{constructor(){this.lastYieldTime=performance.now()}needsYield(){return performance.now()-this.lastYieldTime>=8}async yield(){"undefined"==typeof requestAnimationFrame||"undefined"!=typeof document&&!0===document.hidden?await wi():await new Promise(e=>{let t=!1;const i=()=>{!1===t&&(t=!0,e())};requestAnimationFrame(()=>setTimeout(i,0)),setTimeout(i,100)}),this.lastYieldTime=performance.now()}}class hw{constructor(e,t={}){this.isRenderer=!0;const{logarithmicDepthBuffer:i=!1,reversedDepthBuffer:r=!1,alpha:n=!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=n,this.logarithmicDepthBuffer=i,this.reversedDepthBuffer=r,this.outputColorSpace=Xt,this.toneMapping=0,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=s,this.stencil=a,this.info=new QT,this.contextNode=Tf(),this.library=new WE,this.lighting=new $E,this._drawingPipeline=null,this.drawingPipeline=new nw,this._samples=l||(!0===o?4:0),this._onCanvasTargetResize=this._onCanvasTargetResize.bind(this),this._onCanvasTargetDispose=this._onCanvasTargetDispose.bind(this),this._canvasTarget=new iw(e.getDomElement()),this._canvasTarget.addEventListener("resize",this._onCanvasTargetResize),this._canvasTarget.addEventListener("dispose",this._onCanvasTargetDispose),this._canvasTarget.isDefaultCanvasTarget=!0,this._inspector=new dm,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._quadCache=new Map,this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null,this._frameBufferTargets=new Map;const d=!0===this.alpha?0:1;this._clearColor=new Sm(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.onError=this._onError,this._outputBufferType=c,this._cacheShadowNodes=new WeakMap,this._initialized=!1,this._callDepth=-1,this._initPromise=null,this._compilationPromises=null,this._precompilationState=null,this._currentSourceMaterial=null,this.transparent=!0,this.opaque=!0,this.shadowMap={enabled:!1,transmitted:!1,type:1},this.xr=new YE(this,h),this.debug={checkShaderErrors:!0,diagnostics:{keywords:!1},onNodeBuilderCreated:null,onShaderError:null,getShaderAsync:async(e,t,i)=>{await this.compileAsync(i,t,e);const r=this.needsFrameBufferTarget&&null===this._renderTarget?this._getFrameBufferTarget():this._renderTarget||this._outputRenderTarget,n=this._renderLists.get(e,t,this.lighting),s=this._renderContexts.get(r,this._mrt,0,t),a=e.overrideMaterial||i.material,o=this._objects.get(i,a,e,t,n.lightsNode,s,s.clippingContext),{fragmentShader:l,vertexShader:u}=o.getNodeBuilderState();return{fragmentShader:l,vertexShader:u}}}}set drawingPipeline(e){e.renderer=this,this._drawingPipeline=e}get drawingPipeline(){return this._drawingPipeline}async init(){return null!==this._initPromise||(this._initPromise=new Promise(async(e,t)=>{let i=this.backend;try{await i.init(this)}catch(e){if(null===this._getFallback)return void t(e);try{this.backend=i=this._getFallback(e),await i.init(this)}catch(e){return void t(e)}}!0===this.logarithmicDepthBuffer&&!0===this.reversedDepthBuffer&&(Ti("WebGPURenderer: Logarithmic depth buffer is ignored when reversed depth buffer is enabled."),this.logarithmicDepthBuffer=!1),this._nodes=new OE(this,i),this._animation=new NT(this,this._nodes,this.info),this._attributes=new XT(i,this.info),this._background=new TM(this,this._nodes),this._geometries=new ZT(i,this._attributes,this.info),this._textures=new xM(this,i,this.info),this._pipelines=new nM(i,this._nodes,this.info),this._bindings=new aM(i,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new kT(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new fM,this._bundles=new HE,this._renderContexts=new vM(this),this._initialized=!0,e(this)})),this._initPromise}get domElement(){return this._canvasTarget.domElement}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,i=null,r=null){if(!0===this._isDeviceLost)return;!1===this._initialized&&await this.init();const n=this.drawingPipeline.prepareAsync(e,t);void 0!==n&&await n,2===this.shadowMap.type&&(Ti("WebGPURenderer: PCFSoftShadowMap has been removed. Using PCFShadowMap instead."),this.shadowMap.type=1);const s=this._nodes.nodeFrame,a=s.renderId,o=this._currentRenderContext,l=this._currentRenderObjectFunction,u=this._handleObjectFunction,c=this._compilationPromises;null===i&&(i=e);const h=!0===e.isScene?e:!0===i.isScene?i:sw,d=this.needsFrameBufferTarget&&null===this._renderTarget,p=this._renderTarget||this._outputRenderTarget,f=!0===this.xr.isPresenting&&this.isOutputTarget,m=d?this._getFrameBufferTarget():p,g=this._activeCubeFace,_=this._activeMipmapLevel,v={useFrameBufferTarget:d,renderTarget:m,outputRenderTarget:d?p:this._renderTarget,activeCubeFace:g,activeMipmapLevel:_,item:null,materialSide:null,mrt:this._mrt,outputMRT:this._mrt};this._beginPreCompile(v);const b=this._renderContexts.get(m,this._mrt,this._callDepth,t);v.renderContext=b;const y=[];this._currentRenderContext=b,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=y,s.renderId++,s.update(),b.depth=this.depth,b.stencil=this.stencil,b.clippingContext||(b.clippingContext=new zE),b.clippingContext.updateGlobal(h,t),!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),t=this._updateCamera(t,f),h.onBeforeRender(this,e,t,m),this.drawingPipeline.begin(t,b);const x=this._renderLists.get(h,t,this.lighting);if(this.drawingPipeline.beginRenderList(x),this.drawingPipeline.project(e,t,0,x,b.clippingContext),i!==e&&i.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&x.pushLight(e)}),this.drawingPipeline.finishRenderList(x),null!==m){this._textures.updateRenderTarget(m,_);const e=this._textures.get(m);b.textures=e.textures,b.depthTexture=e.depthTexture}else b.textures=null,b.depthTexture=null;i!==e?this._background.update(i,x,b):this._background.update(h,x,b);const S=x.opaque,T=x.transparent,M=x.transparentDoublePass,E=x.lightsNode;!0===this.opaque&&S.length>0&&this._renderObjects(S,t,h,E),!0===this.transparent&&T.length>0&&this._renderTransparents(T,M,t,h,E),s.renderId=a,this._currentRenderContext=o,this._currentRenderObjectFunction=l,this._handleObjectFunction=u,this._compilationPromises=c,this._finishPreCompile();const w=y.length;let A=0;const R=new cw,C=new Set,N=()=>{A++,null!==r&&r(new ProgressEvent("progress",{lengthComputable:!0,loaded:A,total:w}))},P=async()=>{if(!1===R.needsYield())return;const e=this._precompilationState;this._finishPreCompile(),await R.yield(),this._beginPreCompile(e)};for(const e of y){if(void 0!==e.computeNodes){await this.compileComputeAsync(e.computeNodes),N();continue}const t=[],i=e.precompilationState;i.item=e,this._beginPreCompile(i);const r=this._objects.get(e.object,e.material,e.scene,e.camera,e.lightsNode,e.renderContext,e.clippingContext,e.passId);if(r.drawRange=e.object.geometry.drawRange,r.group=e.group,await this._nodes.getForRenderAsync(r,P),this._nodes.updateBefore(r),this._geometries.updateForRender(r),this._nodes.updateForRender(r),this._bindings.updateForRender(r),this._pipelines.getForRender(r,t),this._nodes.updateAfter(r),this._finishPreCompile(),t.length>0){const e=Promise.all(t).then(()=>{C.delete(e),N()});for(C.add(e);C.size>=16;)await Promise.race(C)}else N();R.needsYield()&&await R.yield()}await Promise.all(C)}_beginPreCompile(e){const{useFrameBufferTarget:t,renderTarget:i,mrt:r,renderContext:n,item:s}=e;!0===t&&this.setRenderTarget(i),this.setMRT(r),null!==s&&(e.materialSide=s.material.side,s.material.side=s.side),this._callDepth++,e.previousRenderContext=this._currentRenderContext,void 0!==n&&(this._currentRenderContext=n),this._precompilationState=e}_finishPreCompile(){const{useFrameBufferTarget:e,outputRenderTarget:t,activeCubeFace:i,activeMipmapLevel:r,outputMRT:n,previousRenderContext:s,item:a,materialSide:o}=this._precompilationState;!0===e&&this.setRenderTarget(t,i,r),this.setMRT(n),null!==a&&(a.material.side=o),this._currentRenderContext=s,this._callDepth--,this._precompilationState=null}async compileComputeAsync(e,t=null){if(!0===this._isDeviceLost)return;!1===this._initialized&&await this.init();const i=Array.isArray(e)?e:[e];if(0===i.length||i.some(e=>null==e||!0!==e.isComputeNode))throw new Error("THREE.Renderer: .compileComputeAsync() expects a ComputeNode.");const r=i.length;let n=0;const s=new cw,a=new Set,o=()=>{n++,null!==t&&t(new ProgressEvent("progress",{lengthComputable:!0,loaded:n,total:r}))},l=async()=>{s.needsYield()&&await s.yield()},u=this._pipelines,c=this._bindings,h=this._nodes;for(const e of i){if(!1===u.has(e)){const t=()=>{e.removeEventListener("dispose",t),u.delete(e),c.deleteForCompute(e),h.delete(e)};e.addEventListener("dispose",t);const i=e.onInitFunction;null!==i&&i.call(e,{renderer:this})}await h.getForComputeAsync(e,l),h.updateBeforeForCompute(e),h.updateForCompute(e),c.updateForCompute(e);const t=c.getForCompute(e),i=[];if(u.getForCompute(e,t,i),h.updateAfterForCompute(e),i.length>0){const e=Promise.all(i).then(()=>{a.delete(e),o()});for(a.add(e);a.size>=16;)await Promise.race(a)}else o();await l()}await Promise.all(a)}async renderAsync(e,t){Ei('Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.render(e,t)}async waitForGPU(){Mi("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=dg,t.modelNormalViewMatrix=pg):this.highPrecision&&(delete t.modelViewMatrix,delete t.modelNormalViewMatrix)}get highPrecision(){const e=this.contextNode.value;return e.modelViewMatrix===dg&&e.modelNormalViewMatrix===pg}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getOutputBufferType(){return this._outputBufferType}getColorBufferType(){return Ei('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}`),Mi(t),this._isDeviceLost=!0}_onError(e){let t=`WebGPURenderer: Uncaptured ${e.api} ${e.type}`;e.message&&(t+=`: ${e.message}`),Mi(t)}_bundleNeedsUpdate(e,t){if(void 0===t.bundleGPU||e.version!==t.version||t.drawingPipeline!==this.drawingPipeline)return!0;const i=this._attributes;if(t.attributesDisposeVersion!==i.disposeVersion){t.attributesDisposeVersion=i.disposeVersion;for(const e of t.renderObjects){const r=e.getIndex();let n=null!==r&&!1===i.has(r);for(const t of e.getVertexBuffers())!1===i.has(t)&&(n=!0);if(n)return t.version=null,!0}}return!1}_renderBundle(e,t,i){const{bundleGroup:r,camera:n,renderList:s}=e,a=this._currentRenderContext,o=this._bundles.get(r,n,a),l=this.backend.get(o);if(this._bundleNeedsUpdate(r,l)){this.backend.beginBundle(a);const e=this._currentRenderBundle;this._currentRenderBundle=o,l.version=r.version,l.drawingPipeline=this.drawingPipeline;const{transparentDoublePass:u,transparent:c,opaque:h}=s;!0===this.opaque&&h.length>0&&this._renderObjects(h,n,t,i),!0===this.transparent&&c.length>0&&this._renderTransparents(c,u,n,t,i),this._currentRenderBundle=e,this.backend.finishBundle(a,o)}else{const{renderObjects:e}=l;for(let t=0,i=e.length;t<i;t++){const i=e[t],r=this._nodes.needsRefresh(i);r===gi?(this._nodes.updateBefore(i),this._geometries.updateForRender(i),this._nodes.updateForRender(i),this._bindings.updateForRender(i),this._nodes.updateAfter(i)):r===mi&&(this._nodes.updateBefore(i),this._nodes.updateForRender(i),this._bindings.updateSharedForRender(i),this._nodes.updateAfter(i))}}this.backend.addBundle(a,o)}render(e,t){if(!1===this._initialized)throw new Error('THREE.Renderer: .render() called before the backend is initialized. Use "await renderer.init();" before rendering.');this._animation.start(),this._renderScene(e,t)}get initialized(){return this._initialized}_renderOutputLayers(e,t){if(!0===this.backend.isWebGLBackend&&!0===t.multiview||!0!==t.texture.isArrayTexture||t.texture.image.depth<=1)return void this._renderScene(e,e.camera,!1);const i=this._activeCubeFace;try{for(let i=0;i<t.texture.image.depth;i++)this._nodes.setOutputLayerIndex(i),this._activeCubeFace=i,this._renderScene(e,e.camera,!1)}finally{this._nodes.setOutputLayerIndex(0),this._activeCubeFace=i}}_getFrameBufferTarget(){if(!1===this.needsFrameBufferTarget)return null;const{width:e,height:t}=this.getDrawingBufferSize(aw),{depth:i,stencil:r}=this,n=this._outputRenderTarget||this._canvasTarget;let s=this._frameBufferTargets.get(n);if(void 0===s){s=new cr(e,t,{depthBuffer:i,stencilBuffer:r,type:this._outputBufferType,format:tt,colorSpace:Qi.workingColorSpace,generateMipmaps:!1,minFilter:Oe,magFilter:Oe,samples:this.samples}),s.isPostProcessingRenderTarget=!0;const a=()=>{n.removeEventListener("dispose",a),s.dispose(),this._frameBufferTargets.delete(n);const e=this._quadCache.get(s);void 0!==e&&(e.quad.material.dispose(),this._quadCache.delete(s))};n.addEventListener("dispose",a),this._frameBufferTargets.set(n,s)}const a=this.getOutputRenderTarget();s.depthBuffer=i,s.stencilBuffer=r,null!==a?s.setSize(a.width,a.height,a.depth):s.setSize(e,t,1);const o=this._outputRenderTarget?this._outputRenderTarget.viewport:n._viewport,l=this._outputRenderTarget?this._outputRenderTarget.scissor:n._scissor,u=this._outputRenderTarget?1:n._pixelRatio,c=this._outputRenderTarget?this._outputRenderTarget.scissorTest:n._scissorTest;return s.viewport.copy(o),s.scissor.copy(l),s.viewport.multiplyScalar(u),s.scissor.multiplyScalar(u),s.scissorTest=c,s.multiview=null!==a&&a.multiview,s.useArrayDepthTexture=null!==a&&a.useArrayDepthTexture,s.resolveDepthBuffer=null===a||a.resolveDepthBuffer,s.resolveStencilBuffer=null===a||a.resolveStencilBuffer,s.storeMultisampledColorBuffer=null===a||a.storeMultisampledColorBuffer,s.storeMultisampledDepthBuffer=null===a||a.storeMultisampledDepthBuffer,s.storeMultisampledStencilBuffer=null===a||a.storeMultisampledStencilBuffer,s._autoAllocateDepthBuffer=null!==a&&a._autoAllocateDepthBuffer,s}_renderScene(e,t,i=!0){if(!0===this._isDeviceLost)return;2===this.shadowMap.type&&(Ti("WebGPURenderer: PCFSoftShadowMap has been removed. Using PCFShadowMap instead."),this.shadowMap.type=1);const r=i?this._getFrameBufferTarget():null,n=this._nodes.nodeFrame,s=n.renderId,a=this._currentRenderContext,o=this._currentRenderObjectFunction,l=this._handleObjectFunction,u=this._currentRenderBundle;this._currentRenderBundle=null,this.lighting.beginRender(e),this._callDepth++;const c=!0===e.isScene?e:sw,h=this._renderTarget||this._outputRenderTarget,d=!0===this.xr.isPresenting&&this.isOutputTarget,p=this._activeCubeFace,f=this._activeMipmapLevel;let m;if(null!==r?(m=r,this.setRenderTarget(m)):m=h,null!==m&&!0===m.depthBuffer){const e=this._textures.get(m);!0!==e.depthInitialized&&((!1===this.autoClear||!0===this.autoClear&&!1===this.autoClearDepth)&&this.clearDepth(),e.depthInitialized=!0)}const g=this._renderContexts.get(m,this._mrt,this._callDepth,t);this._currentRenderContext=g,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this._handleObjectFunction=this._renderObjectDirect,this.info.calls++,this.info.render.calls++,this.info.render.frameCalls++,n.renderId=this.info.calls,this.backend.updateTimeStampUID(g),this.inspector.beginRender(this.backend.getTimestampUID(g),e,t,m),!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),t=this._updateCamera(t,d);const _=this._canvasTarget;let v=_._viewport,b=_._scissor,y=_._scissorTest,x=_._pixelRatio;null!==m&&(v=m.viewport,b=m.scissor,y=m.scissorTest,x=1);const S=void 0===v.minDepth?0:v.minDepth,T=void 0===v.maxDepth?1:v.maxDepth;g.viewportValue.copy(v).multiplyScalar(x).floor(),g.viewportValue.width>>=f,g.viewportValue.height>>=f,g.viewportValue.minDepth=S,g.viewportValue.maxDepth=T,g.scissorValue.copy(b).multiplyScalar(x).floor(),g.scissorValue.width>>=f,g.scissorValue.height>>=f,g.clippingContext||(g.clippingContext=new zE),g.clippingContext.updateGlobal(c,t),c.onBeforeRender(this,e,t,m),this.drawingPipeline.begin(t,g),this._renderLists.update(n.frameId);const M=this._renderLists.get(e,t,this.lighting);if(this.drawingPipeline.beginRenderList(M),this.drawingPipeline.project(e,t,0,M,g.clippingContext),this.drawingPipeline.finishRenderList(M),!0===this.sortObjects&&M.sort(this._opaqueSort,this._transparentSort),null!==m){this._textures.updateRenderTarget(m,f);const e=this._textures.get(m);g.textures=e.textures,g.depthTexture=e.depthTexture,g.width=e.width,g.height=e.height,g.renderTarget=m,g.depth=m.depthBuffer,g.stencil=m.stencilBuffer}else this.getDrawingBufferSize(aw),g.textures=null,g.depthTexture=null,g.width=aw.width,g.height=aw.height,g.depth=this.depth,g.stencil=this.stencil;g.width>>=f,g.height>>=f,g.activeCubeFace=p,g.activeMipmapLevel=f,g.occlusionQueryCount=M.occlusionQueryCount,g.fullscreenPass=!0===e.isQuadMesh,g.scissorValue.max(lw.set(0,0,0,0)),g.scissorValue.x+g.scissorValue.width>g.width&&(g.scissorValue.width=Math.max(g.width-g.scissorValue.x,0)),g.scissorValue.y+g.scissorValue.height>g.height&&(g.scissorValue.height=Math.max(g.height-g.scissorValue.y,0)),ow.set(0,0,g.width,g.height),g.viewport=!1===g.viewportValue.equals(ow),g.scissor=y&&!1===g.scissorValue.equals(ow),this._background.update(c,M,g),g.camera=t,this.backend.beginRender(g);const{bundles:E,lightsNode:w,transparentDoublePass:A,transparent:R,opaque:C}=M;return E.length>0&&this._renderBundles(E,c,w),!0===this.opaque&&C.length>0&&this._renderObjects(C,t,c,w),!0===this.transparent&&R.length>0&&this._renderTransparents(R,A,t,c,w),this.backend.finishRender(g),n.renderId=s,this._currentRenderContext=a,this._currentRenderObjectFunction=o,this._handleObjectFunction=l,this._currentRenderBundle=u,this.lighting.finishRender(e),this._callDepth--,null!==r&&(this.setRenderTarget(h,p,f),this._renderOutput(m)),c.onAfterRender(this,e,t,m),this.inspector.finishRender(this.backend.getTimestampUID(g)),g}_setXRLayerSize(e,t){this._canvasTarget._width=e,this._canvasTarget._height=t,this.setViewport(0,0,e,t)}_renderOutput(e){const t=this._nodes.getOutputCacheKey();let i,r=this._quadCache.get(e);void 0===r?(i=new ny(new Jb),i.name="Output Color Transform",i.material.name="outputColorTransform",i.material.fragmentNode=this._nodes.getOutputNode(e.texture),r={quad:i,cacheKey:t},this._quadCache.set(e,r)):(i=r.quad,r.cacheKey!==t&&(i.material.fragmentNode=this._nodes.getOutputNode(e.texture),i.material.needsUpdate=!0,r.cacheKey=t));const n=this.autoClear,s=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderOutputLayers(i,e),this.autoClear=n,this.xr.enabled=s}getMaxAnisotropy(){return this.backend.capabilities.getMaxAnisotropy()}getActiveCubeFace(){return this._activeCubeFace}getActiveMipmapLevel(){return this._activeMipmapLevel}async setAnimationLoop(e){!1===this._initialized&&await this.init(),null!==e&&this._animation.start(),this._animation.setAnimationLoop(e)}getAnimationLoop(){return this._animation.getAnimationLoop()}async getArrayBufferAsync(e,t=null,i=0,r=-1){if(null!==t&&t.isReadbackBuffer&&!1===this.info.memoryMap.has(t)){this.info.createReadbackBuffer(t);const e=()=>{t.removeEventListener("dispose",e),this.info.destroyReadbackBuffer(t)};t.addEventListener("dispose",e)}if(i%4!=0||r>0&&r%4!=0)throw new Error('THREE.Renderer: "getArrayBufferAsync()" offset and count must be a multiple of 4.');return await this.backend.getArrayBufferAsync(e,t,i,r)}getContext(){return this.backend.getContext()}getPixelRatio(){return this._canvasTarget.getPixelRatio()}getDrawingBufferSize(e){return this._canvasTarget.getDrawingBufferSize(e)}getSize(e){return this._canvasTarget.getSize(e)}setPixelRatio(e=1){this._canvasTarget.setPixelRatio(e)}setDrawingBufferSize(e,t,i){this.xr&&this.xr.isPresenting||this._canvasTarget.setDrawingBufferSize(e,t,i)}setSize(e,t,i=!0){this.xr&&this.xr.isPresenting||this._canvasTarget.setSize(e,t,i)}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}getScissor(e){return this._canvasTarget.getScissor(e)}setScissor(e,t,i,r){this._canvasTarget.setScissor(e,t,i,r)}getScissorTest(){return this._canvasTarget.getScissorTest()}setScissorTest(e){this._canvasTarget.setScissorTest(e),this.backend.setScissorTest(e)}resetState(){if(!1===this._initialized)throw new Error('THREE.Renderer: .resetState() called before the backend is initialized. Use "await renderer.init();" before using this method.');this.backend.resetState()}getViewport(e){return this._canvasTarget.getViewport(e)}setViewport(e,t,i,r,n=0,s=1){this._canvasTarget.setViewport(e,t,i,r,n,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,i=!0){if(!1===this._initialized)throw new Error('THREE.Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before using this method.');const r=this._renderTarget||this._getFrameBufferTarget();let n=null;if(null!==r){this._textures.updateRenderTarget(r);const e=this._textures.get(r);n=this._renderContexts.get(r,null,-1),n.textures=e.textures,n.depthTexture=e.depthTexture,n.width=e.width,n.height=e.height,n.renderTarget=r,n.depth=r.depthBuffer,n.stencil=r.stencilBuffer;const t=this.backend.getClearColor();n.clearColorValue.r=t.r,n.clearColorValue.g=t.g,n.clearColorValue.b=t.b,n.clearColorValue.a=t.a,n.clearDepthValue=this.getClearDepth(),n.clearStencilValue=this.getClearStencil(),n.activeCubeFace=this.getActiveCubeFace(),n.activeMipmapLevel=this.getActiveMipmapLevel(),!0===r.depthBuffer&&(e.depthInitialized=!0)}this.backend.clear(e,t,i,n),null!==r&&null===this._renderTarget&&this._renderOutput(r)}clearColor(){this.clear(!0,!1,!1)}clearDepth(){this.clear(!1,!0,!1)}clearStencil(){this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,i=!0){Ei('Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.clear(e,t,i)}async clearColorAsync(){Ei('Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.'),this.clear(!0,!1,!1)}async clearDepthAsync(){Ei('Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!0,!1)}async clearStencilAsync(){Ei('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!==Qi.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||!0===this._currentRenderContext?.fullscreenPass)&&(e=0),e}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:0}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:Qi.workingColorSpace}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||null===this._renderTarget}async dispose(){if(null!==this._initPromise&&await this.init(),!0===this._initialized){this.drawingPipeline.dispose(),this.lighting.dispose(),this._inspector.dispose(),this._animation.dispose(),this._objects.dispose(),this._geometries.dispose(),this._attributes.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose();for(const e of this._frameBufferTargets.keys())e.dispose();this._destroyCanvasTarget(this._canvasTarget),this._textures.dispose(),this.info.dispose(),await this.backend.dispose()}this.setRenderTarget(null)}setRenderTarget(e,t=0,i=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=i}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),this._canvasTarget.addEventListener("dispose",this._onCanvasTargetDispose)}getCanvasTarget(){return this._canvasTarget}_resetXRState(){this.backend.setXRTarget(null),this.setOutputRenderTarget(null),this.setRenderTarget(null);for(const e of this._frameBufferTargets.keys())e.dispose()}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e,t=null){if(!0===this._isDeviceLost)return;if(!1===this._initialized)return Ti('Renderer: ".compute()" called before the backend is initialized. Try using ".computeAsync()" instead.'),this.computeAsync(e,t);const i=Array.isArray(e)?e:[e];if(0===i.length||i.some(e=>!0!==e?.isComputeNode))throw new Error('THREE.Renderer: ".compute()" expects a "ComputeNode".');if(null!==t&&i.some(e=>null!==e.count||null!==e.dispatchSize))throw new Error('THREE.Renderer: A dispatch size cannot be passed to "renderer.compute()" for nodes created with "compute( count )". Use "computeKernel()" instead.');this._animation.start();const r=this._nodes.nodeFrame,n=r.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,r.renderId=this.info.calls,this.backend.updateTimeStampUID(e),this.inspector.beginCompute(this.backend.getTimestampUID(e),e);const s=this.backend,a=this._pipelines,o=this._bindings,l=this._nodes;s.beginCompute(e);for(const r of i){if(!1===a.has(r)){const e=()=>{r.removeEventListener("dispose",e),a.delete(r),o.deleteForCompute(r),l.delete(r)};r.addEventListener("dispose",e);const t=r.onInitFunction;null!==t&&t.call(r,{renderer:this})}l.updateBeforeForCompute(r),l.updateForCompute(r),o.updateForCompute(r);const i=o.getForCompute(r),n=a.getForCompute(r,i);this._updateDispatchSize(r,t),s.compute(e,r,i,n,t),l.updateAfterForCompute(r)}s.finishCompute(e),r.renderId=n,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 Ei('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('THREE.Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before using this method.');return this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){Ei('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('THREE.Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before using this method.');this._textures.updateTexture(e)}initRenderTarget(e){if(!1===this._initialized)throw new Error('THREE.Renderer: .initRenderTarget() called before the backend is initialized. Use "await renderer.init();" before using this method.');this._textures.updateRenderTarget(e);const t=this._textures.get(e),i=this._renderContexts.get(e);i.textures=t.textures,i.depthTexture=t.depthTexture,i.width=t.width,i.height=t.height,i.renderTarget=e,i.depth=e.depthBuffer,i.stencil=e.stencilBuffer,this.backend.initRenderTarget(i)}copyFramebufferToTexture(e,t=null){if(null!==t)if(t.isVector2)t=lw.set(t.x,t.y,e.image.width,e.image.height).floor();else{if(!t.isVector4)return void Mi("Renderer.copyFramebufferToTexture: Invalid rectangle.");t=lw.copy(t).floor()}else t=lw.set(0,0,e.image.width,e.image.height);let i,r=this._currentRenderContext;null!==r?i=r.renderTarget:(i=this._renderTarget||this._getFrameBufferTarget(),null!==i&&(this._textures.updateRenderTarget(i),r=this._textures.get(i))),this._textures.updateTexture(e,{renderTarget:i}),this.backend.copyFramebufferToTexture(e,r,t),this._inspector.copyFramebufferToTexture(e)}copyTextureToTexture(e,t,i=null,r=null,n=0,s=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,i,r,n,s),this._inspector.copyTextureToTexture(e,t)}async readRenderTargetPixelsAsync(e,t,i,r,n,s=0,a=0){return this.backend.copyTextureToBuffer(e.textures[s],t,i,r,n,a)}_renderBundles(e,t,i){for(const r of e)this._renderBundle(r,t,i)}_renderTransparents(e,t,i,r,n){if(t.length>0){for(const{material:e}of t)e.side=1;this._renderObjects(t,i,r,n,"backSide");for(const{material:e}of t)e.side=0;this._renderObjects(e,i,r,n);for(const{material:e}of t)e.side=2}else this._renderObjects(e,i,r,n)}_renderObjects(e,t,i,r,n=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,i,t,o,l,u,r,c,n)}}_getShadowNodes(e){const t=e.version;let i=this._cacheShadowNodes.get(e);if(void 0===i||i.version!==t){const r=e.map&&e.map.isTexture,n=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(r||n||s||a){let t,i;if(s?(t=e.castShadowNode.rgb,i=e.castShadowNode.a,!0!==this.shadowMap.transmitted&&Ei("Renderer: `shadowMap.transmitted` needs to be set to `true` when using `material.castShadowNode`.")):(t=Dh(0),i=Eh(1)),r&&(i=i.mul(A_("map","texture",e).a)),n&&(i=i.mul(e.colorNode.a)),l=Oh(t,i),a){const t=e.maskShadowNode||e.maskNode;l=yh(([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),i={version:t,colorNode:l,depthNode:u,positionNode:o},this._cacheShadowNodes.set(e,i)}return i}_updateCamera(e,t){const i=this.xr,r=!0===i.enabled&&!0===i.isPresenting&&!0===t;if(!1===r){let t=!1;if(!0===this.reversedDepthBuffer&&!0!==e.reversedDepth){if(e._reversedDepth=!0,e.isArrayCamera)for(const t of e.cameras)t._reversedDepth=!0;t=!0}const i=this.coordinateSystem;if(e.coordinateSystem!==i){if(e.coordinateSystem=i,e.isArrayCamera)for(const t of e.cameras)t.coordinateSystem=i;t=!0}if(!0===t&&(e.updateProjectionMatrix(),e.isArrayCamera))for(const t of e.cameras)t.updateProjectionMatrix()}return null===e.parent&&!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),!0===r&&(!0===i.cameraAutoUpdate&&i.updateCamera(e),e=i.getCamera()),e}_updateDispatchSize(e,t){const i=null!==t?t:e.dispatchSize;i&&!0===i.isIndirectStorageBufferAttribute&&this._attributes.update(i,WT)}renderObject(e,t,i,r,n,s,a,o=null,l=null){let u,c,h,d,p,f,m,g=!1;const _=this._currentSourceMaterial;if(e.onBeforeRender(this,t,i,r,n,s),!0===n.allowOverride&&null!==t.overrideMaterial){this._currentSourceMaterial=n;const e=t.overrideMaterial;if(g=!0,u=e.isNodeMaterial?e.colorNode:null,c=e.isNodeMaterial?e.depthNode:null,h=e.isNodeMaterial?e.positionNode:null,d=t.overrideMaterial.side,p=e.displacementMap,f=e.displacementScale,m=e.displacementBias,n.positionNode&&n.positionNode.isNode&&(e.positionNode=n.positionNode),e._alphaTest=n.alphaTest,e.alphaMap=n.alphaMap,e.displacementMap=n.displacementMap,e.displacementScale=n.displacementScale,e.displacementBias=n.displacementBias,e.transparent=n.transparent||n.transmission>0||n.transmissionNode&&n.transmissionNode.isNode||n.backdropNode&&n.backdropNode.isNode,e.isShadowPassMaterial){const{colorNode:t,depthNode:i,positionNode:r}=this._getShadowNodes(n);3===this.shadowMap.type?e.side=null!==n.shadowSide?n.shadowSide:n.side:e.side=null!==n.shadowSide?n.shadowSide:uw[n.side],null!==t&&(e.colorNode=t),null!==i&&(e.depthNode=i),null!==r&&(e.positionNode=r)}n=e}!0===n.transparent&&2===n.side&&!1===n.forceSinglePass?(n.side=1,this._handleObjectFunction(e,n,t,i,a,s,o,"backSide"),n.side=0,this._handleObjectFunction(e,n,t,i,a,s,o,l),n.side=2):this._handleObjectFunction(e,n,t,i,a,s,o,l),g&&(t.overrideMaterial.colorNode=u,t.overrideMaterial.depthNode=c,t.overrideMaterial.positionNode=h,t.overrideMaterial.side=d,t.overrideMaterial.displacementMap=p,t.overrideMaterial.displacementScale=f,t.overrideMaterial.displacementBias=m),this._currentSourceMaterial=_,e.onAfterRender(this,t,i,r,n,s)}hasCompatibility(e){if(!1===this._initialized)throw new Error('THREE.Renderer: .hasCompatibility() called before the backend is initialized. Use "await renderer.init();" before using this method.');return this.backend.hasCompatibility(e)}_renderObjectDirect(e,t,i,r,n,s,a,o){const l=this._objects.get(e,t,i,r,n,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===gi?(this._nodes.updateBefore(l),this._geometries.updateForRender(l),this._nodes.updateForRender(l),this._bindings.updateForRender(l)):u===mi&&(this._nodes.updateBefore(l),this._nodes.updateForRender(l),this._bindings.updateSharedForRender(l)),this._pipelines.updateForRender(l),this._pipelines.isReady(l)?(this.backend.draw(l,this.info),u!==fi&&this._nodes.updateAfter(l)):null!==this._currentRenderBundle&&(this.backend.get(this._currentRenderBundle).version=-1)}_createObjectPipeline(e,t,i,r,n,s,a,o){if(null!==this._compilationPromises)return void this._compilationPromises.push({object:e,material:t,side:t.side,scene:i,camera:r,lightsNode:n,group:s,clippingContext:a,passId:o,renderContext:this._currentRenderContext,precompilationState:{...this._precompilationState,useFrameBufferTarget:!0,renderTarget:this.getRenderTarget(),mrt:this.getMRT(),renderContext:this._currentRenderContext}});const l=this._objects.get(e,t,i,r,n,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()}_onCanvasTargetDispose(e){this._destroyCanvasTarget(e.target)}_destroyCanvasTarget(e){e.removeEventListener("dispose",this._onCanvasTargetDispose),this._initialized&&this.backend.destroyCanvasTarget(e)}get compile(){return this.compileAsync}}class dw{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}clone(){return Object.assign(new this.constructor,this)}}class pw extends dw{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)+(jT-e%jT)%jT;var e}get buffer(){return this._buffer}update(){return!0}release(){this._buffer=null}}class fw extends pw{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let mw=0;class gw extends fw{constructor(e,t){super("UniformBuffer_"+(e&&e.name?e.name:mw++)),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 _w extends fw{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[],this._updateRangeCache=new Map,this._addedIndices=new Set}addUniformUpdateRange(e){const t=e.index;if(this._addedIndices.has(t))return;let i=this._updateRangeCache.get(t);void 0===i&&(i={start:0,count:0},this._updateRangeCache.set(t,i)),i.start=e.offset,i.count=e.itemSize,this._addedIndices.add(t),this.updateRanges.push(i)}clearUpdateRanges(){this._addedIndices.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 i=0,r=this.uniforms.length;i<r;i++){const r=this.uniforms[i],n=r.boundary,s=r.itemSize*e,a=t%jT,o=a%n,l=a+o;t+=o,0!==l&&jT-l<s&&(t+=jT-l),r.offset=t/e,r.index=i,t+=s}return Math.ceil(t/jT)*jT}update(){let e=!1;for(const t of this.uniforms)!0===this.updateByType(t)&&(e=!0);return e}release(){super.release(),this._values=null}clone(){const e=super.clone();return e._buffer=null,e._values=null,e._updateRanges=[],e._updateRangeCache=new Map,e._addedIndices=new Set,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 Mi("WebGPUUniformsGroup: Unsupported uniform type.",e)}updateNumber(e){let t=!1;const i=this.values,r=e.getValue(),n=e.offset,s=e.getType();if(i[n]!==r){this._getBufferForType(s)[n]=i[n]=r,t=!0,this.addUniformUpdateRange(e)}return t}updateVector2(e){let t=!1;const i=this.values,r=e.getValue(),n=e.offset,s=e.getType();if(i[n+0]!==r.x||i[n+1]!==r.y){const a=this._getBufferForType(s);a[n+0]=i[n+0]=r.x,a[n+1]=i[n+1]=r.y,t=!0,this.addUniformUpdateRange(e)}return t}updateVector3(e){let t=!1;const i=this.values,r=e.getValue(),n=e.offset,s=e.getType();if(i[n+0]!==r.x||i[n+1]!==r.y||i[n+2]!==r.z){const a=this._getBufferForType(s);a[n+0]=i[n+0]=r.x,a[n+1]=i[n+1]=r.y,a[n+2]=i[n+2]=r.z,t=!0,this.addUniformUpdateRange(e)}return t}updateVector4(e){let t=!1;const i=this.values,r=e.getValue(),n=e.offset,s=e.getType();if(i[n+0]!==r.x||i[n+1]!==r.y||i[n+2]!==r.z||i[n+3]!==r.w){const a=this._getBufferForType(s);a[n+0]=i[n+0]=r.x,a[n+1]=i[n+1]=r.y,a[n+2]=i[n+2]=r.z,a[n+3]=i[n+3]=r.w,t=!0,this.addUniformUpdateRange(e)}return t}updateColor(e){let t=!1;const i=this.values,r=e.getValue(),n=e.offset;if(i[n+0]!==r.r||i[n+1]!==r.g||i[n+2]!==r.b){const s=this.buffer;s[n+0]=i[n+0]=r.r,s[n+1]=i[n+1]=r.g,s[n+2]=i[n+2]=r.b,t=!0,this.addUniformUpdateRange(e)}return t}updateMatrix3(e){let t=!1;const i=this.values,r=e.getValue().elements,n=e.offset;if(i[n+0]!==r[0]||i[n+1]!==r[1]||i[n+2]!==r[2]||i[n+4]!==r[3]||i[n+5]!==r[4]||i[n+6]!==r[5]||i[n+8]!==r[6]||i[n+9]!==r[7]||i[n+10]!==r[8]){const s=this.buffer;s[n+0]=i[n+0]=r[0],s[n+1]=i[n+1]=r[1],s[n+2]=i[n+2]=r[2],s[n+4]=i[n+4]=r[3],s[n+5]=i[n+5]=r[4],s[n+6]=i[n+6]=r[5],s[n+8]=i[n+8]=r[6],s[n+9]=i[n+9]=r[7],s[n+10]=i[n+10]=r[8],t=!0,this.addUniformUpdateRange(e)}return t}updateMatrix4(e){let t=!1;const i=this.values,r=e.getValue().elements,n=e.offset;if(!1===function(e,t,i){for(let r=0,n=t.length;r<n;r++)if(e[i+r]!==t[r])return!1;return!0}(i,r,n)){this.buffer.set(r,n),function(e,t,i){for(let r=0,n=t.length;r<n;r++)e[i+r]=t[r]}(i,r,n),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 vw=0;class bw extends _w{constructor(e,t){super(e),this.id=vw++,this.groupNode=t,this.isNodeUniformsGroup=!0}}class yw extends dw{constructor(e,t){super(e),this._texture=t,this.version=-1,this.generation=null,this.samplerKey="",this.isSampler=!0}set texture(e){this._texture!==e&&(this._texture=e,this.reset())}get texture(){return this._texture}update(){const{texture:e,version:t}=this;return t!==e.version&&(this.version=e.version,!0)}reset(){this.generation=null,this.version=-1}release(){this._texture=null}}let xw=0;class Sw extends yw{constructor(e,t){super(e,t),this.id=xw++,this.store=!1,this.mipLevel=0,this.isSampledTexture=!0}}class Tw extends Sw{constructor(e,t,i,r=null){super(e,t?t.value:null),this.textureNode=t,this.groupNode=i,this.access=r}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}clone(){const e=super.clone();return e.texture=this.textureNode.value,e}}class Mw extends Tw{constructor(e,t,i,r=null){super(e,t,i,r),this.isSampledCubeTexture=!0}}class Ew extends Tw{constructor(e,t,i,r=null){super(e,t,i,r),this.isSampledTexture3D=!0}}const ww={textureGather:new wy("\nvec4 tsl_textureGather( const int comp, sampler2D map, vec2 coord, ivec2 offset, bool flipY ) {\n\tif ( flipY ) offset.y = - offset.y;\n\tvec2 size = vec2( textureSize( map, 0 ) );\n\tvec2 st = floor( coord * size + vec2( offset ) - 0.5 );\n\tvec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;\n\tvec4 ret = vec4(\n\t\ttextureLod( map, ij.xw, 0.0 )[ comp ],\n\t\ttextureLod( map, ij.zw, 0.0 )[ comp ],\n\t\ttextureLod( map, ij.zy, 0.0 )[ comp ],\n\t\ttextureLod( map, ij.xy, 0.0 )[ comp ]\n\t);\n\treturn flipY ? ret.wzyx : ret;\n}\n"),textureGatherArray:new wy("\nvec4 tsl_textureGather_array( const int comp, sampler2DArray map, vec3 coord, ivec2 offset, bool flipY ) {\n\tif ( flipY ) offset.y = - offset.y;\n\tvec2 size = vec2( textureSize( map, 0 ).xy );\n\tvec2 st = floor( coord.xy * size + vec2( offset ) - 0.5 );\n\tvec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;\n\tvec4 ret = vec4(\n\t\ttextureLod( map, vec3( ij.xw, coord.z ), 0.0 )[ comp ],\n\t\ttextureLod( map, vec3( ij.zw, coord.z ), 0.0 )[ comp ],\n\t\ttextureLod( map, vec3( ij.zy, coord.z ), 0.0 )[ comp ],\n\t\ttextureLod( map, vec3( ij.xy, coord.z ), 0.0 )[ comp ]\n\t);\n\treturn flipY ? ret.wzyx : ret;\n}\n"),textureGatherCompare:new wy("\nvec4 tsl_textureGatherCompare( sampler2DShadow map, vec2 coord, ivec2 offset, float ref, bool flipY ) {\n\tif ( flipY ) offset.y = - offset.y;\n\tvec2 size = vec2( textureSize( map, 0 ) );\n\tvec2 st = floor( coord * size + vec2( offset ) - 0.5 );\n\tvec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;\n\tvec4 ret = vec4(\n\t\ttextureLod( map, vec3( ij.xw, ref ), 0.0 ),\n\t\ttextureLod( map, vec3( ij.zw, ref ), 0.0 ),\n\t\ttextureLod( map, vec3( ij.zy, ref ), 0.0 ),\n\t\ttextureLod( map, vec3( ij.xy, ref ), 0.0 )\n\t);\n\treturn flipY ? ret.wzyx : ret;\n}\n"),textureGatherCompareArray:new wy("\nvec4 tsl_textureGatherCompare_array( sampler2DArrayShadow map, vec3 coord, ivec2 offset, float ref, bool flipY ) {\n\tif ( flipY ) offset.y = - offset.y;\n\tvec2 size = vec2( textureSize( map, 0 ).xy );\n\tvec2 st = floor( coord.xy * size + vec2( offset ) - 0.5 );\n\tvec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;\n\tvec4 ret = vec4(\n\t\ttexture( map, vec4( ij.xw, coord.z, ref ) ),\n\t\ttexture( map, vec4( ij.zw, coord.z, ref ) ),\n\t\ttexture( map, vec4( ij.zy, coord.z, ref ) ),\n\t\ttexture( map, vec4( ij.xy, coord.z, ref ) )\n\t);\n\treturn flipY ? ret.wzyx : ret;\n}\n"),floatpack_snorm_4x8:new wy("uint tsl_packSnorm4x8( vec4 v ) { uvec4 u = uvec4( ivec4( round( clamp( v, -1.0, 1.0 ) * 127.0 ) ) & 0xff ); return u.x | u.y << 8 | u.z << 16 | u.w << 24; }"),floatpack_unorm_4x8:new wy("uint tsl_packUnorm4x8( vec4 v ) { uvec4 u = uvec4( round( clamp( v, 0.0, 1.0 ) * 255.0 ) ); return u.x | u.y << 8 | u.z << 16 | u.w << 24; }"),floatunpack_snorm_4x8:new wy("vec4 tsl_unpackSnorm4x8( uint x ) { return max( vec4( ivec4( x << 24, x << 16, x << 8, x ) >> 24 ) / 127.0, -1.0 ); }"),floatunpack_unorm_4x8:new wy("vec4 tsl_unpackUnorm4x8( uint x ) { return vec4( uvec4( x, x >> 8, x >> 16, x >> 24 ) & 0xffu ) / 255.0; }")},Aw={equals:"equal",bitcast_float_int:"floatBitsToInt",bitcast_int_float:"intBitsToFloat",bitcast_uint_float:"uintBitsToFloat",bitcast_float_uint:"floatBitsToUint",floatpack_snorm_2x16:"packSnorm2x16",floatpack_unorm_2x16:"packUnorm2x16",floatpack_float16_2x16:"packHalf2x16",floatpack_snorm_4x8:"tsl_packSnorm4x8",floatpack_unorm_4x8:"tsl_packUnorm4x8",floatunpack_snorm_2x16:"unpackSnorm2x16",floatunpack_unorm_2x16:"unpackUnorm2x16",floatunpack_float16_2x16:"unpackHalf2x16",floatunpack_snorm_4x8:"tsl_unpackSnorm4x8",floatunpack_unorm_4x8:"tsl_unpackUnorm4x8"},Rw={low:"lowp",medium:"mediump",high:"highp"},Cw={swizzleAssign:!0,storageBuffer:!1},Nw={perspective:"smooth",linear:"noperspective"},Pw={centroid:"centroid"},Lw="\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",Dw=new Set(["const","uniform","buffer","shared","attribute","varying","coherent","volatile","restrict","readonly","writeonly","atomic_uint","layout","centroid","flat","smooth","noperspective","patch","sample","invariant","precise","break","continue","do","for","while","switch","case","default","if","else","subroutine","in","out","inout","int","void","bool","true","false","float","double","discard","return","vec2","vec3","vec4","ivec2","ivec3","ivec4","bvec2","bvec3","bvec4","uint","uvec2","uvec3","uvec4","dvec2","dvec3","dvec4","mat2","mat3","mat4","mat2x2","mat2x3","mat2x4","mat3x2","mat3x3","mat3x4","mat4x2","mat4x3","mat4x4","dmat2","dmat3","dmat4","dmat2x2","dmat2x3","dmat2x4","dmat3x2","dmat3x3","dmat3x4","dmat4x2","dmat4x3","dmat4x4","lowp","mediump","highp","precision","sampler2D","sampler3D","samplerCube","sampler2DShadow","samplerCubeShadow","sampler2DArray","sampler2DArrayShadow","isampler2D","isampler3D","isamplerCube","isampler2DArray","usampler2D","usampler3D","usamplerCube","usampler2DArray","struct","common","partition","active","asm","class","union","enum","typedef","template","this","resource","goto","inline","noinline","public","static","extern","external","interface","long","short","half","fixed","unsigned","superp","input","output","hvec2","hvec3","hvec4","fvec2","fvec3","fvec4","sampler3DRect","filter","sizeof","cast","namespace","using","main"]);class Uw extends pE{constructor(e,t){super(e,t,new DE),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==$t}_include(e){const t=ww[e];return t.build(this),this.addInclude(t),t}getMethod(e){return void 0!==ww[e]&&this._include(e),Aw[e]||e}getBitcastMethod(e,t){const i=this.getComponentType(t),r=this.getComponentType(e);return"float"!==i&&"float"!==r&&this.getTypeLength(t)===this.getTypeLength(e)?this.getType(e):this.getMethod(`bitcast_${i}_${r}`)}getFloatPackingMethod(e,t="2x16"){return this.getMethod(`floatpack_${e}_${t}`)}getFloatUnpackingMethod(e,t="2x16"){return this.getMethod(`floatunpack_${e}_${t}`)}getTernary(e,t,i){return`${e} ? ${t} : ${i}`}getVectorSelect(e,t,i,r){const n=this.getComponentType(r);if("float"===n)return`mix( ${i}, ${t}, ${e} )`;const s=this.getType(r);if("bool"===n){const n=this.getType(this.getTypeFromLength(this.getTypeLength(r),"int")),a=`${n}( ${i} )`;return`${s}( ${a} + ${`${n}( ${e} )`} * ( ${`${n}( ${t} )`} - ${a} ) )`}return`${i} + ${`${s}( ${e} )`} * ( ${t} - ${i} )`}getOutputStructName(){return""}buildFunctionCode(e){const t=e.layout,i=this.flowShaderNode(e),r=[];for(const e of t.inputs)r.push(this.getType(e.type)+" "+e.name);return`${this.getType(t.type)} ${t.name}( ${r.join(", ")} ) {\n\n\t${i.vars}\n\n${i.code}\n\treturn ${i.result};\n\n}`}setupPBO(e){const t=e.value;if(void 0===t.pbo){const e=t.array,i=t.count*t.itemSize,{itemSize:r}=t,n=t.array.constructor.name.toLowerCase().includes("int");let s=n?st:nt;2===r?s=n?ot:at:3===r?s=n?lt:et:4===r&&(s=n?ut:tt);const a={Float32Array:$e,Uint8Array:ze,Uint16Array:He,Uint32Array:je,Int8Array:Ge,Int16Array:Ve,Int32Array:We,Uint8ClampedArray:ze},o=Math.pow(2,Math.ceil(Math.log2(Math.sqrt(i/r))));let l=Math.ceil(i/r/o);o*l*r<i&&l++;const u=o*l*r,c=new e.constructor(u);c.set(e,0),t.array=c;const h=new Rs(t.array,o,l,s,a[t.array.constructor.name]||$e);h.needsUpdate=!0,h.isPBOTexture=!0;const d=new Xg(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)}isReservedKeyword(e){return Dw.has(e)}generatePBO(e){const{node:t,indexNode:i}=e,r=t.value;if(this.renderer.backend.has(r)){this.renderer.backend.get(r).pbo=r.pbo}const n=this.getUniformFromNode(r.pboNode,"texture",this.shaderStage,this.context.nodeName),s=this.getPropertyName(n);this.increaseUsage(i);const a=i.build(this,"uint"),o=this.getDataFromNode(e);let l=o.propertyName;if(void 0===l){const i=this.getVarFromNode(e);l=this.getPropertyName(i);const n=this.getDataFromNode(t);let u=n.propertySizeName;void 0===u&&(u=l+"Size",this.getVarFromNode(t,u,"uint"),this.addLineFlowCode(`${u} = uint( textureSize( ${s}, 0 ).x )`,e),n.propertySizeName=u);const{itemSize:c}=r,h="."+ac.join("").slice(0,c),d=`ivec2(${a} % ${u}, ${a} / ${u})`,p=this.generateTextureLoad(null,s,d,"0",null,null);let f="vec4";r.pbo.type===je?f="uvec4":r.pbo.type===We&&(f="ivec4");const m=this.getTypeFromLength(c,this.getComponentType(f)),g=e.getNodeType(this);this.addLineFlowCode(`${l} = ${this.format(`${f}(${p})${h}`,m,g)}`,e),o.propertyName=l}return l}generateTextureLoad(e,t,i,r,n,s){let a;return null===r&&(r="0"),a=n?s?`texelFetchOffset( ${t}, ivec3( ${i}, ${n} ), int( ${r} ), ${s} )`:`texelFetch( ${t}, ivec3( ${i}, ${n} ), int( ${r} ) )`:s?`texelFetchOffset( ${t}, ${i}, int( ${r} ), ${s} )`:`texelFetch( ${t}, ${i}, int( ${r} ) )`,null!==e&&e.isDepthTexture&&(a+=".x"),a}generateTexture(e,t,i,r,n){return r&&(i=`vec3( ${i}, ${r} )`),e.isDepthTexture?n?`textureOffset( ${t}, ${i}, ${n} ).x`:`texture( ${t}, ${i} ).x`:n?`textureOffset( ${t}, ${i}, ${n} )`:`texture( ${t}, ${i} )`}generateTextureSize(e,t,i){return`textureSize( ${t}, ${i} )`}generateTextureLevel(e,t,i,r,n,s){return n&&(i=`vec3( ${i}, ${n} )`),e.isDepthTexture?s?`textureLodOffset( ${t}, ${i}, ${r}, ${s} ).x`:`textureLod( ${t}, ${i}, ${r} ).x`:s?`textureLodOffset( ${t}, ${i}, ${r}, ${s} )`:`textureLod( ${t}, ${i}, ${r} )`}generateTextureBias(e,t,i,r,n,s){return n&&(i=`vec3( ${i}, ${n} )`),s?`textureOffset( ${t}, ${i}, ${s}, ${r} )`:`texture( ${t}, ${i}, ${r} )`}generateTextureGrad(e,t,i,r,n,s){return n&&(i=`vec3( ${i}, ${n} )`),s?`textureGradOffset( ${t}, ${i}, ${r[0]}, ${r[1]}, ${s} )`:`textureGrad( ${t}, ${i}, ${r[0]}, ${r[1]} )`}generateTextureCompare(e,t,i,r,n,s,a=this.shaderStage){if("fragment"===a)return e.isCubeTexture?`texture( ${t}, vec4( ${i}, ${r} ) )`:n?s?`textureOffset( ${t}, vec4( ${i}, ${n}, ${r} ), ${s} )`:`texture( ${t}, vec4( ${i}, ${n}, ${r} ) )`:s?`textureOffset( ${t}, vec3( ${i}, ${r} ), ${s} )`:`texture( ${t}, vec3( ${i}, ${r} ) )`;Mi(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${a} shader.`)}generateTextureGather(e,t,i,r,n,s,a){return e.isDepthTexture&&(r="0"),null===s&&(s="ivec2( 0 )"),null===a&&(a="false"),n?(this._include("textureGatherArray"),`tsl_textureGather_array( ${r}, ${t}, vec3( ${i}, ${n} ), ${s}, ${a} )`):(this._include("textureGather"),`tsl_textureGather( ${r}, ${t}, ${i}, ${s}, ${a} )`)}generateTextureGatherCompare(e,t,i,r,n,s,a){return null===s&&(s="ivec2( 0 )"),null===a&&(a="false"),n?(this._include("textureGatherCompareArray"),`tsl_textureGatherCompare_array( ${t}, vec3( ${i}, ${n} ), ${s}, ${r}, ${a} )`):(this._include("textureGatherCompare"),`tsl_textureGatherCompare( ${t}, ${i}, ${s}, ${r}, ${a} )`)}getUniformBufferName(e,t){return this.getDataFromNode(e.node,t,this.globalCache).uniformGPU.name}_getBindGroup(e,t){for(let i=0;i<t.length;i++)!0===t[i].isNodeUniformBuffer&&(t[i].name="NodeBuffer_"+e+"_"+i);return super._getBindGroup(e,t)}getUniforms(e){const t=this.uniforms[e],i=[],r={};for(const n of t){let t=null,s=!1;if("texture"===n.type||"texture3D"===n.type){const e=n.node,i=e.value,r=this.getComponentTypeFromTexture(i),s="float"===r?"":r.charAt(0);t="texture3D"===n.type&&!1===i.isArrayTexture?`${s}sampler3D ${n.name};`:i.compareFunction&&e.isSampleCompare()?!0===i.isArrayTexture?`sampler2DArrayShadow ${n.name};`:`sampler2DShadow ${n.name};`:!0===i.isArrayTexture||!0===i.isDataArrayTexture||!0===i.isCompressedArrayTexture?`${s}sampler2DArray ${n.name};`:`${s}sampler2D ${n.name};`}else if("cubeTexture"===n.type)t=`samplerCube ${n.name};`;else if("cubeDepthTexture"===n.type){t=n.node.value.compareFunction?`samplerCubeShadow ${n.name};`:`samplerCube ${n.name};`}else if("buffer"===n.type){const i=n.node,r=this.getType(i.bufferType),s=i.bufferCount,a=s>0?s:"";t=`${this.getUniformBufferName(n,e)} {\n\t${r} ${n.name}[${a}];\n};\n`}else{const e=n.groupNode.name;if(void 0===r[e]){const t=this.uniformGroups[e];if(void 0!==t){const i=[];for(const e of t.uniforms){const t=e.getType(),r=this.getVectorType(t),n=e.nodeUniform.node.precision;let s=`${r} ${e.name};`;null!==n&&(s=Rw[n]+" "+s),i.push("\t"+s)}r[e]=i}}s=!0}if(!s){const e=n.node.precision;null!==e&&(t=Rw[e]+" "+t),t="uniform "+t,i.push(t)}}let n="";for(const e in r){const t=r[e];n+=this._getGLSLUniformStruct(e,t.join("\n"))+"\n"}return n+=i.join("\n"),n}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==We){let i=e;e.isInterleavedBufferAttribute&&(i=e.data);const r=i.array;!1==(r instanceof Uint32Array||r instanceof Int32Array)&&(t=t.slice(1))}return t}getAttributes(e){let t="";if("vertex"===e||"compute"===e){const e=this.getAttributesArray();let i=0;for(const r of e)t+=`layout( location = ${i++} ) in ${r.type} ${r.name};\n`}return t}getStructMembers(e){const t=[];for(const i of e.members)t.push(`\t${i.type} ${i.name};`);return t.join("\n")}getStructs(e){const t=[],i=this.structs[e],r=[];for(const e of i)if(e.output)for(const t of e.members)r.push(`layout( location = ${t.index} ) out ${t.type} ${t.name};`);else{let i="struct "+e.name+" {\n";i+=this.getStructMembers(e),i+="\n};\n",t.push(i)}return"fragment"===e&&0===r.length&&r.push(`layout( location = 0 ) out ${this.getOutputType()} fragColor;`),"\n"+r.join("\n")+"\n\n"+t.join("\n")}generateConstStatement(e,t,i=null){return`const ${this.getVar(e,t,i)}`}generateVarStatement(e,t,i=null){return this.getVar(e,t,i)}getVaryings(e){let t="vertex"===e&&!0===this.context.invariant?"invariant gl_Position;\n":"";const i=this.varyings;if("vertex"===e||"compute"===e)for(const r of i){"compute"===e&&(r.needsInterpolation=!0);const i=this.getType(r.type);if(r.needsInterpolation)if(r.interpolationType){t+=`${Nw[r.interpolationType]||r.interpolationType} ${Pw[r.interpolationSampling]||""} out ${i} ${r.name};\n`}else{t+=`${i.includes("int")||i.includes("uv")||i.includes("iv")?"flat ":""}out ${i} ${r.name};\n`}else t+=`${i} ${r.name};\n`}else if("fragment"===e)for(const e of i)if(e.needsInterpolation){const i=this.getType(e.type);if(e.interpolationType){t+=`${Nw[e.interpolationType]||e.interpolationType} ${Pw[e.interpolationSampling]||""} in ${i} ${e.name};\n`}else{t+=`${i.includes("int")||i.includes("uv")||i.includes("iv")?"flat ":""}in ${i} ${e.name};\n`}}for(const i of this.builtins[e])t+=`${i};\n`;return t}getVertexIndex(){return"uint( gl_VertexID )"}getInstanceIndex(){return"uint( gl_InstanceID )"}getInvocationLocalIndex(){return`uint( gl_InstanceID ) % ${this.compute.workgroupSize.reduce((e,t)=>e*t,1)}u`}getSubgroupSize(){Mi("GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node")}getInvocationSubgroupIndex(){Mi("GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node")}getSubgroupIndex(){Mi("GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node")}enableSubGroups(){Mi("GLSLNodeBuilder: WebGLBackend does not support subgroup operations")}enableShaderF16(){Mi("GLSLNodeBuilder: WebGLBackend does not support 16 bit floats")}enableDualSourceBlending(){Mi("GLSLNodeBuilder: WebGLBackend does not support dual source blending")}getDrawIndex(){return this.renderer.backend.extensions.has("WEBGL_multi_draw")?"uint( gl_DrawID )":"nodeUniformDrawId"}getFrontFacing(){return"gl_FrontFacing"}getFragCoord(){return"gl_FragCoord.xy"}getFragDepth(){return"gl_FragDepth"}enableExtension(e,t,i=this.shaderStage){const r=this.extensions[i]||(this.extensions[i]=new Map);!1===r.has(e)&&r.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 i=this.extensions[e];if(void 0!==i)for(const{name:e,behavior:r}of i.values())t.push(`#extension ${e} : ${r}`);return t.join("\n")}getClipDistance(){return"gl_ClipDistance"}isAvailable(e){let t=Cw[e];if(void 0===t){let i;switch(t=!1,e){case"float32Filterable":i="OES_texture_float_linear";break;case"clipDistance":i="WEBGL_clip_cull_distance"}if(void 0!==i){const e=this.renderer.backend.extensions;e.has(i)&&(e.get(i),t=!0)}Cw[e]=t}return t}isFlipY(){return!0}enableHardwareClipping(e){this.enableExtension("GL_ANGLE_clip_cull_distance","require"),this.builtins.vertex.push(`out float gl_ClipDistance[ ${e} ]`)}enableMultiview(){this.enableExtension("GL_OVR_multiview2","require","fragment"),this.enableExtension("GL_OVR_multiview2","require","vertex"),this.builtins.vertex.push("layout(num_views = 2) in")}registerTransform(e,t){this.transforms.push({varyingName:e,attributeNode:t})}getTransforms(){const e=this.transforms;let t="";for(let i=0;i<e.length;i++){const r=e[i],n=this.getPropertyName(r.attributeNode);n&&(t+=`${r.varyingName} = ${n};\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${Lw}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\n\n// attributes\n${e.attributes}\n\n// vars\n${e.vars}\n\n// codes\n${e.codes}\n\nvoid main() {\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${Lw}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\n\n// vars\n${e.vars}\n\n// codes\n${e.codes}\n\nvoid main() {\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 i="// code\n\n";i+=this.flowCode[t];const r=this.flowNodes[t],n=r[r.length-1];for(const e of r){const r=this.getFlowData(e),s=e.name;s&&(i.length>0&&(i+="\n"),i+=`\t// flow -> ${s}\n\t`),i+=`${r.code}\n\t`,e===n&&"compute"!==t&&(i+="// result\n\t","vertex"===t?(i+="gl_Position = ",i+=`${this.format(r.result,n.getNodeType(this),"vec4")};`):"fragment"===t&&(e.outputNode.isOutputStructNode||(i+="fragColor = ",i+=`${this.format(r.result,n.getNodeType(this),this.getOutputType())};`)))}const s=e[t];if(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,!0),s.structs=this.getStructs(t),s.codes=this.getCodes(t),s.transforms=this.getTransforms(t),s.flow=i,"vertex"===t){const e=this.renderer.backend.extensions;this.object.isBatchedMesh&&!1===e.has("WEBGL_multi_draw")&&(s.uniforms+="\nuniform uint nodeUniformDrawId;\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,i,r=null){const n=super.getUniformFromNode(e,t,i,"buffer"===t?null:r),s=this.getDataFromNode(e,i,this.globalCache);let a=s.uniformGPU;if(void 0===a){const r=e.groupNode,o=r.name,l=this.getBindGroupArray(o,i);if("texture"===t)a=new Tw(n.name,n.node,r),l.push(a);else if("cubeTexture"===t||"cubeDepthTexture"===t)a=new Mw(n.name,n.node,r),l.push(a);else if("texture3D"===t)a=new Ew(n.name,n.node,r),l.push(a);else if("buffer"===t){const t=new gw(e,r);l.push(t),a=t}else{let e=this.uniformGroups[o];void 0===e?(e=new bw(o,r),this.uniformGroups[o]=e,l.push(e)):-1===l.indexOf(e)&&l.push(e),a=this.getNodeUniform(n,t);const i=a.name,s=e.uniforms.some(e=>e.name===i);s||e.addUniform(a)}s.uniformGPU=a}return n}}let Iw=null,Fw=null;class Ow{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={[di]:null,[hi]:null},this.trackTimestamp=!0===e.trackTimestamp}async init(e){this.renderer=e}get coordinateSystem(){}beginRender(){}finishRender(){}setXRTarget(){}beginCompute(){}finishCompute(){}draw(){}deleteVertexState(){}compute(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}updateBinding(){}createRenderPipeline(){}createComputePipeline(){}destroyPipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}updateSampler(){}destroySampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}createIndirectStorageAttribute(){}createUniformBuffer(){}destroyUniformBuffer(){}updateAttribute(){}destroyAttribute(){}getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}getContext(){}updateSize(){}updateViewport(){}destroyCanvasTarget(){}updateTimeStampUID(e){const t=this.get(e),i=this.renderer.info.frame;let r,n=e.id;Array.isArray(e)?(n=e.map(e=>e.id).join(","),r="c:"+this.renderer.info.compute.frameCalls):r=!0===e.isComputeNode?"c:"+this.renderer.info.compute.frameCalls:"r:"+this.renderer.info.render.frameCalls,t.timestampUID=r+":"+n+":f"+i}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:")?hi:di;return this.timestampQueryPool[t]}getTimestamp(e){return this._getQueryPool(e).getTimestamp(e)}get hasTimestamp(){return!1}hasTimestampQuery(e){return this._getQueryPool(e).hasTimestampQuery(e)}isOccluded(){}getOcclusionData(e){const t=this.get(e);void 0===t.occlusionData&&(t.occlusionData=new WeakMap);let i=t.occlusionData.get(e.camera);return void 0===i&&(i={},t.occlusionData.set(e.camera,i)),i}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp)return void Ei("WebGPURenderer: Timestamp tracking is disabled.");const t=this.timestampQueryPool[e];if(!t)return;const i=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=i,i}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getDrawingBufferSize(){return Iw=Iw||new Vi,this.renderer.getDrawingBufferSize(Iw)}setScissorTest(){}resetState(){}getClearColor(){const e=this.renderer;return Fw=Fw||new Sm,e.getClearColor(Fw),Fw.getRGB(Fw),Fw}getDomElement(){let e=this.domElement;return null===e&&(e=void 0!==this.parameters.canvas?this.parameters.canvas:bi(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${N} 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(){}async dispose(){for(const e of Object.values(this.timestampQueryPool))null!==e&&await e.dispose()}}let Bw,kw,zw=0;class Gw{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.id=e.id}get bufferGPU(){return this.buffers[this.activeBufferIndex]}get transformBuffer(){return this.buffers[1^this.activeBufferIndex]}switchBuffers(){this.activeBufferIndex^=1}}class Vw{constructor(e){this.backend=e}createAttribute(e,t){const i=this.backend,{gl:r}=i,n=i.getBufferAttribute(e);if(void 0!==i.get(n).bufferGPU)return;const s=e.array,a=e.usage||r.STATIC_DRAW,o=this._createBuffer(r,t,s,a);let l;if(s instanceof Float32Array)l=r.FLOAT;else if("undefined"!=typeof Float16Array&&s instanceof Float16Array)l=r.HALF_FLOAT;else if(s instanceof Uint16Array)l=e.isFloat16BufferAttribute?r.HALF_FLOAT:r.UNSIGNED_SHORT;else if(s instanceof Int16Array)l=r.SHORT;else if(s instanceof Uint32Array)l=r.UNSIGNED_INT;else if(s instanceof Int32Array)l=r.INT;else if(s instanceof Int8Array)l=r.BYTE;else if(s instanceof Uint8Array)l=r.UNSIGNED_BYTE;else{if(!(s instanceof Uint8ClampedArray))throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+s);l=r.UNSIGNED_BYTE}let u={bufferGPU:o,bufferType:t,type:l,byteLength:s.byteLength,bytesPerElement:s.BYTES_PER_ELEMENT,version:n.version,pbo:e.pbo,isInteger:l===r.INT||l===r.UNSIGNED_INT||e.gpuType===We,id:zw++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(r,t,s,a);u=new Gw(u,e)}i.set(n,u)}updateAttribute(e){const t=this.backend,{gl:i}=t,r=e.array,n=t.getBufferAttribute(e),s=t.get(n),a=n.updateRanges,o=s.bufferType===i.ELEMENT_ARRAY_BUFFER?i.COPY_WRITE_BUFFER:s.bufferType;if(i.bindBuffer(o,s.bufferGPU),0===a.length)i.bufferSubData(o,0,r);else{for(let e=0,t=a.length;e<t;e++){const t=a[e];i.bufferSubData(o,t.start*r.BYTES_PER_ELEMENT,r,t.start,t.count)}n.clearUpdateRanges()}i.bindBuffer(o,null),s.version=n.version}destroyAttribute(e){const t=this.backend,{gl:i}=t,r=t.getBufferAttribute(e),n=t.get(r);if(void 0!==n.buffers)for(const e of n.buffers)i.deleteBuffer(e);else i.deleteBuffer(n.bufferGPU);t.delete(r)}async getArrayBufferAsync(e,t=null,i=0,r=-1){const n=this.backend,{gl:s}=n,a=n.getBufferAttribute(e),o=n.get(a),{bufferGPU:l}=o,u=-1===r?o.byteLength-i:r;let c;if(null===t)c=new Uint8Array(new ArrayBuffer(u));else if(t.isReadbackBuffer){if(!0===t._mapped)throw new Error("THREE.WebGPURenderer: ReadbackBuffer must be released before being used again.");const e=()=>{t.buffer=null,t._mapped=!1,t.removeEventListener("release",e),t.removeEventListener("dispose",e)};t.addEventListener("release",e),t.addEventListener("dispose",e),c=new Uint8Array(new ArrayBuffer(u)),t.buffer=c.buffer}else c=new Uint8Array(t);return s.bindBuffer(s.COPY_READ_BUFFER,l),s.getBufferSubData(s.COPY_READ_BUFFER,i,c),s.bindBuffer(s.COPY_READ_BUFFER,null),s.bindBuffer(s.COPY_WRITE_BUFFER,null),t&&t.isReadbackBuffer?t:c.buffer}_createBuffer(e,t,i,r){const n=e.createBuffer(),s=this.backend.state;return t===e.ELEMENT_ARRAY_BUFFER&&null!==s.currentVAO&&s.resetVertexState(),e.bindBuffer(t,n),e.bufferData(t,i,r),e.bindBuffer(t,null),n}}class Hw{constructor(e){this.backend=e,this.cache=new Map}getVAO(e,t,i=null){const r=this.backend,n=r.get(e),s=null!==i?r.get(i):null,a=null!==s?s.bufferGPU:null;if(!1===this._needsUpdate(n,t,a))return n.vaoGPU;let o="",l="";const u=[],c=[];for(let e=0;e<t.length;e++){const i=t[e],n=r.get(r.getBufferAttribute(i));o+=":"+n.id,i.isInterleavedBufferAttribute&&(o+="."+i.offset),l+=":"+(n.activeBufferIndex||0),u.push(n.bufferGPU),c.push(n)}null!==s&&(o+="|"+s.id,c.push(s));let h=this.cache.get(o);if(o!==n.vaoKey){if(void 0!==n.vaoKey&&this._releaseEntry(n.vaoKey),void 0===h){h={vaos:new Map,buffersData:c,usedTimes:0},this.cache.set(o,h);for(const e of c)void 0===e.vaoKeys&&(e.vaoKeys=new Set),e.vaoKeys.add(o)}h.usedTimes++,n.vaoKey=o}let d=h.vaos.get(l);return void 0===d&&(d=this._createVAO(t,a),h.vaos.set(l,d)),n.vaoGPU=d,n.vertexBuffers=u,n.indexBuffer=a,d}releaseVAO(e){const t=this.backend.get(e);void 0!==t.vaoKey&&(this._releaseEntry(t.vaoKey),t.vaoKey=void 0,t.vaoGPU=void 0,t.vertexBuffers=void 0,t.indexBuffer=void 0)}releaseBuffer(e){if(void 0!==e.vaoKeys)for(const t of e.vaoKeys)this._deleteEntry(t)}dispose(){const{gl:e}=this.backend;for(const t of this.cache.values())for(const i of t.vaos.values())e.deleteVertexArray(i);this.cache.clear()}_needsUpdate(e,t,i){const r=e.vertexBuffers;if(void 0===r||r.length!==t.length||e.indexBuffer!==i)return!0;for(let e=0;e<t.length;e++){const i=this.backend.getBufferAttribute(t[e]);if(this.backend.get(i).bufferGPU!==r[e])return!0}return!1}_releaseEntry(e){const t=this.cache.get(e);void 0!==t&&(t.usedTimes--,0===t.usedTimes&&this._deleteEntry(e))}_deleteEntry(e){const{gl:t,state:i}=this.backend,r=this.cache.get(e);for(const e of r.vaos.values())i.currentVAO===e&&i.resetVertexState(),t.deleteVertexArray(e);for(const t of r.buffersData)t.vaoKeys.delete(e);this.cache.delete(e)}_createVAO(e,t){const{gl:i,state:r}=this.backend,n=i.createVertexArray();r.setVertexState(n,t);for(let t=0;t<e.length;t++){const r=e[t],n=this.backend.getBufferAttribute(r),s=this.backend.get(n);let a,o;if(i.bindBuffer(i.ARRAY_BUFFER,s.bufferGPU),i.enableVertexAttribArray(t),!0===r.isInterleavedBufferAttribute){a=(!0===n.isInterleavedBuffer?n.stride:n.itemSize)*s.bytesPerElement,o=r.offset*s.bytesPerElement}else a=0,o=0;s.isInteger?i.vertexAttribIPointer(t,r.itemSize,s.type,a,o):i.vertexAttribPointer(t,r.itemSize,s.type,r.normalized,a,o),!0!==n.isInstancedBufferAttribute&&!0!==n.isInstancedInterleavedBuffer||i.vertexAttribDivisor(t,n.meshPerAttribute)}return i.bindBuffer(i.ARRAY_BUFFER,null),n}}class Ww{constructor(e){this.backend=e,this.gl=this.backend.gl,this.enabled={},this.parameters={},this.currentFlipSided=null,this.currentCullFace=null,this.currentProgram=null,this.currentBlendingEnabled=!1,this.currentBlending=null,this.currentBlendEquation=null,this.currentBlendEquationAlpha=null,this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentBlendColor=new Yr(0,0,0),this.currentBlendAlpha=0,this.currentPremultipledAlpha=null,this.currentPolygonOffsetFactor=null,this.currentPolygonOffsetUnits=null,this.currentColorMask=null,this.currentDepthReversed=!1,this.currentDepthFunc=null,this.currentDepthMask=null,this.currentStencilFunc=null,this.currentStencilRef=null,this.currentStencilFuncMask=null,this.currentStencilFail=null,this.currentStencilZFail=null,this.currentStencilZPass=null,this.currentStencilMask=null,this.currentLineWidth=null,this.currentClippingPlanes=0,this.currentVAO=null,this.currentIndex=null,this.currentBoundFramebuffers={},this.currentDrawbuffers=new WeakMap,this.maxTextures=this.gl.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.currentTextureSlot=null,this.currentBoundTextures={},this.currentBoundBufferBases={},this._init()}_init(){const e=this.gl;Bw={[H]:e.FUNC_ADD,[W]:e.FUNC_SUBTRACT,[j]:e.FUNC_REVERSE_SUBTRACT,[$]:e.MIN,[X]:e.MAX},kw={[q]:e.ZERO,[Y]:e.ONE,[K]:e.SRC_COLOR,[Q]:e.SRC_ALPHA,[ne]:e.SRC_ALPHA_SATURATE,[ie]:e.DST_COLOR,[ee]:e.DST_ALPHA,[Z]:e.ONE_MINUS_SRC_COLOR,[J]:e.ONE_MINUS_SRC_ALPHA,[re]:e.ONE_MINUS_DST_COLOR,[te]:e.ONE_MINUS_DST_ALPHA,[se]:e.CONSTANT_COLOR,[ae]:e.ONE_MINUS_CONSTANT_COLOR,[oe]:e.CONSTANT_ALPHA,[le]:e.ONE_MINUS_CONSTANT_ALPHA};const t=e.getParameter(e.SCISSOR_BOX),i=e.getParameter(e.VIEWPORT);this.currentScissor=(new ur).fromArray(t),this.currentViewport=(new ur).fromArray(i),this._tempVec4=new ur}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:i}=this;e!==t&&(i.lineWidth(e),this.currentLineWidth=e)}setMRTBlending(e,t,i){const r=this.gl,n=this.backend.drawBuffersIndexedExt;if(n){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=i:0!==e.blending&&(o=e)}else o=i;null!==o?this._setMRTBlendingIndex(s,o):n.blendFuncSeparateiOES(s,r.ONE,r.ZERO,r.ONE,r.ZERO)}this.currentBlending=null,this.currentBlendEquation=null,this.currentBlendEquationAlpha=null,this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentPremultipledAlpha=null}else Ei("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:i}=this,r=this.backend.drawBuffersIndexedExt,n=t.blending,s=t.blendSrc,a=t.blendDst,o=t.blendEquation,l=t.premultipliedAlpha;if(5===n){const i=null!==t.blendSrcAlpha?t.blendSrcAlpha:s,n=null!==t.blendDstAlpha?t.blendDstAlpha:a,l=null!==t.blendEquationAlpha?t.blendEquationAlpha:o;r.blendEquationSeparateiOES(e,Bw[o],Bw[l]),r.blendFuncSeparateiOES(e,kw[s],kw[a],kw[i],kw[n])}else if(r.blendEquationSeparateiOES(e,i.FUNC_ADD,i.FUNC_ADD),l)switch(n){case 1:default:r.blendFuncSeparateiOES(e,i.ONE,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA);break;case 2:r.blendFuncSeparateiOES(e,i.ONE,i.ONE,i.ONE,i.ONE);break;case 3:r.blendFuncSeparateiOES(e,i.ZERO,i.ONE_MINUS_SRC_COLOR,i.ZERO,i.ONE);break;case 4:r.blendFuncSeparateiOES(e,i.DST_COLOR,i.ONE_MINUS_SRC_ALPHA,i.ZERO,i.ONE)}else switch(n){case 1:default:r.blendFuncSeparateiOES(e,i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA);break;case 2:r.blendFuncSeparateiOES(e,i.SRC_ALPHA,i.ONE,i.ONE,i.ONE);break;case 3:r.blendFuncSeparateiOES(e,i.ZERO,i.ONE_MINUS_SRC_COLOR,i.ZERO,i.ONE);break;case 4:r.blendFuncSeparateiOES(e,i.DST_COLOR,i.ONE_MINUS_SRC_ALPHA,i.ZERO,i.ONE)}}setBlending(e,t,i,r,n,s,a,o,l,u){const{gl:c}=this;if(0!==e){if(!1===this.currentBlendingEnabled&&(this.enable(c.BLEND),this.currentBlendingEnabled=!0),5===e)n=n||t,s=s||i,a=a||r,t===this.currentBlendEquation&&n===this.currentBlendEquationAlpha||(c.blendEquationSeparate(Bw[t],Bw[n]),this.currentBlendEquation=t,this.currentBlendEquationAlpha=n),i===this.currentBlendSrc&&r===this.currentBlendDst&&s===this.currentBlendSrcAlpha&&a===this.currentBlendDstAlpha||(c.blendFuncSeparate(kw[i],kw[r],kw[s],kw[a]),this.currentBlendSrc=i,this.currentBlendDst=r,this.currentBlendSrcAlpha=s,this.currentBlendDstAlpha=a),!1!==o.equals(this.currentBlendColor)&&l===this.currentBlendAlpha||(c.blendColor(o.r,o.g,o.b,l),this.currentBlendColor.copy(o),this.currentBlendAlpha=l),this.currentBlending=e,this.currentPremultipledAlpha=!1;else if(e!==this.currentBlending||u!==this.currentPremultipledAlpha){if(this.currentBlendEquation===H&&this.currentBlendEquationAlpha===H||(c.blendEquation(c.FUNC_ADD),this.currentBlendEquation=H,this.currentBlendEquationAlpha=H),u)switch(e){case 1:c.blendFuncSeparate(c.ONE,c.ONE_MINUS_SRC_ALPHA,c.ONE,c.ONE_MINUS_SRC_ALPHA);break;case 2:c.blendFunc(c.ONE,c.ONE);break;case 3:c.blendFuncSeparate(c.ZERO,c.ONE_MINUS_SRC_COLOR,c.ZERO,c.ONE);break;case 4:c.blendFuncSeparate(c.DST_COLOR,c.ONE_MINUS_SRC_ALPHA,c.ZERO,c.ONE);break;default:Mi("WebGLState: Invalid blending: ",e)}else switch(e){case 1:c.blendFuncSeparate(c.SRC_ALPHA,c.ONE_MINUS_SRC_ALPHA,c.ONE,c.ONE_MINUS_SRC_ALPHA);break;case 2:c.blendFuncSeparate(c.SRC_ALPHA,c.ONE,c.ONE,c.ONE);break;case 3:Mi("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case 4:Mi("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:Mi("WebGLState: Invalid blending: ",e)}this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentBlending=e,this.currentPremultipledAlpha=u}}else!0===this.currentBlendingEnabled&&(this.disable(c.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=Ai[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,i,r){const n=this._tempVec4.set(e,t,i,r);if(!1===this.currentScissor.equals(n)){const{gl:e}=this;e.scissor(n.x,n.y,n.z,n.w),this.currentScissor.copy(n)}}viewport(e,t,i,r){const n=this._tempVec4.set(e,t,i,r);if(!1===this.currentViewport.equals(n)){const{gl:e}=this;e.viewport(n.x,n.y,n.z,n.w),this.currentViewport.copy(n)}}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,i){this.currentStencilFunc===e&&this.currentStencilRef===t&&this.currentStencilFuncMask===i||(this.gl.stencilFunc(e,t,i),this.currentStencilFunc=e,this.currentStencilRef=t,this.currentStencilFuncMask=i)}setStencilOp(e,t,i){this.currentStencilFail===e&&this.currentStencilZFail===t&&this.currentStencilZPass===i||(this.gl.stencilOp(e,t,i),this.currentStencilFail=e,this.currentStencilZFail=t,this.currentStencilZPass=i)}setMaterial(e,t,i){const{gl:r}=this;2===e.side?this.disable(r.CULL_FACE):this.enable(r.CULL_FACE);let n=1===e.side;t&&(n=!n),this.setFlipSided(n),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.blendColor,e.blendAlpha,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(r.SAMPLE_ALPHA_TO_COVERAGE):this.disable(r.SAMPLE_ALPHA_TO_COVERAGE),this.currentClippingPlanes!==i){const e=12288;for(let t=0;t<8;t++)t<i?this.enable(e+t):this.disable(e+t);this.currentClippingPlanes=i}}setPolygonOffset(e,t,i){const{gl:r}=this;e?(this.enable(r.POLYGON_OFFSET_FILL),this.currentPolygonOffsetFactor===t&&this.currentPolygonOffsetUnits===i||(this.currentPolygonOffsetFactor=t,this.currentPolygonOffsetUnits=i,this.currentDepthReversed&&(t=-t,i=-i),r.polygonOffset(t,i))):this.disable(r.POLYGON_OFFSET_FILL)}useProgram(e){return this.currentProgram!==e&&(this.gl.useProgram(e),this.currentProgram=e,!0)}setVertexState(e,t=null){const i=this.gl;return(this.currentVAO!==e||this.currentIndex!==t)&&(i.bindVertexArray(e),null!==t&&i.bindBuffer(i.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:i,currentBoundFramebuffers:r}=this;return r[e]!==t&&(i.bindFramebuffer(e,t),r[e]=t,e===i.DRAW_FRAMEBUFFER&&(r[i.FRAMEBUFFER]=t),e===i.FRAMEBUFFER&&(r[i.DRAW_FRAMEBUFFER]=t),!0)}drawBuffers(e,t){const{gl:i}=this;let r=[],n=!1;if(null!==e.textures){r=this.currentDrawbuffers.get(t),void 0===r&&(r=[i.COLOR_ATTACHMENT0],this.currentDrawbuffers.set(t,r));const s=e.textures;if(r.length!==s.length){for(let e=0,t=s.length;e<t;e++)r[e]=i.COLOR_ATTACHMENT0+e;r.length=s.length,n=!0}}else r[0]!==i.BACK&&(r[0]=i.BACK,n=!0);n&&i.drawBuffers(r)}activeTexture(e){const{gl:t,currentTextureSlot:i,maxTextures:r}=this;void 0===e&&(e=t.TEXTURE0+r-1),i!==e&&(t.activeTexture(e),this.currentTextureSlot=e)}bindTexture(e,t,i){const{gl:r,currentTextureSlot:n,currentBoundTextures:s,maxTextures:a}=this;void 0===i&&(i=null===n?r.TEXTURE0+a-1:n);let o=s[i];void 0===o&&(o={type:void 0,texture:void 0},s[i]=o),o.type===e&&o.texture===t||(n!==i&&(r.activeTexture(i),this.currentTextureSlot=i),r.bindTexture(e,t),o.type=e,o.texture=t)}bindBufferBase(e,t,i){const{gl:r}=this,n=`${e}-${t}`;return this.currentBoundBufferBases[n]!==i&&(r.bindBufferBase(e,t,i),this.currentBoundBufferBases[n]=i,!0)}unbindTexture(){const{gl:e,currentTextureSlot:t,currentBoundTextures:i}=this,r=i[t];void 0!==r&&void 0!==r.type&&(e.bindTexture(r.type,null),r.type=void 0,r.texture=void 0)}getParameter(e){const{gl:t,parameters:i}=this;return void 0!==i[e]?i[e]:t.getParameter(e)}pixelStorei(e,t){const{gl:i,parameters:r}=this;r[e]!==t&&(i.pixelStorei(e,t),r[e]=t)}reset(){const{gl:e}=this;e.disable(e.BLEND),e.disable(e.CULL_FACE),e.disable(e.DEPTH_TEST),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SCISSOR_TEST),e.disable(e.STENCIL_TEST),e.disable(e.SAMPLE_ALPHA_TO_COVERAGE),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ZERO),e.blendFuncSeparate(e.ONE,e.ZERO,e.ONE,e.ZERO),e.blendColor(0,0,0,0),e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.depthMask(!0),e.depthFunc(e.LESS),e.clearDepth(1),e.stencilMask(4294967295),e.stencilFunc(e.ALWAYS,0,4294967295),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.clearStencil(0),e.cullFace(e.BACK),e.frontFace(e.CCW),e.polygonOffset(0,0),e.activeTexture(e.TEXTURE0),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),e.bindFramebuffer(e.READ_FRAMEBUFFER,null),e.useProgram(null),e.lineWidth(1),e.scissor(0,0,e.canvas.width,e.canvas.height),e.viewport(0,0,e.canvas.width,e.canvas.height),e.pixelStorei(e.PACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!1),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.BROWSER_DEFAULT_WEBGL),e.pixelStorei(e.PACK_ROW_LENGTH,0),e.pixelStorei(e.PACK_SKIP_PIXELS,0),e.pixelStorei(e.PACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_ROW_LENGTH,0),e.pixelStorei(e.UNPACK_IMAGE_HEIGHT,0),e.pixelStorei(e.UNPACK_SKIP_PIXELS,0),e.pixelStorei(e.UNPACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_SKIP_IMAGES,0),this.resetVertexState(),this.enabled={},this.parameters={},this.currentFlipSided=null,this.currentCullFace=null,this.currentProgram=null,this.currentBlendingEnabled=!1,this.currentBlending=null,this.currentBlendEquation=null,this.currentBlendEquationAlpha=null,this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentBlendColor.set(0,0,0),this.currentBlendAlpha=0,this.currentPremultipledAlpha=null,this.currentPolygonOffsetFactor=null,this.currentPolygonOffsetUnits=null,this.currentColorMask=null,this.currentDepthFunc=null,this.currentDepthMask=null,this.currentStencilFunc=null,this.currentStencilRef=null,this.currentStencilFuncMask=null,this.currentStencilFail=null,this.currentStencilZFail=null,this.currentStencilZPass=null,this.currentStencilMask=null,this.currentLineWidth=null,this.currentClippingPlanes=0,this.currentBoundFramebuffers={},this.currentDrawbuffers=new WeakMap,this.currentTextureSlot=null,this.currentBoundTextures={},this.currentBoundBufferBases={},this.currentScissor.set(0,0,e.canvas.width,e.canvas.height),this.currentViewport.set(0,0,e.canvas.width,e.canvas.height),this.currentDepthReversed=!1,!0===this.backend.renderer.reversedDepthBuffer&&this.setReversedDepth(!0)}}class jw{constructor(e){this.backend=e,this.gl=this.backend.gl,this.extensions=e.extensions}convert(e,t=""){const{gl:i,extensions:r}=this;let n;const s=Qi.getTransfer(t);if(e===ze)return i.UNSIGNED_BYTE;if(e===qe)return i.UNSIGNED_SHORT_4_4_4_4;if(e===Ye)return i.UNSIGNED_SHORT_5_5_5_1;if(e===Ze)return i.UNSIGNED_INT_5_9_9_9_REV;if(e===Qe)return i.UNSIGNED_INT_10F_11F_11F_REV;if(e===Ge)return i.BYTE;if(e===Ve)return i.SHORT;if(e===He)return i.UNSIGNED_SHORT;if(e===We)return i.INT;if(e===je)return i.UNSIGNED_INT;if(e===$e)return i.FLOAT;if(e===Xe)return i.HALF_FLOAT;if(e===Je)return i.ALPHA;if(e===et)return i.RGB;if(e===tt)return i.RGBA;if(e===it)return i.DEPTH_COMPONENT;if(e===rt)return i.DEPTH_STENCIL;if(e===nt)return i.RED;if(e===st)return i.RED_INTEGER;if(e===at)return i.RG;if(e===ot)return i.RG_INTEGER;if(e===ut)return i.RGBA_INTEGER;if(e===ct||e===ht||e===dt||e===pt)if(s===Kt){if(n=r.get("WEBGL_compressed_texture_s3tc_srgb"),null===n)return null;if(e===ct)return n.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(e===ht)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(e===dt)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(e===pt)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(n=r.get("WEBGL_compressed_texture_s3tc"),null===n)return null;if(e===ct)return n.COMPRESSED_RGB_S3TC_DXT1_EXT;if(e===ht)return n.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(e===dt)return n.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(e===pt)return n.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(e===ft||e===mt||e===gt||e===_t){if(n=r.get("WEBGL_compressed_texture_pvrtc"),null===n)return null;if(e===ft)return n.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(e===mt)return n.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(e===gt)return n.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(e===_t)return n.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(e===vt||e===bt||e===yt||e===xt||e===St||e===Tt||e===Mt){if(n=r.get("WEBGL_compressed_texture_etc"),null===n)return null;if(e===vt||e===bt)return s===Kt?n.COMPRESSED_SRGB8_ETC2:n.COMPRESSED_RGB8_ETC2;if(e===yt)return s===Kt?n.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:n.COMPRESSED_RGBA8_ETC2_EAC;if(e===xt)return n.COMPRESSED_R11_EAC;if(e===St)return n.COMPRESSED_SIGNED_R11_EAC;if(e===Tt)return n.COMPRESSED_RG11_EAC;if(e===Mt)return n.COMPRESSED_SIGNED_RG11_EAC}if(e===Et||e===wt||e===At||e===Rt||e===Ct||e===Nt||e===Pt||e===Lt||e===Dt||e===Ut||e===It||e===Ft||e===Ot||e===Bt){if(n=r.get("WEBGL_compressed_texture_astc"),null===n)return null;if(e===Et)return s===Kt?n.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:n.COMPRESSED_RGBA_ASTC_4x4_KHR;if(e===wt)return s===Kt?n.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:n.COMPRESSED_RGBA_ASTC_5x4_KHR;if(e===At)return s===Kt?n.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:n.COMPRESSED_RGBA_ASTC_5x5_KHR;if(e===Rt)return s===Kt?n.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:n.COMPRESSED_RGBA_ASTC_6x5_KHR;if(e===Ct)return s===Kt?n.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:n.COMPRESSED_RGBA_ASTC_6x6_KHR;if(e===Nt)return s===Kt?n.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:n.COMPRESSED_RGBA_ASTC_8x5_KHR;if(e===Pt)return s===Kt?n.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:n.COMPRESSED_RGBA_ASTC_8x6_KHR;if(e===Lt)return s===Kt?n.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:n.COMPRESSED_RGBA_ASTC_8x8_KHR;if(e===Dt)return s===Kt?n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:n.COMPRESSED_RGBA_ASTC_10x5_KHR;if(e===Ut)return s===Kt?n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:n.COMPRESSED_RGBA_ASTC_10x6_KHR;if(e===It)return s===Kt?n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:n.COMPRESSED_RGBA_ASTC_10x8_KHR;if(e===Ft)return s===Kt?n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:n.COMPRESSED_RGBA_ASTC_10x10_KHR;if(e===Ot)return s===Kt?n.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:n.COMPRESSED_RGBA_ASTC_12x10_KHR;if(e===Bt)return s===Kt?n.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:n.COMPRESSED_RGBA_ASTC_12x12_KHR}if(e===kt||e===zt||e===Gt){if(n=r.get("EXT_texture_compression_bptc"),null===n)return null;if(e===kt)return s===Kt?n.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:n.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(e===zt)return n.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(e===Gt)return n.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}if(e===Vt||e===Ht||e===Wt||e===jt){if(n=r.get("EXT_texture_compression_rgtc"),null===n)return null;if(e===Vt)return n.COMPRESSED_RED_RGTC1_EXT;if(e===Ht)return n.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(e===Wt)return n.COMPRESSED_RED_GREEN_RGTC2_EXT;if(e===jt)return n.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}return e===Ke?i.UNSIGNED_INT_24_8:void 0!==i[e]?i[e]:null}_clientWaitAsync(){const{gl:e}=this,t=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0);return e.flush(),new Promise((i,r)=>{!function n(){const s=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(s===e.WAIT_FAILED)return e.deleteSync(t),void r();s!==e.TIMEOUT_EXPIRED?(e.deleteSync(t),i()):requestAnimationFrame(n)}()})}}let $w,Xw,qw,Yw=!1;class Kw{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},this._srcFramebuffer=null,this._dstFramebuffer=null,!1===Yw&&(this._init(),Yw=!0)}_init(){const e=this.gl;$w={[Pe]:e.REPEAT,[Le]:e.CLAMP_TO_EDGE,[De]:e.MIRRORED_REPEAT},Xw={[Ue]:e.NEAREST,[Ie]:e.NEAREST_MIPMAP_NEAREST,[Fe]:e.NEAREST_MIPMAP_LINEAR,[Oe]:e.LINEAR,[Be]:e.LINEAR_MIPMAP_NEAREST,[ke]:e.LINEAR_MIPMAP_LINEAR},qw={[Qt]:e.NEVER,[si]:e.ALWAYS,[Jt]:e.LESS,[ti]:e.LEQUAL,[ei]:e.EQUAL,[ni]:e.GEQUAL,[ii]:e.GREATER,[ri]:e.NOTEQUAL}}getGLTextureType(e){const{gl:t}=this;let i;return i=!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,i}getInternalFormat(e,t,i,r,n,s=!1){const{gl:a,extensions:o}=this;if(null!==e){if(void 0!==a[e])return a[e];Ti("WebGLBackend: Attempt to use non-existing WebGL internal format '"+e+"'")}let l=null;r&&(l=o.get("EXT_texture_norm16"),l||Ti("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let u=t;if(t===a.RED&&(i===a.FLOAT&&(u=a.R32F),i===a.HALF_FLOAT&&(u=a.R16F),i===a.UNSIGNED_BYTE&&(u=a.R8),i===a.BYTE&&(u=a.R8_SNORM),i===a.UNSIGNED_SHORT&&l&&(u=l.R16_EXT),i===a.SHORT&&l&&(u=l.R16_SNORM_EXT)),t===a.RED_INTEGER&&(i===a.UNSIGNED_BYTE&&(u=a.R8UI),i===a.UNSIGNED_SHORT&&(u=a.R16UI),i===a.UNSIGNED_INT&&(u=a.R32UI),i===a.BYTE&&(u=a.R8I),i===a.SHORT&&(u=a.R16I),i===a.INT&&(u=a.R32I)),t===a.RG&&(i===a.FLOAT&&(u=a.RG32F),i===a.HALF_FLOAT&&(u=a.RG16F),i===a.UNSIGNED_BYTE&&(u=a.RG8),i===a.BYTE&&(u=a.RG8_SNORM),i===a.UNSIGNED_SHORT&&l&&(u=l.RG16_EXT),i===a.SHORT&&l&&(u=l.RG16_SNORM_EXT)),t===a.RG_INTEGER&&(i===a.UNSIGNED_BYTE&&(u=a.RG8UI),i===a.UNSIGNED_SHORT&&(u=a.RG16UI),i===a.UNSIGNED_INT&&(u=a.RG32UI),i===a.BYTE&&(u=a.RG8I),i===a.SHORT&&(u=a.RG16I),i===a.INT&&(u=a.RG32I)),t===a.RGB){const e=s?Yt:Qi.getTransfer(n);i===a.FLOAT&&(u=a.RGB32F),i===a.HALF_FLOAT&&(u=a.RGB16F),i===a.UNSIGNED_BYTE&&(u=e===Kt?a.SRGB8:a.RGB8),i===a.BYTE&&(u=a.RGB8_SNORM),i===a.UNSIGNED_SHORT&&l&&(u=l.RGB16_EXT),i===a.SHORT&&l&&(u=l.RGB16_SNORM_EXT),i===a.UNSIGNED_SHORT_5_6_5&&(u=a.RGB565),i===a.UNSIGNED_SHORT_5_5_5_1&&(u=a.RGB5_A1),i===a.UNSIGNED_SHORT_4_4_4_4&&(u=a.RGB4),i===a.UNSIGNED_INT_5_9_9_9_REV&&(u=a.RGB9_E5),i===a.UNSIGNED_INT_10F_11F_11F_REV&&(u=a.R11F_G11F_B10F)}if(t===a.RGB_INTEGER&&(i===a.UNSIGNED_BYTE&&(u=a.RGB8UI),i===a.UNSIGNED_SHORT&&(u=a.RGB16UI),i===a.UNSIGNED_INT&&(u=a.RGB32UI),i===a.BYTE&&(u=a.RGB8I),i===a.SHORT&&(u=a.RGB16I),i===a.INT&&(u=a.RGB32I)),t===a.RGBA){const e=s?Yt:Qi.getTransfer(n);i===a.FLOAT&&(u=a.RGBA32F),i===a.HALF_FLOAT&&(u=a.RGBA16F),i===a.UNSIGNED_BYTE&&(u=e===Kt?a.SRGB8_ALPHA8:a.RGBA8),i===a.BYTE&&(u=a.RGBA8_SNORM),i===a.UNSIGNED_SHORT&&l&&(u=l.RGBA16_EXT),i===a.SHORT&&l&&(u=l.RGBA16_SNORM_EXT),i===a.UNSIGNED_SHORT_4_4_4_4&&(u=a.RGBA4),i===a.UNSIGNED_SHORT_5_5_5_1&&(u=a.RGB5_A1)}return t===a.RGBA_INTEGER&&(i===a.UNSIGNED_BYTE&&(u=a.RGBA8UI),i===a.UNSIGNED_SHORT&&(u=a.RGBA16UI),i===a.UNSIGNED_INT&&(u=a.RGBA32UI),i===a.BYTE&&(u=a.RGBA8I),i===a.SHORT&&(u=a.RGBA16I),i===a.INT&&(u=a.RGBA32I)),t===a.DEPTH_COMPONENT&&(i===a.UNSIGNED_SHORT&&(u=a.DEPTH_COMPONENT16),i===a.UNSIGNED_INT&&(u=a.DEPTH_COMPONENT24),i===a.FLOAT&&(u=a.DEPTH_COMPONENT32F)),t===a.DEPTH_STENCIL&&(i===a.UNSIGNED_INT_24_8&&(u=a.DEPTH24_STENCIL8),i===a.FLOAT&&(u=a.DEPTH32F_STENCIL8)),u!==a.R16F&&u!==a.R32F&&u!==a.RG16F&&u!==a.RG32F&&u!==a.RGBA16F&&u!==a.RGBA32F||o.get("EXT_color_buffer_float"),u}setTextureParameters(e,t){const{gl:i,extensions:r,backend:n}=this,{state:s}=this.backend,a=Qi.getPrimaries(Qi.workingColorSpace),o=t.colorSpace===$t?null:Qi.getPrimaries(t.colorSpace),l=t.colorSpace===$t||a===o?i.NONE:i.BROWSER_DEFAULT_WEBGL;s.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,t.flipY),s.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),s.pixelStorei(i.UNPACK_ALIGNMENT,t.unpackAlignment),s.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,l),i.texParameteri(e,i.TEXTURE_WRAP_S,$w[t.wrapS]),i.texParameteri(e,i.TEXTURE_WRAP_T,$w[t.wrapT]),e!==i.TEXTURE_3D&&e!==i.TEXTURE_2D_ARRAY||t.isArrayTexture||i.texParameteri(e,i.TEXTURE_WRAP_R,$w[t.wrapR]),i.texParameteri(e,i.TEXTURE_MAG_FILTER,Xw[t.magFilter]);const u=t.mipmaps.length>0,c=t.minFilter===Oe&&u?ke:t.minFilter;if(i.texParameteri(e,i.TEXTURE_MIN_FILTER,Xw[c]),t.compareFunction&&(i.texParameteri(e,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE),i.texParameteri(e,i.TEXTURE_COMPARE_FUNC,qw[t.compareFunction])),!0===r.has("EXT_texture_filter_anisotropic")){if(t.magFilter===Ue)return;if(t.minFilter!==Fe&&t.minFilter!==ke)return;if(t.type===$e&&!1===r.has("OES_texture_float_linear"))return;if(t.anisotropy>1){const s=r.get("EXT_texture_filter_anisotropic");i.texParameterf(e,s.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,n.capabilities.getMaxAnisotropy()))}}}createDefaultTexture(e){const{gl:t,backend:i,defaultTextures:r}=this,n=this.getGLTextureType(e);let s=r[n];void 0===s&&(s=t.createTexture(),i.state.bindTexture(n,s),t.texParameteri(n,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(n,t.TEXTURE_MAG_FILTER,t.NEAREST),r[n]=s),i.set(e,{textureGPU:s,glTextureType:n})}createTexture(e,t){const{gl:i,backend:r}=this;let n,s,a,o,l;if(!0===e.isExternalTexture)n=e.sourceTexture,s=this.getGLTextureType(e);else{const{levels:u,width:c,height:h,depth:d}=t;a=r.utils.convert(e.format,e.colorSpace),o=r.utils.convert(e.type),l=this.getInternalFormat(e.internalFormat,a,o,e.normalized,e.colorSpace,e.isVideoTexture),n=i.createTexture(),s=this.getGLTextureType(e),r.state.bindTexture(s,n),this.setTextureParameters(s,e),e.isArrayTexture||e.isDataArrayTexture||e.isCompressedArrayTexture?i.texStorage3D(i.TEXTURE_2D_ARRAY,u,l,c,h,d):e.isData3DTexture?i.texStorage3D(i.TEXTURE_3D,u,l,c,h,d):e.isVideoTexture||i.texStorage2D(s,u,l,c,h)}r.set(e,{textureGPU:n,glTextureType:s,glFormat:a,glType:o,glInternalFormat:l})}copyBufferToTexture(e,t){const{gl:i,backend:r}=this,{state:n}=r,{textureGPU:s,glTextureType:a,glFormat:o,glType:l}=r.get(t),{width:u,height:c}=t.source.data;i.bindBuffer(i.PIXEL_UNPACK_BUFFER,e),r.state.bindTexture(a,s),n.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,!1),n.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),i.texSubImage2D(a,0,0,0,u,c,o,l,0),i.bindBuffer(i.PIXEL_UNPACK_BUFFER,null),r.state.unbindTexture()}updateTexture(e,t){const{gl:i}=this,{width:r,height:n}=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.isCompressedCubeTexture)for(let t=0;t<6;t++){const r=e.image[t].mipmaps;for(let e=0;e<r.length;e++){const n=r[e];o===i.RGBA?i.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+t,e,0,0,n.width,n.height,o,l,n.data):null!==o?i.compressedTexSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+t,e,0,0,n.width,n.height,o,n.data):Ti("WebGLBackend: Unsupported compressed texture format")}}else if(e.isCompressedTexture){const r=e.mipmaps,n=t.image,s=null!==o&&o!==i.RGBA;for(let t=0;t<r.length;t++){const a=r[t];if(e.isCompressedArrayTexture)if(s)if(e.layerUpdates.size>0){const r=uo(a.width,a.height,e.format,e.type);for(const n of e.layerUpdates){const e=a.data.subarray(n*r/a.data.BYTES_PER_ELEMENT,(n+1)*r/a.data.BYTES_PER_ELEMENT);i.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,t,0,0,n,a.width,a.height,1,o,e)}}else i.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,t,0,0,0,a.width,a.height,n.depth,o,a.data);else o===i.RGBA?i.texSubImage3D(i.TEXTURE_2D_ARRAY,t,0,0,0,a.width,a.height,n.depth,o,l,a.data):Ti("WebGLBackend: Unsupported compressed texture format.");else s?i.compressedTexSubImage2D(i.TEXTURE_2D,t,0,0,a.width,a.height,o,a.data):o===i.RGBA?i.texSubImage2D(i.TEXTURE_2D,t,0,0,a.width,a.height,o,l,a.data):Ti("WebGLBackend: Unsupported compressed texture format.")}e.isCompressedArrayTexture&&e.layerUpdates.size>0&&e.clearLayerUpdates()}else if(e.isCubeTexture){const s=t.images,a=e.mipmaps;for(let e=0;e<6;e++){const t=Zw(s[e]);i.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,0,0,r,n,o,l,t);for(let t=0;t<a.length;t++){const r=Zw(a[t].images[e]);i.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+e,t+1,0,0,r.width,r.height,o,l,r)}}}else if(e.isDataArrayTexture||e.isArrayTexture){const r=t.image;if(e.layerUpdates.size>0){const t=uo(r.width,r.height,e.format,e.type);for(const n of e.layerUpdates){const e=r.data.subarray(n*t/r.data.BYTES_PER_ELEMENT,(n+1)*t/r.data.BYTES_PER_ELEMENT);i.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,n,r.width,r.height,1,o,l,e)}e.clearLayerUpdates()}else i.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,0,r.width,r.height,r.depth,o,l,r.data)}else if(e.isData3DTexture){const e=t.image;i.texSubImage3D(i.TEXTURE_3D,0,0,0,0,e.width,e.height,e.depth,o,l,e.data)}else if(e.isVideoTexture)e.update(),i.texImage2D(a,0,u,o,l,t.image);else if(e.isHTMLTexture)"function"==typeof i.texElementImage2D&&(3===i.texElementImage2D.length?i.texElementImage2D(i.TEXTURE_2D,i.RGBA8,t.image):i.texElementImage2D(i.TEXTURE_2D,0,i.RGBA,i.RGBA,i.UNSIGNED_BYTE,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],r=Zw(t);i.texSubImage2D(a,e,0,0,t.width,t.height,o,l,r)}else{const e=Zw(t.image);i.texSubImage2D(a,0,0,0,r,n,o,l,e)}}}generateMipmaps(e){const{gl:t,backend:i}=this,{textureGPU:r,glTextureType:n}=i.get(e);i.state.bindTexture(n,r),t.generateMipmap(n)}deallocateRenderBuffers(e){const{gl:t,backend:i}=this;if(e){const r=i.get(e);if(r.renderBufferStorageSetup=void 0,r.framebuffers){for(const e in r.framebuffers)t.deleteFramebuffer(r.framebuffers[e]);delete r.framebuffers}if(r.depthRenderbuffer&&(t.deleteRenderbuffer(r.depthRenderbuffer),delete r.depthRenderbuffer),r.stencilRenderbuffer&&(t.deleteRenderbuffer(r.stencilRenderbuffer),delete r.stencilRenderbuffer),r.msaaFrameBuffer&&(t.deleteFramebuffer(r.msaaFrameBuffer),delete r.msaaFrameBuffer),r.msaaRenderbuffers){for(let e=0;e<r.msaaRenderbuffers.length;e++)t.deleteRenderbuffer(r.msaaRenderbuffers[e]);delete r.msaaRenderbuffers}}}destroyTexture(e,t=!1){const{gl:i,backend:r}=this,{textureGPU:n,renderTarget:s}=r.get(e);this.deallocateRenderBuffers(s),!1===t&&!0!==e.isExternalTexture&&i.deleteTexture(n),r.delete(e)}copyTextureToTexture(e,t,i=null,r=null,n=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,b,y,x;l.bindTexture(c,u);const S=e.isCompressedTexture?e.mipmaps[s]:e.image;if(null!==i)p=i.max.x-i.min.x,f=i.max.y-i.min.y,m=i.isBox3?i.max.z-i.min.z:1,g=i.min.x,_=i.min.y,v=i.isBox3?i.min.z:0;else{const t=Math.pow(2,-n);p=Math.floor(S.width*t),f=Math.floor(S.height*t),m=e.isDataArrayTexture||e.isArrayTexture?S.depth:e.isData3DTexture?Math.floor(S.depth*t):1,g=0,_=0,v=0}null!==r?(b=r.x,y=r.y,x=r.z):(b=0,y=0,x=0),l.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,t.flipY),l.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),l.pixelStorei(a.UNPACK_ALIGNMENT,t.unpackAlignment);const T=l.getParameter(a.UNPACK_ROW_LENGTH),M=l.getParameter(a.UNPACK_IMAGE_HEIGHT),E=l.getParameter(a.UNPACK_SKIP_PIXELS),w=l.getParameter(a.UNPACK_SKIP_ROWS),A=l.getParameter(a.UNPACK_SKIP_IMAGES);l.pixelStorei(a.UNPACK_ROW_LENGTH,S.width),l.pixelStorei(a.UNPACK_IMAGE_HEIGHT,S.height),l.pixelStorei(a.UNPACK_SKIP_PIXELS,g),l.pixelStorei(a.UNPACK_SKIP_ROWS,_),l.pixelStorei(a.UNPACK_SKIP_IMAGES,v);const R=e.isDataArrayTexture||e.isData3DTexture||e.isArrayTexture,C=t.isDataArrayTexture||t.isData3DTexture||t.isArrayTexture;if(e.isDepthTexture){const t=o.get(e);null===this._srcFramebuffer&&(this._srcFramebuffer=a.createFramebuffer()),null===this._dstFramebuffer&&(this._dstFramebuffer=a.createFramebuffer());const i=e.format===rt?a.DEPTH_STENCIL_ATTACHMENT:a.DEPTH_ATTACHMENT,r=l.currentBoundFramebuffers[a.READ_FRAMEBUFFER]??null,c=l.currentBoundFramebuffers[a.DRAW_FRAMEBUFFER]??null;l.bindFramebuffer(a.READ_FRAMEBUFFER,this._srcFramebuffer),l.bindFramebuffer(a.DRAW_FRAMEBUFFER,this._dstFramebuffer),a.framebufferTexture2D(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,null,0),a.framebufferTexture2D(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,null,0);for(let e=0;e<m;e++)R?a.framebufferTextureLayer(a.READ_FRAMEBUFFER,i,t.textureGPU,n,v+e):a.framebufferTexture2D(a.READ_FRAMEBUFFER,i,a.TEXTURE_2D,t.textureGPU,n),C?a.framebufferTextureLayer(a.DRAW_FRAMEBUFFER,i,u,s,x+e):a.framebufferTexture2D(a.DRAW_FRAMEBUFFER,i,a.TEXTURE_2D,u,s),a.blitFramebuffer(g,_,g+p,_+f,b,y,b+p,y+f,a.DEPTH_BUFFER_BIT,a.NEAREST);a.framebufferTexture2D(a.READ_FRAMEBUFFER,i,a.TEXTURE_2D,null,0),a.framebufferTexture2D(a.DRAW_FRAMEBUFFER,i,a.TEXTURE_2D,null,0),l.bindFramebuffer(a.READ_FRAMEBUFFER,r),l.bindFramebuffer(a.DRAW_FRAMEBUFFER,c)}else if(0!==n||e.isRenderTargetTexture||o.has(e)){const t=o.get(e);null===this._srcFramebuffer&&(this._srcFramebuffer=a.createFramebuffer()),null===this._dstFramebuffer&&(this._dstFramebuffer=a.createFramebuffer());const i=l.currentBoundFramebuffers[a.READ_FRAMEBUFFER]??null,r=l.currentBoundFramebuffers[a.DRAW_FRAMEBUFFER]??null;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,n,v+e):a.framebufferTexture2D(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,t.textureGPU,n),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!==n?a.blitFramebuffer(g,_,g+p,_+f,b,y,b+p,y+f,a.COLOR_BUFFER_BIT,a.NEAREST):C?a.copyTexSubImage3D(c,s,b,y,x+e,g,_,p,f):a.copyTexSubImage2D(c,s,b,y,g,_,p,f);l.bindFramebuffer(a.READ_FRAMEBUFFER,i),l.bindFramebuffer(a.DRAW_FRAMEBUFFER,r)}else C?e.isDataTexture||e.isData3DTexture?a.texSubImage3D(c,s,b,y,x,p,f,m,d,h,S.data):t.isCompressedArrayTexture?a.compressedTexSubImage3D(c,s,b,y,x,p,f,m,d,S.data):a.texSubImage3D(c,s,b,y,x,p,f,m,d,h,S):e.isDataTexture?a.texSubImage2D(a.TEXTURE_2D,s,b,y,p,f,d,h,S.data):e.isCompressedTexture?a.compressedTexSubImage2D(a.TEXTURE_2D,s,b,y,S.width,S.height,d,S.data):a.texSubImage2D(a.TEXTURE_2D,s,b,y,p,f,d,h,S);l.pixelStorei(a.UNPACK_ROW_LENGTH,T),l.pixelStorei(a.UNPACK_IMAGE_HEIGHT,M),l.pixelStorei(a.UNPACK_SKIP_PIXELS,E),l.pixelStorei(a.UNPACK_SKIP_ROWS,w),l.pixelStorei(a.UNPACK_SKIP_IMAGES,A),0===s&&!0===t.generateMipmaps&&!0===t.mipmapsAutoUpdate&&a.generateMipmap(c),l.unbindTexture()}copyFramebufferToTexture(e,t,i){const{gl:r}=this,{state:n}=this.backend,{textureGPU:s}=this.backend.get(e),{x:a,y:o,z:l,w:u}=i,c=!0===e.isDepthTexture||t.renderTarget&&t.renderTarget.samples>0,h=t.renderTarget?t.renderTarget.height:this.backend.getDrawingBufferSize().y;if(c){const i=0!==a||0!==o;let c,d;if(!0===e.isDepthTexture?(c=r.DEPTH_BUFFER_BIT,d=r.DEPTH_ATTACHMENT,t.stencil&&(c|=r.STENCIL_BUFFER_BIT)):(c=r.COLOR_BUFFER_BIT,d=r.COLOR_ATTACHMENT0),i){const e=this.backend.get(t.renderTarget),i=e.framebuffers[t.getCacheKey()],d=e.msaaFrameBuffer;n.bindFramebuffer(r.DRAW_FRAMEBUFFER,i),n.bindFramebuffer(r.READ_FRAMEBUFFER,d);const p=h-o-u;r.blitFramebuffer(a,p,a+l,p+u,a,p,a+l,p+u,c,r.NEAREST),n.bindFramebuffer(r.READ_FRAMEBUFFER,i),n.bindTexture(r.TEXTURE_2D,s),r.copyTexSubImage2D(r.TEXTURE_2D,0,0,0,a,p,l,u),n.unbindTexture()}else{const e=r.createFramebuffer();n.bindFramebuffer(r.DRAW_FRAMEBUFFER,e),r.framebufferTexture2D(r.DRAW_FRAMEBUFFER,d,r.TEXTURE_2D,s,0),r.blitFramebuffer(0,0,l,u,0,0,l,u,c,r.NEAREST),r.deleteFramebuffer(e)}}else n.bindTexture(r.TEXTURE_2D,s),r.copyTexSubImage2D(r.TEXTURE_2D,0,0,0,a,h-u-o,l,u),n.unbindTexture();!0===e.generateMipmaps&&!0===e.mipmapsAutoUpdate&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t,i,r=!1){const{gl:n}=this,{depthTexture:s,renderTarget:a}=t,{depthBuffer:o,stencilBuffer:l,width:u,height:c}=a;if(n.bindRenderbuffer(n.RENDERBUFFER,e),o&&!l){let t=n.DEPTH_COMPONENT24;if(!0===r){this.extensions.get("WEBGL_multisampled_render_to_texture").renderbufferStorageMultisampleEXT(n.RENDERBUFFER,a.samples,t,u,c)}else i>0?(s&&s.isDepthTexture&&s.type===$e&&(t=n.DEPTH_COMPONENT32F),n.renderbufferStorageMultisample(n.RENDERBUFFER,i,t,u,c)):n.renderbufferStorage(n.RENDERBUFFER,t,u,c);n.framebufferRenderbuffer(n.FRAMEBUFFER,n.DEPTH_ATTACHMENT,n.RENDERBUFFER,e)}else if(o&&l){if(i>0){let e=n.DEPTH24_STENCIL8;s&&s.isDepthTexture&&s.type===$e&&(e=n.DEPTH32F_STENCIL8),n.renderbufferStorageMultisample(n.RENDERBUFFER,i,e,u,c)}else n.renderbufferStorage(n.RENDERBUFFER,n.DEPTH_STENCIL,u,c);n.framebufferRenderbuffer(n.FRAMEBUFFER,n.DEPTH_STENCIL_ATTACHMENT,n.RENDERBUFFER,e)}n.bindRenderbuffer(n.RENDERBUFFER,null)}async copyTextureToBuffer(e,t,i,r,n,s){const{backend:a,gl:o}=this,{textureGPU:l,glFormat:u,glType:c}=this.backend.get(e),h=o.createFramebuffer();if(a.state.bindFramebuffer(o.READ_FRAMEBUFFER,h),e.isData3DTexture||e.isDataArrayTexture||e.isArrayTexture)o.framebufferTextureLayer(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,l,0,s);else{const t=e.isCubeTexture?o.TEXTURE_CUBE_MAP_POSITIVE_X+s:o.TEXTURE_2D;o.framebufferTexture2D(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,t,l,0)}const d=this._getTypedArrayType(c),p=r*n*this._getBytesPerTexel(c,u),f=o.createBuffer();a.state.pixelStorei(o.PACK_ALIGNMENT,1),o.bindBuffer(o.PIXEL_PACK_BUFFER,f),o.bufferData(o.PIXEL_PACK_BUFFER,p,o.STREAM_READ),o.readPixels(t,i,r,n,u,c,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),await a.utils._clientWaitAsync();const m=new d(p/d.BYTES_PER_ELEMENT);return o.bindBuffer(o.PIXEL_PACK_BUFFER,f),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,m),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),a.state.bindFramebuffer(o.READ_FRAMEBUFFER,null),o.deleteBuffer(f),o.deleteFramebuffer(h),m}_getTypedArrayType(e){const{gl:t}=this;if(e===t.UNSIGNED_BYTE)return Uint8Array;if(e===t.BYTE)return Int8Array;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.SHORT)return Int16Array;if(e===t.UNSIGNED_INT)return Uint32Array;if(e===t.INT)return Int32Array;if(e===t.UNSIGNED_INT_5_9_9_9_REV)return Uint32Array;if(e===t.UNSIGNED_INT_10F_11F_11F_REV)return Uint32Array;if(e===t.HALF_FLOAT)return Uint16Array;if(e===t.FLOAT)return Float32Array;throw new Error(`THREE.WebGLTextureUtils: Unsupported WebGL type: ${e}`)}_getBytesPerTexel(e,t){const{gl:i}=this;if(e===i.UNSIGNED_SHORT_4_4_4_4||e===i.UNSIGNED_SHORT_5_5_5_1||e===i.UNSIGNED_SHORT_5_6_5)return 2;if(e===i.UNSIGNED_INT_5_9_9_9_REV||e===i.UNSIGNED_INT_10F_11F_11F_REV)return 4;let r=0;return e!==i.UNSIGNED_BYTE&&e!==i.BYTE||(r=1),e!==i.UNSIGNED_SHORT&&e!==i.SHORT&&e!==i.HALF_FLOAT||(r=2),e!==i.UNSIGNED_INT&&e!==i.INT&&e!==i.FLOAT||(r=4),t===i.RGBA||t===i.RGBA_INTEGER?4*r:t===i.RGB?3*r:t===i.RG||t===i.RG_INTEGER?2*r:t===i.RED||t===i.RED_INTEGER||t===i.ALPHA?r:void 0}dispose(){const{gl:e}=this;null!==this._srcFramebuffer&&e.deleteFramebuffer(this._srcFramebuffer),null!==this._dstFramebuffer&&e.deleteFramebuffer(this._dstFramebuffer)}}function Zw(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 Qw{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 Jw{constructor(e){this.backend=e,this.maxAnisotropy=null,this.maxUniformBlockSize=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 i=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(i.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}getUniformBufferLimit(){if(null!==this.maxUniformBlockSize)return this.maxUniformBlockSize;const e=this.backend.gl;return this.maxUniformBlockSize=e.getParameter(e.MAX_UNIFORM_BLOCK_SIZE),this.maxUniformBlockSize}}const eA={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 tA{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:i,mode:r,object:n,type:s,info:a,index:o}=this;0!==o?i.drawElements(r,t,s,e):i.drawArrays(r,e,t),a.update(n,t,1)}renderInstances(e,t,i){const{gl:r,mode:n,type:s,index:a,object:o,info:l}=this;0!==i&&(0!==a?r.drawElementsInstanced(n,t,s,e,i):r.drawArraysInstanced(n,e,t,i),l.update(o,t,i))}renderMultiDraw(e,t,i){const{extensions:r,mode:n,object:s,info:a}=this;if(0===i)return;const o=r.get("WEBGL_multi_draw");if(null===o)for(let r=0;r<i;r++)this.render(e[r],t[r]);else{0!==this.index?o.multiDrawElementsWEBGL(n,t,0,this.type,e,0,i):o.multiDrawArraysWEBGL(n,e,0,t,0,i);let r=0;for(let e=0;e<i;e++)r+=t[e];a.update(s,r,1)}}}class iA{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&&(Ti(`TimestampQueryPool: No timestamp available for uid ${e}.`),t=0),t}hasTimestampQuery(e){return this.timestamps.has(e)}allocateQueriesForContext(){}async resolveQueriesAsync(){}dispose(){}}class rA extends iA{constructor(e,t,i=2048){if(super(i),this.gl=e,this.type=t,this.ext=e.getExtension("EXT_disjoint_timer_query_webgl2")||e.getExtension("EXT_disjoint_timer_query"),!this.ext)return Ti("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;this.currentQueryIndex+2>this.maxQueries&&(this.resolveQueriesAsync(),this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=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 i=this.queries[t];if(i)try{"inactive"===this.queryStates.get(t)&&(this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,i),this.activeQuery=t,this.queryStates.set(t,"started"))}catch(e){Mi("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){Mi("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,i]of this.queryOffsets){if("ended"===this.queryStates.get(i)){const r=this.queries[i];e.set(t,this.resolveQuery(r))}}if(0===e.size)return this.lastValue;const t={},i=[];this.timestamps.clear();for(const[r,n]of e){const e=r.match(/^(.*):f(\d+)$/),s=parseInt(e[2]);!1===i.includes(s)&&i.push(s),void 0===t[s]&&(t[s]=0);const a=await n;this.timestamps.set(r,a),t[s]+=a}const r=t[i[i.length-1]];return this.lastValue=r,this.frames=i,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,r}catch(e){return Mi("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 i,r=!1;const n=e=>{r||(r=!0,i&&(clearTimeout(i),i=null),t(e))},s=()=>{if(this.isDisposed)n(this.lastValue);else try{if(this.gl.getParameter(this.ext.GPU_DISJOINT_EXT))return void n(this.lastValue);if(!this.gl.getQueryParameter(e,this.gl.QUERY_RESULT_AVAILABLE))return void(i=setTimeout(s,1));const r=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT);t(Number(r)/1e6)}catch(e){Mi("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.timestamps.clear(),this.frames=[],this.lastValue=0,this.activeQuery=null}}}const nA=[];class sA extends Ow{constructor(e={}){super(e),this.isWebGLBackend=!0,this.attributeUtils=null,this.vertexArrayUtils=null,this.extensions=null,this.capabilities=null,this.textureUtils=null,this.bufferRenderer=null,this.gl=null,this.state=null,this.utils=null,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,i={antialias:e.currentSamples>0,alpha:!0,depth:e.depth,stencil:e.stencil},r=void 0!==t.context?t.context:e.domElement.getContext("webgl2",i);function n(t){t.preventDefault();const i={api:"WebGL",message:t.statusMessage||"Unknown reason",reason:null,originalEvent:t};e.onDeviceLost(i)}this._onContextLost=n,e.domElement.addEventListener("webglcontextlost",n,!1),this.gl=r,this.extensions=new Qw(this),this.capabilities=new Jw(this),this.attributeUtils=new Vw(this),this.vertexArrayUtils=new Hw(this),this.textureUtils=new Kw(this),this.bufferRenderer=new tA(this),this.state=new Ww(this),this.utils=new jw(this),this.extensions.get("EXT_color_buffer_float"),this.extensions.get("WEBGL_clip_cull_distance"),this.extensions.get("OES_texture_float_linear"),this.extensions.get("EXT_color_buffer_half_float"),this.extensions.get("WEBGL_multisampled_render_to_texture"),this.extensions.get("WEBGL_render_shared_exponent"),this.extensions.get("WEBGL_multi_draw"),this.extensions.get("OVR_multiview2"),this.extensions.get("EXT_clip_control"),this.disjoint=this.extensions.get("EXT_disjoint_timer_query_webgl2"),this.parallel=this.extensions.get("KHR_parallel_shader_compile"),this.drawBuffersIndexedExt=this.extensions.get("OES_draw_buffers_indexed"),t.reversedDepthBuffer&&(this.extensions.has("EXT_clip_control")?e.reversedDepthBuffer=!0:(Ti("WebGPURenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer."),e.reversedDepthBuffer=!1)),e.reversedDepthBuffer&&this.state.setReversedDepth(!0)}get coordinateSystem(){return ui}get hasTimestamp(){return null!==this.disjoint}async getArrayBufferAsync(e,t=null,i=0,r=-1){return await this.attributeUtils.getArrayBufferAsync(e,t,i,r)}async makeXRCompatible(){!0!==this.gl.getContextAttributes().xrCompatible&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,i=null){const r=this.gl;this.set(e.texture,{textureGPU:t,glTextureType:this.textureUtils.getGLTextureType(e.texture),glInternalFormat:r.RGBA8}),null!==i&&(this.set(e.depthTexture,{textureGPU:i,glTextureType:this.textureUtils.getGLTextureType(e.depthTexture),glInternalFormat:e.stencilBuffer?r.DEPTH24_STENCIL8:r.DEPTH_COMPONENT24}),!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!0===e._autoAllocateDepthBuffer&&!1===e.multiview&&Ti("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 rA(this.gl,e,2048));const i=this.timestampQueryPool[e];null!==i.allocateQueriesForContext(t)&&i.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,i=this.get(e);if(e.viewport)this.updateViewport(e);else{const{width:i,height:r}=e;t.viewport(0,0,i,r)}if(e.scissor)this.updateScissor(e);else{const{width:i,height:r}=e;t.scissor(0,0,i,r)}t.setScissorTest(e.scissor),this.initTimestampQuery(di,this.getTimestampUID(e)),i.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1);const r=e.occlusionQueryCount,n=this.getOcclusionData(e);r>0?(n.currentOcclusionQueries=n.occlusionQueries,n.currentOcclusionQueryObjects=n.occlusionQueryObjects,n.lastOcclusionObject=null,n.occlusionQueries=new Array(r),n.occlusionQueryObjects=new Array(r),n.occlusionQueryIndex=0):void 0!==n.lastOcclusionObject&&(n.lastOcclusionObject=void 0)}finishRender(e){const{gl:t,state:i}=this,r=this.get(e).previousContext;i.resetVertexState();if(e.occlusionQueryCount>0){const i=this.getOcclusionData(e).lastOcclusionObject;i&&!0===i.occlusionTest&&t.endQuery(t.ANY_SAMPLES_PASSED),this.resolveOccludedAsync(e)}const n=e.textures;if(null!==n)for(let e=0;e<n.length;e++){const t=n[e];!0===t.generateMipmaps&&!0===t.mipmapsAutoUpdate&&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}=r;i.viewport(0,0,e,t)}if(r.scissor)this.updateScissor(r);else{const{width:e,height:t}=r;i.scissor(0,0,e,t)}i.setScissorTest(r.scissor)}this.prepareTimestampBuffer(di,this.getTimestampUID(e))}resolveOccludedAsync(e){const t=this.getOcclusionData(e),{currentOcclusionQueries:i,currentOcclusionQueryObjects:r}=t;if(i&&r){const e=new WeakSet,{gl:n}=this;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueries=null;const s=()=>{let a=!0;for(let t=0;t<i.length;t++){const s=i[t];s&&(n.getQueryParameter(s,n.QUERY_RESULT_AVAILABLE)?(0===n.getQueryParameter(s,n.QUERY_RESULT)&&e.add(r[t]),i[t]=null,n.deleteQuery(s)):a=!1)}!1===a?requestAnimationFrame(s):t.occluded=e};s()}}isOccluded(e,t){const i=this.getOcclusionData(e);return i.occluded&&i.occluded.has(t)}updateViewport(e){const{state:t}=this,{x:i,y:r,width:n,height:s}=e.viewportValue;t.viewport(i,e.height-s-r,n,s)}updateScissor(e){const{state:t}=this,{x:i,y:r,width:n,height:s}=e.scissorValue;t.scissor(i,e.height-s-r,n,s)}setScissorTest(e){this.state.setScissorTest(e)}resetState(){this.state.reset()}getClearColor(){const e=super.getClearColor();return e.r*=e.a,e.g*=e.a,e.b*=e.a,e}clear(e,t,i,r=null,n=!0,s=!0){const{gl:a,renderer:o}=this;if(null===r){r={textures:null,clearColorValue:this.getClearColor()}}let l=0;if(e&&(l|=a.COLOR_BUFFER_BIT),t&&(l|=a.DEPTH_BUFFER_BIT),i&&(l|=a.STENCIL_BUFFER_BIT),0!==l){let u;u=r.clearColorValue?r.clearColorValue:this.getClearColor();const c=o.getClearDepth(),h=o.getClearStencil();if(e&&this.state.setColorMask(!0),t&&this.state.setDepthMask(!0),i&&this.state.setStencilMask(4294967295),null===r.textures)e&&a.clearColor(u.r,u.g,u.b,u.a),t&&a.clearDepth(c),i&&a.clearStencil(h),a.clear(l);else{if(n&&this._setFramebuffer(r),e)for(let e=0;e<r.textures.length;e++){const t=r.mrt?r.mrt.getClearColor(r.textures[e].name):null;null!==t?a.clearBufferfv(a.COLOR,e,[t.r,t.g,t.b,t.a]):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&&i?a.clearBufferfi(a.DEPTH_STENCIL,0,c,h):t?a.clearBufferfv(a.DEPTH,0,[c]):i&&a.clearBufferiv(a.STENCIL,0,[h]),n&&s&&this._resolveRenderTarget(r),n&&null!==this._currentContext&&this._currentContext!==r&&this._setFramebuffer(this._currentContext)}}}beginCompute(e){const{state:t,gl:i}=this;t.bindFramebuffer(i.FRAMEBUFFER,null),this.initTimestampQuery(hi,this.getTimestampUID(e))}compute(e,t,i,r,n=null){const{state:s,gl:a}=this;!1===this.discard&&(s.enable(a.RASTERIZER_DISCARD),this.discard=!0);const{programGPU:o,transformAttributes:l,attributes:u}=this.get(r);for(let e=0;e<u.length;e++)this._updateComputeAttribute(u[e]);for(let e=0;e<l.length;e++)this._updateComputeAttribute(l[e]);const c=this.vertexArrayUtils.getVAO(r,u);s.setVertexState(c),s.useProgram(o),this._bindUniforms(i);for(let e=0;e<l.length;e++)a.bindBufferBase(a.TRANSFORM_FEEDBACK_BUFFER,e,this.get(l[e]).transformBuffer);a.beginTransformFeedback(a.POINTS),n=null!==n?n:t.count,Array.isArray(n)?(Ei("WebGLBackend.compute(): The count parameter must be a single number, not an array."),n=n[0]):n&&"object"==typeof n&&n.isIndirectStorageBufferAttribute&&(Ei("WebGLBackend.compute(): The count parameter must be a single number, not IndirectStorageBufferAttribute"),n=t.count),u[0].isStorageInstancedBufferAttribute?a.drawArraysInstanced(a.POINTS,0,1,n):a.drawArrays(a.POINTS,0,n),a.endTransformFeedback();for(let e=0;e<l.length;e++)a.bindBufferBase(a.TRANSFORM_FEEDBACK_BUFFER,e,null);for(let e=0;e<l.length;e++){const t=this.get(l[e]);t.pbo&&this.has(t.pbo)&&this.textureUtils.copyBufferToTexture(t.transformBuffer,t.pbo),t.switchBuffers()}}_updateComputeAttribute(e){const t=this.getBufferAttribute(e),i=e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute?HT:GT;this.renderer._attributes.update(t,i)}finishCompute(e){const{state:t,gl:i}=this;this.discard=!1,t.disable(i.RASTERIZER_DISCARD),this.prepareTimestampBuffer(hi,this.getTimestampUID(e)),this._currentContext&&this._setFramebuffer(this._currentContext)}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.isArrayTexture&&e.camera.isArrayCamera}_draw(e,t,i,r,n,s){if(e.isBatchedMesh)if(!1===this.hasFeature("WEBGL_multi_draw")){const{gl:i}=this,r=i.getUniformLocation(s,"nodeUniformDrawId"),n=e._multiDrawStarts,a=e._multiDrawCounts,o=e._multiDrawCount;for(let e=0;e<o;e++)i.uniform1ui(r,e),t.render(n[e],a[e])}else t.renderMultiDraw(e._multiDrawStarts,e._multiDrawCounts,e._multiDrawCount);else n>1?t.renderInstances(i,r,n):t.render(i,r)}draw(e){const{object:t,pipeline:i,material:r,context:n,hardwareClippingPlanes:s}=e,{programGPU:a}=this.get(i),{gl:o,state:l}=this,u=e.getDrawParameters();if(null===u)return;this._bindUniforms(e.getBindings());const c=t.isMesh&&t.matrixWorld.determinantAffine()<0;l.setMaterial(r,c,s),null!==n.mrt&&null!==n.textures&&l.setMRTBlending(n.textures,n.mrt,r),l.useProgram(a);const h=e.getIndex(),d=this.vertexArrayUtils.getVAO(e,e.getAttributes(),h);if(l.setVertexState(d),n.occlusionQueryCount>0){const e=this.getOcclusionData(n),i=e.lastOcclusionObject;if(i!==t){if(null!==i&&!0===i.occlusionTest&&(o.endQuery(o.ANY_SAMPLES_PASSED),e.occlusionQueryIndex++),!0===t.occlusionTest){const i=o.createQuery();o.beginQuery(o.ANY_SAMPLES_PASSED,i),e.occlusionQueries[e.occlusionQueryIndex]=i,e.occlusionQueryObjects[e.occlusionQueryIndex]=t}e.lastOcclusionObject=t}}const p=this.bufferRenderer;t.isPoints?p.mode=o.POINTS:t.isLineSegments?p.mode=o.LINES:t.isLine?p.mode=o.LINE_STRIP:t.isLineLoop?p.mode=o.LINE_LOOP:!0===r.wireframe?(l.setLineWidth(r.wireframeLinewidth*this.renderer.getPixelRatio()),p.mode=o.LINES):p.mode=o.TRIANGLES;const{vertexCount:f,instanceCount:m}=u;let{firstVertex:g}=u;if(p.object=t,null!==h){g*=h.array.BYTES_PER_ELEMENT;const e=this.get(h);p.index=h.count,p.type=e.type}else p.index=0;if(!0===e.camera.isArrayCamera&&e.camera.cameras.length>0&&!1===e.camera.isMultiViewCamera){const i=this.get(e.camera),r=e.camera.cameras,s=e.getBindingGroup("cameraIndex").bindings[0];if(void 0===i.indexesGPU||i.indexesGPU.length!==r.length){const e=new Uint32Array([0,0,0,0]),t=[];for(let i=0,n=r.length;i<n;i++){const r=o.createBuffer();e[0]=i,o.bindBuffer(o.UNIFORM_BUFFER,r),o.bufferData(o.UNIFORM_BUFFER,e,o.STATIC_DRAW),t.push(r)}i.indexesGPU=t}let u=0;e:for(const t of e.getBindings())for(const e of t.bindings){if(e===s)break e;(e.isUniformsGroup||e.isUniformBuffer)&&u++}const c=this._currentContext.renderTarget,h=null===c||!0===c.isPostProcessingRenderTarget?this.renderer.getPixelRatio():1,d=this._isRenderCameraDepthArray(this._currentContext),_=this._currentContext.activeCubeFace;if(d){const e=this.get(this._currentContext.depthTexture);if(e.clearedRenderId!==this.renderer._nodes.nodeFrame.renderId){e.clearedRenderId=this.renderer._nodes.nodeFrame.renderId;const{stencilBuffer:t}=c;for(let e=0,i=r.length;e<i;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=_,this._currentContext.activeCubeFace=_}}const v=n.frustumArray;for(let n=0,s=r.length;n<s;n++){const s=r[n];if(t.layers.test(s.layers)&&(!1===e.camera.perCameraFrustumCulled||!1===t.frustumCulled||t.intersectsFrustum(v.getFrustum(n)))){d&&(this.renderer._activeCubeFace=n,this._currentContext.activeCubeFace=n,this._setFramebuffer(this._currentContext));const r=s.viewport;if(void 0!==r){const t=r.x*h,i=r.y*h,n=r.width*h,s=r.height*h;l.viewport(Math.floor(t),Math.floor(e.context.height-s-i),Math.floor(n),Math.floor(s))}l.bindBufferBase(o.UNIFORM_BUFFER,u,i.indexesGPU[n]),this._draw(t,p,g,f,m,a)}this._currentContext.activeCubeFace=_,this.renderer._activeCubeFace=_}}else this._draw(t,p,g,f,m,a)}deleteVertexState(e){this.vertexArrayUtils.releaseVAO(e)}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,i,r,n,s){return this.textureUtils.copyTextureToBuffer(e,t,i,r,n,s)}updateSampler(){return""}createNodeBuilder(e,t){return new Uw(e,t)}createProgram(e){const t=this.gl,{stage:i,code:r}=e,n="fragment"===i?t.createShader(t.FRAGMENT_SHADER):t.createShader(t.VERTEX_SHADER);t.shaderSource(n,r),t.compileShader(n),this.set(e,{shaderGPU:n})}destroyProgram(e){const t=this.gl,i=this.get(e);t.deleteShader(i.shaderGPU),this.delete(e)}createRenderPipeline(e,t){const i=this.gl,r=e.pipeline,{fragmentProgram:n,vertexProgram:s}=r,a=i.createProgram(),o=this.get(n).shaderGPU,l=this.get(s).shaderGPU;if(i.attachShader(a,o),i.attachShader(a,l),i.linkProgram(a),this.set(r,{programGPU:a,fragmentShader:o,vertexShader:l}),null!==t&&this.parallel){const n=new Promise(t=>{const n=this.parallel,s=()=>{i.getProgramParameter(a,n.COMPLETION_STATUS_KHR)?(this._completeCompile(e,r),t()):requestAnimationFrame(s)};s()});return void t.push(n)}this._completeCompile(e,r)}destroyPipeline(e){const t=this.gl,i=this.get(e);!0===e.isComputePipeline&&this.vertexArrayUtils.releaseVAO(e),t.deleteProgram(i.programGPU),this.delete(e)}_handleSource(e,t){const i=e.split("\n"),r=[],n=Math.max(t-6,0),s=Math.min(t+6,i.length);for(let e=n;e<s;e++){const n=e+1;r.push(`${n===t?">":" "} ${n}: ${i[e]}`)}return r.join("\n")}_getShaderErrors(e,t,i){const r=e.getShaderParameter(t,e.COMPILE_STATUS),n=(e.getShaderInfoLog(t)||"").trim();if(r&&""===n)return"";const s=/ERROR: 0:(\d+)/.exec(n);if(s){const r=parseInt(s[1]);return i.toUpperCase()+"\n\n"+n+"\n\n"+this._handleSource(e.getShaderSource(t),r)}return n}_logProgramError(e,t,i){if(this.renderer.debug.checkShaderErrors){const r=this.gl,n=(r.getProgramInfoLog(e)||"").trim();if(!1===r.getProgramParameter(e,r.LINK_STATUS))if("function"==typeof this.renderer.debug.onShaderError)this.renderer.debug.onShaderError(r,e,i,t);else{const s=this._getShaderErrors(r,i,"vertex"),a=this._getShaderErrors(r,t,"fragment");Mi("WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(e,r.VALIDATE_STATUS)+"\n\nProgram Info Log: "+n+"\n"+s+"\n"+a)}else""!==n&&Ti("WebGLProgram: Program Info Log:",n)}}_completeCompile(e,t){const{state:i,gl:r}=this,n=this.get(t),{programGPU:s,fragmentShader:a,vertexShader:o}=n;!1===r.getProgramParameter(s,r.LINK_STATUS)&&this._logProgramError(s,a,o),i.useProgram(s);const l=e.getBindings();this._setupBindings(l,s),this.set(t,{programGPU:s,pipeline:s})}createComputePipeline(e,t,i=null){const{gl:r}=this,n={stage:"fragment",code:"#version 300 es\nprecision highp float;\nvoid main() {}"};this.createProgram(n);const{computeProgram:s}=e,a=r.createProgram(),o=this.get(n).shaderGPU,l=this.get(s).shaderGPU,u=e.transforms,c=[],h=[];for(let e=0;e<u.length;e++){const t=u[e];c.push(t.varyingName),h.push(t.attributeNode)}r.attachShader(a,o),r.attachShader(a,l),r.transformFeedbackVaryings(a,c,r.SEPARATE_ATTRIBS),r.linkProgram(a);const d=e.attributes,p=[],f=[];for(let e=0;e<d.length;e++)p.push(d[e].node.attribute);for(let e=0;e<h.length;e++)f.push(h[e].attribute);if(this.set(e,{programGPU:a,fragmentShader:o,vertexShader:l,transformAttributes:f,attributes:p}),null!==i&&this.parallel){const n=this.parallel,s=new Promise(i=>{const s=()=>{r.getProgramParameter(a,n.COMPLETION_STATUS_KHR)?(this._completeComputeCompile(e,t),i()):requestAnimationFrame(s)};s()});return void i.push(s)}this._completeComputeCompile(e,t)}_completeComputeCompile(e,t){const{state:i,gl:r}=this,{programGPU:n,fragmentShader:s,vertexShader:a}=this.get(e);!1===r.getProgramParameter(n,r.LINK_STATUS)&&this._logProgramError(n,s,a),i.useProgram(n),this._setupBindings(t,n)}createBindings(e,t){if(!1===this._knownBindings.has(t)){this._knownBindings.add(t);let e=0,i=0;for(const r of t){this.set(r,{textures:i,uniformBuffers:e});for(const t of r.bindings)t.isUniformBuffer&&e++,t.isSampledTexture&&i++}}this.updateBindings(e,t)}updateBindings(e){const{gl:t}=this;for(const i of e.bindings){const e=this.get(i);if(i.isUniformsGroup||i.isUniformBuffer){const r=i.buffer,n=e.bufferGPU;t.bindBuffer(t.UNIFORM_BUFFER,n);const s=i.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,n),0===s.length)t.bufferData(t.UNIFORM_BUFFER,r,t.DYNAMIC_DRAW);else{const e=_i(r),i=e?1:r.BYTES_PER_ELEMENT;for(let n=0,a=s.length;n<a;n++){const a=s[n],o=a.start*i,l=a.count*i,u=o*(e?r.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,u,r,o,l)}}this.set(i,e)}else if(i.isSampledTexture){const{textureGPU:t,glTextureType:r}=this.get(i.texture);e.textureGPU=t,e.glTextureType=r,this.set(i,e)}}}updateBinding(e){const t=this.gl;if(e.isUniformsGroup||e.isUniformBuffer){const i=this.get(e).bufferGPU,r=e.buffer,n=e.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,i),0===n.length)t.bufferData(t.UNIFORM_BUFFER,r,t.DYNAMIC_DRAW);else{const e=_i(r),i=e?1:r.BYTES_PER_ELEMENT;let s=n[0].start;for(let a=0,o=n.length;a<o;a++){const o=n[a],l=n[a+1],u=o.start+o.count;if(void 0!==l&&l.start===u)continue;const c=s*i,h=(u-s)*i,d=c*(e?r.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,d,r,c,h),void 0!==l&&(s=l.start)}}}}createUniformBuffer(e){const t=this.get(e);if(void 0===t.bufferGPU){const i=this.gl,r=e.buffer;t.bufferGPU=i.createBuffer(),i.bindBuffer(i.UNIFORM_BUFFER,t.bufferGPU),i.bufferData(i.UNIFORM_BUFFER,r.byteLength,i.DYNAMIC_DRAW)}}destroyUniformBuffer(e){const t=this.get(e);this.gl.deleteBuffer(t.bufferGPU),this.delete(e)}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.vertexArrayUtils.releaseBuffer(this.get(this.getBufferAttribute(e))),this.attributeUtils.destroyAttribute(e)}hasFeature(e){const t=Object.keys(eA).filter(t=>eA[t]===e),i=this.extensions;for(let e=0;e<t.length;e++)if(i.has(t[e]))return!0;return!1}copyTextureToTexture(e,t,i=null,r=null,n=0,s=0){this.textureUtils.copyTextureToTexture(e,t,i,r,n,s)}copyFramebufferToTexture(e,t,i){this.textureUtils.copyFramebufferToTexture(e,t,i)}hasCompatibility(e){return e===pi||super.hasCompatibility(e)}initRenderTarget(e){const{gl:t,state:i}=this;this._setFramebuffer(e),i.bindFramebuffer(t.FRAMEBUFFER,null)}_setFramebuffer(e){const{gl:t,state:i}=this;let r=null;if(null!==e.textures){const n=e.renderTarget,s=this.get(n),{depthBuffer:a,stencilBuffer:o}=n,l=!0===n.isCubeRenderTarget,u=!0===n.isXRRenderTarget,c=!0===u&&!0===n._hasExternalTextures;let h=s.msaaFrameBuffer,d=s.depthRenderbuffer;const p=this.extensions.get("WEBGL_multisampled_render_to_texture"),f=this.extensions.get("OVR_multiview2"),m=this._useMultisampledExtension(n);let g=n.samples;null!==e.depthTexture&&e.depthTexture.renderTarget!==n&&!1===m&&g>0&&(Ei('WebGLBackend: Shared depth texture is not supported with MSAA when "WEBGL_multisampled_render_to_texture" is unsupported. Falling back to single-sample rendering.'),g=0);const _=_M(e);let v;if(l?(s.cubeFramebuffers||(s.cubeFramebuffers={}),v=s.cubeFramebuffers[_]):u&&!1===c?v=this._xrFramebuffer:(s.framebuffers||(s.framebuffers={}),v=s.framebuffers[_]),void 0===v){v=t.createFramebuffer(),i.bindFramebuffer(t.FRAMEBUFFER,v);const r=e.textures,a=[];if(l){s.cubeFramebuffers[_]=v;const{textureGPU:i}=this.get(r[0]),n=e.activeCubeFace,a=e.activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+n,i,a)}else{s.framebuffers[_]=v;for(let i=0;i<r.length;i++){const s=r[i],a=this.get(s),o=t.COLOR_ATTACHMENT0+i;if(n.multiview)f.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,o,a.textureGPU,0,g,0,2);else if(a.glTextureType===t.TEXTURE_2D_ARRAY||a.glTextureType===t.TEXTURE_3D){const i=e.activeCubeFace,r=e.activeMipmapLevel;t.framebufferTextureLayer(t.FRAMEBUFFER,o,a.textureGPU,r,i)}else if(m)p.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,o,t.TEXTURE_2D,a.textureGPU,0,g);else{const i=e.activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,o,t.TEXTURE_2D,a.textureGPU,i)}}}const u=o?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(!0===n._autoAllocateDepthBuffer){const i=t.createRenderbuffer();this.textureUtils.setupRenderBufferStorage(i,e,0,m),s.xrDepthRenderbuffer=i,a.push(o?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT),t.bindRenderbuffer(t.RENDERBUFFER,i),t.framebufferRenderbuffer(t.FRAMEBUFFER,u,t.RENDERBUFFER,i)}else if(null!==e.depthTexture){a.push(o?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT);const i=this.get(e.depthTexture);if(n.multiview)f.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,u,i.textureGPU,0,g,0,2);else if(c&&m)p.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,u,t.TEXTURE_2D,i.textureGPU,0,g);else if(e.depthTexture.isArrayTexture){const r=e.activeCubeFace;t.framebufferTextureLayer(t.FRAMEBUFFER,u,i.textureGPU,0,r)}else if(e.depthTexture.isCubeTexture){const r=e.activeCubeFace;t.framebufferTexture2D(t.FRAMEBUFFER,u,t.TEXTURE_CUBE_MAP_POSITIVE_X+r,i.textureGPU,0)}else t.framebufferTexture2D(t.FRAMEBUFFER,u,t.TEXTURE_2D,i.textureGPU,0)}s.depthInvalidationArray=a}else{if(this._isRenderCameraDepthArray(e)){i.bindFramebuffer(t.FRAMEBUFFER,v);const r=e.activeCubeFace,n=this.get(e.depthTexture),s=o?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;t.framebufferTextureLayer(t.FRAMEBUFFER,s,n.textureGPU,0,r)}if((u||m||n.multiview)&&!0!==n._isOpaqueFramebuffer){if(i.bindFramebuffer(t.FRAMEBUFFER,v),e.textures.length>0){const i=this.get(e.textures[0]);n.multiview?f.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,i.textureGPU,0,g,0,2):m?p.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i.textureGPU,0,g):t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i.textureGPU,0)}const r=o?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(!0===n._autoAllocateDepthBuffer){const e=s.xrDepthRenderbuffer;t.bindRenderbuffer(t.RENDERBUFFER,e),t.framebufferRenderbuffer(t.FRAMEBUFFER,r,t.RENDERBUFFER,e)}else{const i=this.get(e.depthTexture);n.multiview?f.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,r,i.textureGPU,0,g,0,2):m?p.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,r,t.TEXTURE_2D,i.textureGPU,0,g):t.framebufferTexture2D(t.FRAMEBUFFER,r,t.TEXTURE_2D,i.textureGPU,0)}}}if(g>0&&!1===m&&!n.multiview){if(void 0===h){h=t.createFramebuffer(),i.bindFramebuffer(t.FRAMEBUFFER,h);const r=[],n=e.textures;for(let i=0;i<n.length;i++){r[i]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,r[i]);const n=e.textures[i],s=this.get(n);t.renderbufferStorageMultisample(t.RENDERBUFFER,g,s.glInternalFormat,e.width,e.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+i,t.RENDERBUFFER,r[i])}t.bindRenderbuffer(t.RENDERBUFFER,null),s.msaaFrameBuffer=h,s.msaaRenderbuffers=r,a&&void 0===d&&(d=t.createRenderbuffer(),this.textureUtils.setupRenderBufferStorage(d,e,g),s.depthRenderbuffer=d)}r=s.msaaFrameBuffer}else r=v;i.drawBuffers(e,v)}i.bindFramebuffer(t.FRAMEBUFFER,r)}_setupBindings(e,t){const i=this.gl;let r=0,n=0;for(const s of e)for(const e of s.bindings)if(e.isUniformsGroup||e.isUniformBuffer){const n=r++,s=i.getUniformBlockIndex(t,e.name);i.uniformBlockBinding(t,s,n)}else if(e.isSampledTexture){const r=n++,s=i.getUniformLocation(t,e.name);i.uniform1i(s,r)}}_bindUniforms(e){const{gl:t,state:i}=this;let r=0,n=0;for(const s of e)for(const e of s.bindings){const s=this.get(e);if(e.isUniformsGroup||e.isUniformBuffer){const e=r++;i.bindBufferBase(t.UNIFORM_BUFFER,e,s.bufferGPU)}else if(e.isSampledTexture){const e=n++;i.bindTexture(s.glTextureType,s.textureGPU,t.TEXTURE0+e)}}}_resolveRenderTarget(e){const{gl:t,state:i}=this,r=e.renderTarget;if(null!==e.textures&&r){const n=this.get(r);if(r.samples>0&&void 0!==n.msaaFrameBuffer&&!1===this._useMultisampledExtension(r)){const s=n.framebuffers[e.getCacheKey()],a=e.textures;let o=!1===r.resolveColorBuffer||0===a.length?0:t.COLOR_BUFFER_BIT;r.resolveDepthBuffer&&(r.depthBuffer&&(o|=t.DEPTH_BUFFER_BIT),r.stencilBuffer&&r.resolveStencilBuffer&&(o|=t.STENCIL_BUFFER_BIT));const l=n.msaaFrameBuffer,u=n.msaaRenderbuffers,c=a.length>1,h=Math.max(a.length,1);if(i.bindFramebuffer(t.READ_FRAMEBUFFER,l),i.bindFramebuffer(t.DRAW_FRAMEBUFFER,s),c)for(let e=0;e<a.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 i=0;i<h;i++){if(c){const{textureGPU:e}=this.get(a[i]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,u[i]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0)}if(e.scissor){const{x:i,y:r,width:n,height:s}=e.scissorValue,a=e.height-s-r;t.blitFramebuffer(i,a,i+n,a+s,i,a,i+n,a+s,o,t.NEAREST)}else t.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,o,t.NEAREST)}if(c)for(let e=0;e<a.length;e++){const{textureGPU:i}=this.get(a[e]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.RENDERBUFFER,u[e]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.TEXTURE_2D,i,0)}if(!0===this._supportsInvalidateFramebuffer){if(!1===r.storeMultisampledColorBuffer)for(let e=0;e<a.length;e++)nA.push(t.COLOR_ATTACHMENT0+e);r.depthBuffer&&!1===r.storeMultisampledDepthBuffer&&nA.push(r.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT),nA.length>0&&(t.invalidateFramebuffer(t.READ_FRAMEBUFFER,nA),nA.length=0)}}else if(!0===this._supportsInvalidateFramebuffer&&n.framebuffers&&(!0===r._autoAllocateDepthBuffer||r.samples>0&&!1===r.storeMultisampledDepthBuffer)){const r=n.framebuffers[e.getCacheKey()];i.bindFramebuffer(t.DRAW_FRAMEBUFFER,r),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,n.depthInvalidationArray)}}}_useMultisampledExtension(e){return!0===e.multiview||e.samples>0&&!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!1!==e._autoAllocateDepthBuffer}async dispose(){if(await super.dispose(),null!==this.vertexArrayUtils&&this.vertexArrayUtils.dispose(),null!==this.textureUtils&&this.textureUtils.dispose(),void 0===this.parameters.canvas){const e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext()}this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const aA="point-list",oA="line-list",lA="line-strip",uA="triangle-list",cA="undefined"!=typeof self&&self.GPUShaderStage?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},hA="never",dA="less",pA="equal",fA="less-equal",mA="greater",gA="not-equal",_A="greater-equal",vA="always",bA="store",yA="discard",xA="load",SA="clear",TA="ccw",MA="cw",EA="none",wA="back",AA="uint16",RA="uint32",CA="r8unorm",NA="r8snorm",PA="r8uint",LA="r8sint",DA="r16uint",UA="r16sint",IA="r16float",FA="rg8unorm",OA="rg8snorm",BA="rg8uint",kA="rg8sint",zA="r16unorm",GA="r16snorm",VA="r32uint",HA="r32sint",WA="r32float",jA="rg16uint",$A="rg16sint",XA="rg16float",qA="rgba8unorm",YA="rgba8unorm-srgb",KA="rgba8snorm",ZA="rgba8uint",QA="rgba8sint",JA="bgra8unorm",eR="bgra8unorm-srgb",tR="rg16unorm",iR="rg16snorm",rR="rgb9e5ufloat",nR="rgb10a2unorm",sR="rg11b10ufloat",aR="rg32uint",oR="rg32sint",lR="rg32float",uR="rgba16uint",cR="rgba16sint",hR="rgba16float",dR="rgba16unorm",pR="rgba16snorm",fR="rgba32uint",mR="rgba32sint",gR="rgba32float",_R="depth16unorm",vR="depth24plus",bR="depth24plus-stencil8",yR="depth32float",xR="depth32float-stencil8",SR="bc1-rgba-unorm",TR="bc1-rgba-unorm-srgb",MR="bc2-rgba-unorm",ER="bc2-rgba-unorm-srgb",wR="bc3-rgba-unorm",AR="bc3-rgba-unorm-srgb",RR="bc4-r-unorm",CR="bc4-r-snorm",NR="bc5-rg-unorm",PR="bc5-rg-snorm",LR="bc6h-rgb-ufloat",DR="bc6h-rgb-float",UR="bc7-rgba-unorm",IR="bc7-rgba-unorm-srgb",FR="etc2-rgb8unorm",OR="etc2-rgb8unorm-srgb",BR="etc2-rgb8a1unorm",kR="etc2-rgb8a1unorm-srgb",zR="etc2-rgba8unorm",GR="etc2-rgba8unorm-srgb",VR="eac-r11unorm",HR="eac-r11snorm",WR="eac-rg11unorm",jR="eac-rg11snorm",$R="astc-4x4-unorm",XR="astc-4x4-unorm-srgb",qR="astc-5x4-unorm",YR="astc-5x4-unorm-srgb",KR="astc-5x5-unorm",ZR="astc-5x5-unorm-srgb",QR="astc-6x5-unorm",JR="astc-6x5-unorm-srgb",eC="astc-6x6-unorm",tC="astc-6x6-unorm-srgb",iC="astc-8x5-unorm",rC="astc-8x5-unorm-srgb",nC="astc-8x6-unorm",sC="astc-8x6-unorm-srgb",aC="astc-8x8-unorm",oC="astc-8x8-unorm-srgb",lC="astc-10x5-unorm",uC="astc-10x5-unorm-srgb",cC="astc-10x6-unorm",hC="astc-10x6-unorm-srgb",dC="astc-10x8-unorm",pC="astc-10x8-unorm-srgb",fC="astc-10x10-unorm",mC="astc-10x10-unorm-srgb",gC="astc-12x10-unorm",_C="astc-12x10-unorm-srgb",vC="astc-12x12-unorm",bC="astc-12x12-unorm-srgb",yC="clamp-to-edge",xC="repeat",SC="mirror-repeat",TC="linear",MC="nearest",EC="zero",wC="one",AC="src",RC="one-minus-src",CC="src-alpha",NC="one-minus-src-alpha",PC="dst",LC="one-minus-dst",DC="dst-alpha",UC="one-minus-dst-alpha",IC="src-alpha-saturated",FC="constant",OC="one-minus-constant",BC="add",kC="subtract",zC="reverse-subtract",GC="min",VC="max",HC=0,WC=15,jC="keep",$C="zero",XC="replace",qC="invert",YC="increment-clamp",KC="decrement-clamp",ZC="increment-wrap",QC="decrement-wrap",JC="storage",eN="read-only-storage",tN="write-only",iN="read-only",rN="read-write",nN="non-filtering",sN="comparison",aN="float",oN="unfilterable-float",lN="depth",uN="sint",cN="uint",hN="2d",dN="3d",pN="2d",fN="2d-array",mN="cube",gN="3d",_N="all",vN="depth-only",bN="vertex",yN="instance",xN={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"},SN={"texture-compression-s3tc":"texture-compression-bc","texture-compression-etc1":"texture-compression-etc2"};class TN extends yw{constructor(e,t,i){super(e,t?t.value:null),this.textureNode=t,this.groupNode=i}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}clone(){const e=super.clone();return e.texture=this.textureNode.value,e}}class MN extends pw{constructor(e,t){super(e,t?t.array:null),this._attribute=t,this.isStorageBuffer=!0}get attribute(){return this._attribute}}let EN=0;class wN extends MN{constructor(e,t){super("StorageBuffer_"+(e&&e.name?e.name:EN++)),this.nodeUniform=e,this.access=e?e.access:rc,this.groupNode=t}get attribute(){return this.nodeUniform.value}get buffer(){return this.nodeUniform.value.array}}const AN=[null];class RN{constructor(e){this.backend=e,this._preferredCanvasFormat=null}getCurrentDepthStencilFormat(e){let t;return e.depth&&(t=null!==e.depthTexture?this.getTextureFormatGPU(e.depthTexture):e.stencil?!0===this.backend.renderer.reversedDepthBuffer?xR:bR:!0===this.backend.renderer.reversedDepthBuffer?yR:vR),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 i=this.backend.get(e);t=void 0!==i.texture?i.texture.sampleCount:this.backend.renderer.currentSamples}else e.renderTarget&&(t=e.renderTarget.samples);t=this.getSampleCount(t||1);const i=t>1&&null!==e.renderTarget&&!0!==e.isDepthTexture&&!0!==e.isFramebufferTexture,r=t>1&&null!==e.renderTarget&&!0===e.isDepthTexture&&!0===e.isArrayTexture;return{samples:t,primarySamples:i||r?1:t,isMSAA:i}}getCurrentColorFormat(e){let t;return t=null!==e.textures?e.textures.length>0?this.getTextureFormatGPU(e.textures[0]):null: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?aA:e.isLineSegments||e.isMesh&&!0===t.wireframe?oA:e.isLine?lA:e.isMesh?uA:void 0}getStripIndexFormat(e,t){if(null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments)return t.index.array instanceof Uint16Array?AA:RA}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 null===this._preferredCanvasFormat&&(this._preferredCanvasFormat=navigator.gpu.getPreferredCanvasFormat()),this._preferredCanvasFormat;if(e===ze)return JA;if(e===Xe)return hR;throw new Error("THREE.WebGPUUtils: Unsupported output buffer type.")}}function CN(e,t){AN[0]=t,e.queue.submit(AN),AN[0]=null}class NN{constructor(){this.label="",this.layout=null,this.entries=[]}reset(){this.label="",this.layout=null,this.entries.length=0}}class PN{constructor(){this.label="",this.size=0,this.usage=0,this.mappedAtCreation=!1}reset(){this.label="",this.size=0,this.usage=0,this.mappedAtCreation=!1}}class LN{constructor(){this.label=""}reset(){this.label=""}}class DN{constructor(){this.label="",this.colorFormats=null,this.depthStencilFormat=void 0,this.sampleCount=1,this.depthReadOnly=!1,this.stencilReadOnly=!1}reset(){this.label="",this.colorFormats=null,this.depthStencilFormat=void 0,this.sampleCount=1,this.depthReadOnly=!1,this.stencilReadOnly=!1}}class UN{constructor(){this.view=null,this.depthSlice=void 0,this.resolveTarget=void 0,this.clearValue=void 0,this.loadOp=void 0,this.storeOp=void 0}reset(){this.view=null,this.depthSlice=void 0,this.resolveTarget=void 0,this.clearValue=void 0,this.loadOp=void 0,this.storeOp=void 0}}class IN{constructor(){this.label="",this.colorAttachments=[],this.depthStencilAttachment=void 0,this.occlusionQuerySet=void 0,this.timestampWrites=void 0,this.maxDrawCount=5e7}reset(){this.label="",this.colorAttachments.length=0,this.depthStencilAttachment=void 0,this.occlusionQuerySet=void 0,this.timestampWrites=void 0,this.maxDrawCount=5e7}}class FN{constructor(){this.label="",this.layout=null,this.vertex=null,this.primitive={},this.depthStencil=void 0,this.multisample=new ON,this.fragment=null}reset(){this.label="",this.layout=null,this.vertex=null,this.primitive={},this.depthStencil=void 0,this.multisample.reset(),this.fragment=null}}class ON{constructor(){this.count=1,this.mask=4294967295,this.alphaToCoverageEnabled=!1}reset(){this.count=1,this.mask=4294967295,this.alphaToCoverageEnabled=!1}}class BN{constructor(){this.label="",this.code="",this.compilationHints=[]}reset(){this.label="",this.code="",this.compilationHints.length=0}}class kN{constructor(){this.label="",this.size={width:0,height:1,depthOrArrayLayers:1},this.mipLevelCount=1,this.sampleCount=1,this.dimension="2d",this.format=void 0,this.usage=void 0,this.viewFormats=[],this.textureBindingViewDimension=void 0}reset(){this.label="",this.size.width=0,this.size.height=1,this.size.depthOrArrayLayers=1,this.mipLevelCount=1,this.sampleCount=1,this.dimension="2d",this.format=void 0,this.usage=void 0,this.viewFormats.length=0,this.textureBindingViewDimension=void 0}}class zN{constructor(){this.label="",this.format=void 0,this.dimension=void 0,this.usage=0,this.aspect="all",this.baseMipLevel=0,this.mipLevelCount=void 0,this.baseArrayLayer=0,this.arrayLayerCount=void 0,this.swizzle="rgba"}reset(){this.label="",this.format=void 0,this.dimension=void 0,this.usage=0,this.aspect="all",this.baseMipLevel=0,this.mipLevelCount=void 0,this.baseArrayLayer=0,this.arrayLayerCount=void 0,this.swizzle="rgba"}}const GN=new NN,VN=new PN,HN=new LN,WN=new DN,jN=new IN,$N=new FN,XN=new UN,qN=new BN,YN=new kN,KN=new zN;class ZN extends zT{constructor(e){super(),this.device=e;this.mipmapSampler=e.createSampler({minFilter:TC}),this.flipYSampler=e.createSampler({minFilter:MC}),VN.size=4,VN.usage=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,this.flipUniformBuffer=e.createBuffer(VN),VN.reset(),e.queue.writeBuffer(this.flipUniformBuffer,0,new Uint32Array([1])),VN.size=4,VN.usage=GPUBufferUsage.UNIFORM,this.noFlipUniformBuffer=e.createBuffer(VN),VN.reset(),this.transferPipelines={},qN.label="mipmap",qN.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",this.mipmapShaderModule=e.createShaderModule(qN),qN.reset()}getTransferPipeline(e,t){const i=`${e}-${t=t||"2d-array"}`;let r=this.transferPipelines[i];return void 0===r&&($N.label=`mipmap-${e}-${t}`,$N.vertex={module:this.mipmapShaderModule},$N.fragment={module:this.mipmapShaderModule,entryPoint:`main_${t.replace("-","_")}`,targets:[{format:e}]},$N.layout="auto",r=this.device.createRenderPipeline($N),$N.reset(),this.transferPipelines[i]=r),r}flipY(e,t,i=0){const r=t.format,{width:n,height:s}=t.size;YN.size.width=n,YN.size.height=s,YN.format=r,YN.usage=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING;const a=this.device.createTexture(YN);YN.reset();const o=this.getTransferPipeline(r,e.textureBindingViewDimension),l=this.getTransferPipeline(r,a.textureBindingViewDimension),u=this.device.createCommandEncoder(HN),c=(e,t,i,r,n,s)=>{const a=e.getBindGroupLayout(0);KN.dimension=t.textureBindingViewDimension||"2d-array",KN.mipLevelCount=1;const o=t.createView(KN);KN.reset(),GN.layout=a,GN.entries.push({binding:0,resource:this.flipYSampler},{binding:1,resource:o},{binding:2,resource:{buffer:s?this.flipUniformBuffer:this.noFlipUniformBuffer}});const l=this.device.createBindGroup(GN);GN.reset(),KN.dimension="2d",KN.mipLevelCount=1,KN.baseArrayLayer=n,KN.arrayLayerCount=1;const c=r.createView(KN);KN.reset(),XN.view=c,XN.loadOp=SA,XN.storeOp=bA,jN.colorAttachments.push(XN);const h=u.beginRenderPass(jN);jN.reset(),XN.reset(),h.setPipeline(e),h.setBindGroup(0,l),h.draw(3,1,0,i),h.end()};c(o,e,i,a,0,!1),c(l,a,0,e,i,!0),CN(this.device,u.finish()),a.destroy()}generateMipmaps(e,t=null){const i=this.get(e),r=i.layers||this._mipmapCreateBundles(e);let n=t;null===n&&(HN.label="mipmapEncoder",n=this.device.createCommandEncoder(HN),HN.reset()),this._mipmapRunBundles(n,r),null===t&&CN(this.device,n.finish()),i.layers=r}_mipmapCreateBundles(e){const t=e.textureBindingViewDimension||"2d-array",i=this.getTransferPipeline(e.format,t),r=i.getBindGroupLayout(0),n=[];for(let s=1;s<e.mipLevelCount;s++)for(let a=0;a<e.depthOrArrayLayers;a++){KN.dimension=t,KN.baseMipLevel=s-1,KN.mipLevelCount=1;const o=e.createView(KN);KN.reset(),GN.layout=r,GN.entries.push({binding:0,resource:this.mipmapSampler},{binding:1,resource:o},{binding:2,resource:{buffer:this.noFlipUniformBuffer}});const l=this.device.createBindGroup(GN);GN.reset(),KN.dimension="2d",KN.baseMipLevel=s,KN.mipLevelCount=1,KN.baseArrayLayer=a,KN.arrayLayerCount=1;const u=e.createView(KN);KN.reset();const c=new UN;c.view=u,c.loadOp=SA,c.storeOp=bA;const h=new IN;h.colorAttachments.push(c),WN.colorFormats=[e.format];const d=this.device.createRenderBundleEncoder(WN);WN.reset(),d.setPipeline(i),d.setBindGroup(0,l),d.draw(3,1,0,a),n.push({renderBundles:[d.finish()],passDescriptor:h})}return n}_mipmapRunBundles(e,t){const i=t.length;for(let r=0;r<i;r++){const i=t[r],n=e.beginRenderPass(i.passDescriptor);n.executeBundles(i.renderBundles),n.end()}}}class QN{constructor(){this.texture=null,this.mipLevel=0,this.origin={x:0,y:0,z:0},this.aspect="all"}reset(){this.texture=null,this.mipLevel=0,this.origin.x=0,this.origin.y=0,this.origin.z=0,this.aspect="all"}}class JN{constructor(){this.width=0,this.height=1,this.depthOrArrayLayers=1}reset(){this.width=0,this.height=1,this.depthOrArrayLayers=1}}const eP=new PN,tP=new LN,iP=new class{constructor(){this.label="",this.addressModeU="clamp-to-edge",this.addressModeV="clamp-to-edge",this.addressModeW="clamp-to-edge",this.magFilter="nearest",this.minFilter="nearest",this.mipmapFilter="nearest",this.lodMinClamp=0,this.lodMaxClamp=32,this.compare=void 0,this.maxAnisotropy=1}reset(){this.label="",this.addressModeU="clamp-to-edge",this.addressModeV="clamp-to-edge",this.addressModeW="clamp-to-edge",this.magFilter="nearest",this.minFilter="nearest",this.mipmapFilter="nearest",this.lodMinClamp=0,this.lodMaxClamp=32,this.compare=void 0,this.maxAnisotropy=1}},rP=new QN,nP=new class{constructor(){this.buffer=null,this.offset=0,this.bytesPerRow=void 0,this.rowsPerImage=void 0}reset(){this.buffer=null,this.offset=0,this.bytesPerRow=void 0,this.rowsPerImage=void 0}},sP=new class{constructor(){this.offset=0,this.bytesPerRow=void 0,this.rowsPerImage=void 0}reset(){this.offset=0,this.bytesPerRow=void 0,this.rowsPerImage=void 0}},aP=new class{constructor(){this.source=null,this.origin={x:0,y:0},this.flipY=!1}reset(){this.source=null,this.origin.x=0,this.origin.y=0,this.flipY=!1}},oP=new class extends QN{constructor(){super(),this.colorSpace="srgb",this.premultipliedAlpha=!1}reset(){super.reset(),this.colorSpace="srgb",this.premultipliedAlpha=!1}},lP=new kN,uP=new JN,cP={[Qt]:"never",[Jt]:"less",[ei]:"equal",[ti]:"less-equal",[ii]:"greater",[ni]:"greater-equal",[si]:"always",[ri]:"not-equal"},hP=[0,1,3,2,4,5];function dP(e,t,i,r,n,s,a,o,l,u){rP.texture=t,rP.mipLevel=i,rP.origin.z=r,sP.offset=s,sP.bytesPerRow=a,sP.rowsPerImage=o,uP.width=l,uP.height=u,e.queue.writeTexture(rP,n.data,sP,uP),rP.reset(),sP.reset(),uP.reset()}class pP{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,i=e.texture,r=e.textureNode,n=!0===i.isDepthTexture&&null!==i.compareFunction&&r.isSampleCompare()&&t.hasCompatibility(pi),s=i.minFilter+"-"+i.magFilter+"-"+i.wrapS+"-"+i.wrapT+"-"+(i.wrapR||"0")+"-"+i.anisotropy+"-"+(!0===i.isDepthTexture?1:0)+"-"+(n?i.compareFunction:0);let a=this._samplerCache.get(s);if(void 0===a){iP.addressModeU=this._convertAddressMode(i.wrapS),iP.addressModeV=this._convertAddressMode(i.wrapT),iP.addressModeW=this._convertAddressMode(i.wrapR),iP.magFilter=this._convertFilterMode(i.magFilter),iP.minFilter=this._convertFilterMode(i.minFilter),iP.mipmapFilter=this._convertMipmapFilterMode(i.minFilter),i.isDepthTexture&&!1===n&&(iP.magFilter=MC,iP.minFilter=MC,iP.mipmapFilter=MC),iP.magFilter===TC&&iP.minFilter===TC&&iP.mipmapFilter===TC&&(iP.maxAnisotropy=i.anisotropy),n&&(iP.compare=cP[i.compareFunction]);const e=t.device.createSampler(iP);iP.reset(),a={sampler:e,usedTimes:0},this._samplerCache.set(s,a)}const o=t.get(e);return o.sampler!==a.sampler&&(this._releaseSampler(o),o.samplerKey=s,o.sampler=a.sampler,a.usedTimes++),s}destroySampler(e){this._releaseSampler(this.backend.get(e))}_releaseSampler(e){if(void 0!==e.sampler){const t=this._samplerCache.get(e.samplerKey);t.usedTimes--,0===t.usedTimes&&this._samplerCache.delete(e.samplerKey),e.sampler=void 0,e.samplerKey=void 0}}createDefaultTexture(e){let t;const i=fP(e,this.backend.device);t=e.isCubeTexture?this._getDefaultCubeTextureGPU(i):this._getDefaultTextureGPU(i),this.backend.get(e).texture=t}createTexture(e,t={}){const i=this.backend,r=i.get(e);if(r.initialized){if(!0===r.externalTexture)return;throw new Error("THREE.WebGPUTextureUtils: Texture already initialized.")}if(e.isExternalTexture)return r.texture=e.sourceTexture,void(r.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:n,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||fP(e,i.device);r.format=u;const{samples:c,primarySamples:h,isMSAA:d}=i.utils.getTextureSampleData(e),p=e.renderTarget,f=c>1&&null!==p&&a>1&&l===hN,m=void 0!==GPUTextureUsage.TRANSIENT_ATTACHMENT&&!1===f,g=!0===e.isDepthTexture&&m&&!1===p?.storeMultisampledDepthBuffer&&(!1===p.stencilBuffer||!1===p.storeMultisampledStencilBuffer),_=!0!==e.isDepthTexture&&m&&!1===p?.storeMultisampledColorBuffer;let v=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC;!0===e.isStorageTexture&&(v|=GPUTextureUsage.STORAGE_BINDING),!0!==e.isCompressedTexture&&!0!==e.isCompressedArrayTexture&&u!==rR&&(v|=GPUTextureUsage.RENDER_ATTACHMENT),h>1&&g&&(v=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TRANSIENT_ATTACHMENT);const b=new kN;if(b.label=e.name,b.size.width=n,b.size.height=s,b.size.depthOrArrayLayers=a,b.mipLevelCount=o,b.sampleCount=h,b.dimension=l,b.format=u,b.usage=v,void 0===u)return Ti("WebGPURenderer: Texture format not supported."),void this.createDefaultTexture(e);e.isCubeTexture&&(b.textureBindingViewDimension=mN);try{r.texture=i.device.createTexture(b)}catch(t){return Ti("WebGPURenderer: Failed to create texture with descriptor:",b),void this.createDefaultTexture(e)}if(d||f){const e=Object.assign({},b);if(e.label=e.label+"-msaa",e.sampleCount=c,e.mipLevelCount=1,(g||_)&&(e.usage=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TRANSIENT_ATTACHMENT),f){e.size=Object.assign({},e.size,{depthOrArrayLayers:1}),r.msaaTextures=[];for(let t=0;t<a;t++)e.label=b.label+"-msaa-"+t,r.msaaTextures.push(i.device.createTexture(e))}else r.msaaTexture=i.device.createTexture(e)}r.initialized=!0,r.textureDescriptorGPU=b}destroyTexture(e,t=!1){const i=this.backend,r=i.get(e);if(void 0!==r.texture&&!1===t&&!0!==e.isExternalTexture&&!0!==r.externalTexture&&r.texture.destroy(),void 0!==r.msaaTexture&&r.msaaTexture.destroy(),void 0!==r.msaaTextures)for(const e of r.msaaTextures)e.destroy();i.delete(e)}generateMipmaps(e,t=null){const i=this.backend.get(e);this._generateMipmaps(i.texture,t)}getColorBuffer(){const e=this.backend,t=e.renderer.getCanvasTarget(),{width:i,height:r}=e.getDrawingBufferSize(),n=e.renderer.currentSamples,s=t.colorTexture,a=e.get(s);if(void 0!==a.texture&&s.width===i&&s.height===r&&s.samples===n)return a.texture;let o=a.texture;return o&&o.destroy(),lP.label="colorBuffer",lP.size.width=i,lP.size.height=r,lP.sampleCount=e.utils.getSampleCount(e.renderer.currentSamples),lP.format=e.utils.getPreferredCanvasFormat(),lP.usage=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,o=e.device.createTexture(lP),lP.reset(),s.image.width=i,s.image.height=r,s.samples=n,a.texture=o,o}getDepthBuffer(e=!0,t=!1){const i=this.backend,r=i.renderer.getCanvasTarget(),{width:n,height:s}=i.getDrawingBufferSize(),a=i.renderer.currentSamples,o=r.depthTexture;if(o.width===n&&o.height===s&&o.samples===a&&o.depth===e&&o.stencil===t)return i.get(o).texture;const l=i.get(o).texture;let u,c;if(t?(u=rt,c=!0===i.renderer.reversedDepthBuffer?$e:Ke):e&&(u=it,c=!0===i.renderer.reversedDepthBuffer?$e:je),void 0!==l){if(o.image.width===n&&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=n,o.image.height=s,o.samples=a,this.createTexture(o,{width:n,height:s}),i.get(o).texture}updateTexture(e,t){const i=this.backend.get(e),r=e.mipmaps,{textureDescriptorGPU:n}=i;if(!e.isRenderTargetTexture&&void 0!==n){if(e.isDataTexture)if(r.length>0)for(let t=0,s=r.length;t<s;t++){const s=r[t];this._copyBufferToTexture(s,i.texture,n,0,e.flipY,0,t)}else this._copyBufferToTexture(t.image,i.texture,n,0,e.flipY);else if(e.isArrayTexture||e.isDataArrayTexture||e.isData3DTexture)if(e.layerUpdates&&e.layerUpdates.size>0){for(const r of e.layerUpdates)this._copyBufferToTexture(t.image,i.texture,n,r,e.flipY,r);e.clearLayerUpdates()}else for(let r=0;r<t.image.depth;r++)this._copyBufferToTexture(t.image,i.texture,n,r,e.flipY,r);else if(e.isCompressedTexture||e.isCompressedArrayTexture)if(e.isCompressedCubeTexture)for(let t=0;t<6;t++)this._copyCompressedBufferToTexture(e.image[t].mipmaps,i.texture,n,null,t);else e.isCompressedArrayTexture&&e.layerUpdates.size>0?(this._copyCompressedBufferToTexture(e.mipmaps,i.texture,n,e.layerUpdates),e.clearLayerUpdates()):this._copyCompressedBufferToTexture(e.mipmaps,i.texture,n);else if(e.isCubeTexture)this._copyCubeMapToTexture(e,i.texture,n);else if(e.isHTMLTexture){const t=this.backend.device,r=this.backend.renderer.domElement,s=e.image;if("function"!=typeof t.queue.copyElementImageToTexture)return;if(!i.hasPaintCallback)return i.hasPaintCallback=!0,void r.requestPaint();const a=n.size.width,o=n.size.height;2===t.queue.copyElementImageToTexture.length?t.queue.copyElementImageToTexture({source:s},{destination:{texture:i.texture},width:a,height:o}):t.queue.copyElementImageToTexture(s,a,o,{texture:i.texture}),e.flipY&&this._flipY(i.texture,n)}else if(r.length>0)for(let t=0,s=r.length;t<s;t++){const s=r[t];this._copyImageToTexture(s,i.texture,n,0,e.flipY,e.premultiplyAlpha,t)}else this._copyImageToTexture(t.image,i.texture,n,0,e.flipY,e.premultiplyAlpha);i.version=e.version}}async copyTextureToBuffer(e,t,i,r,n,s){const a=this.backend.device,o=this.backend.get(e),l=o.texture,u=o.textureDescriptorGPU.format,c=r*this._getBytesPerTexel(u),h=256*Math.ceil(c/256);eP.size=n*h,eP.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ;const d=a.createBuffer(eP);eP.reset();const p=a.createCommandEncoder(tP);rP.texture=l,rP.origin.x=t,rP.origin.y=i,rP.origin.z=s,nP.buffer=d,nP.bytesPerRow=h,uP.width=r,uP.height=n,p.copyTextureToBuffer(rP,nP,uP),rP.reset(),nP.reset(),uP.reset();const f=this._getTypedArrayType(u);CN(a,p.finish()),await d.mapAsync(GPUMapMode.READ);const m=new Uint8Array(d.getMappedRange()),g=new Uint8Array(c*n);for(let e=0;e<n;e++){const t=e*h;g.set(m.subarray(t,t+c),e*c)}return d.destroy(),new f(g.buffer)}dispose(){this._samplerCache.clear()}_getDefaultTextureGPU(e){let t=this.defaultTexture[e];if(void 0===t){const i=new lr;i.minFilter=Ue,i.magFilter=Ue,this.createTexture(i,{width:1,height:1,format:e}),this.defaultTexture[e]=t=i}return this.backend.get(t).texture}_getDefaultCubeTextureGPU(e){let t=this.defaultCubeTexture[e];if(void 0===t){const i=new Xs;i.minFilter=Ue,i.magFilter=Ue,this.createTexture(i,{width:1,height:1,depth:6}),this.defaultCubeTexture[e]=t=i}return this.backend.get(t).texture}_copyCubeMapToTexture(e,t,i){const r=e.images,n=e.mipmaps;for(let s=0;s<6;s++){const a=r[s],o=!0===e.flipY?hP[s]:s;a.isDataTexture?this._copyBufferToTexture(a.image,t,i,o,e.flipY):this._copyImageToTexture(a,t,i,o,e.flipY,e.premultiplyAlpha);for(let r=0;r<n.length;r++){const a=n[r].images[s];a.isDataTexture?this._copyBufferToTexture(a.image,t,i,o,e.flipY,0,r+1):this._copyImageToTexture(a,t,i,o,e.flipY,e.premultiplyAlpha,r+1)}}}_copyImageToTexture(e,t,i,r,n,s,a=0){const o=this.backend.device,l=a>0?e.width:i.size.width,u=a>0?e.height:i.size.height;aP.source=e,aP.flipY=n,oP.texture=t,oP.mipLevel=a,oP.origin.z=r,oP.premultipliedAlpha=s,uP.width=l,uP.height=u;try{o.queue.copyExternalImageToTexture(aP,oP,uP)}catch(e){}finally{aP.reset(),oP.reset(),uP.reset()}}_getPassUtils(){let e=this._passUtils;return null===e&&(this._passUtils=e=new ZN(this.backend.device)),e}_generateMipmaps(e,t=null){this._getPassUtils().generateMipmaps(e,t)}_flipY(e,t,i=0){this._getPassUtils().flipY(e,t,i)}_copyBufferToTexture(e,t,i,r,n,s=0,a=0){const o=this.backend.device,l=e.data,u=this._getBytesPerTexel(i.format),c=e.width*u;rP.texture=t,rP.mipLevel=a,rP.origin.z=r,sP.offset=e.width*e.height*u*s,sP.bytesPerRow=c,uP.width=e.width,uP.height=e.height,o.queue.writeTexture(rP,l,sP,uP),rP.reset(),sP.reset(),uP.reset(),!0===n&&this._flipY(t,i,r)}_copyCompressedBufferToTexture(e,t,i,r=null,n=-1){const s=this.backend.device,a=this._getBlockData(i.format),o=i.size.depthOrArrayLayers>1,l=r&&r.size>0?r:null;for(let r=0;r<e.length;r++){const u=e[r],c=u.width,h=u.height,d=o?i.size.depthOrArrayLayers:1,p=Math.ceil(c/a.width)*a.byteLength,f=Math.ceil(h/a.height),m=p*f,g=Math.ceil(c/a.width)*a.width,_=f*a.height;if(-1!==n)dP(s,t,r,n,u,0,p,f,g,_);else if(null!==l)for(const e of l)dP(s,t,r,e,u,e*m,p,f,g,_);else for(let e=0;e<d;e++)dP(s,t,r,e,u,e*m,p,f,g,_)}}_getBlockData(e){return e===SR||e===TR?{byteLength:8,width:4,height:4}:e===MR||e===ER||e===wR||e===AR?{byteLength:16,width:4,height:4}:e===RR||e===CR?{byteLength:8,width:4,height:4}:e===NR||e===PR||e===LR||e===DR||e===UR||e===IR?{byteLength:16,width:4,height:4}:e===FR||e===OR||e===BR||e===kR?{byteLength:8,width:4,height:4}:e===zR||e===GR?{byteLength:16,width:4,height:4}:e===VR||e===HR?{byteLength:8,width:4,height:4}:e===WR||e===jR||e===$R||e===XR?{byteLength:16,width:4,height:4}:e===qR||e===YR?{byteLength:16,width:5,height:4}:e===KR||e===ZR?{byteLength:16,width:5,height:5}:e===QR||e===JR?{byteLength:16,width:6,height:5}:e===eC||e===tC?{byteLength:16,width:6,height:6}:e===iC||e===rC?{byteLength:16,width:8,height:5}:e===nC||e===sC?{byteLength:16,width:8,height:6}:e===aC||e===oC?{byteLength:16,width:8,height:8}:e===lC||e===uC?{byteLength:16,width:10,height:5}:e===cC||e===hC?{byteLength:16,width:10,height:6}:e===dC||e===pC?{byteLength:16,width:10,height:8}:e===fC||e===mC?{byteLength:16,width:10,height:10}:e===gC||e===_C?{byteLength:16,width:12,height:10}:e===vC||e===bC?{byteLength:16,width:12,height:12}:{byteLength:this._getBytesPerTexel(e),width:1,height:1}}_convertAddressMode(e){let t=yC;return e===Pe?t=xC:e===De&&(t=SC),t}_convertFilterMode(e){let t=TC;return e!==Ue&&e!==Ie&&e!==Fe||(t=MC),t}_convertMipmapFilterMode(e){return e===Fe||e===ke?TC:MC}_getBytesPerTexel(e){return e===CA||e===NA||e===PA||e===LA?1:e===DA||e===UA||e===IA||e===FA||e===OA||e===BA||e===kA||e===zA||e===GA?2:e===VA||e===HA||e===WA||e===jA||e===$A||e===XA||e===qA||e===YA||e===KA||e===ZA||e===QA||e===JA||e===eR||e===tR||e===iR||e===rR||e===nR||e===sR||e===yR||e===vR||e===bR||e===xR?4:e===aR||e===oR||e===lR||e===uR||e===cR||e===hR||e===dR||e===pR?8:e===fR||e===mR||e===gR?16:void 0}_getTypedArrayType(e){return e===PA?Uint8Array:e===LA?Int8Array:e===CA?Uint8Array:e===NA?Int8Array:e===BA?Uint8Array:e===kA?Int8Array:e===FA?Uint8Array:e===OA?Int8Array:e===ZA?Uint8Array:e===QA?Int8Array:e===qA||e===YA?Uint8Array:e===KA?Int8Array:e===DA?Uint16Array:e===UA?Int16Array:e===jA?Uint16Array:e===$A?Int16Array:e===uR?Uint16Array:e===cR?Int16Array:e===IA||e===XA||e===hR||e===zA?Uint16Array:e===GA?Int16Array:e===tR?Uint16Array:e===iR?Int16Array:e===dR?Uint16Array:e===pR?Int16Array:e===VA?Uint32Array:e===HA?Int32Array:e===WA?Float32Array:e===aR?Uint32Array:e===oR?Int32Array:e===lR?Float32Array:e===fR?Uint32Array:e===mR?Int32Array:e===gR?Float32Array:e===JA||e===eR?Uint8Array:e===nR||e===rR||e===sR?Uint32Array:e===yR?Float32Array:e===vR||e===bR?Uint32Array:e===xR?Float32Array:void 0}_getDimension(e){let t;return t=e.is3DTexture||e.isData3DTexture?dN:hN,t}}function fP(e,t){const i=e.format,r=e.type,n=e.normalized,s=e.colorSpace,a=Qi.getTransfer(s);let o,l=!1;if(n&&(l=t.features.has(xN.TextureFormatsTier1),!1===l&&Ti("WebGPURenderer: Unable to use normalized textures without texture-formats-tier1 feature.")),!0===e.isCompressedTexture||!0===e.isCompressedArrayTexture)switch(i){case ct:case ht:o=a===Kt?TR:SR;break;case dt:o=a===Kt?ER:MR;break;case pt:o=a===Kt?AR:wR;break;case Vt:o=RR;break;case Ht:o=CR;break;case Wt:o=NR;break;case jt:o=PR;break;case kt:o=a===Kt?IR:UR;break;case zt:o=DR;break;case Gt:o=LR;break;case bt:case vt:o=a===Kt?OR:FR;break;case yt:o=a===Kt?GR:zR;break;case xt:o=VR;break;case St:o=HR;break;case Tt:o=WR;break;case Mt:o=jR;break;case Et:o=a===Kt?XR:$R;break;case wt:o=a===Kt?YR:qR;break;case At:o=a===Kt?ZR:KR;break;case Rt:o=a===Kt?JR:QR;break;case Ct:o=a===Kt?tC:eC;break;case Nt:o=a===Kt?rC:iC;break;case Pt:o=a===Kt?sC:nC;break;case Lt:o=a===Kt?oC:aC;break;case Dt:o=a===Kt?uC:lC;break;case Ut:o=a===Kt?hC:cC;break;case It:o=a===Kt?pC:dC;break;case Ft:o=a===Kt?mC:fC;break;case Ot:o=a===Kt?_C:gC;break;case Bt:o=a===Kt?bC:vC;break;case tt:o=r===Xe?hR:a===Kt?YA:qA;break;default:Mi("WebGPURenderer: Unsupported texture format.",i)}else switch(i){case tt:switch(r){case Ge:o=KA;break;case Ve:o=l?pR:cR;break;case He:o=l?dR:uR;break;case je:o=fR;break;case We:o=mR;break;case ze:o=a===Kt?YA:qA;break;case Xe:o=hR;break;case $e:o=gR;break;default:Mi("WebGPURenderer: Unsupported texture type with RGBAFormat.",r)}break;case et:switch(r){case Ze:o=rR;break;case Qe:o=sR;break;default:Mi("WebGPURenderer: Unsupported texture type with RGBFormat.",r)}break;case nt:switch(r){case Ge:o=NA;break;case Ve:o=l?GA:UA;break;case He:o=l?zA:DA;break;case je:o=VA;break;case We:o=HA;break;case ze:o=CA;break;case Xe:o=IA;break;case $e:o=WA;break;default:Mi("WebGPURenderer: Unsupported texture type with RedFormat.",r)}break;case at:switch(r){case Ge:o=OA;break;case Ve:o=l?iR:$A;break;case He:o=l?tR:jA;break;case je:o=aR;break;case We:o=oR;break;case ze:o=FA;break;case Xe:o=XA;break;case $e:o=lR;break;default:Mi("WebGPURenderer: Unsupported texture type with RGFormat.",r)}break;case it:switch(r){case He:o=_R;break;case je:o=vR;break;case $e:o=yR;break;default:Mi("WebGPURenderer: Unsupported texture type with DepthFormat.",r)}break;case rt:switch(r){case Ke:o=bR;break;case $e:t&&!1===t.features.has(xN.Depth32FloatStencil8)&&Mi('WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.'),o=xR;break;default:Mi("WebGPURenderer: Unsupported texture type with DepthStencilFormat.",r)}break;case st:switch(r){case We:o=HA;break;case je:o=VA;break;default:Mi("WebGPURenderer: Unsupported texture type with RedIntegerFormat.",r)}break;case ot:switch(r){case We:o=oR;break;case je:o=aR;break;default:Mi("WebGPURenderer: Unsupported texture type with RGIntegerFormat.",r)}break;case ut:switch(r){case We:o=mR;break;case je:o=fR;break;default:Mi("WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.",r)}break;default:Mi("WebGPURenderer: Unsupported texture format.",i)}return o}const mP=/^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,gP=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,_P={f32:"float",i32:"int",u32:"uint",bool:"bool","vec2<f32>":"vec2","vec2<i32>":"ivec2","vec2<u32>":"uvec2","vec2<bool>":"bvec2",vec2f:"vec2",vec2i:"ivec2",vec2u:"uvec2",vec2b:"bvec2","vec3<f32>":"vec3","vec3<i32>":"ivec3","vec3<u32>":"uvec3","vec3<bool>":"bvec3",vec3f:"vec3",vec3i:"ivec3",vec3u:"uvec3",vec3b:"bvec3","vec4<f32>":"vec4","vec4<i32>":"ivec4","vec4<u32>":"uvec4","vec4<bool>":"bvec4",vec4f:"vec4",vec4i:"ivec4",vec4u:"uvec4",vec4b:"bvec4","mat2x2<f32>":"mat2",mat2x2f:"mat2","mat3x3<f32>":"mat3",mat3x3f:"mat3","mat4x4<f32>":"mat4",mat4x4f:"mat4",sampler:"sampler",sampler_comparison:"samplerComparison",texture_1d:"texture",texture_2d:"texture",texture_2d_array:"texture",texture_multisampled_2d:"cubeTexture",texture_depth_2d:"depthTexture",texture_depth_2d_array:"depthTexture",texture_depth_multisampled_2d:"depthTexture",texture_depth_cube:"depthTexture",texture_depth_cube_array:"depthTexture",texture_3d:"texture3D",texture_cube:"cubeTexture",texture_cube_array:"cubeTexture",texture_storage_1d:"storageTexture",texture_storage_2d:"storageTexture",texture_storage_2d_array:"storageTexture",texture_storage_3d:"storageTexture"};class vP extends RE{constructor(e){const{type:t,inputs:i,name:r,inputsCode:n,blockCode:s,outputType:a}=(e=>{const t=(e=e.replace(/^(?:\s*\/\/[^\r\n]*|\s*\/\*[\s\S]*?\*\/|\s*)+/,"")).match(mP);if(null!==t&&4===t.length){const i=t[2],r=[];let n=null;for(;null!==(n=gP.exec(i));)r.push({name:n[1],type:n[2]});const s=[];for(let e=0;e<r.length;e++){const{name:t,type:i}=r[e];let n=i;n.startsWith("ptr")?n="pointer":(n.startsWith("texture")&&(n=i.split("<")[0]),n=_P[n]),s.push(new mE(n,t))}const a=e.substring(t[0].length),o=t[3]||"void",l=void 0!==t[1]?t[1]:"";return{type:_P[o]||o,inputs:s,name:l,inputsCode:i,blockCode:a,outputType:o}}throw new Error("THREE.WGSLNodeFunction: Function is not a WGSL code.")})(e);super(t,i,r),this.inputsCode=n,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 bP extends AE{parseFunction(e){return new vP(e)}}const yP={[tc]:"read",[ic]:"write",[rc]:"read_write"},xP={[Pe]:"repeat",[Le]:"clamp",[De]:"mirror"},SP={vertex:cA.VERTEX,fragment:cA.FRAGMENT,compute:cA.COMPUTE},TP={instance:!0,swizzleAssign:!1,storageBuffer:!0},MP={"^^":"tsl_xor"},EP={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>"},wP={},AP={tsl_xor:new wy("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new wy("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new wy("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new wy("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new wy("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new wy("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new wy("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new wy("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 wy("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 wy("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new wy("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 wy("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),inverse_mat2:new wy("\nfn tsl_inverse_mat2( m : mat2x2<f32> ) -> mat2x2<f32> {\n\n\tlet det = m[ 0 ][ 0 ] * m[ 1 ][ 1 ] - m[ 0 ][ 1 ] * m[ 1 ][ 0 ];\n\n\treturn mat2x2<f32>(\n\t\tm[ 1 ][ 1 ], - m[ 0 ][ 1 ],\n\t\t- m[ 1 ][ 0 ], m[ 0 ][ 0 ]\n\t) * ( 1.0 / det );\n\n}\n"),inverse_mat3:new wy("\nfn tsl_inverse_mat3( m : mat3x3<f32> ) -> mat3x3<f32> {\n\n\tlet a00 = m[ 0 ][ 0 ]; let a01 = m[ 0 ][ 1 ]; let a02 = m[ 0 ][ 2 ];\n\tlet a10 = m[ 1 ][ 0 ]; let a11 = m[ 1 ][ 1 ]; let a12 = m[ 1 ][ 2 ];\n\tlet a20 = m[ 2 ][ 0 ]; let a21 = m[ 2 ][ 1 ]; let a22 = m[ 2 ][ 2 ];\n\n\tlet b01 = a22 * a11 - a12 * a21;\n\tlet b11 = - a22 * a10 + a12 * a20;\n\tlet b21 = a21 * a10 - a11 * a20;\n\n\tlet det = a00 * b01 + a01 * b11 + a02 * b21;\n\n\treturn mat3x3<f32>(\n\t\tb01, ( - a22 * a01 + a02 * a21 ), ( a12 * a01 - a02 * a11 ),\n\t\tb11, ( a22 * a00 - a02 * a20 ), ( - a12 * a00 + a02 * a10 ),\n\t\tb21, ( - a21 * a00 + a01 * a20 ), ( a11 * a00 - a01 * a10 )\n\t) * ( 1.0 / det );\n\n}\n"),inverse_mat4:new wy("\nfn tsl_inverse_mat4( m : mat4x4<f32> ) -> mat4x4<f32> {\n\n\tlet a00 = m[ 0 ][ 0 ]; let a01 = m[ 0 ][ 1 ]; let a02 = m[ 0 ][ 2 ]; let a03 = m[ 0 ][ 3 ];\n\tlet a10 = m[ 1 ][ 0 ]; let a11 = m[ 1 ][ 1 ]; let a12 = m[ 1 ][ 2 ]; let a13 = m[ 1 ][ 3 ];\n\tlet a20 = m[ 2 ][ 0 ]; let a21 = m[ 2 ][ 1 ]; let a22 = m[ 2 ][ 2 ]; let a23 = m[ 2 ][ 3 ];\n\tlet a30 = m[ 3 ][ 0 ]; let a31 = m[ 3 ][ 1 ]; let a32 = m[ 3 ][ 2 ]; let a33 = m[ 3 ][ 3 ];\n\n\tlet b00 = a00 * a11 - a01 * a10;\n\tlet b01 = a00 * a12 - a02 * a10;\n\tlet b02 = a00 * a13 - a03 * a10;\n\tlet b03 = a01 * a12 - a02 * a11;\n\tlet b04 = a01 * a13 - a03 * a11;\n\tlet b05 = a02 * a13 - a03 * a12;\n\tlet b06 = a20 * a31 - a21 * a30;\n\tlet b07 = a20 * a32 - a22 * a30;\n\tlet b08 = a20 * a33 - a23 * a30;\n\tlet b09 = a21 * a32 - a22 * a31;\n\tlet b10 = a21 * a33 - a23 * a31;\n\tlet b11 = a22 * a33 - a23 * a32;\n\n\tlet det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n\treturn mat4x4<f32>(\n\t\ta11 * b11 - a12 * b10 + a13 * b09,\n\t\ta02 * b10 - a01 * b11 - a03 * b09,\n\t\ta31 * b05 - a32 * b04 + a33 * b03,\n\t\ta22 * b04 - a21 * b05 - a23 * b03,\n\t\ta12 * b08 - a10 * b11 - a13 * b07,\n\t\ta00 * b11 - a02 * b08 + a03 * b07,\n\t\ta32 * b02 - a30 * b05 - a33 * b01,\n\t\ta20 * b05 - a22 * b02 + a23 * b01,\n\t\ta10 * b10 - a11 * b08 + a13 * b06,\n\t\ta01 * b08 - a00 * b10 - a03 * b06,\n\t\ta30 * b04 - a31 * b02 + a33 * b00,\n\t\ta21 * b02 - a20 * b04 - a23 * b00,\n\t\ta11 * b07 - a10 * b09 - a12 * b06,\n\t\ta00 * b09 - a01 * b07 + a02 * b06,\n\t\ta31 * b01 - a30 * b03 - a32 * b00,\n\t\ta20 * b03 - a21 * b01 + a22 * b00\n\t) * ( 1.0 / det );\n\n}\n"),biquadraticTexture:new wy("\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 wy("\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")},RP={dFdx:"dpdx",dFdy:"- dpdy",mod_float:"tsl_mod_float",mod_vec2:"tsl_mod_vec2",mod_vec3:"tsl_mod_vec3",mod_vec4:"tsl_mod_vec4",equals_bool:"tsl_equals_bool",equals_bvec2:"tsl_equals_bvec2",equals_bvec3:"tsl_equals_bvec3",equals_bvec4:"tsl_equals_bvec4",inverse_mat2:"tsl_inverse_mat2",inverse_mat3:"tsl_inverse_mat3",inverse_mat4:"tsl_inverse_mat4",inversesqrt:"inverseSqrt",faceforward:"faceForward",bitcast:"bitcast<f32>",floatpack_snorm_2x16:"pack2x16snorm",floatpack_unorm_2x16:"pack2x16unorm",floatpack_float16_2x16:"pack2x16float",floatpack_snorm_4x8:"pack4x8snorm",floatpack_unorm_4x8:"pack4x8unorm",floatunpack_snorm_2x16:"unpack2x16snorm",floatunpack_unorm_2x16:"unpack2x16unorm",floatunpack_float16_2x16:"unpack2x16float",floatunpack_snorm_4x8:"unpack4x8snorm",floatunpack_unorm_4x8:"unpack4x8unorm"},CP=new Set(["alias","break","case","const","const_assert","continue","continuing","default","diagnostic","discard","else","enable","false","fn","for","if","let","loop","override","requires","return","struct","switch","true","var","while","NULL","Self","abstract","active","alignas","alignof","as","asm","asm_fragment","async","attribute","auto","await","become","binding_array","cast","catch","class","co_await","co_return","co_yield","coherent","column_major","common","compile","compile_fragment","concept","const_cast","consteval","constexpr","constinit","crate","debugger","decltype","delete","demote","demote_to_helper","do","dynamic_cast","enum","explicit","export","extends","extern","external","fallthrough","filter","final","finally","friend","from","fxgroup","get","goto","groupshared","highp","impl","implements","import","inline","instanceof","interface","layout","lowp","macro","macro_rules","match","mediump","meta","mod","module","move","mut","mutable","namespace","new","nil","noexcept","noinline","nointerpolation","non_coherent","noncoherent","noperspective","null","nullptr","of","operator","package","packoffset","partition","pass","patch","pixelfragment","precise","precision","premerge","priv","protected","pub","public","readonly","ref","regardless","register","reinterpret_cast","require","resource","restrict","self","set","shared","sizeof","smooth","snorm","static","static_assert","static_cast","std","subroutine","super","target","template","this","thread_local","throw","trait","try","type","typedef","typeid","typename","typeof","union","unless","unorm","unsafe","unsized","use","using","varying","virtual","volatile","wgsl","where","with","writeonly","yield","main"]);let NP="";!0!==("undefined"!=typeof navigator&&/Firefox|Deno/g.test(navigator.userAgent))&&(NP+="diagnostic( off, derivative_uniformity );\n");class PP extends pE{constructor(e,t){super(e,t,new bP),this.uniformGroups={},this.uniformGroupsBindings={},this.builtins={},this.directives={},this.scopedArrays=new Map,this.allowEarlyReturns=!0,this.allowGlobalVariables=!0}_generateTextureSample(e,t,i,r,n,s=this.shaderStage){return"fragment"===s?r?n?`textureSample( ${t}, ${t}_sampler, ${i}, ${r}, ${n} )`:`textureSample( ${t}, ${t}_sampler, ${i}, ${r} )`:n?`textureSample( ${t}, ${t}_sampler, ${i}, ${n} )`:`textureSample( ${t}, ${t}_sampler, ${i} )`:this.generateTextureSampleLevel(e,t,i,"0",r)}generateTextureSampleLevel(e,t,i,r,n,s){return!1===this.isUnfilterable(e)?n?s?`textureSampleLevel( ${t}, ${t}_sampler, ${i}, ${n}, ${r}, ${s} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${i}, ${n}, ${r} )`:s?`textureSampleLevel( ${t}, ${t}_sampler, ${i}, ${r}, ${s} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${i}, ${r} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,i,s,r,n):this.generateTextureLod(e,t,i,n,s,r)}generateWrapFunction(e){const t=`tsl_coord_${xP[e.wrapS]}S_${xP[e.wrapT]}T_${e.is3DTexture||e.isData3DTexture?"3d":"2d"}`;let i=wP[t];if(void 0===i){const r=[],n=e.is3DTexture||e.isData3DTexture?"vec3f":"vec2f";let s=`fn ${t}( coord : ${n} ) -> ${n} {\n\n\treturn ${n}(\n`;const a=(e,t)=>{e===Pe?(r.push(AP.repeatWrapping_float),s+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===Le?(r.push(AP.clampWrapping_float),s+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===De?(r.push(AP.mirrorWrapping_float),s+=`\t\ttsl_mirrorWrapping_float( coord.${t} )`):(s+=`\t\tcoord.${t}`,Ti(`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",wP[t]=i=new wy(s,r)}return i.build(this),t}generateArrayDeclaration(e,t){return`array< ${this.getType(e)}, ${t} >`}generateTextureDimension(e,t,i){const r=this.getDataFromNode(e,this.shaderStage,this.cache);void 0===r.dimensionsSnippet&&(r.dimensionsSnippet={});let n=r.dimensionsSnippet[i];if(void 0===r.dimensionsSnippet[i]){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}${i?`, u32( ${i} )`:""}`,n=new Ef(new sm(`textureDimensions( ${s} )`,a)),r.dimensionsSnippet[i]=n,(e.isArrayTexture||e.isDataArrayTexture||e.is3DTexture||e.isData3DTexture)&&(r.arrayLayerCount=new Ef(new sm(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(r.cubeFaceCount=new Ef(new sm("6u","u32")))}return n.build(this)}generateTextureSize(e,t,i){const{primarySamples:r}=this.renderer.backend.utils.getTextureSampleData(e);return`textureDimensions( ${r>1||e.isStorageTexture?t:`${t}, ${i}`} )`}generateFilteredTexture(e,t,i,r,n="0u",s){const a=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,n);return r&&(i=`${i} + vec2<f32>(${r}) / ${o}`),s?(this._include("biquadraticTextureArray"),`tsl_biquadraticTexture_array( ${t}, ${a}( ${i} ), ${o}, u32( ${s} ), u32( ${n} ) )`):(this._include("biquadraticTexture"),`tsl_biquadraticTexture( ${t}, ${a}( ${i} ), ${o}, u32( ${n} ) )`)}generateTextureLod(e,t,i,r,n,s="0u"){if(!0===e.isCubeTexture){n&&(i=`${i} + vec3<f32>(${n})`);return`textureSampleLevel( ${t}, ${t}_sampler, ${i}, ${e.isDepthTexture?"u32":"f32"}( ${s} ) )`}const a=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,s),l=e.is3DTexture||e.isData3DTexture?"vec3":"vec2";n&&(i=`${i} + ${l}<f32>(${n}) / ${l}<f32>( ${o} )`);return i=`${l}<u32>( clamp( floor( ${a}( ${i} ) * ${l}<f32>( ${o} ) ), ${`${l}<f32>( 0 )`}, ${`${l}<f32>( ${o} - ${"vec3"===l?"vec3<u32>( 1, 1, 1 )":"vec2<u32>( 1, 1 )"} )`} ) )`,this.generateTextureLoad(e,t,i,s,r,null)}generateStorageTextureLoad(e,t,i,r,n,s){let a;return s&&(i=`${i} + ${s}`),a=n?`textureLoad( ${t}, ${i}, ${n} )`:`textureLoad( ${t}, ${i} )`,a}generateTextureLoad(e,t,i,r,n,s){let a;return null===r&&(r="0u"),s&&(i=`${i} + ${s}`),n?a=`textureLoad( ${t}, ${i}, ${n}, u32( ${r} ) )`:(a=`textureLoad( ${t}, ${i}, u32( ${r} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(a+=".x")),a}generateTextureStore(e,t,i,r,n){let s;return s=r?`textureStore( ${t}, ${i}, ${r}, ${n} )`:`textureStore( ${t}, ${i}, ${n} )`,s}isSampleCompare(e){return!0===e.isDepthTexture&&null!==e.compareFunction&&this.renderer.hasCompatibility(pi)}isUnfilterable(e){return"float"!==this.getComponentTypeFromTexture(e)||!this.isAvailable("float32Filterable")&&e.type===$e||!1===this.isSampleCompare(e)&&e.minFilter===Ue&&e.magFilter===Ue||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1||!0===e.normalized&&(e.type===Ve||e.type===He)}generateTexture(e,t,i,r,n,s=this.shaderStage){let a=null;return a=this.isUnfilterable(e)?this.generateTextureLod(e,t,i,r,n,"0",s):this._generateTextureSample(e,t,i,r,n,s),a}generateTextureGrad(e,t,i,r,n,s,a=this.shaderStage){if("fragment"===a)return this.isUnfilterable(e)?this.generateTexture(e,t,i,n,s,a):n?s?`textureSampleGrad( ${t}, ${t}_sampler, ${i}, ${n}, ${r[0]}, ${r[1]}, ${s} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${i}, ${n}, ${r[0]}, ${r[1]} )`:s?`textureSampleGrad( ${t}, ${t}_sampler, ${i}, ${r[0]}, ${r[1]}, ${s} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${i}, ${r[0]}, ${r[1]} )`;Mi(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${a} shader.`)}generateTextureCompare(e,t,i,r,n,s,a=this.shaderStage){if("fragment"===a)return!0===e.isDepthTexture&&!0===e.isArrayTexture?s?`textureSampleCompare( ${t}, ${t}_sampler, ${i}, ${n}, ${r}, ${s} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${i}, ${n}, ${r} )`:s?`textureSampleCompare( ${t}, ${t}_sampler, ${i}, ${r}, ${s} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${i}, ${r} )`;Mi(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${a} shader.`)}generateTextureGather(e,t,i,r,n,s){const{primarySamples:a}=this.renderer.backend.utils.getTextureSampleData(e);if(a>1){const n=this.generateTextureDimension(e,t,"0u");let a=`vec2<i32>( floor( ${i} * vec2<f32>( ${n} ) - 0.5 ) )`;s&&(a=`${a} + ${s}`);const o=new Ef(new sm(a,"ivec2")).build(this),l=`vec2<i32>( ${n} ) - 1`,u=(i,n)=>{const s=this.generateTextureLoad(e,t,`clamp( ${o} + vec2<i32>( ${i}, ${n} ), vec2<i32>( 0 ), ${l} )`,null,null,null);return!0===e.isDepthTexture?s:`${s}[ ${r} ]`};return`vec4<${this.getComponentTypeFromTexture(e).charAt(0)}32>( ${u(0,1)}, ${u(1,1)}, ${u(1,0)}, ${u(0,0)} )`}const o=!0===e.isDepthTexture?"":`${r}, `;return n?s?`textureGather( ${o}${t}, ${t}_sampler, ${i}, ${n}, ${s} )`:`textureGather( ${o}${t}, ${t}_sampler, ${i}, ${n} )`:s?`textureGather( ${o}${t}, ${t}_sampler, ${i}, ${s} )`:`textureGather( ${o}${t}, ${t}_sampler, ${i})`}generateTextureGatherCompare(e,t,i,r,n,s){return n?s?`textureGatherCompare( ${t}, ${t}_sampler, ${i}, ${n}, ${r}, ${s} )`:`textureGatherCompare( ${t}, ${t}_sampler, ${i}, ${n}, ${r})`:s?`textureGatherCompare( ${t}, ${t}_sampler, ${i}, ${r}, ${s} )`:`textureGatherCompare( ${t}, ${t}_sampler, ${i}, ${r})`}generateTextureLevel(e,t,i,r,n,s){return!1===this.isUnfilterable(e)?n?s?`textureSampleLevel( ${t}, ${t}_sampler, ${i}, ${n}, ${r}, ${s} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${i}, ${n}, ${r} )`:s?`textureSampleLevel( ${t}, ${t}_sampler, ${i}, ${r}, ${s} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${i}, ${r} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,i,s,r,n):this.generateTextureLod(e,t,i,n,s,r)}generateTextureBias(e,t,i,r,n,s,a=this.shaderStage){if("fragment"===a)return n?s?`textureSampleBias( ${t}, ${t}_sampler, ${i}, ${n}, ${r}, ${s} )`:`textureSampleBias( ${t}, ${t}_sampler, ${i}, ${n}, ${r} )`:s?`textureSampleBias( ${t}, ${t}_sampler, ${i}, ${r}, ${s} )`:`textureSampleBias( ${t}, ${t}_sampler, ${i}, ${r} )`;Mi(`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,i=e.type;return"texture"===i||"cubeTexture"===i||"cubeDepthTexture"===i||"storageTexture"===i||"texture3D"===i?t:"buffer"===i||"storageBuffer"===i||"indirectStorageBuffer"===i?t+".value":e.groupNode.name+"."+t}return super.getPropertyName(e)}getDeclarationName(e){if(!0===e.isNodeUniform){const t=e.type;if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t)return e.name}return super.getDeclarationName(e)}isReservedKeyword(e){return CP.has(e)}getOutputStructName(){return"output"}getFunctionOperator(e){const t=MP[e];return void 0!==t?(this._include(t),t):null}getNodeAccess(e,t){return"compute"!==t?!0===e.isAtomic?"vertex"===t?(Ti("WebGPURenderer: Atomic operations are not supported in the vertex stage. They are only available in the fragment and compute stages."),tc):rc:"fragment"===t&&!0===e.isStorageTextureNode&&e.access===rc?rc:tc:e.access}getStorageAccess(e,t){return yP[this.getNodeAccess(e,t)]}getUniformFromNode(e,t,i,r=null){const n=super.getUniformFromNode(e,t,i,r),s=this.getDataFromNode(e,i,this.globalCache);if(void 0===s.uniformGPU){let r;const a=e.groupNode,o=a.name,l=this.getBindGroupArray(o,i);if("texture"===t||"cubeTexture"===t||"cubeDepthTexture"===t||"storageTexture"===t||"texture3D"===t){let s=null;const o=this.getNodeAccess(e,i);"texture"===t||"storageTexture"===t?s=!0===e.value.is3DTexture?new Ew(n.name,n.node,a,o):new Tw(n.name,n.node,a,o):"cubeTexture"===t||"cubeDepthTexture"===t?s=new Mw(n.name,n.node,a,o):"texture3D"===t&&(s=new Ew(n.name,n.node,a,o)),s.store=!0===e.isStorageTextureNode,s.mipLevel=s.store?e.mipLevel:0,s.setVisibility(SP[i]);if(!0===e.value.isCubeTexture||!1===this.isUnfilterable(e.value)&&!1===s.store||null!==e.gatherNode){const e=new TN(`${n.name}_sampler`,n.node,a);e.setVisibility(SP[i]),l.push(e,s),r=[e,s]}else l.push(s),r=[s]}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const n=new("buffer"===t?gw:wN)(e,a);n.setVisibility(SP[i]),l.push(n),r=n}else{let e=this.uniformGroups[o];void 0===e&&(e=new bw(o,a),e.setVisibility(cA.VERTEX|cA.FRAGMENT|cA.COMPUTE),this.uniformGroups[o]=e),-1===l.indexOf(e)&&l.push(e),r=this.getNodeUniform(n,t);const i=r.name,s=e.uniforms.some(e=>e.name===i);s||e.addUniform(r)}s.uniformGPU=r}return n}getBuiltin(e,t,i,r=this.shaderStage){const n=this.builtins[r]||(this.builtins[r]=new Map);return!1===n.has(e)&&n.set(e,{name:e,property:t,type:i}),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,i=this.flowShaderNode(e),r=[];for(const e of t.inputs)r.push(e.name+" : "+this.getType(e.type));let n=`fn ${t.name}( ${r.join(", ")} ) -> ${this.getType(t.type)} {\n${i.vars}\n${i.code}\n`;return i.result&&(n+=`\treturn ${i.result};\n`),n+="\n}\n",n}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=[],i=this.directives[e];if(void 0!==i)for(const e of i)t.push(`enable ${e};`);return t.join("\n")}enableSubGroups(){!1===this.renderer.hasFeature("subgroups")&&Mi("WGSLNodeBuilder: The 'subgroups' feature is not supported by the current device."),this.enableDirective("subgroups")}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=[],i=this.builtins[e];if(void 0!==i)for(const{name:r,property:n,type:s}of i.values()){const i=!0===this.context.invariant&&"vertex"===e&&"position"===r?"@invariant ":"";t.push(`${i}@builtin( ${r} ) ${n} : ${s}`)}return t.join(",\n\t")}getScopedArray(e,t,i,r,n){return!1===this.scopedArrays.has(e)&&this.scopedArrays.set(e,{name:e,scope:t,bufferType:i,bufferCount:r,isAtomic:n}),e}getScopedArrays(e){if("compute"!==e)return;const t=[];for(const{name:e,scope:i,bufferType:r,bufferCount:n,isAtomic:s}of this.scopedArrays.values()){let a=this.getType(r);!0===s&&(a=`atomic<${a}>`),t.push(`var<${i}> ${e}: array< ${a}, ${n} >;`)}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 i=this.getAttributesArray();for(let e=0,r=i.length;e<r;e++){const r=i[e],n=r.name,s=this.getType(r.type);t.push(`@location( ${e} ) ${n} : ${s}`)}}return t.join(",\n\t")}getStructMembers(e){const t=[];for(const i of e.members){const r=e.output?"@location( "+i.index+" ) ":"";let n=this.getType(i.type);i.atomic&&(n="atomic< "+n+" >"),t.push(`\t${r+i.name} : ${n}`)}return e.output&&t.push(`\t${this.getBuiltins("output")}`),t.join(",\n")}getStructs(e){let t="";const i=this.structs[e];if(i.length>0){const e=[];for(const t of i){let i=`struct ${t.name} {\n`;i+=this.getStructMembers(t),i+="\n};",e.push(i)}t="\n"+e.join("\n\n")+"\n"}return t}getVar(e,t,i=null,r=""){let n=`var${r} ${t} : `;return n+=null!==i?this.generateArrayDeclaration(e,i):this.getType(e),n}generateConstStatement(e,t){return`const ${t}`}generateVarStatement(e,t,i=null){return this.getVar(e,t,i)}generateLetStatement(e,t){return`let ${t}`}getVars(e,t=!1){let i="";t&&(i="<private>");const r=[],n=this.vars[e];if(void 0!==n)for(const e of n)r.push(`${this.getVar(e.type,e.name,e.count,i)};`);return t?r.join("\n"):`\n\t${r.join("\n\t")}\n`}getVaryings(e){const t=[];if("vertex"===e&&this.getBuiltin("position","builtinClipSpace","vec4<f32>","vertex"),"vertex"===e||"fragment"===e){const i=this.varyings,r=this.vars[e];let n=0;for(let s=0;s<i.length;s++){const a=i[s];if(a.needsInterpolation){let e=`@location( ${n++} )`;if(a.interpolationType){const t=null!==a.interpolationSampling?`, ${a.interpolationSampling} )`:" )";e+=` @interpolate( ${a.interpolationType}${t}`}else/^(int|uint|ivec|uvec)/.test(a.type)&&(e+=" @interpolate(flat, either)");t.push(`${e} ${a.name} : ${this.getType(a.type)}`)}else"vertex"===e&&!1===r.includes(a)&&r.push(a)}}const i=this.getBuiltins(e);i&&t.push(i);const r=t.join(",\n\t");return"vertex"===e?this._getWGSLStruct("VaryingsStruct","\t"+r):r}getUniforms(e){const t=this.renderer.backend,i=this.uniforms[e],r=[],n=[],s=[],a={};for(const s of i){const i=s.groupNode.name,o=this.bindingsIndexes[i];if("texture"===s.type||"cubeTexture"===s.type||"cubeDepthTexture"===s.type||"storageTexture"===s.type||"texture3D"===s.type){const i=s.node,n=i.value;let a;(!0===n.isCubeTexture||!1===this.isUnfilterable(n)&&!0!==i.isStorageTextureNode||null!==i.gatherNode)&&(this.isSampleCompare(n)&&i.isSampleCompare()?r.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${s.name}_sampler : sampler_comparison;`):r.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${s.name}_sampler : sampler;`));let l="";const{primarySamples:u}=t.utils.getTextureSampleData(n);if(u>1&&(l="_multisampled"),!0===n.isCubeTexture&&!0===n.isDepthTexture)a="texture_depth_cube";else if(!0===n.isCubeTexture)a="texture_cube<f32>";else if(!0===n.isDepthTexture)a=t.compatibilityMode&&null===n.compareFunction?`texture${l}_2d<f32>`:`texture_depth${l}_2d${!0===n.isArrayTexture?"_array":""}`;else if(!0===s.node.isStorageTextureNode){const i=fP(n,t.device),r=this.getStorageAccess(s.node,e),o=s.node.value.is3DTexture,l=s.node.value.isArrayTexture;a=`texture_storage_${o?"3d":"2d"+(l?"_array":"")}<${i}, ${r}>`}else if(!0===n.isArrayTexture||!0===n.isDataArrayTexture||!0===n.isCompressedArrayTexture){a=`texture_2d_array<${this.getComponentTypeFromTexture(n).charAt(0)}32>`}else if(!0===n.is3DTexture||!0===n.isData3DTexture){a=`texture_3d<${this.getComponentTypeFromTexture(n).charAt(0)}32>`}else{a=`texture${l}_2d<${this.getComponentTypeFromTexture(n).charAt(0)}32>`}r.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${s.name} : ${a};`)}else if("buffer"===s.type||"storageBuffer"===s.type||"indirectStorageBuffer"===s.type){const t=s.node,i=this.getType(t.getNodeType(this)),r=t.bufferCount,a=r>0&&"buffer"===s.type?", "+r:"",l=t.isStorageBufferNode?`storage, ${this.getStorageAccess(t,e)}`:"uniform",u=`\tvalue : array< ${t.isAtomic?`atomic<${i}>`:`${i}`}${a} >`;n.push(this._getWGSLStructBinding(s.name,u,l,o.binding++,o.group))}else{const e=s.groupNode.name;if(void 0===a[e]){const t=this.uniformGroups[e];if(void 0!==t){const i=[];for(const e of t.uniforms){const t=e.getType(),r=this.getType(this.getVectorType(t));i.push(`\t${e.name} : ${r}`)}let r=this.uniformGroupsBindings[e];void 0===r&&(r={index:o.binding++,id:o.group},this.uniformGroupsBindings[e]=r),a[e]={index:r.index,id:r.id,snippets:i}}}}}for(const e in a){const t=a[e];s.push(this._getWGSLStructBinding(e,t.snippets.join(",\n"),"uniform",t.index,t.id))}return[...r,...n,...s].join("\n")}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){this.shaderStage=t;const i=this.allowGlobalVariables,r=e[t];r.uniforms=this.getUniforms(t),r.attributes=this.getAttributes(t),r.varyings=this.getVaryings(t),r.structs=this.getStructs(t),r.vars=this.getVars(t,i),r.codes=this.getCodes(t),r.directives=this.getDirectives(t),r.scopedArrays=this.getScopedArrays(t);let n="// code\n\n";n+=this.flowCode[t];const s=this.flowNodes[t],a=s[s.length-1],o=a.outputNode,l=void 0!==o&&!0===o.isOutputStructNode;for(const e of s){const i=this.getFlowData(e),s=e.name;if(s&&(n.length>0&&(n+="\n"),n+=`\t// flow -> ${s}\n`),n+=`${i.code}\n\t`,e===a&&"compute"!==t)if(n+="// result\n\n\t","vertex"===t)n+=`varyings.builtinClipSpace = ${i.result};`;else if("fragment"===t)if(l)r.returnType=o.getNodeType(this),r.structs+="var<private> output : "+r.returnType+";",n+=`return ${i.result};`;else{let e=`\t@location( 0 ) color: ${this.getType(this.getOutputType())}`;const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),r.returnType="OutputStruct",r.structs+=this._getWGSLStruct("OutputStruct",e),r.structs+="\nvar<private> output : OutputStruct;",n+=`output.color = ${this.format(i.result,a.getNodeType(this),this.getOutputType())};\n\n\treturn output;`}}r.flow=n}if(this.shaderStage=null,null!==this.material)this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment);else{const t=this.compute.workgroupSize;this.computeShader=this._getWGSLComputeCode(e.compute,t)}}getMethod(e,t=null){let i;return null!==t&&(i=this._getWGSLMethod(e+"_"+t)),void 0===i&&(i=this._getWGSLMethod(e)),i||e}getBitcastMethod(e){return`bitcast<${this.getType(e)}>`}getFloatPackingMethod(e,t="2x16"){return this.getMethod(`floatpack_${e}_${t}`)}getFloatUnpackingMethod(e,t="2x16"){return this.getMethod(`floatunpack_${e}_${t}`)}getTernary(e,t,i){return`select( ${i}, ${t}, ${e} )`}getType(e){return EP[e]||e}isAvailable(e){let t=TP[e];return void 0===t&&("float32Filterable"===e?t=this.renderer.hasFeature("float32-filterable"):"clipDistance"===e&&(t=this.renderer.hasFeature("clip-distances")),TP[e]=t),t}_getWGSLMethod(e){return void 0!==AP[e]&&this._include(e),RP[e]}_include(e){const t=AP[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// vars\n${e.vars}\n\n// codes\n${e.codes}\n\n@vertex\nfn main( ${e.attributes} ) -> VaryingsStruct {\n\n\t// flow\n\t${e.flow}\n\n\treturn varyings;\n\n}\n`}_getWGSLFragmentCode(e){return`${this.getSignature()}\n// global\n${NP}\n\n// directives\n${e.directives}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// vars\n${e.vars}\n\n// codes\n${e.codes}\n\n@fragment\nfn main( ${e.varyings} ) -> ${e.returnType} {\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLComputeCode(e,t){const[i,r,n]=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// vars\n${this.allowGlobalVariables?e.vars:""}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${i}, ${r}, ${n} )\nfn main( ${e.attributes} ) {\n\n\t// local vars\n\t${this.allowGlobalVariables?"":e.vars}\n\n\t// system\n\tinstanceIndex = globalId.x\n\t\t+ globalId.y * ( ${i} * numWorkgroups.x )\n\t\t+ globalId.z * ( ${i} * numWorkgroups.x ) * ( ${r} * numWorkgroups.y );\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLStruct(e,t){return`\nstruct ${e} {\n${t}\n};`}_getWGSLStructBinding(e,t,i,r=0,n=0){const s=e+"Struct";return`${this._getWGSLStruct(s,t)}\n@binding( ${r} ) @group( ${n} )\nvar<${i}> ${e} : ${s};`}}const LP=new PN,DP=new LN,UP=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32"]],[Uint32Array,["uint32"]],[Float32Array,["float32"]]]);"undefined"!=typeof Float16Array&&UP.set(Float16Array,["float16"]);const IP=new Map([[Bn,["float16"]]]),FP=new Map([[Int32Array,"sint32"],[Uint32Array,"uint32"],[Float32Array,"float32"]]),OP=new Uint8Array(4);function BP(e,t,i,r,n){const s=new Uint8Array(i.buffer,i.byteOffset,i.byteLength),a=4*Math.floor(r*i.BYTES_PER_ELEMENT/4),o=(r+n)*i.BYTES_PER_ELEMENT,l=4*Math.floor(o/4);l>a&&e.queue.writeBuffer(t,a,s,a,l-a),o>l&&(OP.fill(0),OP.set(s.subarray(l,l+4)),e.queue.writeBuffer(t,l,OP))}class kP{constructor(e){this.backend=e}createAttribute(e,t){const i=this.backend,r=i.getBufferAttribute(e),n=i.get(r);let s=n.buffer;if(void 0===s){const a=i.device;let o,l=r.array;if(!1===e.normalized&&!0!==e.isInterleavedBufferAttribute)if(l.constructor===Int16Array||l.constructor===Int8Array)l=new Int32Array(l);else if(l.constructor===Uint16Array||l.constructor===Uint8Array){const e=t&GPUBufferUsage.INDEX,i=t&GPUBufferUsage.STORAGE,r=e&&!i?Uint16Array:Uint32Array;if(l.constructor!==r&&(l=new r(l)),e&&i)for(let e=0;e<l.length;e++)65535===l[e]&&(l[e]=4294967295)}if(r.array=l,(r.isStorageBufferAttribute||r.isStorageInstancedBufferAttribute)&&3===r.itemSize)o=4;else if(r.itemSize>1&&r.itemSize*l.BYTES_PER_ELEMENT%4!=0){const e=r.itemSize*l.BYTES_PER_ELEMENT;o=4*Math.floor((e+3)/4)/l.BYTES_PER_ELEMENT}if(void 0!==o){const e=r.itemSize,t=new l.constructor(r.count*o);for(let i=0;i<r.count;i++)t.set(l.subarray(i*e,i*e+e),i*o);(r.isStorageBufferAttribute||r.isStorageInstancedBufferAttribute)&&(r.itemSize=o,r.array=t),l=t,n._itemSize=e,n._paddedItemSize=o}const u=l.byteLength,c=u+(4-u%4)%4;LP.label=r.name,LP.size=c,LP.usage=t,LP.mappedAtCreation=!0,s=a.createBuffer(LP),LP.reset(),new l.constructor(s.getMappedRange()).set(l),s.unmap(),n.buffer=s}}updateAttribute(e){const t=this.backend,i=t.device,r=t.getBufferAttribute(e),n=t.get(r),s=t.get(r).buffer;let a=r.array;const o=n._itemSize,l=n._paddedItemSize;if(void 0!==l){a=new a.constructor(r.count*l);for(let e=0;e<r.count;e++)a.set(r.array.subarray(e*o,e*o+o),e*l);(r.isStorageBufferAttribute||r.isStorageInstancedBufferAttribute)&&(r.array=a)}const u=r.updateRanges,c=_i(a)&&a.BYTES_PER_ELEMENT<4;if(0===u.length)c?BP(i,s,a,0,a.length):i.queue.writeBuffer(s,0,a,0);else{const e=_i(a),t=e?1:a.BYTES_PER_ELEMENT;for(let r=0,n=u.length;r<n;r++){const n=u[r];let h,d;if(void 0!==l){const e=Math.floor(n.start/o);h=e*l*t,d=(Math.ceil((n.start+n.count)/o)-e)*l*t}else h=n.start*t,d=n.count*t;if(c)BP(i,s,a,h,d);else{const t=h*(e?a.BYTES_PER_ELEMENT:1);i.queue.writeBuffer(s,t,a,h,d)}}r.clearUpdateRanges()}}getVertexBufferLayout(e){const t=e.getAttributes(),i=new Map;for(let e=0;e<t.length;e++){const r=t[e],n=r.array.BYTES_PER_ELEMENT,s=this.backend.getBufferAttribute(r);let a=i.get(s);if(void 0===a){let e,t;!0===s.isInterleavedBuffer?(e=s.stride*n,t=s.isInstancedInterleavedBuffer?yN:bN):(e=s.itemSize*n,t=s.isInstancedBufferAttribute?yN:bN,s.itemSize>1&&e%4!=0&&(e=4*Math.floor((e+3)/4))),a={arrayStride:e,attributes:[],stepMode:t},i.set(s,a)}const o=this._getVertexFormat(r),l=!0===r.isInterleavedBufferAttribute?r.offset*n:0;a.attributes.push({shaderLocation:e,offset:l,format:o})}return Array.from(i.values())}getVertexBufferLayoutCacheKey(e){const t=this.getVertexBufferLayout(e);let i="";for(const e of t){i+=e.arrayStride+","+e.stepMode+",";for(const t of e.attributes)i+=t.shaderLocation+","+t.offset+","+t.format+","}return i}destroyAttribute(e){const t=this.backend,i=t.getBufferAttribute(e);t.get(i).buffer.destroy(),t.delete(i)}async getArrayBufferAsync(e,t=null,i=0,r=-1){const n=this.backend,s=n.device,a=n.get(n.getBufferAttribute(e)).buffer,o=-1===r?a.size-i:r;let l;if(null!==t&&t.isReadbackBuffer){const e=n.get(t);if(!0===t._mapped)throw new Error("THREE.WebGPUAttributeUtils: ReadbackBuffer must be released before being used again.");if(t._mapped=!0,void 0===e.readBufferGPU){LP.label=`${t.name}_readback`,LP.size=t.maxByteLength,LP.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,l=s.createBuffer(LP),LP.reset();const i=()=>{t.buffer=null,t._mapped=!1,l.unmap()},r=()=>{t.buffer=null,t._mapped=!1,l.destroy(),n.delete(t),t.removeEventListener("release",i),t.removeEventListener("dispose",r)};t.addEventListener("release",i),t.addEventListener("dispose",r),e.readBufferGPU=l}else l=e.readBufferGPU}else LP.label=`${e.name}_readback`,LP.size=o,LP.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,l=s.createBuffer(LP),LP.reset();DP.label=`readback_encoder_${e.name}`;const u=s.createCommandEncoder(DP);DP.reset(),u.copyBufferToBuffer(a,i,l,0,o);if(CN(s,u.finish()),await l.mapAsync(GPUMapMode.READ,0,o),null===t){const e=l.getMappedRange(0,o).slice();return l.destroy(),e}if(t.isReadbackBuffer)return t.buffer=l.getMappedRange(0,o),t;{const e=l.getMappedRange(0,o);return new Uint8Array(t).set(new Uint8Array(e)),l.destroy(),t}}_getVertexFormat(e){const{itemSize:t,normalized:i}=e,r=e.array.constructor,n=e.constructor;let s;if(1===t)s=FP.get(r);else{const e=(IP.get(n)||UP.get(r))[i?1:0];if(e){const i=r.BYTES_PER_ELEMENT*t,n=4*Math.floor((i+3)/4)/r.BYTES_PER_ELEMENT;if(n%1)throw new Error("THREE.WebGPUAttributeUtils: Bad vertex format item size.");s=`${e}x${n}`}}return s||Mi("WebGPUAttributeUtils: Vertex format not supported yet."),s}}const zP=new NN,GP=new PN,VP=new zN;class HP{constructor(e){this.layoutGPU=e,this.usedTimes=0}}class WP{constructor(e){this.backend=e,this._bindGroupLayoutCache=new Map}createBindingsLayout(e){const t=this.backend,i=t.device,r=t.get(e);if(r.layout)return r.layout.layoutGPU;const n=this._createLayoutEntries(e),s=cc(JSON.stringify(n));let a=this._bindGroupLayoutCache.get(s);return void 0===a&&(a=new HP(i.createBindGroupLayout({entries:n})),this._bindGroupLayoutCache.set(s,a)),a.usedTimes++,r.layout=a,r.layoutKey=s,a.layoutGPU}createBindings(e,t,i,r=0){const{backend:n}=this,s=n.get(e),a=this.createBindingsLayout(e);let o;""!==i&&(void 0===s.groups&&(s.groups={},s.versions={}),s.versions[i]===r&&(o=s.groups[i])),void 0===o&&(o=this.createBindGroup(e,a),""!==i&&(s.groups[i]=o,s.versions[i]=r)),s.group=o}updateBinding(e){const t=this.backend,i=t.device,r=e.buffer,n=t.get(e).buffer,s=e.updateRanges;if(0===s.length)i.queue.writeBuffer(n,0,r,0);else{const e=_i(r),t=e?1:r.BYTES_PER_ELEMENT;let a=s[0].start;for(let o=0,l=s.length;o<l;o++){const l=s[o],u=s[o+1],c=l.start+l.count;if(void 0!==u&&u.start===c)continue;const h=a*t,d=(c-a)*t,p=h*(e?r.BYTES_PER_ELEMENT:1);i.queue.writeBuffer(n,p,r,h,d),void 0!==u&&(a=u.start)}}}createBindGroupIndex(e,t){const i=this.backend.device,r=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,n=e[0];GP.label="bindingCameraIndex_"+n,GP.size=16,GP.usage=r;const s=i.createBuffer(GP);GP.reset(),i.queue.writeBuffer(s,0,e,0),zP.label="bindGroupCameraIndex_"+n,zP.layout=t,zP.entries.push({binding:0,resource:{buffer:s}});const a=i.createBindGroup(zP);return zP.reset(),a}createBindGroup(e,t){const i=this.backend,r=i.device;let n=0;zP.label="bindGroup_"+e.name,zP.layout=t;for(const t of e.bindings){if(t.isUniformBuffer){const e=i.get(t);zP.entries.push({binding:n,resource:{buffer:e.buffer}})}else if(t.isStorageBuffer){const e=i.get(t.attribute).buffer;zP.entries.push({binding:n,resource:{buffer:e}})}else if(t.isSampledTexture){const e=i.get(t.texture);let s;if(void 0!==e.externalTexture)s=r.importExternalTexture({source:e.externalTexture});else{const i=t.store?1:e.texture.mipLevelCount,r=t.store?t.mipLevel:0;let n=`view-${e.texture.width}-${e.texture.height}`;if(e.texture.depthOrArrayLayers>1&&(n+=`-${e.texture.depthOrArrayLayers}`),n+=`-${i}-${r}`,s=e[n],void 0===s){const a=t.texture.isDepthTexture?vN:_N;let o;o=t.isSampledCubeTexture?mN:t.texture.isArrayTexture||t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?fN:t.isSampledTexture3D?gN:pN,VP.aspect=a,VP.dimension=o,VP.mipLevelCount=i,VP.baseMipLevel=r,s=e[n]=e.texture.createView(VP),VP.reset()}}zP.entries.push({binding:n,resource:s})}else if(t.isSampler){const e=i.get(t);zP.entries.push({binding:n,resource:e.sampler})}n++}const s=r.createBindGroup(zP);return zP.reset(),s}_createLayoutEntries(e){const t=[];let i=0;for(const r of e.bindings){const e=this.backend,n={binding:i,visibility:r.visibility};if(r.isUniformBuffer||r.isStorageBuffer){const e={};r.isStorageBuffer&&(r.visibility&cA.COMPUTE?r.access===rc||r.access===ic?e.type=JC:e.type=eN:r.nodeUniform&&r.nodeUniform.isAtomic&&r.visibility&cA.FRAGMENT?e.type=JC:e.type=eN),n.buffer=e}else if(r.isSampledTexture&&r.store){const e={};e.format=this.backend.get(r.texture).texture.format;const t=r.access;e.access=t===rc?rN:t===ic?tN:iN,r.texture.isArrayTexture?e.viewDimension=fN:r.texture.is3DTexture&&(e.viewDimension=gN),n.storageTexture=e}else if(r.isSampledTexture){const t={},{primarySamples:i}=e.utils.getTextureSampleData(r.texture);if(i>1&&(t.multisampled=!0,r.texture.isDepthTexture||(t.sampleType=oN)),r.texture.isDepthTexture)e.compatibilityMode&&null===r.texture.compareFunction?t.sampleType=oN:t.sampleType=lN;else{const e=r.texture.type;e===We?t.sampleType=uN:e===je?t.sampleType=cN:!0!==r.texture.normalized||e!==Ve&&e!==He?e===$e&&(this.backend.hasFeature("float32-filterable")?t.sampleType=aN:t.sampleType=oN):t.sampleType=oN}r.isSampledCubeTexture?t.viewDimension=mN:r.texture.isArrayTexture||r.texture.isDataArrayTexture||r.texture.isCompressedArrayTexture?t.viewDimension=fN:r.isSampledTexture3D&&(t.viewDimension=gN),n.texture=t}else if(r.isSampler){const t={};r.texture.isDepthTexture&&(null!==r.texture.compareFunction&&r.textureNode.isSampleCompare()&&e.hasCompatibility(pi)?t.type=sN:t.type=nN),n.sampler=t}else Mi(`WebGPUBindingUtils: Unsupported binding "${r}".`);t.push(n),i++}return t}deleteBindGroupData(e){const{backend:t}=this,i=t.get(e);i.layout&&(i.layout.usedTimes--,0===i.layout.usedTimes&&this._bindGroupLayoutCache.delete(i.layoutKey),i.layout=void 0,i.layoutKey=void 0)}dispose(){this._bindGroupLayoutCache.clear()}}class jP{constructor(e){this.backend=e}getMaxAnisotropy(){return 16}getUniformBufferLimit(){return this.backend.device.limits.maxUniformBufferBindingSize}}const $P=new class{constructor(){this.label="",this.layout=null,this.compute=null}reset(){this.label="",this.layout=null,this.compute=null}},XP=new class{constructor(){this.label="",this.bindGroupLayouts=null}reset(){this.label="",this.bindGroupLayouts=null}},qP=new DN,YP=new FN;class KP{constructor(e){this.backend=e}_getSampleCount(e){return this.backend.utils.getSampleCountRenderContext(e)}createRenderPipeline(e,t){const{object:i,material:r,geometry:n,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:i}=e.layout;d.push(i)}const p=l.attributeUtils.getVertexBufferLayout(e);let f;0===r.blending||1===r.blending&&!1===r.transparent||(f=this._getBlending(r));let m={};!0===r.stencilWrite&&(m={compare:this._getStencilCompare(r),failOp:this._getStencilOperation(r.stencilFail),depthFailOp:this._getStencilOperation(r.stencilZFail),passOp:this._getStencilOperation(r.stencilZPass)});const g=this._getColorWriteMask(r),_=[];if(null!==e.context.textures){const t=e.context.textures,i=e.context.mrt;for(let e=0;e<t.length;e++){const r=t[e],n=c.getTextureFormatGPU(r);let s;if(null!==i)if(!0!==this.backend.compatibilityMode){const e=i.getBlendMode(r.name);6===e.blending?s=f:0!==e.blending&&(s=this._getBlending(e))}else Ei("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:n,blend:s,writeMask:g})}}else{const t=c.getCurrentColorFormat(e.context);_.push({format:t,blend:f,writeMask:g})}const v=l.get(a).module,b=l.get(o).module,y=this._getPrimitiveState(i,n,r),x=this._getDepthCompare(r),S=c.getCurrentDepthStencilFormat(e.context),T=this._getSampleCount(e.context);XP.bindGroupLayouts=d;const M=u.createPipelineLayout(XP);XP.reset(),YP.label=`renderPipeline_${r.name||r.type}_${r.id}`,YP.vertex=Object.assign({},v,{buffers:p}),YP.fragment=Object.assign({},b,{targets:_}),YP.primitive=y,YP.multisample.count=T,YP.multisample.alphaToCoverageEnabled=r.alphaToCoverage&&T>1,YP.layout=M;const E={},w=e.context.depth,A=e.context.stencil;!0!==w&&!0!==A||(!0===w&&(E.format=S,E.depthWriteEnabled=r.depthWrite,E.depthCompare=x),!0===A&&(E.stencilFront=m,E.stencilBack=m,E.stencilReadMask=r.stencilFuncMask,E.stencilWriteMask=r.stencilWriteMask),!0===r.polygonOffset&&y.topology===uA&&(E.depthBias=this.backend.parameters.reversedDepthBuffer?-r.polygonOffsetUnits:r.polygonOffsetUnits,E.depthBiasSlopeScale=this.backend.parameters.reversedDepthBuffer?-r.polygonOffsetFactor:r.polygonOffsetFactor,E.depthBiasClamp=0),YP.depthStencil=E),u.pushErrorScope("validation");const R=[{program:a,module:v.module},{program:o,module:b.module}],C=YP.label;if(null===t)h.pipeline=u.createRenderPipeline(YP),YP.reset(),u.popErrorScope().then(e=>{null!==e&&(h.error=!0,Mi(`WebGPURenderer: Render pipeline creation failed (${C}): ${e.message}`),this._reportShaderDiagnostics(R,C))});else{const e=new Promise(async e=>{try{let e=null,t=null;try{t=u.createRenderPipelineAsync(YP)}catch(t){e=t}YP.reset();const i=u.popErrorScope();if(null!==t)try{h.pipeline=await t}catch(t){e=t}const r=await i;if(null!==r||null!==e){h.error=!0;const t=r&&r.message||e&&e.message||"unknown";Mi(`WebGPURenderer: Async render pipeline creation failed (${C}): ${t}`),await this._reportShaderDiagnostics(R,C)}}finally{e()}});t.push(e)}}createBundleEncoder(e,t="renderBundleEncoder"){const i=this.backend,{utils:r,device:n}=i,s=r.getCurrentDepthStencilFormat(e),a=r.getCurrentColorFormats(e),o=this._getSampleCount(e);qP.label=t,qP.colorFormats=a,qP.depthStencilFormat=s,qP.sampleCount=o;const l=n.createRenderBundleEncoder(qP);return qP.reset(),l}createComputePipeline(e,t,i=null){const r=this.backend,n=r.device,s=r.get(e.computeProgram).module,a=r.get(e),o=[];for(const e of t){const t=r.get(e),{layoutGPU:i}=t.layout;o.push(i)}const l=e.computeProgram,u=`computePipeline_${l.stage}${l.name?`_${l.name}`:""}`;n.pushErrorScope("validation"),XP.bindGroupLayouts=o;const c=n.createPipelineLayout(XP);if(XP.reset(),$P.label=u,$P.compute=s,$P.layout=c,null===i)a.pipeline=n.createComputePipeline($P),$P.reset(),n.popErrorScope().then(e=>{null!==e&&(a.error=!0,Mi(`WebGPURenderer: Compute pipeline creation failed (${u}): ${e.message}`),this._reportShaderDiagnostics([{program:l,module:s.module}],u))});else{const e=new Promise(async e=>{try{let e=null,t=null;try{t=n.createComputePipelineAsync($P)}catch(t){e=t}$P.reset();const i=n.popErrorScope();if(null!==t)try{a.pipeline=await t}catch(t){e=t}const r=await i;if(null!==r||null!==e){a.error=!0;const t=r&&r.message||e&&e.message||"unknown";Mi(`WebGPURenderer: Async compute pipeline creation failed (${u}): ${t}`),await this._reportShaderDiagnostics([{program:l,module:s.module}],u)}}finally{e()}});i.push(e)}}async _reportShaderDiagnostics(e,t){for(const{program:i,module:r}of e){const e=await r.getCompilationInfo();if(0===e.messages.length)continue;const n=i.code.split("\n");for(const r of e.messages){const e=r.lineNum>0?` at line ${r.lineNum}${r.linePos>0?`:${r.linePos}`:""}`:"",s=`WebGPURenderer [${t} / ${i.stage} ${r.type}]${e}: ${r.message}`;let a="";r.lineNum>0&&r.lineNum<=n.length&&(a=`\n ${n[r.lineNum-1]}`,r.linePos>0&&(a+=`\n ${" ".repeat(r.linePos-1)}^`)),("error"===r.type?Mi:Ti)(s+a)}}}_getBlending(e){let t,i;const r=e.blending,n=e.blendSrc,s=e.blendDst,a=e.blendEquation;if(5===r){const r=null!==e.blendSrcAlpha?e.blendSrcAlpha:n,o=null!==e.blendDstAlpha?e.blendDstAlpha:s,l=null!==e.blendEquationAlpha?e.blendEquationAlpha:a;t={srcFactor:this._getBlendFactor(n),dstFactor:this._getBlendFactor(s),operation:this._getBlendOperation(a)},i={srcFactor:this._getBlendFactor(r),dstFactor:this._getBlendFactor(o),operation:this._getBlendOperation(l)}}else{const n=(e,r,n,s)=>{t={srcFactor:e,dstFactor:r,operation:BC},i={srcFactor:n,dstFactor:s,operation:BC}};if(e.premultipliedAlpha)switch(r){case 1:n(wC,NC,wC,NC);break;case 2:n(wC,wC,wC,wC);break;case 3:n(EC,RC,EC,wC);break;case 4:n(PC,NC,EC,wC)}else switch(r){case 1:n(CC,NC,wC,NC);break;case 2:n(CC,wC,wC,wC);break;case 3:Mi(`WebGPURenderer: "SubtractiveBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`);break;case 4:Mi(`WebGPURenderer: "MultiplyBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`)}}if(void 0!==t&&void 0!==i)return{color:t,alpha:i};Mi("WebGPURenderer: Invalid blending: ",r)}_getBlendFactor(e){let t;switch(e){case q:t=EC;break;case 201:t=wC;break;case 202:t=AC;break;case 203:t=RC;break;case Q:t=CC;break;case J:t=NC;break;case 208:t=PC;break;case 209:t=LC;break;case 206:t=DC;break;case 207:t=UC;break;case 210:t=IC;break;case 211:case 213:t=FC;break;case 212:case 214:t=OC;break;default:Mi("WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const i=e.stencilFunc;switch(i){case 512:t=hA;break;case 519:t=vA;break;case 513:t=dA;break;case 515:t=fA;break;case 514:t=pA;break;case 518:t=_A;break;case 516:t=mA;break;case 517:t=gA;break;default:Mi("WebGPURenderer: Invalid stencil function.",i)}return t}_getStencilOperation(e){let t;switch(e){case Zt:t=jC;break;case 0:t=$C;break;case 7681:t=XC;break;case 5386:t=qC;break;case 7682:t=YC;break;case 7683:t=KC;break;case 34055:t=ZC;break;case 34056:t=QC;break;default:Mi("WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case H:t=BC;break;case 101:t=kC;break;case 102:t=zC;break;case 103:t=GC;break;case 104:t=VC;break;default:Mi("WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,i){const r={},n=this.backend.utils;r.topology=n.getPrimitiveTopology(e,i),r.stripIndexFormat=n.getStripIndexFormat(e,t);let s=1===i.side;return e.isMesh&&e.matrixWorld.determinantAffine()<0&&(s=!s),r.frontFace=!0===s?MA:TA,r.cullMode=2===i.side?EA:wA,r}_getColorWriteMask(e){return!0===e.colorWrite?WC:HC}_getDepthCompare(e){let t;if(!1===e.depthTest)t=vA;else{const i=this.backend.parameters.reversedDepthBuffer?Ai[e.depthFunc]:e.depthFunc;switch(i){case 0:t=hA;break;case 1:t=vA;break;case 2:t=dA;break;case 3:t=fA;break;case 4:t=pA;break;case 5:t=_A;break;case 6:t=mA;break;case 7:t=gA;break;default:Mi("WebGPUPipelineUtils: Invalid depth function.",i)}}return t}}class ZP{constructor(){this.label="",this.type=void 0,this.count=0}reset(){this.label="",this.type=void 0,this.count=0}}const QP=new PN,JP=new LN,eL=new ZP;class tL extends iA{constructor(e,t,i=2048){super(i),this.device=e,this.type=t,eL.label=`queryset_global_timestamp_${t}`,eL.type="timestamp",eL.count=this.maxQueries,this.querySet=this.device.createQuerySet(eL),eL.reset();const r=8*this.maxQueries;QP.label=`buffer_timestamp_resolve_${t}`,QP.size=r,QP.usage=GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC,this.resolveBuffer=this.device.createBuffer(QP),QP.reset(),QP.label=`buffer_timestamp_result_${t}`,QP.size=r,QP.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,this.resultBuffer=this.device.createBuffer(QP),QP.reset()}allocateQueriesForContext(e){if(!this.trackTimestamp||this.isDisposed)return null;this.currentQueryIndex+2>this.maxQueries&&(this.resolveQueriesAsync(),this.currentQueryIndex=0,this.queryOffsets.clear());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,i=8*t;this.currentQueryIndex=0,this.queryOffsets.clear();const r=this.device.createCommandEncoder(JP);r.resolveQuerySet(this.querySet,0,t,this.resolveBuffer,0),r.copyBufferToBuffer(this.resolveBuffer,0,this.resultBuffer,0,i);const n=r.finish();if(CN(this.device,n),"unmapped"!==this.resultBuffer.mapState)return this.lastValue;if(await this.resultBuffer.mapAsync(GPUMapMode.READ,0,i),this.isDisposed)return"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue;const s=new BigUint64Array(this.resultBuffer.getMappedRange(0,i)),a={},o=[];this.timestamps.clear();for(const[t,i]of e){const e=t.match(/^(.*):f(\d+)$/),r=parseInt(e[2]);!1===o.includes(r)&&o.push(r),void 0===a[r]&&(a[r]=0);const n=s[i],l=s[i+1],u=Number(l-n)/1e6;this.timestamps.set(t,u),a[r]+=u}const l=a[o[o.length-1]];return this.resultBuffer.unmap(),this.lastValue=l,this.frames=o,l}catch(e){return Mi("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){Mi("Error waiting for pending resolve:",e)}if(this.resultBuffer&&"mapped"===this.resultBuffer.mapState)try{this.resultBuffer.unmap()}catch(e){Mi("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.timestamps.clear(),this.frames=[],this.pendingResolve=null}}}class iL{constructor(){this.view=null,this.depthLoadOp=void 0,this.depthStoreOp=void 0,this.depthClearValue=void 0,this.depthReadOnly=!1,this.stencilLoadOp=void 0,this.stencilStoreOp=void 0,this.stencilClearValue=0,this.stencilReadOnly=!1}reset(){this.view=null,this.depthLoadOp=void 0,this.depthStoreOp=void 0,this.depthClearValue=void 0,this.depthReadOnly=!1,this.stencilLoadOp=void 0,this.stencilStoreOp=void 0,this.stencilClearValue=0,this.stencilReadOnly=!1}}const rL={r:0,g:0,b:0,a:1},nL={r:0,g:0,b:0,a:0},sL=new PN,aL=new LN,oL=new class{constructor(){this.label="",this.timestampWrites=void 0}reset(){this.label="",this.timestampWrites=void 0}},lL=new ZP,uL=new BN,cL=new class{constructor(){this.querySet=null,this.beginningOfPassWriteIndex=void 0,this.endOfPassWriteIndex=void 0}reset(){this.querySet=null,this.beginningOfPassWriteIndex=void 0,this.endOfPassWriteIndex=void 0}},hL=new QN,dL=new QN,pL=new kN,fL=new zN,mL=new JN;class gL extends Ow{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 RN(this),this.attributeUtils=new kP(this),this.bindingUtils=new WP(this),this.capabilities=new jP(this),this.pipelineUtils=new KP(this),this.textureUtils=new pP(this),this.occludedResolveCache=new Map;const t="undefined"==typeof navigator||!1===/Android/.test(navigator.userAgent);this._compatibility={[pi]:t}}async init(e){await super.init(e);const t=this.parameters;let i;if(void 0===t.device){const r={powerPreference:t.powerPreference,featureLevel:"compatibility",xrCompatible:e.xr.enabled},n="undefined"!=typeof navigator?await navigator.gpu.requestAdapter(r):null;if(null===n)throw new Error("THREE.WebGPUBackend: Unable to create WebGPU adapter.");const s=Object.values(xN),a=[];for(const e of s)n.features.has(e)&&a.push(e);const o={requiredFeatures:a,requiredLimits:t.requiredLimits};i=await n.requestDevice(o)}else i=t.device;this.compatibilityMode=!i.features.has("core-features-and-limits"),this.compatibilityMode&&(e._samples=0),i.lost.then(t=>{if("destroyed"===t.reason)return;const i={api:"WebGPU",message:t.message||"Unknown reason",reason:t.reason||null,originalEvent:t};e.onDeviceLost(i)}),i.onuncapturederror=t=>{const i=t.error,r=i&&i.constructor?i.constructor.name:"GPUError",n=i&&i.message||"Unknown uncaptured GPU error";e.onError({api:"WebGPU",type:r,message:n,originalEvent:t})},this.device=i,this.trackTimestamp=this.trackTimestamp&&this.hasFeature(xN.TimestampQuery),this.updateSize()}setXRRenderTargetTextures(e,t,i=null){const r=this.get(e.texture);r.texture=t,r.format=t.format,r.externalTexture=!0,r.xrViewDescriptors=i,r.initialized=!0}get context(){const e=this.renderer.getCanvasTarget(),t=this.get(e);let i=t.context;if(void 0===i){const r=this.parameters;i=!0===e.isDefaultCanvasTarget&&void 0!==r.context?r.context:e.domElement.getContext("webgpu"),"setAttribute"in e.domElement&&e.domElement.setAttribute("data-engine",`three.js r${N} webgpu`);const n=r.alpha?"premultiplied":"opaque",s=r.outputType===Xe?"extended":"standard";i.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:n,toneMapping:{mode:s}}),t.context=i}return i}get coordinateSystem(){return ci}get hasTimestamp(){return!0}async getArrayBufferAsync(e,t=null,i=0,r=-1){return await this.attributeUtils.getArrayBufferAsync(e,t,i,r)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){const e=this.renderer,t=e.getCanvasTarget(),i=this.get(t),r=e.currentSamples;let n=i.descriptor;if(void 0===n||i.samples!==r){if(n=new IN,n.colorAttachments.push(new UN),!0===e.depth||!0===e.stencil){const t=new iL;t.view=this.textureUtils.getDepthBuffer(e.depth,e.stencil).createView(),n.depthStencilAttachment=t}const t=n.colorAttachments[0];r>0?t.view=this.textureUtils.getColorBuffer().createView():t.resolveTarget=void 0,i.descriptor=n,i.samples=r}const s=n.colorAttachments[0];return r>0?s.resolveTarget=this.context.getCurrentTexture().createView():s.view=this.context.getCurrentTexture().createView(),n}_isRenderCameraDepthArray(e){const t=e.camera;return e.depthTexture&&!0===e.depthTexture.isArrayTexture&&null!==t&&!0===t.isArrayCamera}_hasExternalTexture(e){const t=e.textures;if(null===t)return!1;for(let e=0;e<t.length;e++)if(!0===this.get(t[e]).externalTexture)return!0;return!1}_getExternalMSAATextures(e,t,i){const r=this.utils.getSampleCount(e.sampleCount);if(1===r){if(void 0!==t.msaaTextures){for(const e of t.msaaTextures)e.destroy();t.msaaTextures=void 0}return null}const n=e.renderTarget,s=n.width,a=n.height,o=t.format;if(void 0===t.msaaTextures||t.msaaTextures.length!==i||t.msaaWidth!==s||t.msaaHeight!==a||t.msaaSamples!==r||t.msaaFormat!==o){if(void 0!==t.msaaTextures)for(const e of t.msaaTextures)e.destroy();pL.size.width=s,pL.size.height=a,pL.sampleCount=r,pL.format=o,pL.usage=GPUTextureUsage.RENDER_ATTACHMENT,t.msaaTextures=[];for(let e=0;e<i;e++)pL.label=n.texture.name+"-msaa-"+e,t.msaaTextures.push(this.device.createTexture(pL));pL.reset(),t.msaaWidth=s,t.msaaHeight=a,t.msaaSamples=r,t.msaaFormat=o}return t.msaaTextures}_createExternalTextureViews(e,t){const i=[],r=e.camera,n=t.xrViewDescriptors,s=Math.max(n?.length||0,e.activeCubeFace+1,1),a=this._getExternalMSAATextures(e,t,s);if(n&&null!==r&&!0===r.isArrayCamera)for(let r=0;r<n.length;r++){const s=t.texture.createView(n[r]);i.push({view:null!==a?a[r].createView():s,resolveTarget:null!==a&&!0===e.renderTarget.resolveColorBuffer?s:void 0,depthSlice:void 0})}else{const r=e.activeCubeFace,n=t.texture.createView({dimension:pN,baseArrayLayer:r,arrayLayerCount:1});i.push({view:null!==a?a[r].createView():n,resolveTarget:null!==a&&!0===e.renderTarget.resolveColorBuffer?n:void 0,depthSlice:void 0})}return i}_getRenderPassDescriptor(e,t={}){const i=e.renderTarget,r=this.get(i),n=this._hasExternalTexture(e);let s=r.descriptors;(void 0===s||r.width!==i.width||r.height!==i.height||r.samples!==i.samples||n)&&(s={},r.descriptors=s);const a=e.getCacheKey();let o=s[a];if(void 0===o||n){const t=e.textures,n=[];let l;const u=this._isRenderCameraDepthArray(e);for(let r=0;r<t.length;r++){const s=this.get(t[r]);if(!0!==s.externalTexture){if(fL.label=`colorAttachment_${r}`,fL.baseMipLevel=e.activeMipmapLevel,fL.mipLevelCount=1,fL.baseArrayLayer=e.activeCubeFace,fL.arrayLayerCount=1,fL.dimension=pN,i.isRenderTarget3D)l=e.activeCubeFace,fL.baseArrayLayer=0,fL.dimension=gN;else if(i.isRenderTarget&&t[r].image.depth>1)if(!0===u){const t=e.camera.cameras;for(let e=0;e<t.length;e++){fL.baseArrayLayer=e,fL.arrayLayerCount=1,fL.dimension=pN;const t=s.texture.createView(fL),r=s.msaaTextures?.[e];n.push({view:void 0!==r?r.createView():t,resolveTarget:void 0!==r&&!0===i.resolveColorBuffer?t:void 0,depthSlice:void 0})}}else fL.dimension=fN;if(!0!==u){const t=s.texture.createView(fL);let r,a;void 0!==s.msaaTexture?(r=s.msaaTexture.createView(),a=!0===i.resolveColorBuffer?t:void 0):void 0!==s.msaaTextures?(r=s.msaaTextures[e.activeCubeFace].createView(),a=!0===i.resolveColorBuffer?t:void 0):(r=t,a=void 0),n.push({view:r,resolveTarget:a,depthSlice:l})}fL.reset()}else n.push(...this._createExternalTextureViews(e,s))}const c=[];for(let e=0;e<n.length;e++){const t=n[e],i=new UN;i.view=t.view,i.depthSlice=t.depthSlice,i.resolveTarget=t.resolveTarget,c.push(i)}if(o={textureViews:n,colorAttachments:c,descriptor:new IN},e.depth){const t=this.get(e.depthTexture);(e.depthTexture.isArrayTexture||e.depthTexture.isCubeTexture)&&(fL.dimension=pN,fL.arrayLayerCount=1,fL.baseArrayLayer=e.activeCubeFace);const i=new iL,r=t.msaaTextures?.[e.activeCubeFace];i.view=void 0!==r?r.createView():t.texture.createView(fL),o.depthStencilAttachment=i,fL.reset()}s[a]=o,r.width=i.width,r.height=i.height,r.samples=i.samples,r.activeMipmapLevel=e.activeMipmapLevel,r.activeCubeFace=e.activeCubeFace}const l=o.descriptor;l.reset();for(let e=0;e<o.colorAttachments.length;e++){const i=o.colorAttachments[e];let r={r:0,g:0,b:0,a:1};0===e&&t.clearValue&&(r=t.clearValue),i.loadOp=t.loadOp||xA,i.storeOp=t.storeOp||bA,i.clearValue=r,l.colorAttachments.push(i)}return o.depthStencilAttachment&&(l.depthStencilAttachment=o.depthStencilAttachment),l}beginRender(e){const t=this.get(e),i=this.device,r=e.occlusionQueryCount,n=this.getOcclusionData(e);let s,a;r>0?(n.currentOcclusionQuerySet&&n.currentOcclusionQuerySet.destroy(),n.currentOcclusionQueryBuffer&&n.currentOcclusionQueryBuffer.destroy(),n.currentOcclusionQuerySet=n.occlusionQuerySet,n.currentOcclusionQueryBuffer=n.occlusionQueryBuffer,n.currentOcclusionQueryObjects=n.occlusionQueryObjects,lL.label=`occlusionQuerySet_${e.id}`,lL.type="occlusion",lL.count=r,s=i.createQuerySet(lL),lL.reset(),n.occlusionQuerySet=s,n.occlusionQueryIndex=0,n.occlusionQueryObjects=new Array(r),n.lastOcclusionObject=null):void 0!==n.lastOcclusionObject&&(n.lastOcclusionObject=void 0,n.occlusionQuerySet.destroy(),n.occlusionQuerySet=void 0),a=null===e.textures?this._getDefaultRenderPassDescriptor():this._getRenderPassDescriptor(e,{loadOp:xA}),this.initTimestampQuery(di,this.getTimestampUID(e),a),a.occlusionQuerySet=s;const o=a.depthStencilAttachment,l=e.renderTarget,u=e.sampleCount>1&&!1===l?.storeMultisampledColorBuffer,c=e.sampleCount>1&&!1===l?.storeMultisampledDepthBuffer,h=e.sampleCount>1&&!1===l?.storeMultisampledStencilBuffer,d=!0===e.fullscreenPass&&this._hasExternalTexture(e);if(null!==e.textures){const t=a.colorAttachments;for(let i=0;i<t.length;i++){const r=t[i];if(e.clearColor||u||d){const t=e.mrt?e.mrt.getClearColor(e.textures[i].name):null;null!==t?r.clearValue=t:0===i?r.clearValue=e.clearColorValue:(rL.r=0,rL.g=0,rL.b=0,rL.a=1,r.clearValue=rL),r.loadOp=SA}else r.loadOp=xA;r.storeOp=u?yA:bA}}else{const t=a.colorAttachments[0];e.clearColor?(t.clearValue=e.clearColorValue,t.loadOp=SA):t.loadOp=xA,t.storeOp=bA}e.depth&&(e.clearDepth||c?(o.depthClearValue=e.clearDepthValue,o.depthLoadOp=SA):o.depthLoadOp=xA,o.depthStoreOp=c?yA:bA),e.stencil&&(e.clearStencil||h?(o.stencilClearValue=e.clearStencilValue,o.stencilLoadOp=SA):o.stencilLoadOp=xA,o.stencilStoreOp=h?yA:bA),aL.label="renderContext_"+e.id;const p=i.createCommandEncoder(aL);if(aL.reset(),!0===this._isRenderCameraDepthArray(e)){const i=e.camera.cameras,r=this.get(e.depthTexture).texture;t.layerDescriptors&&t.layerDescriptors.length===i.length&&t.layerDepthTexture===r?this._updateArrayCameraLayerDescriptors(e,t,a,i):(this._createArrayCameraLayerDescriptors(e,t,a,i),t.layerDepthTexture=r),this._createArrayCameraBundleEncoders(e,t),t.arrayCameraRenderStages=[],t.currentPass=null}else{t.bundleEncoders=void 0,t.bundleSets=void 0,t.arrayCameraRenderStages=void 0;const i=p.beginRenderPass(a);t.currentPass=i,e.viewport&&this.updateViewport(e),e.scissor&&this.updateScissor(e)}t.descriptor=a,t.encoder=p,t.renderBundles=[],this._resetRenderContextData(t)}_resetRenderContextData(e){e.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},void 0===e.currentBlendColor&&(e.currentBlendColor=new Yr),e.currentBlendColor.setRGB(0,0,0),e.currentBlendAlpha=0,e.currentStencilRef=0}_createArrayCameraBundleEncoders(e,t){const i=e.camera.cameras;t.bundleEncoders=[],t.bundleSets=[];for(let r=0;r<i.length;r++){const i=this.pipelineUtils.createBundleEncoder(e,"renderBundleArrayCamera_"+r),n={attributes:{},bindingGroups:[],pipeline:null,index:null};t.bundleEncoders.push(i),t.bundleSets.push(n)}}_finishArrayCameraBundleEncoders(e){const t=[];for(const i of e.bundleEncoders)t.push(i.finish());return t}_createArrayCameraLayerDescriptors(e,t,i,r){const n=i.depthStencilAttachment;t.layerDescriptors=[];const s=this.get(e.depthTexture);s.viewCache||(s.viewCache=[]);for(let a=0;a<r.length;a++){const r=new IN;if(r.label=i.label,r.occlusionQuerySet=i.occlusionQuerySet,r.timestampWrites=i.timestampWrites,i.colorAttachments.length>0){const e=i.colorAttachments[0],t=i.colorAttachments[a],n=new UN;n.view=t.view,n.depthSlice=t.depthSlice,n.resolveTarget=t.resolveTarget,n.loadOp=e.loadOp,n.storeOp=e.storeOp,n.clearValue=e.clearValue,r.colorAttachments.push(n)}if(i.depthStencilAttachment){const t=a;if(!s.viewCache[t]){const e=s.msaaTextures?.[t];void 0!==e?s.viewCache[t]=e.createView():(fL.dimension=pN,fL.baseArrayLayer=a,fL.arrayLayerCount=1,s.viewCache[t]=s.texture.createView(fL)),fL.reset()}const i=new iL;i.view=s.viewCache[t],i.depthLoadOp=n.depthLoadOp||SA,i.depthStoreOp=n.depthStoreOp||bA,i.depthClearValue=n.depthClearValue??1,e.stencil&&(i.stencilLoadOp=n.stencilLoadOp,i.stencilStoreOp=n.stencilStoreOp,i.stencilClearValue=n.stencilClearValue),r.depthStencilAttachment=i}else{const e=new iL;e.view=n.view,e.depthLoadOp=n.depthLoadOp,e.depthStoreOp=n.depthStoreOp,e.depthClearValue=n.depthClearValue,e.depthReadOnly=n.depthReadOnly,e.stencilLoadOp=n.stencilLoadOp,e.stencilStoreOp=n.stencilStoreOp,e.stencilClearValue=n.stencilClearValue,e.stencilReadOnly=n.stencilReadOnly,r.depthStencilAttachment=e}t.layerDescriptors.push(r)}}_updateArrayCameraLayerDescriptors(e,t,i,r){const n=e.renderTarget,s=e.sampleCount>1&&!1===n?.storeMultisampledDepthBuffer,a=e.sampleCount>1&&!1===n?.storeMultisampledStencilBuffer;for(let n=0;n<r.length;n++){const r=t.layerDescriptors[n];if(r.timestampWrites=i.timestampWrites,i.colorAttachments.length>0){const e=i.colorAttachments[0],t=i.colorAttachments[n],s=r.colorAttachments[0];s.view=t.view,s.resolveTarget=t.resolveTarget,s.depthSlice=t.depthSlice,s.loadOp=e.loadOp,s.storeOp=e.storeOp,s.clearValue=e.clearValue}if(r.depthStencilAttachment){const t=r.depthStencilAttachment;e.depth&&(e.clearDepth||s?(t.depthClearValue=e.clearDepthValue,t.depthLoadOp=SA):t.depthLoadOp=xA),e.stencil&&(e.clearStencil||a?(t.stencilClearValue=e.clearStencilValue,t.stencilLoadOp=SA):t.stencilLoadOp=xA)}}}finishRender(e){const t=this.get(e),i=e.occlusionQueryCount,r=this.getOcclusionData(e);t.renderBundles.length>0&&t.currentPass.executeBundles(t.renderBundles);const n=r.lastOcclusionObject;n&&!0===n.occlusionTest&&t.currentPass.endOcclusionQuery();const s=t.encoder;if(!0===this._isRenderCameraDepthArray(e)){const i=this._finishArrayCameraBundleEncoders(t),r=t.arrayCameraRenderStages;r.push({bundles:i});for(let i=0;i<t.layerDescriptors.length;i++){const n=t.layerDescriptors[i],a=n.colorAttachments.map(e=>e.loadOp),o=n.colorAttachments.map(e=>e.storeOp),l=n.depthStencilAttachment?.depthLoadOp,u=n.depthStencilAttachment?.depthStoreOp,c=n.depthStencilAttachment?.stencilLoadOp,h=n.depthStencilAttachment?.stencilStoreOp;for(let t=0;t<r.length;t++){const d=r[t],p=d.bundles[i],f=t===r.length-1;for(let e=0;e<n.colorAttachments.length;e++){const i=n.colorAttachments[e];i.loadOp=0===t?a[e]:xA,i.storeOp=f?o[e]:bA}e.depth&&(n.depthStencilAttachment.depthLoadOp=0===t?l:xA,n.depthStencilAttachment.depthStoreOp=f?u:bA),e.stencil&&(n.depthStencilAttachment.stencilLoadOp=0===t?c:xA,n.depthStencilAttachment.stencilStoreOp=f?h:bA);const m=s.beginRenderPass(n);if(e.viewport){const{x:t,y:i,width:r,height:n,minDepth:s,maxDepth:a}=e.viewportValue;m.setViewport(t,i,r,n,s,a)}if(e.scissor){const{x:t,y:i,width:r,height:n}=e.scissorValue;m.setScissorRect(t,i,r,n)}if(m.executeBundles([p]),m.end(),void 0!==d.framebufferCopy){const{texture:e,sourceGPU:t,destinationGPU:r,rectangle:n,generateMipmaps:a}=d.framebufferCopy;this._copyFramebufferToTexture(s,e,t,r,n,i,a)}}for(let e=0;e<n.colorAttachments.length;e++)n.colorAttachments[e].loadOp=a[e],n.colorAttachments[e].storeOp=o[e];e.depth&&(n.depthStencilAttachment.depthLoadOp=l,n.depthStencilAttachment.depthStoreOp=u),e.stencil&&(n.depthStencilAttachment.stencilLoadOp=c,n.depthStencilAttachment.stencilStoreOp=h)}}else t.currentPass&&t.currentPass.end();if(i>0){const n=8*i;let s=this.occludedResolveCache.get(n);void 0===s&&(sL.size=n,sL.usage=GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC,s=this.device.createBuffer(sL),sL.reset(),this.occludedResolveCache.set(n,s)),sL.size=n,sL.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ;const a=this.device.createBuffer(sL);sL.reset(),t.encoder.resolveQuerySet(r.occlusionQuerySet,0,i,s,0),t.encoder.copyBufferToBuffer(s,0,a,0,n),r.occlusionQueryBuffer=a,this.resolveOccludedAsync(e)}if(CN(this.device,t.encoder.finish()),t.currentPass=null,t.encoder=null,null!==e.textures){const t=e.textures;for(let e=0;e<t.length;e++){const i=t[e];!0===i.generateMipmaps&&!0===i.mipmapsAutoUpdate&&this.textureUtils.generateMipmaps(i)}}}isOccluded(e,t){const i=this.getOcclusionData(e);return i.occluded&&i.occluded.has(t)}async resolveOccludedAsync(e){const t=this.getOcclusionData(e),{currentOcclusionQueryBuffer:i,currentOcclusionQueryObjects:r}=t;if(i&&r){const e=new WeakSet;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueryBuffer=null,await i.mapAsync(GPUMapMode.READ);const n=i.getMappedRange(),s=new BigUint64Array(n);for(let t=0;t<r.length;t++){const i=r[t];void 0!==i&&s[t]===BigInt(0)&&e.add(i)}i.destroy(),t.occluded=e}}updateViewport(e){const{currentPass:t}=this.get(e),{x:i,y:r,width:n,height:s,minDepth:a,maxDepth:o}=e.viewportValue;t.setViewport(i,r,n,s,a,o)}updateScissor(e){const{currentPass:t}=this.get(e),{x:i,y:r,width:n,height:s}=e.scissorValue;t.setScissorRect(i,r,n,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,i,r=null){const n=this.device,s=this.renderer;let a,o,l,u=[];if(e){const e=this.getClearColor();rL.r=e.r,rL.g=e.g,rL.b=e.b,rL.a=e.a}if(null===r){o=s.depth,l=s.stencil;const t=this._getDefaultRenderPassDescriptor();if(e){u=t.colorAttachments;const e=u[0];e.clearValue=rL,e.loadOp=SA,e.storeOp=bA}(o||l)&&(a=t.depthStencilAttachment)}else{o=r.depth,l=r.stencil;const n={loadOp:e?SA:xA,clearValue:e?rL:void 0};o&&(n.depthLoadOp=t?SA:xA,n.depthClearValue=t?s.getClearDepth():void 0,n.depthStoreOp=bA),l&&(n.stencilLoadOp=i?SA:xA,n.stencilClearValue=i?s.getClearStencil():void 0,n.stencilStoreOp=bA);const c=this._getRenderPassDescriptor(r,n);u=c.colorAttachments,a=c.depthStencilAttachment}o&&a&&(t?(a.depthLoadOp=SA,a.depthClearValue=s.getClearDepth(),a.depthStoreOp=bA):(a.depthLoadOp=xA,a.depthStoreOp=bA)),l&&a&&(i?(a.stencilLoadOp=SA,a.stencilClearValue=s.getClearStencil(),a.stencilStoreOp=bA):(a.stencilLoadOp=xA,a.stencilStoreOp=bA)),aL.label="clear";const c=n.createCommandEncoder(aL);aL.reset();c.beginRenderPass({colorAttachments:u,depthStencilAttachment:a}).end(),CN(n,c.finish())}beginCompute(e){const t=this.get(e),i="computeGroup_"+e.id;oL.label=i,aL.label=i,this.initTimestampQuery(hi,this.getTimestampUID(e),oL),t.cmdEncoderGPU=this.device.createCommandEncoder(aL),t.passEncoderGPU=t.cmdEncoderGPU.beginComputePass(oL),t.currentPipeline=null,aL.reset(),oL.reset()}compute(e,t,i,r,n=null){const s=this.get(t),a=this.get(e),{passEncoderGPU:o}=a,l=this.get(r).pipeline;a.currentPipeline!==l&&(o.setPipeline(l),a.currentPipeline=l);for(let e=0,t=i.length;e<t;e++){const t=i[e],r=this.get(t);o.setBindGroup(e,r.group)}if(null===n&&(n=t.dispatchSize||t.count),n&&n.isIndirectStorageBufferAttribute){const e=this.get(n).buffer;return void o.dispatchWorkgroupsIndirect(e,0)}if("number"==typeof n){const e=n;if(void 0===s.dispatchSize||s.count!==e){s.dispatchSize=[0,1,1],s.count=e;const i=t.workgroupSize;let r=i[0];for(let e=1;e<i.length;e++)r*=i[e];const a=Math.ceil(e/r),o=this.device.limits.maxComputeWorkgroupsPerDimension;n=[a,1,1],a>o&&(n[0]=Math.min(a,o),n[1]=Math.ceil(a/o)),s.dispatchSize=n}n=s.dispatchSize}o.dispatchWorkgroups(n[0],n[1]||1,n[2]||1)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),CN(this.device,t.cmdEncoderGPU.finish())}_draw(e,t,i,r,n,s,a,o,l,u=-1){const{object:c,material:h,context:d}=e,p=e.getIndex(),f=null!==p;l.pipeline!==r&&(o.setPipeline(r),l.pipeline=r);const m=l.bindingGroups;for(let e=0,t=n.length;e<t;e++){if(e===u)continue;const t=n[e],i=this.get(t).group;m[e]!==i&&(o.setBindGroup(e,i),m[e]=i)}if(!0===f&&l.index!==p){const e=this.get(p).buffer,t=p.array instanceof Uint16Array?AA:RA;o.setIndexBuffer(e,t),l.index=p}for(let e=0,t=s.length;e<t;e++){const t=s[e];if(l.attributes[e]!==t){const i=this.get(t).buffer;o.setVertexBuffer(e,i),l.attributes[e]=t}}if(!0===d.stencil&&!0===h.stencilWrite&&i.currentStencilRef!==h.stencilRef&&(o.setStencilReference(h.stencilRef),i.currentStencilRef=h.stencilRef),5===h.blending&&void 0!==o.setBlendConstant){const e=h.blendColor,t=h.blendAlpha;!1!==e.equals(i.currentBlendColor)&&t===i.currentBlendAlpha||(nL.r=e.r,nL.g=e.g,nL.b=e.b,nL.a=t,o.setBlendConstant(nL),i.currentBlendColor.copy(e),i.currentBlendAlpha=t)}if(!0===c.isBatchedMesh){const e=c._mergedDrawStarts,i=c._mergedDrawCounts,r=c._mergedDrawInstanceCounts,n=c._mergedDrawCount,s=c._multiDrawBytesPerElement;let a=0;for(let l=0;l<n;l++){const n=r[l];!0===f?o.drawIndexed(i[l],n,e[l]/s,0,a):o.draw(i[l],n,e[l],a),t.update(c,i[l],n),a+=n}}else if(!0===f){const{vertexCount:i,instanceCount:r,firstVertex:n}=a,s=e.getIndirect();if(null!==s){const t=this.get(s).buffer,i=e.getIndirectOffset(),r=Array.isArray(i)?i:[i];for(let e=0;e<r.length;e++)o.drawIndexedIndirect(t,r[e])}else o.drawIndexed(i,r,n,0,0),t.update(c,i,r)}else{const{vertexCount:i,instanceCount:r,firstVertex:n}=a,s=e.getIndirect();if(null!==s){const t=this.get(s).buffer,i=e.getIndirectOffset(),r=Array.isArray(i)?i:[i];for(let e=0;e<r.length;e++)o.drawIndirect(t,r[e])}else o.draw(i,r,n,0),t.update(c,i,r)}}draw(e,t){const{object:i,context:r,pipeline:n}=e,s=this.get(r),a=this.get(n),o=a.pipeline;if(!0===a.error)return;const l=e.getDrawParameters();if(null===l)return;const u=e.getBindings(),c=e.getVertexBuffers();if(e.camera.isArrayCamera&&e.camera.cameras.length>0){const n=this.get(e.camera),a=e.camera.cameras,h=e.getBindingGroup("cameraIndex");if(void 0===n.indexesGPU||n.indexesGPU.length!==a.length){const e=this.get(h),t=[],i=new Uint32Array([0,0,0,0]);for(let r=0,n=a.length;r<n;r++){i[0]=r;const{layoutGPU:n}=e.layout,s=this.bindingUtils.createBindGroupIndex(i,n);t.push(s)}n.indexesGPU=t}const d=r.renderTarget,p=null===d||!0===d.isPostProcessingRenderTarget?this.renderer.getPixelRatio():1,f=h?u.indexOf(h):-1,m=r.frustumArray;for(let h=0,d=a.length;h<d;h++){const d=a[h];if(i.layers.test(d.layers)&&(!1===e.camera.perCameraFrustumCulled||!1===i.frustumCulled||i.intersectsFrustum(m.getFrustum(h)))){const i=d.viewport;let a=s.currentPass,m=s.currentSets;const g=void 0!==s.bundleEncoders;if(g){a=s.bundleEncoders[h],m=s.bundleSets[h]}if(i&&!g&&a.setViewport(Math.floor(i.x*p),Math.floor(i.y*p),Math.floor(i.width*p),Math.floor(i.height*p),r.viewportValue.minDepth,r.viewportValue.maxDepth),-1!==f&&n.indexesGPU){const e=n.indexesGPU[h];m.bindingGroups[f]!==e&&(a.setBindGroup(f,e),m.bindingGroups[f]=e)}this._draw(e,t,s,o,u,c,l,a,m,f)}}}else if(s.currentPass){if(s.currentPass instanceof GPURenderBundleEncoder)!0===i.occlusionTest&&Ei("WebGPUBackend: Occlusion queries can not be recorded into render bundles.");else if(r.occlusionQueryCount>0){const e=this.getOcclusionData(r),t=e.lastOcclusionObject;t!==i&&(null!==t&&!0===t.occlusionTest&&(s.currentPass.endOcclusionQuery(),e.occlusionQueryIndex++),!0===i.occlusionTest&&(s.currentPass.beginOcclusionQuery(e.occlusionQueryIndex),e.occlusionQueryObjects[e.occlusionQueryIndex]=i),e.lastOcclusionObject=i)}this._draw(e,t,s,o,u,c,l,s.currentPass,s.currentSets)}}needsRenderUpdate(e){const t=this.get(e),{object:i,material:r,geometry:n}=e,s=this.utils,a=s.getSampleCountRenderContext(e.context),o=s.getCurrentColorSpace(e.context),l=s.getCurrentColorFormat(e.context),u=s.getCurrentDepthStencilFormat(e.context),c=s.getPrimitiveTopology(i,r),h=s.getStripIndexFormat(i,n),d=i.isMesh&&i.matrixWorld.determinantAffine()<0;let p=!1;return t.material===r&&t.materialVersion===r.version&&t.transparent===r.transparent&&t.blending===r.blending&&t.premultipliedAlpha===r.premultipliedAlpha&&t.blendSrc===r.blendSrc&&t.blendDst===r.blendDst&&t.blendEquation===r.blendEquation&&t.blendSrcAlpha===r.blendSrcAlpha&&t.blendDstAlpha===r.blendDstAlpha&&t.blendEquationAlpha===r.blendEquationAlpha&&t.colorWrite===r.colorWrite&&t.depthWrite===r.depthWrite&&t.depthTest===r.depthTest&&t.depthFunc===r.depthFunc&&t.stencilWrite===r.stencilWrite&&t.stencilFunc===r.stencilFunc&&t.stencilFail===r.stencilFail&&t.stencilZFail===r.stencilZFail&&t.stencilZPass===r.stencilZPass&&t.stencilFuncMask===r.stencilFuncMask&&t.stencilWriteMask===r.stencilWriteMask&&t.polygonOffset===r.polygonOffset&&t.polygonOffsetFactor===r.polygonOffsetFactor&&t.polygonOffsetUnits===r.polygonOffsetUnits&&t.side===r.side&&t.alphaToCoverage===r.alphaToCoverage&&t.sampleCount===a&&t.colorSpace===o&&t.colorFormat===l&&t.depthStencilFormat===u&&t.primitiveTopology===c&&t.stripIndexFormat===h&&t.frontFaceCW===d&&t.geometryVersion===e.geometryVersion&&t.clippingContextCacheKey===e.clippingContextCacheKey||(t.material=r,t.materialVersion=r.version,t.transparent=r.transparent,t.blending=r.blending,t.premultipliedAlpha=r.premultipliedAlpha,t.blendSrc=r.blendSrc,t.blendDst=r.blendDst,t.blendEquation=r.blendEquation,t.blendSrcAlpha=r.blendSrcAlpha,t.blendDstAlpha=r.blendDstAlpha,t.blendEquationAlpha=r.blendEquationAlpha,t.colorWrite=r.colorWrite,t.depthWrite=r.depthWrite,t.depthTest=r.depthTest,t.depthFunc=r.depthFunc,t.stencilWrite=r.stencilWrite,t.stencilFunc=r.stencilFunc,t.stencilFail=r.stencilFail,t.stencilZFail=r.stencilZFail,t.stencilZPass=r.stencilZPass,t.stencilFuncMask=r.stencilFuncMask,t.stencilWriteMask=r.stencilWriteMask,t.polygonOffset=r.polygonOffset,t.polygonOffsetFactor=r.polygonOffsetFactor,t.polygonOffsetUnits=r.polygonOffsetUnits,t.side=r.side,t.alphaToCoverage=r.alphaToCoverage,t.sampleCount=a,t.colorSpace=o,t.colorFormat=l,t.depthStencilFormat=u,t.primitiveTopology=c,t.stripIndexFormat=h,t.frontFaceCW=d,t.geometryVersion=e.geometryVersion,t.clippingContextCacheKey=e.clippingContextCacheKey,p=!0),p}getRenderCacheKey(e){const{object:t,material:i,geometry:r}=e,n=this.utils,s=e.context,a=t.isMesh&&t.matrixWorld.determinantAffine()<0;return[i.transparent,i.blending,i.premultipliedAlpha,i.blendSrc,i.blendDst,i.blendEquation,i.blendSrcAlpha,i.blendDstAlpha,i.blendEquationAlpha,i.colorWrite,i.depthWrite,i.depthTest,i.depthFunc,i.stencilWrite,i.stencilFunc,i.stencilFail,i.stencilZFail,i.stencilZPass,i.stencilFuncMask,i.stencilWriteMask,i.polygonOffset,i.polygonOffsetFactor,i.polygonOffsetUnits,i.side,i.alphaToCoverage,a,n.getSampleCountRenderContext(s),n.getCurrentColorSpace(s),n.getCurrentColorFormat(s),n.getCurrentDepthStencilFormat(s),n.getPrimitiveTopology(t,i),n.getStripIndexFormat(t,r),this.attributeUtils.getVertexBufferLayoutCacheKey(e),e.clippingContextCacheKey].join()}updateSampler(e){return this.textureUtils.updateSampler(e)}destroySampler(e){this.textureUtils.destroySampler(e)}createDefaultTexture(e){return this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e,t=!1){this.textureUtils.destroyTexture(e,t)}async copyTextureToBuffer(e,t,i,r,n,s){return this.textureUtils.copyTextureToBuffer(e,t,i,r,n,s)}initTimestampQuery(e,t,i){if(!this.trackTimestamp)return void(i.timestampWrites=void 0);this.timestampQueryPool[e]||(this.timestampQueryPool[e]=new tL(this.device,e,2048));const r=this.timestampQueryPool[e],n=r.allocateQueriesForContext(t);cL.querySet=r.querySet,cL.beginningOfPassWriteIndex=n,cL.endOfPassWriteIndex=n+1,i.timestampWrites=cL}createNodeBuilder(e,t){return new PP(e,t)}createProgram(e){const t=this.get(e);uL.label=e.stage+(""!==e.name?`_${e.name}`:""),uL.code=e.code,t.module={module:this.device.createShaderModule(uL),entryPoint:"main"},uL.reset()}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){this.pipelineUtils.createRenderPipeline(e,t)}createComputePipeline(e,t,i=null){this.pipelineUtils.createComputePipeline(e,t,i)}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 i=this.get(e),r=i.currentPass.finish();this.get(t).bundleGPU=r,i.currentSets=i._currentSets,i.currentPass=i._currentPass,i._currentPass=null,i._currentSets=null}addBundle(e,t){this.get(e).renderBundles.push(this.get(t).bundleGPU)}createUniformBuffer(e){const t=this.get(e);if(void 0===t.buffer){const i=e.byteLength,r=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,n=[];e.visibility&cA.VERTEX&&n.push("vertex"),e.visibility&cA.FRAGMENT&&n.push("fragment"),e.visibility&cA.COMPUTE&&n.push("compute");const s=`(${n.join(",")})`;sL.label=`bindingBuffer${e.id}_${e.name}_${s}`,sL.size=i,sL.usage=r;const a=this.device.createBuffer(sL);sL.reset(),t.buffer=a}}destroyUniformBuffer(e){this.get(e).buffer.destroy(),this.delete(e)}createBindings(e,t,i,r){this.bindingUtils.createBindings(e,t,i,r)}updateBindings(e,t,i,r){this.bindingUtils.createBindings(e,t,i,r)}updateBinding(e){this.bindingUtils.updateBinding(e)}deleteBindGroupData(e){this.bindingUtils.deleteBindGroupData(e)}createIndexAttribute(e){let t=GPUBufferUsage.INDEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST;(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(t|=GPUBufferUsage.STORAGE),this.attributeUtils.createAttribute(e,t)}createAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createIndirectStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.INDIRECT|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}updateSize(){this.delete(this.renderer.getCanvasTarget())}destroyCanvasTarget(e){this.destroyTexture(e.colorTexture),this.destroyTexture(e.depthTexture),this.delete(e)}hasFeature(e){return void 0!==SN[e]&&(e=SN[e]),this.device.features.has(e)}copyTextureToTexture(e,t,i=null,r=null,n=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!==i&&(!0===i.isBox3?(u=i.min.x,c=i.min.y,h=i.min.z,d=i.max.x-i.min.x,p=i.max.y-i.min.y,f=i.max.z-i.min.z):(u=i.min.x,c=i.min.y,d=i.max.x-i.min.x,p=i.max.y-i.min.y,f=1)),null!==r&&(a=r.x,o=r.y,l=r.z||0),aL.label="copyTextureToTexture_"+e.id+"_"+t.id;const m=this.device.createCommandEncoder(aL);aL.reset();const g=this.get(e).texture,_=this.get(t).texture;hL.texture=g,hL.mipLevel=n,hL.origin.x=u,hL.origin.y=c,hL.origin.z=h,dL.texture=_,dL.mipLevel=s,dL.origin.x=a,dL.origin.y=o,dL.origin.z=l,mL.width=d,mL.height=p,mL.depthOrArrayLayers=f,m.copyTextureToTexture(hL,dL,mL),hL.reset(),dL.reset(),mL.reset(),CN(this.device,m.finish()),0===s&&!0===t.generateMipmaps&&!0===t.mipmapsAutoUpdate&&this.textureUtils.generateMipmaps(t)}copyFramebufferToTexture(e,t,i){const r=this.get(t);let n=null;n=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(n.format!==s.format)return void Mi("WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.",n.format,s.format);const a=!0===e.generateMipmaps&&!0===e.mipmapsAutoUpdate&&s.mipLevelCount>1;if(r.encoder&&!0===this._isRenderCameraDepthArray(t)){const o=this._finishArrayCameraBundleEncoders(r);return r.arrayCameraRenderStages.push({bundles:o,framebufferCopy:{texture:e,sourceGPU:n,destinationGPU:s,rectangle:{x:i.x,y:i.y,z:i.z,w:i.w},generateMipmaps:a}}),void this._createArrayCameraBundleEncoders(t,r)}let o;if(r.currentPass?(r.currentPass.end(),o=r.encoder):(aL.label="copyFramebufferToTexture_"+e.id,o=this.device.createCommandEncoder(aL),aL.reset()),this._copyFramebufferToTexture(o,e,n,s,i,0,a),r.currentPass){const{descriptor:e}=r;for(let t=0;t<e.colorAttachments.length;t++)e.colorAttachments[t].loadOp=xA;t.depth&&(e.depthStencilAttachment.depthLoadOp=xA),t.stencil&&(e.depthStencilAttachment.stencilLoadOp=xA),r.currentPass=o.beginRenderPass(e),this._resetRenderContextData(r),t.viewport&&this.updateViewport(t),t.scissor&&this.updateScissor(t)}else CN(this.device,o.finish())}_copyFramebufferToTexture(e,t,i,r,n,s=0,a=t.generateMipmaps){hL.texture=i,hL.origin.x=n.x,hL.origin.y=n.y,hL.origin.z=s,dL.texture=r,mL.width=n.z,mL.height=n.w,e.copyTextureToTexture(hL,dL,mL),hL.reset(),dL.reset(),mL.reset(),!0===a&&r.mipLevelCount>1&&this.textureUtils.generateMipmaps(t,e)}hasCompatibility(e){return void 0!==this._compatibility[e]?this._compatibility[e]:super.hasCompatibility(e)}async dispose(){if(await super.dispose(),this.bindingUtils.dispose(),this.textureUtils.dispose(),this.occludedResolveCache){for(const e of this.occludedResolveCache.values())e.destroy();this.occludedResolveCache.clear()}void 0===this.parameters.device&&null!==this.device&&this.device.destroy()}}class _L extends Va{constructor(e,t,i,r,n,s){super(e,t,i,r,n,s),this.iesMap=null}copy(e,t){return super.copy(e,t),this.iesMap=e.iesMap,this}}class vL extends Va{constructor(e,t,i,r,n,s){super(e,t,i,r,n,s),this.aspect=null}copy(e,t){return super.copy(e,t),this.aspect=e.aspect,this}}Wa.registerNode(Sx),Xa.registerNode(_E),Ya.registerNode(wE),Va.registerNode(bE),qa.registerNode(gE),Ra.registerNode(vE),Za.registerNode(xE),_L.registerNode(yE),vL.registerNode(TE);class bL extends WE{constructor(){super(),this.addMaterial(jS,"MeshPhongMaterial"),this.addMaterial(dT,"MeshStandardMaterial"),this.addMaterial(fT,"MeshPhysicalMaterial"),this.addMaterial(vT,"MeshToonMaterial"),this.addMaterial(BS,"MeshBasicMaterial"),this.addMaterial(HS,"MeshLambertMaterial"),this.addMaterial(AS,"MeshNormalMaterial"),this.addMaterial(yT,"MeshMatcapMaterial"),this.addMaterial(_S,"LineBasicMaterial"),this.addMaterial(bS,"LineDashedMaterial"),this.addMaterial(ET,"PointsMaterial"),this.addMaterial(ST,"SpriteMaterial"),this.addMaterial(CT,"ShadowMaterial"),this.addToneMapping(gy,1),this.addToneMapping(_y,2),this.addToneMapping(vy,3),this.addToneMapping(yy,4),this.addToneMapping(My,6),this.addToneMapping(Ey,7)}}class yL extends hw{constructor(e={}){let t;e.forceWebGL?t=sA:(t=gL,e.getFallback=()=>(Ti("WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new sA(e)));super(new t(e),e),this.library=new bL,this.isWebGPURenderer=!0,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}Wa.registerNode(Sx),Xa.registerNode(_E),Ya.registerNode(wE),Va.registerNode(bE),qa.registerNode(gE),Ra.registerNode(vE),Za.registerNode(xE),_L.registerNode(yE),vL.registerNode(TE);const xL={type:"change"},SL={type:"start"},TL={type:"end"},ML=1e-6,EL=-1,wL=0,AL=1,RL=2,CL=3,NL=4,PL=new Vi,LL=new Vi,DL=new Wi,UL=new Wi,IL=new Wi,FL=new Hi,OL=new Wi,BL=new Wi,kL=new Wi,zL=new Wi;class GL extends lo{constructor(e,t=null){super(e,t),this.screen={left:0,top:0,width:0,height:0},this.rotateSpeed=1,this.zoomSpeed=1.2,this.panSpeed=.3,this.rollSpeed=1,this.noRotate=!1,this.noZoom=!1,this.noPan=!1,this.multiTouchRoll=!1,this.staticMoving=!1,this.dynamicDampingFactor=.2,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.keys=["KeyA","KeyS","KeyD"],this.mouseButtons={LEFT:P,MIDDLE:L,RIGHT:D},this.target=new Wi,this.state=EL,this.keyState=EL,this._lastPosition=new Wi,this._lastUp=new Wi,this._lastZoom=1,this._touchZoomDistanceStart=0,this._touchZoomDistanceEnd=0,this._touchRollAngle=0,this._touchRollPointerIds="",this._lastAngle=0,this._lastRollAngle=0,this._eye=new Wi,this._movePrev=new Vi,this._moveCurr=new Vi,this._lastAxis=new Wi,this._zoomStart=new Vi,this._zoomEnd=new Vi,this._panStart=new Vi,this._panEnd=new Vi,this._pointers=[],this._pointerPositions={},this._onPointerMove=HL.bind(this),this._onPointerDown=VL.bind(this),this._onPointerUp=WL.bind(this),this._onPointerCancel=jL.bind(this),this._onContextMenu=QL.bind(this),this._onMouseWheel=ZL.bind(this),this._onKeyDown=XL.bind(this),this._onKeyUp=$L.bind(this),this._onTouchStart=JL.bind(this),this._onTouchMove=eD.bind(this),this._onTouchEnd=tD.bind(this),this._onMouseDown=qL.bind(this),this._onMouseMove=YL.bind(this),this._onMouseUp=KL.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=""}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(){if(this._eye.subVectors(this.object.position,this.target),this.noRotate||(this._rotateCamera(),!0===this.multiTouchRoll&&this._rollCamera()),this.noZoom||this._zoomCamera(),this.noPan||this._panCamera(),this.object.position.addVectors(this.target,this._eye),this.object.isPerspectiveCamera){this._checkDistances(),this.object.lookAt(this.target);const e=this._lastPosition.distanceToSquared(this.object.position)>ML,t=this._lastUp.distanceToSquared(this.object.up)>ML;(e||t)&&(this.dispatchEvent(xL),this._lastPosition.copy(this.object.position),this._lastUp.copy(this.object.up))}else if(this.object.isOrthographicCamera){this.object.lookAt(this.target);const e=this._lastPosition.distanceToSquared(this.object.position)>ML,t=this._lastUp.distanceToSquared(this.object.up)>ML,i=this._lastZoom!==this.object.zoom;(e||t||i)&&(this.dispatchEvent(xL),this._lastPosition.copy(this.object.position),this._lastUp.copy(this.object.up),this._lastZoom=this.object.zoom)}else console.warn("THREE.TrackballControls: Unsupported camera type.")}reset(){this.state=EL,this.keyState=EL,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(xL),this._lastPosition.copy(this.object.position),this._lastUp.copy(this.object.up),this._lastZoom=this.object.zoom}_panCamera(){if(LL.copy(this._panEnd).sub(this._panStart),LL.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;LL.x*=e,LL.y*=t}LL.multiplyScalar(this._eye.length()*this.panSpeed),UL.copy(this._eye).cross(this.object.up).setLength(LL.x),UL.add(DL.copy(this.object.up).setLength(LL.y)),this.object.position.add(UL),this.target.add(UL),this.staticMoving?this._panStart.copy(this._panEnd):this._panStart.add(LL.subVectors(this._panEnd,this._panStart).multiplyScalar(this.dynamicDampingFactor))}}_rotateCamera(){zL.set(this._moveCurr.x-this._movePrev.x,this._moveCurr.y-this._movePrev.y,0);let e=zL.length();e?(this._eye.copy(this.object.position).sub(this.target),OL.copy(this._eye).normalize(),BL.copy(this.object.up).normalize(),kL.crossVectors(BL,OL).normalize(),BL.setLength(this._moveCurr.y-this._movePrev.y),kL.setLength(this._moveCurr.x-this._movePrev.x),zL.copy(BL.add(kL)),IL.crossVectors(zL,this._eye).normalize(),e*=this.rotateSpeed,FL.setFromAxisAngle(IL,e),this._eye.applyQuaternion(FL),this.object.up.applyQuaternion(FL),this._lastAxis.copy(IL),this._lastAngle=e):!this.staticMoving&&this._lastAngle&&(this._lastAngle*=Math.sqrt(1-this.dynamicDampingFactor),this._eye.copy(this.object.position).sub(this.target),FL.setFromAxisAngle(this._lastAxis,this._lastAngle),this._eye.applyQuaternion(FL),this.object.up.applyQuaternion(FL)),this._movePrev.copy(this._moveCurr)}_rollCamera(){const e=this._getTouchRollAngle();if(e)this._lastRollAngle=e*this.rollSpeed;else{if(this.staticMoving||!this._lastRollAngle)return;this._lastRollAngle*=Math.sqrt(1-this.dynamicDampingFactor)}OL.copy(this._eye).normalize(),FL.setFromAxisAngle(OL,this._lastRollAngle),this.object.up.applyQuaternion(FL)}_getTouchRollAngle(){const e=this._pointers[0],t=this._pointers[1];if(void 0===t||"touch"!==e.pointerType||"touch"!==t.pointerType)return this._touchRollPointerIds="",0;const i=`${e.pointerId},${t.pointerId}`,r=this._pointerPositions[e.pointerId],n=this._pointerPositions[t.pointerId],s=Math.atan2(n.y-r.y,n.x-r.x);if(i!==this._touchRollPointerIds)return this._touchRollPointerIds=i,this._touchRollAngle=s,0;let a=s-this._touchRollAngle;return this._touchRollAngle=s,a>Math.PI?a-=2*Math.PI:a<-Math.PI&&(a+=2*Math.PI),a}_zoomCamera(){let e;this.state===NL?(e=this._touchZoomDistanceStart/this._touchZoomDistanceEnd,this._touchZoomDistanceStart=this._touchZoomDistanceEnd,this.object.isPerspectiveCamera?this._eye.multiplyScalar(e):this.object.isOrthographicCamera?(this.object.zoom=Gi.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=Gi.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 PL.set((e-this.screen.left)/this.screen.width,(t-this.screen.top)/this.screen.height),PL}_getMouseOnCircle(e,t){return PL.set((e-.5*this.screen.width-this.screen.left)/(.5*this.screen.width),(this.screen.height+2*(this.screen.top-t))/this.screen.width),PL}_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 Vi,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 VL(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 HL(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchMove(e):this._onMouseMove(e))}function WL(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 jL(e){this._removePointer(e)}function $L(){!1!==this.enabled&&(this.keyState=EL,window.addEventListener("keydown",this._onKeyDown))}function XL(e){!1!==this.enabled&&(window.removeEventListener("keydown",this._onKeyDown),this.keyState===EL&&(e.code!==this.keys[wL]||this.noRotate?e.code!==this.keys[AL]||this.noZoom?e.code!==this.keys[RL]||this.noPan||(this.keyState=RL):this.keyState=AL:this.keyState=wL))}function qL(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 L:this.state=AL;break;case P:this.state=wL;break;case D:this.state=RL;break;default:this.state=EL}const i=this.keyState!==EL?this.keyState:this.state;i!==wL||this.noRotate?i!==AL||this.noZoom?i!==RL||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(SL)}function YL(e){const t=this.keyState!==EL?this.keyState:this.state;t!==wL||this.noRotate?t!==AL||this.noZoom?t!==RL||this.noPan||this._panEnd.copy(this._getMouseOnScreen(e.pageX,e.pageY)):this._zoomEnd.copy(this._getMouseOnScreen(e.pageX,e.pageY)):this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY))}function KL(){this.state=EL,this.dispatchEvent(TL)}function ZL(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(SL),this.dispatchEvent(TL)}}function QL(e){!1!==this.enabled&&e.preventDefault()}function JL(e){if(this._trackPointer(e),1===this._pointers.length)this.state=CL,this._moveCurr.copy(this._getMouseOnCircle(this._pointers[0].pageX,this._pointers[0].pageY)),this._movePrev.copy(this._moveCurr);else{this.state=NL;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 i=(this._pointers[0].pageX+this._pointers[1].pageX)/2,r=(this._pointers[0].pageY+this._pointers[1].pageY)/2;this._panStart.copy(this._getMouseOnScreen(i,r)),this._panEnd.copy(this._panStart)}this.dispatchEvent(SL)}function eD(e){if(this._trackPointer(e),1===this._pointers.length)this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY));else{const t=this._getSecondPointerPosition(e),i=e.pageX-t.x,r=e.pageY-t.y;this._touchZoomDistanceEnd=Math.sqrt(i*i+r*r);const n=(e.pageX+t.x)/2,s=(e.pageY+t.y)/2;this._panEnd.copy(this._getMouseOnScreen(n,s))}}function tD(e){switch(this._pointers.length){case 0:this.state=EL;break;case 1:this.state=CL,this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY)),this._movePrev.copy(this._moveCurr);break;case 2:this.state=NL;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(TL)}const iD={type:"change"},rD={type:"start"},nD={type:"end"},sD=new ps,aD=new ss,oD=Math.cos(70*Gi.DEG2RAD),lD=new Wi,uD=2*Math.PI,cD=-1,hD=0,dD=1,pD=2,fD=3,mD=4,gD=5,_D=6,vD=1e-6;class bD extends lo{constructor(e,t=null){super(e,t),this.state=cD,this.target=new Wi,this.cursor=new Wi,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:P,MIDDLE:L,RIGHT:D},this.touches={ONE:U,TWO:F},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 Wi,this._lastQuaternion=new Hi,this._lastTargetPosition=new Wi,this._quat=(new Hi).setFromUnitVectors(e.up,new Wi(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new ao,this._sphericalDelta=new ao,this._scale=1,this._panOffset=new Wi,this._rotateStart=new Vi,this._rotateEnd=new Vi,this._rotateDelta=new Vi,this._panStart=new Vi,this._panEnd=new Vi,this._panDelta=new Vi,this._dollyStart=new Vi,this._dollyEnd=new Vi,this._dollyDelta=new Vi,this._dollyDirection=new Wi,this._mouse=new Vi,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=xD.bind(this),this._onPointerDown=yD.bind(this),this._onPointerUp=SD.bind(this),this._onContextMenu=CD.bind(this),this._onMouseWheel=ED.bind(this),this._onKeyDown=wD.bind(this),this._onTouchStart=AD.bind(this),this._onTouchMove=RD.bind(this),this._onMouseDown=TD.bind(this),this._onMouseMove=MD.bind(this),this._interceptControlDown=ND.bind(this),this._interceptControlUp=PD.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.ownerDocument.addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.state=cD,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.ownerDocument.removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.ownerDocument.removeEventListener("keyup",this._interceptControlUp,{capture:!0}),this._controlActive=!1,this._pointers.length=0,this._pointerPositions={},this.domElement.style.touchAction="",this.domElement.style.cursor="auto"}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){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(iD),this.update(),this.state=cD}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;lD.copy(t).sub(this.target),lD.applyQuaternion(this._quat),this._spherical.setFromVector3(lD),this.autoRotate&&this.state===cD&&this._rotateLeft(this._getAutoRotationAngle(e)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let i=this.minAzimuthAngle,r=this.maxAzimuthAngle;isFinite(i)&&isFinite(r)&&(i<-Math.PI?i+=uD:i>Math.PI&&(i-=uD),r<-Math.PI?r+=uD:r>Math.PI&&(r-=uD),this._spherical.theta=i<=r?Math.max(i,Math.min(r,this._spherical.theta)):this._spherical.theta>(i+r)/2?Math.max(i,this._spherical.theta):Math.min(r,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),!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 n=!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),n=e!=this._spherical.radius}if(lD.setFromSpherical(this._spherical),lD.applyQuaternion(this._quatInverse),t.copy(this.target).add(lD),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=lD.length();e=this._clampDistance(t*this._scale);const i=t-e;this.object.position.addScaledVector(this._dollyDirection,i),this.object.updateMatrixWorld(),n=!!i}else if(this.object.isOrthographicCamera){const t=new Wi(this._mouse.x,this._mouse.y,0);t.unproject(this.object);const i=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),n=i!==this.object.zoom;const r=new Wi(this._mouse.x,this._mouse.y,0);r.unproject(this.object),this.object.position.sub(r).add(t),this.object.updateMatrixWorld(),e=lD.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):(sD.origin.copy(this.object.position),sD.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(sD.direction))<oD?this.object.lookAt(this.target):(aD.setFromNormalAndCoplanarPoint(this.object.up,this.target),sD.intersectPlane(aD,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(),n=!0)}return this._scale=1,this._performCursorZoom=!1,!!(n||this._lastPosition.distanceToSquared(this.object.position)>vD||8*(1-this._lastQuaternion.dot(this.object.quaternion))>vD||this._lastTargetPosition.distanceToSquared(this.target)>vD)&&(this.dispatchEvent(iD),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0)}_getAutoRotationAngle(e){return null!==e?uD/60*this.autoRotateSpeed*e:uD/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){lD.setFromMatrixColumn(t,0),lD.multiplyScalar(-e),this._panOffset.add(lD)}_panUp(e,t){!0===this.screenSpacePanning?lD.setFromMatrixColumn(t,1):(lD.setFromMatrixColumn(t,0),lD.crossVectors(this.object.up,lD)),lD.multiplyScalar(e),this._panOffset.add(lD)}_pan(e,t){const i=this.domElement;if(this.object.isPerspectiveCamera){const r=this.object.position;lD.copy(r).sub(this.target);let n=lD.length();n*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*n/i.clientHeight,this.object.matrix),this._panUp(2*t*n/i.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/i.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/i.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){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 i=this.domElement.getBoundingClientRect(),r=e-i.left,n=t-i.top,s=i.width,a=i.height;this._mouse.x=r/s*2-1,this._mouse.y=-n/a*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientY),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(uD*this._rotateDelta.x/t.clientHeight),this._rotateUp(uD*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.zoomToCursor&&(this._performCursorZoom=!0,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()),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(uD*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(-uD*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(uD*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(-uD*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),i=.5*(e.pageX+t.x),r=.5*(e.pageY+t.y);this._rotateStart.set(i,r)}}_handleTouchStartPan(e){if(1===this._pointers.length)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),r=.5*(e.pageY+t.y);this._panStart.set(i,r)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),i=e.pageX-t.x,r=e.pageY-t.y,n=Math.sqrt(i*i+r*r);this._dollyStart.set(0,n)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(1==this._pointers.length)this._rotateEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),r=.5*(e.pageY+t.y);this._rotateEnd.set(i,r)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(uD*this._rotateDelta.x/t.clientHeight),this._rotateUp(uD*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(1===this._pointers.length)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),r=.5*(e.pageY+t.y);this._panEnd.set(i,r)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),i=e.pageX-t.x,r=e.pageY-t.y,n=Math.sqrt(i*i+r*r);this._dollyEnd.set(0,n),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 Vi,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){const t=e.deltaMode,i={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:i.deltaY*=16;break;case 2:i.deltaY*=100}return e.ctrlKey&&!this._controlActive&&(i.deltaY*=10),i}}function yD(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 xD(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchMove(e):this._onMouseMove(e))}function SD(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(nD),this.state=cD,"grab"===this._cursorStyle&&(this.domElement.style.cursor="grab");break;case 1:const t=this._pointers[0],i=this._pointerPositions[t];this._onTouchStart({pointerId:t,pageX:i.x,pageY:i.y})}}function TD(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 L:if(!1===this.enableZoom)return;this._handleMouseDownDolly(e),this.state=dD;break;case P:if(e.ctrlKey||e.metaKey||e.shiftKey){if(!1===this.enablePan)return;this._handleMouseDownPan(e),this.state=pD}else{if(!1===this.enableRotate)return;this._handleMouseDownRotate(e),this.state=hD}break;case D:if(e.ctrlKey||e.metaKey||e.shiftKey){if(!1===this.enableRotate)return;this._handleMouseDownRotate(e),this.state=hD}else{if(!1===this.enablePan)return;this._handleMouseDownPan(e),this.state=pD}break;default:this.state=cD}this.state!==cD&&this.dispatchEvent(rD)}function MD(e){switch(this.state){case hD:if(!1===this.enableRotate)return;this._handleMouseMoveRotate(e);break;case dD:if(!1===this.enableZoom)return;this._handleMouseMoveDolly(e);break;case pD:if(!1===this.enablePan)return;this._handleMouseMovePan(e)}}function ED(e){!1!==this.enabled&&!1!==this.enableZoom&&this.state===cD&&(e.preventDefault(),this.dispatchEvent(rD),this._handleMouseWheel(this._customWheelEvent(e)),this.dispatchEvent(nD))}function wD(e){!1!==this.enabled&&this._handleKeyDown(e)}function AD(e){switch(this._trackPointer(e),this._pointers.length){case 1:switch(this.touches.ONE){case U:if(!1===this.enableRotate){this.state=cD;break}this._handleTouchStartRotate(e),this.state=fD;break;case I:if(!1===this.enablePan){this.state=cD;break}this._handleTouchStartPan(e),this.state=mD;break;default:this.state=cD}break;case 2:switch(this.touches.TWO){case F:if(!1===this.enableZoom&&!1===this.enablePan)return;this._handleTouchStartDollyPan(e),this.state=gD;break;case O:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchStartDollyRotate(e),this.state=_D;break;default:this.state=cD}break;default:this.state=cD}this.state!==cD&&this.dispatchEvent(rD)}function RD(e){switch(this._trackPointer(e),this.state){case fD:if(!1===this.enableRotate)return;this._handleTouchMoveRotate(e),this.update();break;case mD:if(!1===this.enablePan)return;this._handleTouchMovePan(e),this.update();break;case gD:if(!1===this.enableZoom&&!1===this.enablePan)return;this._handleTouchMoveDollyPan(e),this.update();break;case _D:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchMoveDollyRotate(e),this.update();break;default:this.state=cD}}function CD(e){!1!==this.enabled&&e.preventDefault()}function ND(e){"Control"===e.key&&(this._controlActive=!0,this.domElement.ownerDocument.addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function PD(e){"Control"===e.key&&(this._controlActive=!1,this.domElement.ownerDocument.removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}const LD={type:"change"},DD=1e-6,UD=new Hi;class ID extends lo{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 Wi(0,0,0),this._rotationVector=new Wi(0,0,0),this._lastQuaternion=new Hi,this._lastPosition=new Wi,this._status=0,this._onKeyDown=FD.bind(this),this._onKeyUp=OD.bind(this),this._onPointerMove=kD.bind(this),this._onPointerDown=BD.bind(this),this._onPointerUp=zD.bind(this),this._onPointerCancel=GD.bind(this),this._onContextMenu=VD.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),this.domElement.style.touchAction="none"}disconnect(){window.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("keyup",this._onKeyUp),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerCancel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction=""}dispose(){this.disconnect()}update(e){if(!1===this.enabled)return;const t=this.object,i=e*this.movementSpeed,r=e*this.rollSpeed;t.translateX(this._moveVector.x*i),t.translateY(this._moveVector.y*i),t.translateZ(this._moveVector.z*i),UD.set(this._rotationVector.x*r,this._rotationVector.y*r,this._rotationVector.z*r,1).normalize(),t.quaternion.multiply(UD),(this._lastPosition.distanceToSquared(t.position)>DD||8*(1-this._lastQuaternion.dot(t.quaternion))>DD)&&(this.dispatchEvent(LD),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 FD(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 OD(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 BD(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 kD(e){if(!1!==this.enabled&&(!this.dragToLook||this._status>0)){const t=this._getContainerDimensions(),i=t.size[0]/2,r=t.size[1]/2;this._moveState.yawLeft=-(e.pageX-t.offset[0]-i)/i,this._moveState.pitchDown=(e.pageY-t.offset[1]-r)/r,this._updateRotationVector()}}function zD(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 GD(){!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 VD(e){!1!==this.enabled&&e.preventDefault()}const HD={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 WD{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 jD=new ja(-1,1,1,-1,0,1);const $D=new class extends Zn{constructor(){super(),this.setAttribute("position",new kn([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new kn([0,2,0,0,2,0],2))}};class XD{constructor(e){this._mesh=new ws($D,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,jD)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class qD extends WD{constructor(e,t="tDiffuse"){super(),this.textureID=t,this.uniforms=null,this.material=null,e instanceof la?(this.uniforms=e.uniforms,this.material=e):e&&(this.uniforms=oa.clone(e.uniforms),this.material=new la({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 XD(this.material)}render(e,t,i){this.uniforms[this.textureID]&&(this.uniforms[this.textureID].value=i.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 YD extends WD{constructor(e,t){super(),this.scene=e,this.camera=t,this.clear=!0,this.needsSwap=!1,this.inverse=!1}render(e,t,i){const r=e.getContext(),n=e.state;let s,a;n.buffers.color.setMask(!1),n.buffers.depth.setMask(!1),n.buffers.color.setLocked(!0),n.buffers.depth.setLocked(!0),this.inverse?(s=0,a=1):(s=1,a=0),n.buffers.stencil.setTest(!0),n.buffers.stencil.setOp(r.REPLACE,r.REPLACE,r.REPLACE),n.buffers.stencil.setFunc(r.ALWAYS,s,4294967295),n.buffers.stencil.setClear(a),n.buffers.stencil.setLocked(!0),e.setRenderTarget(i),this.clear&&e.clear(),e.render(this.scene,this.camera),e.setRenderTarget(t),this.clear&&e.clear(),e.render(this.scene,this.camera),n.buffers.color.setLocked(!1),n.buffers.depth.setLocked(!1),n.buffers.color.setMask(!0),n.buffers.depth.setMask(!0),n.buffers.stencil.setLocked(!1),n.buffers.stencil.setFunc(r.EQUAL,1,4294967295),n.buffers.stencil.setOp(r.KEEP,r.KEEP,r.KEEP),n.buffers.stencil.setLocked(!0)}}class KD extends WD{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}}class ZD{constructor(e,t){if(this.renderer=e,this._pixelRatio=e.getPixelRatio(),void 0===t){const i=e.getSize(new Vi);this._width=i.width,this._height=i.height,(t=new hr(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 qD(HD),this.copyPass.material.blending=0,this.timer=new to}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 i=!1;for(let t=0,r=this.passes.length;t<r;t++){const r=this.passes[t];if(!1!==r.enabled){if(r.renderToScreen=this.renderToScreen&&this.isLastEnabledPass(t),r.render(this.renderer,this.writeBuffer,this.readBuffer,e,i),r.needsSwap){if(i){const t=this.renderer.getContext(),i=this.renderer.state.buffers.stencil;i.setFunc(t.NOTEQUAL,1,4294967295),this.copyPass.render(this.renderer,this.writeBuffer,this.readBuffer,e),i.setFunc(t.EQUAL,1,4294967295)}this.swapBuffers()}void 0!==YD&&(r instanceof YD?i=!0:r instanceof KD&&(i=!1))}}this.renderer.setRenderTarget(t)}reset(e){if(void 0===e){const t=this.renderer.getSize(new Vi);this._pixelRatio=this.renderer.getPixelRatio(),this._width=t.width,this._height=t.height,(e=this.renderTarget1.clone()).setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.renderTarget1=e,this.renderTarget2=e.clone(),this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2}setSize(e,t){this._width=e,this._height=t;const i=this._width*this._pixelRatio,r=this._height*this._pixelRatio;this.renderTarget1.setSize(i,r),this.renderTarget2.setSize(i,r);for(let e=0;e<this.passes.length;e++)this.passes[e].setSize(i,r)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.copyPass.dispose()}}class QD extends WD{constructor(e,t,i=null,r=null,n=null){super(),this.scene=e,this.camera=t,this.overrideMaterial=i,this.clearColor=r,this.clearAlpha=n,this.clear=!0,this.clearDepth=!1,this.needsSwap=!1,this.isRenderPass=!0,this._oldClearColor=new Yr}render(e,t,i){const r=e.autoClear;let n,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&&(n=e.getClearAlpha(),e.setClearAlpha(this.clearAlpha)),1==this.clearDepth&&e.clearDepth(),e.setRenderTarget(this.renderToScreen?null:i),!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(n),null!==this.overrideMaterial&&(this.scene.overrideMaterial=s),e.autoClear=r}}function JD(){return JD=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var r in i)({}).hasOwnProperty.call(i,r)&&(e[r]=i[r])}return e},JD.apply(null,arguments)}function eU(e,t){return eU=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},eU(e,t)}function tU(e){return tU=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},tU(e)}function iU(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(iU=function(){return!!e})()}function rU(e){var t="function"==typeof Map?new Map:void 0;return rU=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,i)}function i(){return function(e,t,i){if(iU())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var n=new(e.bind.apply(e,r));return i&&eU(n,i.prototype),n}(e,arguments,tU(this).constructor)}return i.prototype=Object.create(e.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),eU(i,e)},rU(e)}var nU={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 sU(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];var r,n=t[0],s=[];for(r=1;r<t.length;r+=1)s.push(t[r]);return s.forEach(function(e){n=n.replace(/%[a-z]/,e)}),n}var aU=function(e){function t(t){var i;if("production"===process.env.NODE_ENV)i=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 r=arguments.length,n=new Array(r>1?r-1:0),s=1;s<r;s++)n[s-1]=arguments[s];i=e.call(this,sU.apply(void 0,[nU[t]].concat(n)))||this}return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(i)}return function(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,eU(e,t)}(t,e),t}(rU(Error));function oU(e){return Math.round(255*e)}function lU(e,t,i){return oU(e)+","+oU(t)+","+oU(i)}function uU(e,t,i,r){if(void 0===r&&(r=lU),0===t)return r(i,i,i);var n=(e%360+360)%360/60,s=(1-Math.abs(2*i-1))*t,a=s*(1-Math.abs(n%2-1)),o=0,l=0,u=0;n>=0&&n<1?(o=s,l=a):n>=1&&n<2?(o=a,l=s):n>=2&&n<3?(l=s,u=a):n>=3&&n<4?(l=a,u=s):n>=4&&n<5?(o=a,u=s):n>=5&&n<6&&(o=s,u=a);var c=i-s/2;return r(o+c,l+c,u+c)}var cU={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 hU=/^#[a-fA-F0-9]{6}$/,dU=/^#[a-fA-F0-9]{8}$/,pU=/^#[a-fA-F0-9]{3}$/,fU=/^#[a-fA-F0-9]{4}$/,mU=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,gU=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,_U=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,vU=/^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 bU(e){if("string"!=typeof e)throw new aU(3);var t=function(e){if("string"!=typeof e)return e;var t=e.toLowerCase();return cU[t]?"#"+cU[t]:e}(e);if(t.match(hU))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(dU)){var i=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:i}}if(t.match(pU))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(fU)){var r=parseFloat((parseInt(""+t[4]+t[4],16)/255).toFixed(2));return{red:parseInt(""+t[1]+t[1],16),green:parseInt(""+t[2]+t[2],16),blue:parseInt(""+t[3]+t[3],16),alpha:r}}var n=mU.exec(t);if(n)return{red:parseInt(""+n[1],10),green:parseInt(""+n[2],10),blue:parseInt(""+n[3],10)};var s=gU.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=_U.exec(t);if(a){var o="rgb("+uU(parseInt(""+a[1],10),parseInt(""+a[2],10)/100,parseInt(""+a[3],10)/100)+")",l=mU.exec(o);if(!l)throw new aU(4,t,o);return{red:parseInt(""+l[1],10),green:parseInt(""+l[2],10),blue:parseInt(""+l[3],10)}}var u=vU.exec(t.substring(0,50));if(u){var c="rgb("+uU(parseInt(""+u[1],10),parseInt(""+u[2],10)/100,parseInt(""+u[3],10)/100)+")",h=mU.exec(c);if(!h)throw new aU(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 aU(5)}function yU(e){return function(e){var t,i=e.red/255,r=e.green/255,n=e.blue/255,s=Math.max(i,r,n),a=Math.min(i,r,n),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 i:t=(r-n)/l+(r<n?6:0);break;case r:t=(n-i)/l+2;break;default:t=(i-r)/l+4}return t*=60,void 0!==e.alpha?{hue:t,saturation:u,lightness:o,alpha:e.alpha}:{hue:t,saturation:u,lightness:o}}(bU(e))}var xU=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 SU(e){var t=e.toString(16);return 1===t.length?"0"+t:t}function TU(e){return SU(Math.round(255*e))}function MU(e,t,i){return xU("#"+TU(e)+TU(t)+TU(i))}function EU(e,t,i){return uU(e,t,i,MU)}function wU(e,t,i){if("number"==typeof e&&"number"==typeof t&&"number"==typeof i)return xU("#"+SU(e)+SU(t)+SU(i));if("object"==typeof e&&void 0===t&&void 0===i)return xU("#"+SU(e.red)+SU(e.green)+SU(e.blue));throw new aU(6)}function AU(e,t,i,r){if("object"==typeof e&&void 0===t&&void 0===i&&void 0===r)return e.alpha>=1?wU(e.red,e.green,e.blue):"rgba("+e.red+","+e.green+","+e.blue+","+e.alpha+")";throw new aU(7)}function RU(e){if("object"!=typeof e)throw new aU(8);if(function(e){return"number"==typeof e.red&&"number"==typeof e.green&&"number"==typeof e.blue&&"number"==typeof e.alpha}(e))return AU(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 wU(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,i,r){if("object"==typeof e&&void 0===t&&void 0===i&&void 0===r)return e.alpha>=1?EU(e.hue,e.saturation,e.lightness):"rgba("+uU(e.hue,e.saturation,e.lightness)+","+e.alpha+")";throw new aU(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,i){if("object"==typeof e&&void 0===t&&void 0===i)return EU(e.hue,e.saturation,e.lightness);throw new aU(1)}(e);throw new aU(8)}function CU(e,t,i){return function(){var r=i.concat(Array.prototype.slice.call(arguments));return r.length>=t?e.apply(this,r):CU(e,t,r)}}function NU(e){return CU(e,e.length,[])}function PU(e,t,i){return Math.max(e,Math.min(t,i))}NU(function(e,t){if("transparent"===t)return t;var i=yU(t);return RU(JD({},i,{hue:i.hue+parseFloat(e)}))}),NU(function(e,t){if("transparent"===t)return t;var i=yU(t);return RU(JD({},i,{lightness:PU(0,1,i.lightness-parseFloat(e))}))}),NU(function(e,t){if("transparent"===t)return t;var i=yU(t);return RU(JD({},i,{saturation:PU(0,1,i.saturation-parseFloat(e))}))}),NU(function(e,t){if("transparent"===t)return t;var i=yU(t);return RU(JD({},i,{lightness:PU(0,1,i.lightness+parseFloat(e))}))});var LU=NU(function(e,t,i){if("transparent"===t)return i;if("transparent"===i)return t;if(0===e)return i;var r=bU(t),n=JD({},r,{alpha:"number"==typeof r.alpha?r.alpha:1}),s=bU(i),a=JD({},s,{alpha:"number"==typeof s.alpha?s.alpha:1}),o=n.alpha-a.alpha,l=2*parseFloat(e)-1,u=((l*o===-1?l:l+o)/(1+l*o)+1)/2,c=1-u;return AU({red:Math.floor(n.red*u+a.red*c),green:Math.floor(n.green*u+a.green*c),blue:Math.floor(n.blue*u+a.blue*c),alpha:n.alpha*parseFloat(e)+a.alpha*(1-parseFloat(e))})}),DU=LU;var UU=NU(function(e,t){if("transparent"===t)return t;var i=bU(t);return AU(JD({},i,{alpha:PU(0,1,(100*("number"==typeof i.alpha?i.alpha:1)+100*parseFloat(e))/100)}))}),IU=UU;NU(function(e,t){if("transparent"===t)return t;var i=yU(t);return RU(JD({},i,{saturation:PU(0,1,i.saturation+parseFloat(e))}))}),NU(function(e,t){return"transparent"===t?t:RU(JD({},yU(t),{hue:parseFloat(e)}))}),NU(function(e,t){return"transparent"===t?t:RU(JD({},yU(t),{lightness:parseFloat(e)}))}),NU(function(e,t){return"transparent"===t?t:RU(JD({},yU(t),{saturation:parseFloat(e)}))}),NU(function(e,t){return"transparent"===t?t:DU(parseFloat(e),"rgb(0, 0, 0)",t)}),NU(function(e,t){return"transparent"===t?t:DU(parseFloat(e),"rgb(255, 255, 255)",t)}),NU(function(e,t){if("transparent"===t)return t;var i=bU(t);return AU(JD({},i,{alpha:PU(0,1,+(100*("number"==typeof i.alpha?i.alpha:1)-100*parseFloat(e)).toFixed(2)/100)}))});var FU=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-FU.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*FU.Bounce.In(2*e):.5*FU.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}}}}),OU=function(){return performance.now()},BU=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=[],i=0;i<arguments.length;i++)t[i]=arguments[i];for(var r=0,n=t;r<n.length;r++){var s=n[r];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 i=0,r=e;i<r.length;i++){var n=r[i];n._group=void 0,delete this._tweens[n.getId()],delete this._tweensAddedDuringUpdate[n.getId()]}},e.prototype.allStopped=function(){return this.getAll().every(function(e){return!e.isPlaying()})},e.prototype.update=function(e,t){void 0===e&&(e=OU()),void 0===t&&(t=!0);var i=Object.keys(this._tweens);if(0!==i.length)for(;i.length>0;){this._tweensAddedDuringUpdate={};for(var r=0;r<i.length;r++){var n=this._tweens[i[r]],s=!t;n&&!1===n.update(e,s)&&!t&&this.remove(n)}i=Object.keys(this._tweensAddedDuringUpdate)}},e}(),kU={Linear:function(e,t){var i=e.length-1,r=i*t,n=Math.floor(r),s=kU.Utils.Linear;return t<0?s(e[0],e[1],r):t>1?s(e[i],e[i-1],i-r):s(e[n],e[n+1>i?i:n+1],r-n)},Utils:{Linear:function(e,t,i){return(t-e)*i+e}}},zU=function(){function e(){}return e.nextId=function(){return e._nextId++},e._nextId=0,e}(),GU=new BU,VU=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=FU.Linear.None,this._interpolationFunction=kU.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=zU.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=GU,GU.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=OU()),void 0===t&&(t=!1),this._isPlaying)return this;if(this._repeat=this._initialRepeat,this._reversed)for(var i in this._reversed=!1,this._valuesStartRepeat)this._swapEndStartRepeatValues(i),this._valuesStart[i]=this._valuesStartRepeat[i];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 r={};for(var n in this._valuesEnd)r[n]=this._valuesEnd[n];this._valuesEnd=r}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,i,r,n){for(var s in i){var a=e[s],o=Array.isArray(a),l=o?"array":typeof a,u=!o&&Array.isArray(i[s]);if("undefined"!==l&&"function"!==l){if(u){if(0===(g=i[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&&(i[s]=c)}if("object"!==l&&!o||!a||u)(void 0===t[s]||n)&&(t[s]=a),o||(t[s]*=1),r[s]=u?i[s].slice().reverse():t[s]||0;else{t[s]=o?[]:{};var f=a;for(var m in f)t[s][m]=f[m];r[s]=o?[]:{};var g=i[s];if(!this._isDynamic){var _={};for(var m in g)_[m]=g[m];i[s]=g=_}this._setupProperties(f,t[s],g,r[s],n)}}}},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=OU()),this._isPaused||!this._isPlaying||(this._isPaused=!0,this._pauseStart=e),this},e.prototype.resume=function(e){return void 0===e&&(e=OU()),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=FU.Linear.None),this._easingFunction=e,this},e.prototype.interpolation=function(e){return void 0===e&&(e=kU.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,i){var r,n,s=this;if(void 0===t&&(t=OU()),void 0===i&&(i=e.autoStartOnUpdate),this._isPaused)return!0;if(!this._goToEnd&&!this._isPlaying){if(!i)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!==(r=this._repeatDelayTime)&&void 0!==r?r: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,i=Math.min(t/s._duration,1);return 0===i&&a===s._duration?1:i}(),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(n in isFinite(this._repeat)&&(this._repeat-=h),this._valuesStartRepeat)this._yoyo||"string"!=typeof this._valuesEnd[n]||(this._valuesStartRepeat[n]=this._valuesStartRepeat[n]+parseFloat(this._valuesEnd[n])),this._yoyo&&this._swapEndStartRepeatValues(n),this._valuesStart[n]=this._valuesStartRepeat[n];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,i,r){for(var n in i)if(void 0!==t[n]){var s=t[n]||0,a=i[n],o=Array.isArray(e[n]),l=Array.isArray(a);!o&&l?e[n]=this._interpolationFunction(a,r):"object"==typeof a&&a?this._updateProperties(e[n],s,a,r):"number"==typeof(a=this._handleRelativeValue(s,a))&&(e[n]=s+(a-s)*r)}},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],i=this._valuesEnd[e];this._valuesStartRepeat[e]="string"==typeof i?this._valuesStartRepeat[e]+parseFloat(i):this._valuesEnd[e],this._valuesEnd[e]=t},e.autoStartOnUpdate=!1,e}();zU.nextId;var HU=GU;HU.getAll.bind(HU),HU.removeAll.bind(HU),HU.add.bind(HU),HU.remove.bind(HU),HU.update.bind(HU);var WU="http://www.w3.org/1999/xhtml",jU={svg:"http://www.w3.org/2000/svg",xhtml:WU,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function $U(e){var t=e+="",i=t.indexOf(":");return i>=0&&"xmlns"!==(t=e.slice(0,i))&&(e=e.slice(i+1)),jU.hasOwnProperty(t)?{space:jU[t],local:e}:e}function XU(e){return function(){var t=this.ownerDocument,i=this.namespaceURI;return i===WU&&t.documentElement.namespaceURI===WU?t.createElement(e):t.createElementNS(i,e)}}function qU(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function YU(e){var t=$U(e);return(t.local?qU:XU)(t)}function KU(){}function ZU(e){return null==e?KU:function(){return this.querySelector(e)}}function QU(){return[]}function JU(e){return function(){return function(e){return null==e?[]:Array.isArray(e)?e:Array.from(e)}(e.apply(this,arguments))}}function eI(e){return function(t){return t.matches(e)}}var tI=Array.prototype.find;function iI(){return this.firstElementChild}var rI=Array.prototype.filter;function nI(){return Array.from(this.children)}function sI(e){return new Array(e.length)}function aI(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}function oI(e,t,i,r,n,s){for(var a,o=0,l=t.length,u=s.length;o<u;++o)(a=t[o])?(a.__data__=s[o],r[o]=a):i[o]=new aI(e,s[o]);for(;o<l;++o)(a=t[o])&&(n[o]=a)}function lI(e,t,i,r,n,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)?n[o]=l:c.set(u,l));for(o=0;o<d;++o)u=a.call(e,s[o],o,s)+"",(l=c.get(u))?(r[o]=l,l.__data__=s[o],c.delete(u)):i[o]=new aI(e,s[o]);for(o=0;o<h;++o)(l=t[o])&&c.get(p[o])===l&&(n[o]=l)}function uI(e){return e.__data__}function cI(e){return"object"==typeof e&&"length"in e?e:Array.from(e)}function hI(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function dI(e){return function(){this.removeAttribute(e)}}function pI(e){return function(){this.removeAttributeNS(e.space,e.local)}}function fI(e,t){return function(){this.setAttribute(e,t)}}function mI(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function gI(e,t){return function(){var i=t.apply(this,arguments);null==i?this.removeAttribute(e):this.setAttribute(e,i)}}function _I(e,t){return function(){var i=t.apply(this,arguments);null==i?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,i)}}function vI(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function bI(e){return function(){this.style.removeProperty(e)}}function yI(e,t,i){return function(){this.style.setProperty(e,t,i)}}function xI(e,t,i){return function(){var r=t.apply(this,arguments);null==r?this.style.removeProperty(e):this.style.setProperty(e,r,i)}}function SI(e){return function(){delete this[e]}}function TI(e,t){return function(){this[e]=t}}function MI(e,t){return function(){var i=t.apply(this,arguments);null==i?delete this[e]:this[e]=i}}function EI(e){return e.trim().split(/^|\s+/)}function wI(e){return e.classList||new AI(e)}function AI(e){this._node=e,this._names=EI(e.getAttribute("class")||"")}function RI(e,t){for(var i=wI(e),r=-1,n=t.length;++r<n;)i.add(t[r])}function CI(e,t){for(var i=wI(e),r=-1,n=t.length;++r<n;)i.remove(t[r])}function NI(e){return function(){RI(this,e)}}function PI(e){return function(){CI(this,e)}}function LI(e,t){return function(){(t.apply(this,arguments)?RI:CI)(this,e)}}function DI(){this.textContent=""}function UI(e){return function(){this.textContent=e}}function II(e){return function(){var t=e.apply(this,arguments);this.textContent=null==t?"":t}}function FI(){this.innerHTML=""}function OI(e){return function(){this.innerHTML=e}}function BI(e){return function(){var t=e.apply(this,arguments);this.innerHTML=null==t?"":t}}function kI(){this.nextSibling&&this.parentNode.appendChild(this)}function zI(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function GI(){return null}function VI(){var e=this.parentNode;e&&e.removeChild(this)}function HI(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function WI(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function jI(e){return function(){var t=this.__on;if(t){for(var i,r=0,n=-1,s=t.length;r<s;++r)i=t[r],e.type&&i.type!==e.type||i.name!==e.name?t[++n]=i:this.removeEventListener(i.type,i.listener,i.options);++n?t.length=n:delete this.__on}}}function $I(e,t,i){return function(){var r,n=this.__on,s=function(e){return function(t){e.call(this,t,this.__data__)}}(t);if(n)for(var a=0,o=n.length;a<o;++a)if((r=n[a]).type===e.type&&r.name===e.name)return this.removeEventListener(r.type,r.listener,r.options),this.addEventListener(r.type,r.listener=s,r.options=i),void(r.value=t);this.addEventListener(e.type,s,i),r={type:e.type,name:e.name,value:t,listener:s,options:i},n?n.push(r):this.__on=[r]}}function XI(e,t,i){var r=vI(e),n=r.CustomEvent;"function"==typeof n?n=new n(t,i):(n=r.document.createEvent("Event"),i?(n.initEvent(t,i.bubbles,i.cancelable),n.detail=i.detail):n.initEvent(t,!1,!1)),e.dispatchEvent(n)}function qI(e,t){return function(){return XI(this,e,t)}}function YI(e,t){return function(){return XI(this,e,t.apply(this,arguments))}}aI.prototype={constructor:aI,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)}},AI.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 KI=[null];function ZI(e,t){this._groups=e,this._parents=t}ZI.prototype={constructor:ZI,select:function(e){"function"!=typeof e&&(e=ZU(e));for(var t=this._groups,i=t.length,r=new Array(i),n=0;n<i;++n)for(var s,a,o=t[n],l=o.length,u=r[n]=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 ZI(r,this._parents)},selectAll:function(e){e="function"==typeof e?JU(e):function(e){return null==e?QU:function(){return this.querySelectorAll(e)}}(e);for(var t=this._groups,i=t.length,r=[],n=[],s=0;s<i;++s)for(var a,o=t[s],l=o.length,u=0;u<l;++u)(a=o[u])&&(r.push(e.call(a,a.__data__,u,o)),n.push(a));return new ZI(r,n)},selectChild:function(e){return this.select(null==e?iI:function(e){return function(){return tI.call(this.children,e)}}("function"==typeof e?e:eI(e)))},selectChildren:function(e){return this.selectAll(null==e?nI:function(e){return function(){return rI.call(this.children,e)}}("function"==typeof e?e:eI(e)))},filter:function(e){"function"!=typeof e&&(e=function(e){return function(){return this.matches(e)}}(e));for(var t=this._groups,i=t.length,r=new Array(i),n=0;n<i;++n)for(var s,a=t[n],o=a.length,l=r[n]=[],u=0;u<o;++u)(s=a[u])&&e.call(s,s.__data__,u,a)&&l.push(s);return new ZI(r,this._parents)},data:function(e,t){if(!arguments.length)return Array.from(this,uI);var i=t?lI:oI,r=this._parents,n=this._groups;"function"!=typeof e&&(e=function(e){return function(){return e}}(e));for(var s=n.length,a=new Array(s),o=new Array(s),l=new Array(s),u=0;u<s;++u){var c=r[u],h=n[u],d=h.length,p=cI(e.call(c,c&&c.__data__,u,r)),f=p.length,m=o[u]=new Array(f),g=a[u]=new Array(f);i(c,h,m,g,l[u]=new Array(d),p,t);for(var _,v,b=0,y=0;b<f;++b)if(_=m[b]){for(b>=y&&(y=b+1);!(v=g[y])&&++y<f;);_._next=v||null}}return(a=new ZI(a,r))._enter=o,a._exit=l,a},enter:function(){return new ZI(this._enter||this._groups.map(sI),this._parents)},exit:function(){return new ZI(this._exit||this._groups.map(sI),this._parents)},join:function(e,t,i){var r=this.enter(),n=this,s=this.exit();return"function"==typeof e?(r=e(r))&&(r=r.selection()):r=r.append(e+""),null!=t&&(n=t(n))&&(n=n.selection()),null==i?s.remove():i(s),r&&n?r.merge(n).order():n},merge:function(e){for(var t=e.selection?e.selection():e,i=this._groups,r=t._groups,n=i.length,s=r.length,a=Math.min(n,s),o=new Array(n),l=0;l<a;++l)for(var u,c=i[l],h=r[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<n;++l)o[l]=i[l];return new ZI(o,this._parents)},selection:function(){return this},order:function(){for(var e=this._groups,t=-1,i=e.length;++t<i;)for(var r,n=e[t],s=n.length-1,a=n[s];--s>=0;)(r=n[s])&&(a&&4^r.compareDocumentPosition(a)&&a.parentNode.insertBefore(r,a),a=r);return this},sort:function(e){function t(t,i){return t&&i?e(t.__data__,i.__data__):!t-!i}e||(e=hI);for(var i=this._groups,r=i.length,n=new Array(r),s=0;s<r;++s){for(var a,o=i[s],l=o.length,u=n[s]=new Array(l),c=0;c<l;++c)(a=o[c])&&(u[c]=a);u.sort(t)}return new ZI(n,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,i=e.length;t<i;++t)for(var r=e[t],n=0,s=r.length;n<s;++n){var a=r[n];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,i=0,r=t.length;i<r;++i)for(var n,s=t[i],a=0,o=s.length;a<o;++a)(n=s[a])&&e.call(n,n.__data__,a,s);return this},attr:function(e,t){var i=$U(e);if(arguments.length<2){var r=this.node();return i.local?r.getAttributeNS(i.space,i.local):r.getAttribute(i)}return this.each((null==t?i.local?pI:dI:"function"==typeof t?i.local?_I:gI:i.local?mI:fI)(i,t))},style:function(e,t,i){return arguments.length>1?this.each((null==t?bI:"function"==typeof t?xI:yI)(e,t,null==i?"":i)):function(e,t){return e.style.getPropertyValue(t)||vI(e).getComputedStyle(e,null).getPropertyValue(t)}(this.node(),e)},property:function(e,t){return arguments.length>1?this.each((null==t?SI:"function"==typeof t?MI:TI)(e,t)):this.node()[e]},classed:function(e,t){var i=EI(e+"");if(arguments.length<2){for(var r=wI(this.node()),n=-1,s=i.length;++n<s;)if(!r.contains(i[n]))return!1;return!0}return this.each(("function"==typeof t?LI:t?NI:PI)(i,t))},text:function(e){return arguments.length?this.each(null==e?DI:("function"==typeof e?II:UI)(e)):this.node().textContent},html:function(e){return arguments.length?this.each(null==e?FI:("function"==typeof e?BI:OI)(e)):this.node().innerHTML},raise:function(){return this.each(kI)},lower:function(){return this.each(zI)},append:function(e){var t="function"==typeof e?e:YU(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})},insert:function(e,t){var i="function"==typeof e?e:YU(e),r=null==t?GI:"function"==typeof t?t:ZU(t);return this.select(function(){return this.insertBefore(i.apply(this,arguments),r.apply(this,arguments)||null)})},remove:function(){return this.each(VI)},clone:function(e){return this.select(e?WI:HI)},datum:function(e){return arguments.length?this.property("__data__",e):this.node().__data__},on:function(e,t,i){var r,n,s=function(e){return e.trim().split(/^|\s+/).map(function(e){var t="",i=e.indexOf(".");return i>=0&&(t=e.slice(i+1),e=e.slice(0,i)),{type:e,name:t}})}(e+""),a=s.length;if(!(arguments.length<2)){for(o=t?$I:jI,r=0;r<a;++r)this.each(o(s[r],t,i));return this}var o=this.node().__on;if(o)for(var l,u=0,c=o.length;u<c;++u)for(r=0,l=o[u];r<a;++r)if((n=s[r]).type===l.type&&n.name===l.name)return l.value},dispatch:function(e,t){return this.each(("function"==typeof t?YI:qI)(e,t))},[Symbol.iterator]:function*(){for(var e=this._groups,t=0,i=e.length;t<i;++t)for(var r,n=e[t],s=0,a=n.length;s<a;++s)(r=n[s])&&(yield r)}};var QI=0;function JI(){this._="@"+(++QI).toString(36)}JI.prototype={constructor:JI,get:function(e){for(var t=this._;!(t in e);)if(!(e=e.parentNode))return;return e[t]},set:function(e,t){return e[this._]=t},remove:function(e){return this._ in e&&delete e[this._]},toString:function(){return this._}};var eF,tF,iF,rF,nF,sF,aF,oF,lF,uF,cF,hF=Symbol.for("pv"),dF={},pF=[],fF=/^m(i|n|o|s|text|space)$/,mF=Array.isArray,gF=pF.slice,_F=Object.assign;function vF(e){e&&e.parentNode&&e.remove()}function bF(e,t,i){var r,n,s,a=_F({},e.props),o=arguments.length;for(s in t)"key"==s?r=t[s]:"ref"==s&&"function"!=typeof e.type?n=t[s]:a[s]=t[s];return o>2&&(a.children=o>3?gF.call(arguments,2):i),yF(e.type,a,void 0!==r?r:e.key,void 0!==n?n:e.ref,null)}function yF(e,t,i,r,n){var s={type:e,props:t,key:i,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:hF,__v:n||++tF,__i:-1,__u:0};return!n&&eF.vnode&&eF.vnode(s),s}function xF(e){return e.children}function SF(e,t){this.props=e,this.context=t,this.__g=0}function TF(e,t){if(null==t)return e.__&&TF(e.__,e.__i+1);for(var i;t<e.__k.length;t++)if((i=e.__k[t])&&i.__e)return i.__e;return"function"!=typeof e.type||e.props.__P?null:TF(e)}function MF(e){var t,i=e.__v,r=i.__e,n=[],s=[],a=e.__P;a&&((t=_F({constructor:hF},i)).__v=i.__v+1,eF.vnode&&eF.vnode(t),IF(a,t,i,e.__n,a.namespaceURI,32&i.__u?[r]:null,n,r||TF(i),32&i.__u,s),t.__v=i.__v,t.__.__k[t.__i]=t,BF(n,t,s),i.__=i.__e=null,t.__e!=r&&EF(t))}function EF(e){if((e=e.__)&&e.__c&&!e.props.__P)return e.__e=null,e.__k.some(function(t){return t&&(e.__e=t.__e)}),EF(e)}function wF(e){(8&e.__g||(e.__g|=8,rF.push(e),sF++))&&nF==eF.debounceRendering||((nF=eF.debounceRendering)||queueMicrotask)(AF)}function AF(){try{for(var e,t=1;rF.length;)rF.length>t&&rF.sort(aF),e=rF.shift(),t=rF.length,8&e.__g&&MF(e)}finally{(sF=rF.length)&&(nF||queueMicrotask)(AF)}}function RF(e,t,i,r,n,s,a,o,l,u,c){var h,d,p,f,m,g,_=r.__k||pF,v=t.length;for(l=CF(i,t,_,l,v),h=0;h<v;h++)null!=(p=i.__k[h])&&(d=~p.__i&&_[p.__i]||dF,p.__i=h,g=IF(e,p,d,n,s,a,o,l,u,c),f=p.__e,(d.ref!=p.ref||8&d.__u)&&(d.ref&&zF(d.ref,null,p,d),p.ref&&c.push(p.ref,p.__c||f,p)),m=m||f,4&p.__u?(l=NF(p,l,e,!d.__v),d.__e&&(d.__e=null)):"function"==typeof p.type&&void 0!==g?l=g:f&&(l=f.nextSibling),p.__u&=-21);return i.__e=m,l}function CF(e,t,i,r,n){var s,a,o,l,u,c,h,d,p,f=i.length,m=f,g=0,_=0,v=e.__k=Array(n);for(s=0;s<n;s++)null!=(a=t[s])&&"boolean"!=typeof a&&"function"!=typeof a?("object"!=typeof a||a.constructor===String?a=v[s]=yF(null,a):mF(a)?a=v[s]=yF(xF,{children:a}):a.constructor===hF&&a.__b?a=v[s]=yF(a.type,a.props,a.key,a.ref,a.__v):v[s]=a,l=s+g,a.__=e,a.__b=e.__b+1,o=null,~(u=a.__i=PF(a,i,l,m))&&(m--,(o=i[u])&&(o.__u|=2)),o&&o.__v?(a.__u|=16,u==l-1?g--:u==l+1?g++:u!=l&&(u>l?g--:g++,_=1)):(~u||(n>f?g--:n<f&&g++),"function"!=typeof a.type&&(a.__u|=4))):v[s]=null;if(_){for(c=[],h=[],s=0;s<n;s++)if((a=v[s])&&16&a.__u){for(g=0,d=c.length;g<d;)c[p=g+d>>1]<a.__i?g=p+1:d=p;c[g]=a.__i,h[s]=g+1}for(g=c.length;s--;)h[s]&&(h[s]==g?g--:v[s].__u|=4)}if(m)for(s=0;s<f;s++)!(o=i[s])||2&o.__u||(o.__e==r&&(r=TF(o)),GF(o,o));return r}function NF(e,t,i,r){var n,s,a,o;if("function"==typeof e.type){if(e.props.__P)return t;if(n=e.__k)for(s=0;s<n.length;s++)n[s]&&(n[s].__=e,t=NF(n[s],t,i,!1));return t}for(t&&!t.parentNode&&(t=TF(e))&&!t.parentNode&&(t=null),a=e.__e,o=t;o&&8==o.nodeType;)o=o.nextSibling;for(a!=o&&(!r&&i.moveBefore&&a.parentNode?i.moveBefore(a,t):i.insertBefore(a,t||null)),t=a;(t=t&&t.nextSibling)&&8==t.nodeType&&!t.data.startsWith("$s"););return t}function PF(e,t,i,r){var n,s=e.key,a=e.type,o=t[i],l=o&&!(2&o.__u);if(null===o&&null==s||l&&s==o.key&&a==o.type)return i;if(r>(l?1:0)){for(n=i-1;n>=0;n--)if((o=t[n])&&!(2&o.__u)&&s==o.key&&a==o.type)return n;for(n=i+1;n<t.length;n++)if((o=t[n])&&!(2&o.__u)&&s==o.key&&a==o.type)return n}return-1}function LF(e,t,i){null==i&&(i=""),"-"==t[0]?e.setProperty(t,i):e[t]=i}function DF(e,t,i,r,n){var s,a;if("style"==t)if("string"==typeof i)e.style.cssText=i;else{if("string"==typeof r&&(e.style.cssText=r=""),r)for(t in r)i&&t in i||LF(e.style,t);if(i)for(t in i)r&&i[t]==r[t]||LF(e.style,t,i[t])}else if("o"==t[0]&&"n"==t[1])"function"!=typeof i&&(i=null),"function"!=typeof r&&(r=null),(e.__e||(e.__e={}))[t]=i,i&&r||(a=cF[t]||(cF[t]=UF(t)),(e.__a||(e.__a={}))[t]=uF,s=t!=(t=t.replace(lF,"$1")),(t=t.slice(2))[0]<"a"&&(t=t.toLowerCase()),i?e.addEventListener(t,a,s):e.removeEventListener(t,a,s));else{if("http://www.w3.org/2000/svg"==n)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{return void(e[t]=null==i?"":i)}catch(e){}if("function"==typeof i)return;null==i||!1===i&&"-"!=t[4]?e.removeAttribute(t):e.setAttribute(t,"popover"==t&&1==i?"":i)}}function UF(e){return function(t){var i=this.__e;if(i){if(i=i[e],null==t[oF])t[oF]=uF++;else if(t[oF]<this.__a[e])return;return i(eF.event?eF.event(t):t)}}}function IF(e,t,i,r,n,s,a,o,l,u){var c,h,d,p,f,m,g,_,v,b,y,x,S,T,M,E,w,A,R=t.type;if(t.constructor!==hF)return null;128&i.__u&&(l=32&i.__u,c=i.__c.__z)&&(t.__u|=l,h=s=[],8==c.nodeType?o=FF(c,s):s.push(c),o=s[0]||o),(c=eF.__b)&&c(t);e:if("function"==typeof R){d=a.length;try{if(_=t.props,v=(c=R.prototype)&&c.render,b=(c=R.contextType)&&r[c.__c],y=c?b?b.props.value:c.__:r,(p=i.__c)?(t.__c=p,2&p.__g&&(p.__g|=1)):(v?t.__c=p=new R(_,y):(t.__c=p=new SF(_,y),p.constructor=R,p.render=VF),b&&b.sub(p),p.state||(p.state={}),p.__n=r,p.__g|=8,p.__h=[],p.__k=[]),v&&(p.__s||(p.__s=p.state),R.getDerivedStateFromProps&&(p.__s==p.state&&(p.__s=_F({},p.__s)),_F(p.__s,R.getDerivedStateFromProps(_,p.__s)))),f=p.props,m=p.state,p.__v=t,i.__c){if(_!==f&&v&&!R.getDerivedStateFromProps&&p.componentWillReceiveProps&&p.componentWillReceiveProps(_,y),t.__v==i.__v&&!(8&p.__g)||!(4&p.__g)&&p.shouldComponentUpdate&&!1===p.shouldComponentUpdate(_,p.__s,y)){t.__v!=i.__v&&(p.props=_,p.state=p.__s,p.__g&=-9),t.__e=i.__e,t.__k=i.__k,t.__k.some(function(e){e&&(e.__=t)}),pF.push.apply(p.__h,p.__k),p.__k=[],p.__h.length&&a.push(p),o=TF(i);break e}p.componentWillUpdate&&p.componentWillUpdate(_,p.__s,y),v&&p.componentDidUpdate&&p.__h.push(function(){p.componentDidUpdate(f,m,g)})}else v&&!R.getDerivedStateFromProps&&p.componentWillMount&&p.componentWillMount(),v&&p.componentDidMount&&p.__h.push(p.componentDidMount);p.context=y,p.props=_,p.__P=e,p.__g&=-5,x=eF.__r,S=v?25:0;do{p.__g&=-9,x&&x(t),c=p.render(p.props,p.state=p.__s,p.context)}while(8&p.__g&&++S<25);v&&(pF.push.apply(p.__h,p.__k),p.__k=[]),p.state=p.__s,p.getChildContext&&(r=_F({},r,p.getChildContext())),v&&i.__c&&p.getSnapshotBeforeUpdate&&(g=p.getSnapshotBeforeUpdate(f,m)),T=c&&c.type===xF&&null==c.key?c.props.children:c,_.__P&&(c=o,n=(e=_.__P).namespaceURI,l=s=null,i.props&&i.props.__P!=e&&(i.__k.some(function(e){e&&GF(e,e)}),i.__k=null),o=i.__k?TF(i,0):null),o=RF(e,mF(T)?T:[T],t,i,r,n,s,a,o,l,u),_.__P&&(t.__e=null,o=c),t.__u&=-161,h&&h.some(vF),p.__h.length&&a.push(p),1&p.__g&&(p.__g&=-4)}catch(e){if(a.length=d,t.__v=null,l||s)if(e&&e.then){if(t.__u|=128|l,s){for(~(w=s.indexOf(o||void 0))||(w=s.length);(A=s[w-1])&&8==A.nodeType;)w--;for(;w<s.length;w++)if(A=s[w])if(s[w]=null,M){if(A==E)break}else{if(8!=A.nodeType)break;A.data.startsWith("$s")&&(E=FF(M=A))}}if(!M){for(;o&&8==o.nodeType&&o.nextSibling;)o=o.nextSibling;M=o}(c=FF(M=t.__c.__z||(t.__c.__z=M)))?(t.__e=M,o=c):t.__e=o,o=o&&o.nextSibling}else s&&s.some(vF);else t.__e=i.__e;t.__k||(t.__k=i.__k||[]),e&&e.then||OF(t),eF.__e(e,t,i)}}else o=t.__e=kF(i.__e,t,i,r,n,s,a,l,u,e);return(c=eF.diffed)&&c(t),o}function FF(e,t){if(e&&8==e.nodeType&&e.data.startsWith("$s"))for(var i=1;e=e.nextSibling;){if(8==e.nodeType)if(e.data.startsWith("$s"))i++;else if(e.data.startsWith("/$s")&&! --i)return e;t&&t.push(e)}}function OF(e){e&&(e.__c&&(e.__c.__g|=4),e.__k&&e.__k.some(OF))}function BF(e,t,i){for(var r=0;r<i.length;)zF(i[r++],i[r++],i[r++]);eF.__c&&eF.__c(t,e),e.some(function(t){try{e=t.__h,t.__h=[],e.some(function(e){e.call(t)})}catch(e){eF.__e(e,t.__v)}})}function kF(e,t,i,r,n,s,a,o,l,u){var c,h,d,p,f,m,g,_,v=i.props||dF,b=t.props,y=t.type;if("svg"==y?n="http://www.w3.org/2000/svg":"math"==y?n="http://www.w3.org/1998/Math/MathML":n||(n="http://www.w3.org/1999/xhtml"),s)for(c=0;c<s.length;c++)if((f=s[c])&&(y?f.localName==y:3==f.nodeType)){e=f,s[c]=null;break}if(!e){if(_=u.ownerDocument||document,!y)return _.createTextNode(b);e=_.createElementNS(n,y,b.is?b:u),o&&(eF.__m&&eF.__m(t,s),o=!1),s=null}if(y){if(u="template"==y&&e.content||e,s="textarea"==y&&null!=b.defaultValue?null:s&&gF.call(u.childNodes),!o&&s)for(v={},c=0;c<e.attributes.length;c++)v[(f=e.attributes[c]).name]=f.value;for(c in v)f=v[c],"dangerouslySetInnerHTML"==c?d=f:"children"==c||c in b||"value"==c&&"defaultValue"in b||"checked"==c&&"defaultChecked"in b||DF(e,c,null,f,n);for(c in b)f=b[c],"children"==c?p=f:"dangerouslySetInnerHTML"==c?h=f:"value"==c?m=f:"checked"==c?g=f:o&&"function"!=typeof f||v[c]===f||DF(e,c,f,v[c],n);h?(o||d&&(h.__html==d.__html||h.__html==e.innerHTML)||(e.innerHTML=h.__html),t.__k=[]):(d&&(e.textContent=""),("foreignObject"==y||"http://www.w3.org/1998/Math/MathML"==n&&fF.test(y))&&(n="http://www.w3.org/1999/xhtml"),RF(u,mF(p)?p:[p],t,i,r,n,s,a,s?s[0]:i.__k&&TF(i,0),o,l),s&&s.some(vF)),o&&"textarea"!=y||(c="value","progress"==y&&null==m?e.removeAttribute(c):null==m||m===e[c]&&("progress"!=y||m)||DF(e,c,m,v[c],n),c="checked",null!=g&&g!=e[c]&&DF(e,c,g,v[c],n))}else v===b||o&&e.data==b||(e.data=b);return e}function zF(e,t,i,r){try{"function"==typeof e?t?t.__x=e(t)||1:r&&(r=r.__c||r.__e)&&(t=r.__x)&&(r.__x=null,"function"==typeof t?t():e(null)):e.current=t}catch(e){eF.__e(e,i)}}function GF(e,t,i){var r,n,s,a;if(eF.unmount&&eF.unmount(e),!(r=e.ref)||r.current&&r.current!=e.__e||zF(r,null,t,e),r=e.__c){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(e){eF.__e(e,t)}r.__P=r.__n=null}if(r=e.__k)for(a=0;a<r.length;a++)r[a]&&GF(r[a],t,"function"!=typeof e.type||i&&!e.props.__P);!i&&(r=e.__c)&&(r=r.__z)&&(n=FF(r,s=[]))&&(r==e.__e&&s.some(vF),vF(n),vF(r)),i||vF(e.__e),e.__e=e.__c=e.__=null}function VF(e,t,i){return this.constructor(e,i)}eF={__e:function(e,t,i,r){for(var n,s,a;t=t.__;)if((n=t.__c)&&!(1&n.__g)){n.__g|=4;try{if((a=(s=n.constructor)&&s.getDerivedStateFromError)&&n.setState(s.getDerivedStateFromError(e)),n.componentDidCatch&&(n.componentDidCatch(e,r||{}),a=1),a&&8&n.__g)return void(n.__g|=2)}catch(t){e=t}}throw sF=0,e}},tF=0,iF=function(e){return null!=e&&e.constructor===hF},SF.prototype.setState=function(e,t){var i=this.__s;i&&i!=this.state||(i=this.__s=_F({},this.state)),"function"==typeof e&&(e=e(_F({},i),this.props)),e&&(_F(i,e),this.__v&&(t&&this.__k.push(t),wF(this)))},SF.prototype.forceUpdate=function(e){this.__v&&(this.__g|=4,e&&this.__h.push(e),wF(this))},SF.prototype.render=xF,rF=[],sF=0,aF=function(e,t){return e.__v.__b-t.__v.__b},oF=Symbol(),lF=/(PointerCapture)$|Capture$/i,uF=0,cF={};const HF=e=>{if("object"!=typeof e)return e;const t=bF(e);return t.props&&(t.props={...t.props},t?.props?.children&&(t.props.children=Array.isArray(t.props.children)?t.props.children.map(HF):HF(t.props.children))),t},WF=(e,t)=>{delete t.__k,function(e,t){var i,r,n,s;eF.__&&eF.__(e,t),9==t.nodeType&&(t=t.documentElement),r=(i=e&&32&e.__u)?null:t.__k,t.__k=yF(xF,{children:[e]}),n=[],s=[],IF(t,t.__k,r||dF,dF,t.namespaceURI,r?null:t.firstChild?gF.call(t.childNodes):null,n,r?r.__e:t.firstChild,i,s),BF(n,t.__k,s),t.__k.props.children=null}(HF(e),t)};!function(e,t){void 0===t&&(t={});var i=t.insertAt;if("undefined"!=typeof document){var r=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css","top"===i&&r.firstChild?r.insertBefore(n,r.firstChild):r.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.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 jF=R({props:{content:{default:!1},offsetX:{triggerUpdate:!1},offsetY:{triggerUpdate:!1}},methods:{positionFromEvent(e,t){const i=e.container,r=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 i=t.ownerSVGElement||t;if(i.createSVGPoint){var r=i.createSVGPoint();return r.x=e.clientX,r.y=e.clientY,[(r=r.matrixTransform(t.getScreenCTM().inverse())).x,r.y]}if(t.getBoundingClientRect){var n=t.getBoundingClientRect();return[e.clientX-n.left-t.clientLeft,e.clientY-n.top-t.clientTop]}}return[e.pageX,e.pageY]}(t,i),n=i.offsetWidth,s=i.offsetHeight,a=[null===e.offsetX||void 0===e.offsetX?`-${r[0]/n*100}%`:"number"==typeof e.offsetX?`calc(-50% + ${e.offsetX}px)`:e.offsetX,null===e.offsetY||void 0===e.offsetY?s>130&&s-r[1]<100?"calc(-100% - 6px)":"21px":"number"==typeof e.offsetY?e.offsetY<0?`calc(-100% - ${Math.abs(e.offsetY)}px)`:`${e.offsetY}px`:e.offsetY];return e.tooltipEl.style("left",r[0]+"px").style("top",r[1]+"px").style("transform",`translate(${a.join(",")})`),this}},init:function(e,t,{style:i={}}={}){const r=function(e){return"string"==typeof e?new ZI([[document.querySelector(e)]],[document.documentElement]):new ZI([[e]],KI)}(!!e&&"object"==typeof e&&!!e.node&&"function"==typeof e.node?e.node():e);t.container=r.node(),"static"===r.style("position")&&r.style("position","relative"),t.tooltipEl=r.append("div").attr("class","float-tooltip-kap"),Object.entries(i).forEach(([e,i])=>t.tooltipEl.style(e,i)),t.tooltipEl.style("left","-10000px").style("display","none");const n=`tooltip-${Math.round(1e12*Math.random())}`;t.mouseInside=!1,r.on(`mousemove.${n}`,e=>{t.mouseInside=!0,this.positionFromEvent(e),t.content&&t.tooltipEl.style("display","inline")}),r.on(`mouseover.${n}`,()=>{t.mouseInside=!0,t.content&&t.tooltipEl.style("display","inline")}),r.on(`mouseout.${n}`,()=>{t.mouseInside=!1,t.tooltipEl.style("display","none")})},update:function(e){e.tooltipEl.style("display",e.content&&e.mouseInside?"inline":"none"),e.content?e.content instanceof HTMLElement?(e.tooltipEl.text(""),e.tooltipEl.append(()=>e.content)):"string"==typeof e.content?e.tooltipEl.html(e.content):(e=>iF(bF(e)))(e.content)?(e.tooltipEl.text(""),WF(e.content,e.tooltipEl.node())):(e.tooltipEl.style("display","none"),console.warn("Tooltip content is invalid, skipping.",e.content,e.content.toString())):e.tooltipEl.text("")}});!function(e,t){void 0===t&&(t={});var i=t.insertAt;if("undefined"!=typeof document){var r=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css","top"===i&&r.firstChild?r.insertBefore(n,r.firstChild):r.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.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}");const $F=e=>{e instanceof Array?e.forEach($F):(e.map&&e.map.dispose(),e.dispose())},XF=e=>{e.geometry&&e.geometry.dispose(),e.material&&$F(e.material),e.texture&&e.texture.dispose(),e.children&&e.children.forEach(XF)},qF=window.THREE?window.THREE:{WebGLRenderer:class{constructor(e={}){const{canvas:t=bi(),context:i=null,depth:r=!0,stencil:n=!1,alpha:s=!1,antialias:a=!1,premultipliedAlpha:o=!0,preserveDrawingBuffer:l=!1,powerPreference:u="default",failIfMajorPerformanceCaveat:c=!1,reversedDepthBuffer:h=!1,outputBufferType:d=ze}=e;let p;if(this.isWebGLRenderer=!0,null!==i){if("undefined"!=typeof WebGLRenderingContext&&i instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");p=i.getContextAttributes().alpha}else p=s;const f=d,m=new Set([ut,ot,st]),g=new Set([ze,je,He,Ke,qe,Ye]),_=new Uint32Array(4),v=new Int32Array(4),b={textures:[],min:[],max:[],resolution:[]};let y=null,x=null;const S=[],T=[];let M=null;this.domElement=t,this.debug={checkShaderErrors:!0,diagnostics:{keywords:!1},onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=0,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const E=this;let w=!1,A=null,R=null,C=null,P=null;this._outputColorSpace=Xt;let L=0,D=0,U=null,I=-1,F=null;const O=new ur,B=new ur;let k=null;const z=new Yr(0);let G=0,V=t.width,H=t.height,W=1,j=null,$=null;const X=new ur(0,0,V,H),q=new ur(0,0,V,H);let Y=!1;const K=new Gs,Z=new Hs;let Q=!1,J=!1;const ee=new fr,te=new Wi,ie=new ur,re={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let ne=!1;function se(){return null===U?W:1}let ae,oe,le,ue,ce,he,de,pe,fe,me,ge,_e,ve,be,ye,xe,Se,Te,Me,Ee,we,Ae,Re,Ce=i;function Ne(e,i){return t.getContext(e,i)}try{const e={alpha:!0,depth:r,stencil:n,antialias:a,premultipliedAlpha:o,preserveDrawingBuffer:l,powerPreference:u,failIfMajorPerformanceCaveat:c};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${N}`),t.addEventListener("webglcontextlost",Ue,!1),t.addEventListener("webglcontextrestored",Ie,!1),t.addEventListener("webglcontextcreationerror",Fe,!1),null===Ce){const t="webgl2";if(Ce=Ne(t,e),null===Ce)throw Ne(t)?new Error("THREE.WebGLRenderer: Error creating WebGL context with your selected attributes."):new Error("THREE.WebGLRenderer: Error creating WebGL context.")}Pe()}catch(e){throw t.removeEventListener("webglcontextlost",Ue,!1),t.removeEventListener("webglcontextrestored",Ie,!1),t.removeEventListener("webglcontextcreationerror",Fe,!1),Mi("WebGLRenderer: "+e.message),e}function Pe(){ae=new Do(Ce),ae.init(),we=new Gu(Ce,ae),oe=new So(Ce,ae,e,we),le=new ku(Ce,ae),oe.reversedDepthBuffer&&h&&le.buffers.depth.setReversed(!0),R=Ce.createFramebuffer(),C=Ce.createFramebuffer(),P=Ce.createFramebuffer(),ue=new Fo(Ce),ce=new Su,he=new zu(Ce,ae,le,ce,oe,we,ue),de=new Lo(E),pe=new ho(Ce),Ae=new yo(Ce,pe),fe=new Uo(Ce,pe,ue,Ae),me=new Bo(Ce,fe,pe,Ae,ue),Te=new Oo(Ce,oe,he),ye=new To(ce),ge=new xu(E,de,ae,oe,Ae,ye),_e=new $u(E,ce),ve=new wu,be=new Lu(ae),Se=new bo(E,de,le,me,p,o),xe=new Bu(E,me,oe),Re=new Xu(Ce,ue,oe,le),Me=new xo(Ce,ae,ue),Ee=new Io(Ce,ae,ue),ue.programs=ge.programs,E.capabilities=oe,E.extensions=ae,E.properties=ce,E.renderLists=ve,E.shadowMap=xe,E.state=le,E.info=ue}f!==ze&&(M=new zo(f,t.width,t.height,a,r,n));const De=new Hu(E,Ce);function Ue(e){e.preventDefault(),xi("WebGLRenderer: Context Lost."),w=!0}function Ie(){xi("WebGLRenderer: Context Restored."),w=!1;const e=ue.autoReset,t=xe.enabled,i=xe.autoUpdate,r=xe.needsUpdate,n=xe.type;Pe(),ue.autoReset=e,xe.enabled=t,xe.autoUpdate=i,xe.needsUpdate=r,xe.type=n}function Fe(e){Mi("WebGLRenderer: A WebGL context could not be created. Reason: ",e.statusMessage)}function Be(e){const t=e.target;t.removeEventListener("dispose",Be),function(e){(function(e){const t=ce.get(e).programs;void 0!==t&&(t.forEach(function(e){ge.releaseProgram(e)}),e.isShaderMaterial&&ge.releaseShaderCache(e))})(e),ce.remove(e)}(t)}function Ge(e,t,i,r){null!==A&&e.isNodeMaterial&&A.setObject(r,e),!0===Q&&ye.setState(e,i,!1),!0===e.transparent&&2===e.side&&!1===e.forceSinglePass?(e.side=1,e.needsUpdate=!0,nt(e,t,r),e.side=0,e.needsUpdate=!0,nt(e,t,r),e.side=2):nt(e,t,r)}this.xr=De,this.getContext=function(){return Ce},this.getContextAttributes=function(){return Ce.getContextAttributes()},this.forceContextLoss=function(){const e=ae.get("WEBGL_lose_context");e&&e.loseContext()},this.forceContextRestore=function(){const e=ae.get("WEBGL_lose_context");e&&e.restoreContext()},this.getPixelRatio=function(){return W},this.setPixelRatio=function(e){void 0!==e&&(W=e,this.setSize(V,H,!1))},this.getSize=function(e){return e.set(V,H)},this.setSize=function(e,i,r=!0){De.isPresenting?Ti("WebGLRenderer: Can't change size while VR device is presenting."):(V=e,H=i,t.width=Math.floor(e*W),t.height=Math.floor(i*W),!0===r&&(t.style.width=e+"px",t.style.height=i+"px"),null!==M&&M.setSize(t.width,t.height),this.setViewport(0,0,e,i))},this.getDrawingBufferSize=function(e){return e.set(V*W,H*W).floor()},this.setDrawingBufferSize=function(e,i,r){V=e,H=i,W=r,t.width=Math.floor(e*r),t.height=Math.floor(i*r),this.setViewport(0,0,e,i)},this.setEffects=function(e){if(f!==ze){if(e)for(let t=0;t<e.length;t++)if(!0===e[t].isOutputPass){Ti("WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}M.setEffects(e||[])}else Mi("WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.")},this.getCurrentViewport=function(e){return e.copy(O)},this.getViewport=function(e){return e.copy(X)},this.setViewport=function(e,t,i,r){e.isVector4?X.set(e.x,e.y,e.z,e.w):X.set(e,t,i,r),le.viewport(O.copy(X).multiplyScalar(se()).round())},this.getScissor=function(e){return e.copy(q)},this.setScissor=function(e,t,i,r){e.isVector4?q.set(e.x,e.y,e.z,e.w):q.set(e,t,i,r),le.scissor(B.copy(q).multiplyScalar(se()).round())},this.getScissorTest=function(){return Y},this.setScissorTest=function(e){le.setScissorTest(Y=e)},this.setOpaqueSort=function(e){j=e},this.setTransparentSort=function(e){$=e},this.getClearColor=function(e){return e.copy(Se.getClearColor())},this.setClearColor=function(){Se.setClearColor(...arguments)},this.getClearAlpha=function(){return Se.getClearAlpha()},this.setClearAlpha=function(){Se.setClearAlpha(...arguments)},this.clear=function(e=!0,t=!0,i=!0){let r=0;if(e){let e=!1;if(null!==U){const t=U.texture.format;e=m.has(t)}if(e){const e=U.texture.type,t=g.has(e),i=Se.getClearColor(),r=Se.getClearAlpha(),n=i.r,s=i.g,a=i.b;t?(_[0]=n,_[1]=s,_[2]=a,_[3]=r,Ce.clearBufferuiv(Ce.COLOR,0,_)):(v[0]=n,v[1]=s,v[2]=a,v[3]=r,Ce.clearBufferiv(Ce.COLOR,0,v))}else r|=Ce.COLOR_BUFFER_BIT}t&&(r|=Ce.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0)),i&&(r|=Ce.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),0!==r&&Ce.clear(r)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.setNodesHandler=function(e){e.setRenderer(this),A=e},this.dispose=function(){t.removeEventListener("webglcontextlost",Ue,!1),t.removeEventListener("webglcontextrestored",Ie,!1),t.removeEventListener("webglcontextcreationerror",Fe,!1),Se.dispose(),ve.dispose(),be.dispose(),he.dispose(),ce.dispose(),de.dispose(),me.dispose(),fe.dispose(),Ae.dispose(),Re.dispose(),ge.dispose(),De.dispose(),De.removeEventListener("sessionstart",We),De.removeEventListener("sessionend",$e),Ze.stop()},this.renderBufferDirect=function(e,t,i,r,n,s){null===t&&(t=re);const a=n.isMesh&&n.matrixWorld.determinantAffine()<0,o=function(e,t,i,r,n){!0!==t.isScene&&(t=re);he.resetTextureUnits();const s=t.fog,a=r.isMeshStandardMaterial||r.isMeshLambertMaterial||r.isMeshPhongMaterial?t.environment:null,o=null===U?E.outputColorSpace:!0===U.isXRRenderTarget?U.texture.colorSpace:Qi.workingColorSpace,l=r.isMeshStandardMaterial||r.isMeshLambertMaterial&&!r.envMap||r.isMeshPhongMaterial&&!r.envMap,u=de.get(r.envMap||a,l),c=!0===r.vertexColors&&!!i.attributes.color&&4===i.attributes.color.itemSize,h=!!i.attributes.tangent&&(!!r.normalMap||r.anisotropy>0),d=!!i.morphAttributes.position,p=!!i.morphAttributes.normal,f=!!i.morphAttributes.color;let m=0;r.toneMapped&&(null!==U&&!0!==U.isXRRenderTarget||(m=E.toneMapping));const g=i.morphAttributes.position||i.morphAttributes.normal||i.morphAttributes.color,_=void 0!==g?g.length:0,v=ce.get(r),y=x.state.lights;if(!0===Q&&(!0===J||e!==F)){const t=e===F&&r.id===I;ye.setState(r,e,t)}let S=!1,T=!1;r.version===v.__version?v.needsLights&&v.lightsStateVersion!==y.state.version||n.isBatchedMesh&&!1===v.batching?S=!0:n.isBatchedMesh||!0!==v.batching?n.isBatchedMesh&&!0===v.batchingColor&&null===n._colorsTexture||n.isBatchedMesh&&!1===v.batchingColor&&null!==n._colorsTexture||n.isInstancedMesh&&!1===v.instancing?S=!0:n.isInstancedMesh||!0!==v.instancing?n.isSkinnedMesh&&!1===v.skinning?S=!0:n.isSkinnedMesh||!0!==v.skinning?n.isInstancedMesh&&!0===v.instancingColor&&null===n.instanceColor||n.isInstancedMesh&&!1===v.instancingColor&&null!==n.instanceColor||n.isInstancedMesh&&!0===v.instancingMorph&&null===n.morphTexture||n.isInstancedMesh&&!1===v.instancingMorph&&null!==n.morphTexture||v.envMap!==u||!0===r.fog&&v.fog!==s?S=!0:void 0===v.numClippingPlanes||v.numClippingPlanes===ye.numPlanes&&v.numIntersection===ye.numIntersection?v.vertexAlphas!==c||v.vertexTangents!==h||v.morphTargets!==d||v.morphNormals!==p||v.morphColors!==f||v.morphTargetsCount!==_||v.numLightProbeGrids!==rt(x.state.lightProbeGridArray)?S=!0:v.outputColorSpace===o&&v.toneMapping===m||(T=!0):S=!0:S=!0:S=!0:S=!0:(S=!0,v.__version=r.version);let M=v.currentProgram;!0!==S&&!0!==T||(M=!0===T?function(e,t,i,r,n){const s=ce.get(e),a=s.currentProgram.id+","+r+","+n;let o=s.programVariants.get(a);void 0===o?(o=nt(e,t,i),s.programVariants.set(a,o)):(s.currentProgram=o,s.uniformsList=null,s.outputColorSpace=r,s.toneMapping=n);return o}(r,t,n,o,m):nt(r,t,n),A&&r.isNodeMaterial&&A.onUpdateProgram(r,M,v));let w=!1,R=!1,C=!1;const N=M.getUniforms(),P=v.uniforms;le.useProgram(M.program)&&(w=!0,R=!0,C=!0);r.id!==I&&(I=r.id,R=!0);if(w||F!==e){le.buffers.depth.getReversed()&&!0!==e.reversedDepth&&(e._reversedDepth=!0,e.updateProjectionMatrix()),N.setValue(Ce,"projectionMatrix",e.projectionMatrix),N.setValue(Ce,"viewMatrix",e.matrixWorldInverse);const t=N.map.cameraPosition;void 0!==t&&t.setValue(Ce,te.setFromMatrixPosition(e.matrixWorld)),oe.logarithmicDepthBuffer&&N.setValue(Ce,"logDepthBufFC",2/(Math.log(e.far+1)/Math.LN2)),(r.isMeshPhongMaterial||r.isMeshToonMaterial||r.isMeshLambertMaterial||r.isMeshBasicMaterial||r.isMeshStandardMaterial||r.isShaderMaterial)&&N.setValue(Ce,"isOrthographic",!0===e.isOrthographicCamera),F!==e&&(F=e,R=!0,C=!0)}v.needsLights&&(y.state.sunShadowMap.length>0&&N.setValue(Ce,"sunShadowMap",y.state.sunShadowMap,he),y.state.directionalShadowMap.length>0&&N.setValue(Ce,"directionalShadowMap",y.state.directionalShadowMap,he),y.state.spotShadowMap.length>0&&N.setValue(Ce,"spotShadowMap",y.state.spotShadowMap,he),y.state.pointShadowMap.length>0&&N.setValue(Ce,"pointShadowMap",y.state.pointShadowMap,he));if(n.isSkinnedMesh){N.setOptional(Ce,n,"bindMatrix"),N.setOptional(Ce,n,"bindMatrixInverse");const e=n.skeleton;e&&(null===e.boneTexture&&e.computeBoneTexture(),N.setValue(Ce,"boneTexture",e.boneTexture,he))}n.isBatchedMesh&&(N.setOptional(Ce,n,"batchingTexture"),N.setValue(Ce,"batchingTexture",n._matricesTexture,he),N.setOptional(Ce,n,"batchingIdTexture"),N.setValue(Ce,"batchingIdTexture",n._indirectTexture,he),N.setOptional(Ce,n,"batchingColorTexture"),null!==n._colorsTexture&&N.setValue(Ce,"batchingColorTexture",n._colorsTexture,he));const L=i.morphAttributes;void 0===L.position&&void 0===L.normal&&void 0===L.color||Te.update(n,i,M);(R||v.receiveShadow!==n.receiveShadow)&&(v.receiveShadow=n.receiveShadow,N.setValue(Ce,"receiveShadow",n.receiveShadow));(r.isMeshStandardMaterial||r.isMeshLambertMaterial||r.isMeshPhongMaterial)&&null===r.envMap&&null!==t.environment&&(P.envMapIntensity.value=t.environmentIntensity);void 0!==P.dfgLUT&&(P.dfgLUT.value=(null===Yu&&(Yu=new Rs(qu,16,16,at,Xe),Yu.name="DFG_LUT",Yu.minFilter=Oe,Yu.magFilter=Oe,Yu.wrapS=Le,Yu.wrapT=Le,Yu.generateMipmaps=!1,Yu.needsUpdate=!0),Yu));if(R){if(N.setValue(Ce,"toneMappingExposure",E.toneMappingExposure),v.needsLights&&(O=C,(D=P).ambientLightColor.needsUpdate=O,D.lightProbe.needsUpdate=O,D.sunLights.needsUpdate=O,D.sunLightShadows.needsUpdate=O,D.directionalLights.needsUpdate=O,D.directionalLightShadows.needsUpdate=O,D.pointLights.needsUpdate=O,D.pointLightShadows.needsUpdate=O,D.spotLights.needsUpdate=O,D.spotLightShadows.needsUpdate=O,D.rectAreaLights.needsUpdate=O,D.hemisphereLights.needsUpdate=O),s&&!0===r.fog&&_e.refreshFogUniforms(P,s),_e.refreshMaterialUniforms(P,r,W,H,x.state.transmissionRenderTarget[e.id]),v.needsLights&&v.numLightProbeGrids>0){const e=b;let t=0;for(const i of x.state.lightProbeGridArray)null!==i.texture&&(e.textures[t]=i.texture,e.min[t]=i.boundingBox.min,e.max[t]=i.boundingBox.max,e.resolution[t]=i.resolution,t++);for(const i in e)e[i].length=t;P.probesSH.value=e.textures,P.probesMin.value=e.min,P.probesMax.value=e.max,P.probesResolution.value=e.resolution}Xl.upload(Ce,lt(v),P,he)}var D,O;r.isShaderMaterial&&!0===r.uniformsNeedUpdate&&(Xl.upload(Ce,lt(v),P,he),r.uniformsNeedUpdate=!1);r.isSpriteMaterial&&N.setValue(Ce,"center",n.center);if(N.setValue(Ce,"modelViewMatrix",n.modelViewMatrix),N.setValue(Ce,"normalMatrix",n.normalMatrix),N.setValue(Ce,"modelMatrix",n.matrixWorld),void 0!==r.uniformsGroups){const e=r.uniformsGroups;for(let t=0,i=e.length;t<i;t++){const i=e[t];Re.update(i,M),Re.bind(i,M)}}return M}(e,t,i,r,n);le.setMaterial(r,a);let l=i.index,u=1;if(!0===r.wireframe){if(l=fe.getWireframeAttribute(i),void 0===l)return;u=2}const c=i.drawRange,h=i.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;Ae.setup(n,r,o,i,l);let g=Me;if(null!==l&&(m=pe.get(l),g=Ee,g.setIndex(m)),n.isMesh)!0===r.wireframe?(le.setLineWidth(r.wireframeLinewidth*se()),g.setMode(Ce.LINES)):g.setMode(Ce.TRIANGLES);else if(n.isLine){let e=r.linewidth;void 0===e&&(e=1),le.setLineWidth(e*se()),n.isLineSegments?g.setMode(Ce.LINES):n.isLineLoop?g.setMode(Ce.LINE_LOOP):g.setMode(Ce.LINE_STRIP)}else n.isPoints?g.setMode(Ce.POINTS):n.isSprite&&g.setMode(Ce.TRIANGLES);if(n.isBatchedMesh)if(ae.get("WEBGL_multi_draw"))g.renderMultiDraw(n._multiDrawStarts,n._multiDrawCounts,n._multiDrawCount);else{const e=n._multiDrawStarts,t=n._multiDrawCounts,i=n._multiDrawCount,s=l?pe.get(l).bytesPerElement:1,a=ce.get(r).currentProgram.getUniforms();for(let r=0;r<i;r++)a.setValue(Ce,"_gl_DrawID",r),g.render(e[r]/s,t[r])}else if(n.isInstancedMesh)g.renderInstances(d,f,n.count);else if(i.isInstancedBufferGeometry){const e=void 0!==i._maxInstanceCount?i._maxInstanceCount:1/0,t=Math.min(i.instanceCount,e);g.renderInstances(d,f,t)}else g.render(d,f)},this.compile=function(e,t,i=null){null===i&&(i=e),null!==A&&A.renderStart(e,t,i),x=be.get(i),x.init(t),T.push(x),i.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(x.pushLight(e),e.castShadow&&x.pushShadow(e))}),e!==i&&e.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(x.pushLight(e),e.castShadow&&x.pushShadow(e))}),x.setupLights(),null!==A&&A.updateLights(x.state.lightsArray),J=this.localClippingEnabled,Q=ye.init(this.clippingPlanes,J),!0===Q&&ye.setGlobalState(this.clippingPlanes,t),null!==A&&xe.render(x.state.shadowsArray,i,t);const r=new Set;return e.traverse(function(e){if(!(e.isMesh||e.isPoints||e.isLine||e.isSprite))return;const n=e.material;if(n)if(Array.isArray(n))for(let s=0;s<n.length;s++){const a=n[s];Ge(a,i,t,e),r.add(a)}else Ge(n,i,t,e),r.add(n)}),x=T.pop(),null!==A&&A.renderEnd(),r},this.compileAsync=function(e,t,i=null){const r=this.compile(e,t,i);return new Promise(t=>{function i(){r.forEach(function(e){const t=ce.get(e).currentProgram;(void 0===t||t.isReady())&&r.delete(e)}),0!==r.size?setTimeout(i,10):t(e)}null!==ae.get("KHR_parallel_shader_compile")?i():setTimeout(i,10)})};let Ve=null;function We(){Ze.stop()}function $e(){Ze.start()}const Ze=new co;function Qe(e,t,i,r){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)i=e.renderOrder;else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)x.pushLight(e),e.castShadow&&x.pushShadow(e);else if(e.isSprite){const n=t.isArrayCamera?Z:K;if(!e.frustumCulled||e.intersectsFrustum(n)){r&&ie.setFromMatrixPosition(e.matrixWorld).applyMatrix4(ee);const n=me.update(e),s=e.material;s.visible&&y.push(e,n,s,i,ie.z,null,t)}}else if(e.isMesh||e.isLine||e.isPoints){const n=t.isArrayCamera?Z:K;if(!e.frustumCulled||e.intersectsFrustum(n)){const n=me.update(e),s=e.material;if(r&&(void 0!==e.boundingSphere?(null===e.boundingSphere&&e.computeBoundingSphere(),ie.copy(e.boundingSphere.center)):(null===n.boundingSphere&&n.computeBoundingSphere(),ie.copy(n.boundingSphere.center)),ie.applyMatrix4(e.matrixWorld).applyMatrix4(ee)),Array.isArray(s)){const r=n.groups;for(let a=0,o=r.length;a<o;a++){const o=r[a],l=s[o.materialIndex];l&&l.visible&&y.push(e,n,l,i,ie.z,o,t)}}else s.visible&&y.push(e,n,s,i,ie.z,null,t)}}const n=e.children;for(let e=0,s=n.length;e<s;e++)Qe(n[e],t,i,r)}function Je(e,t,i,r){const{opaque:n,transmissive:s,transparent:a}=e;x.setupLightsView(i),!0===Q&&ye.setGlobalState(E.clippingPlanes,i),r&&le.viewport(O.copy(r)),n.length>0&&tt(n,t,i),s.length>0&&tt(s,t,i),a.length>0&&tt(a,t,i),le.buffers.depth.setTest(!0),le.buffers.depth.setMask(!0),le.buffers.color.setMask(!0),le.setPolygonOffset(!1)}function et(e,t,i,r){if(null!==(!0===i.isScene?i.overrideMaterial:null))return;if(void 0===x.state.transmissionRenderTarget[r.id]){const e=ae.has("EXT_color_buffer_half_float")||ae.has("EXT_color_buffer_float");x.state.transmissionRenderTarget[r.id]=new hr(1,1,{generateMipmaps:!0,type:e?Xe:ze,minFilter:ke,samples:Math.max(4,oe.samples),stencilBuffer:n,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,colorSpace:Qi.workingColorSpace})}const s=x.state.transmissionRenderTarget[r.id],a=r.viewport||O;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(z),G=E.getClearAlpha(),G<1&&E.setClearColor(16777215,.5),E.clear(),ne&&Se.render(i);const c=E.toneMapping;E.toneMapping=0;const h=r.viewport;if(void 0!==r.viewport&&(r.viewport=void 0),x.setupLightsView(r),!0===Q&&ye.setGlobalState(E.clippingPlanes,r),tt(e,i,r),he.updateMultisampleRenderTarget(s),he.updateRenderTargetMipmap(s),!1===ae.has("WEBGL_multisampled_render_to_texture")){let e=!1;for(let n=0,s=t.length;n<s;n++){const s=t[n],{object:a,geometry:o,material:l,group:u}=s;if(2===l.side&&a.layers.test(r.layers)){const t=l.side;l.side=1,l.needsUpdate=!0,it(a,i,r,o,l,u),l.side=t,l.needsUpdate=!0,e=!0}}!0===e&&(he.updateMultisampleRenderTarget(s),he.updateRenderTargetMipmap(s))}E.setRenderTarget(o,l,u),E.setClearColor(z,G),void 0!==h&&(r.viewport=h),E.toneMapping=c}function tt(e,t,i){const r=!0===t.isScene?t.overrideMaterial:null;for(let n=0,s=e.length;n<s;n++){const s=e[n],{object:a,geometry:o,group:l}=s;let u=s.material;!0===u.allowOverride&&null!==r&&(u=r),a.layers.test(i.layers)&&it(a,t,i,o,u,l)}}function it(e,t,i,r,n,s){null!==A&&n.isNodeMaterial&&A.setObject(e,n),e.onBeforeRender(E,t,i,r,n,s),e.modelViewMatrix.multiplyMatrices(i.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix),n.onBeforeRender(E,t,i,r,e,s),!0===n.transparent&&2===n.side&&!1===n.forceSinglePass?(n.side=1,n.needsUpdate=!0,E.renderBufferDirect(i,t,r,n,e,s),n.side=0,n.needsUpdate=!0,E.renderBufferDirect(i,t,r,n,e,s),n.side=2):E.renderBufferDirect(i,t,r,n,e,s),e.onAfterRender(E,t,i,r,n,s)}function rt(e){let t=0;for(const i of e)null!==i.texture&&t++;return t}function nt(e,t,i){!0!==t.isScene&&(t=re);const r=ce.get(e),n=x.state.lights,s=x.state.shadowsArray,a=n.state.version,o=ge.getParameters(e,n.state,s,t,i,x.state.lightProbeGridArray),l=ge.getProgramCacheKey(o);let u=r.programs;r.environment=e.isMeshStandardMaterial||e.isMeshLambertMaterial||e.isMeshPhongMaterial?t.environment:null,r.fog=t.fog;const c=e.isMeshStandardMaterial||e.isMeshLambertMaterial&&!e.envMap||e.isMeshPhongMaterial&&!e.envMap;r.envMap=de.get(e.envMap||r.environment,c),r.envMapRotation=null!==r.environment&&null===e.envMap?t.environmentRotation:e.envMapRotation,void 0===u&&(e.addEventListener("dispose",Be),u=new Map,r.programs=u,r.programVariants=new Map);let h=u.get(l);if(void 0!==h){if(r.currentProgram===h&&r.lightsStateVersion===a)return ct(e,o),h}else o.uniforms=ge.getUniforms(e),null!==A&&e.isNodeMaterial&&A.build(e,i,o),e.onBeforeCompile(o,E),h=ge.acquireProgram(o,l),u.set(l,h),r.uniforms=o.uniforms;const d=r.uniforms;return(e.isShaderMaterial||e.isRawShaderMaterial)&&!0!==e.clipping||(d.clippingPlanes=ye.uniform),ct(e,o),r.needsLights=function(e){return e.isMeshLambertMaterial||e.isMeshToonMaterial||e.isMeshPhongMaterial||e.isMeshStandardMaterial||e.isShadowMaterial||e.isShaderMaterial&&!0===e.lights}(e),r.lightsStateVersion=a,r.needsLights&&(d.ambientLightColor.value=n.state.ambient,d.lightProbe.value=n.state.probe,d.sunLights.value=n.state.sun,d.sunLightShadows.value=n.state.sunShadow,d.directionalLights.value=n.state.directional,d.directionalLightShadows.value=n.state.directionalShadow,d.spotLights.value=n.state.spot,d.spotLightShadows.value=n.state.spotShadow,d.rectAreaLights.value=n.state.rectArea,d.ltc_1.value=n.state.rectAreaLTC1,d.ltc_2.value=n.state.rectAreaLTC2,d.pointLights.value=n.state.point,d.pointLightShadows.value=n.state.pointShadow,d.hemisphereLights.value=n.state.hemi,d.sunShadowMatrix.value=n.state.sunShadowMatrix,d.sunShadowCascade.value=n.state.sunShadowCascade,d.directionalShadowMatrix.value=n.state.directionalShadowMatrix,d.spotLightMatrix.value=n.state.spotLightMatrix,d.spotLightMap.value=n.state.spotLightMap,d.pointShadowMatrix.value=n.state.pointShadowMatrix),r.numLightProbeGrids=rt(x.state.lightProbeGridArray),r.currentProgram=h,r.uniformsList=null,h}function lt(e){if(null===e.uniformsList){const t=e.currentProgram.getUniforms();e.uniformsList=Xl.seqWithValue(t.seq,e.uniforms)}return e.uniformsList}function ct(e,t){const i=ce.get(e);i.outputColorSpace=t.outputColorSpace,i.batching=t.batching,i.batchingColor=t.batchingColor,i.instancing=t.instancing,i.instancingColor=t.instancingColor,i.instancingMorph=t.instancingMorph,i.skinning=t.skinning,i.morphTargets=t.morphTargets,i.morphNormals=t.morphNormals,i.morphColors=t.morphColors,i.morphTargetsCount=t.morphTargetsCount,i.numClippingPlanes=t.numClippingPlanes,i.numIntersection=t.numClipIntersection,i.vertexAlphas=t.vertexAlphas,i.vertexTangents=t.vertexTangents,i.toneMapping=t.toneMapping}function ht(e){const t=ce.get(e);return t.__readFormat===e.format&&t.__readType===e.type||(t.__readFormat=e.format,t.__readType=e.type,t.__formatReadable=oe.textureFormatReadable(e.format),t.__typeReadable=oe.textureTypeReadable(e.type)),t}Ze.setAnimationLoop(function(e){Ve&&Ve(e)}),"undefined"!=typeof self&&Ze.setContext(self),this.setAnimationLoop=function(e){Ve=e,De.setAnimationLoop(e),null===e?Ze.stop():Ze.start()},De.addEventListener("sessionstart",We),De.addEventListener("sessionend",$e),this.render=function(e,t){if(void 0!==t&&!0!==t.isCamera)return void Mi("WebGLRenderer.render: camera is not an instance of THREE.Camera.");if(!0===w)return;null!==A&&A.renderStart(e,t);const i=!0===De.enabled&&!0===De.isPresenting,r=null!==M&&(null===U||i)&&M.begin(E,U);if(!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&!0===t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),!0!==De.enabled||!0!==De.isPresenting||null!==M&&!1!==M.isCompositing()||(!0===De.cameraAutoUpdate&&De.updateCamera(t),t=De.getCamera()),!0===e.isScene&&e.onBeforeRender(E,e,t,U),x=be.get(e,T.length),x.init(t),x.state.textureUnits=he.getTextureUnits(),T.push(x),ee.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),t.isArrayCamera?Z.setFromArrayCamera(t):K.setFromProjectionMatrix(ee,ui,t.reversedDepth),J=this.localClippingEnabled,Q=ye.init(this.clippingPlanes,J),y=ve.get(e,S.length),y.init(),S.push(y),this.info.render.frame++,!0===De.enabled&&!0===De.isPresenting){const e=E.xr.getDepthSensingMesh();null!==e&&Qe(e,t,-1/0,E.sortObjects)}Qe(e,t,0,E.sortObjects),y.finish(),null!==A&&A.updateLights(x.state.lightsArray),!0===E.sortObjects&&y.sort(j,$),ne=!1===De.enabled||!1===De.isPresenting||!1===De.hasDepthSensing(),ne&&Se.addToRenderList(y,e),!0===this.info.autoReset&&this.info.reset(),!0===Q&&ye.beginShadows();const n=x.state.shadowsArray;xe.render(n,e,t),!0===Q&&ye.endShadows();if(!1===(r&&M.hasRenderPass())){const i=y.opaque,r=y.transmissive;if(x.setupLights(),t.isArrayCamera){const n=t.cameras;if(r.length>0)for(let t=0,s=n.length;t<s;t++){et(i,r,e,n[t])}ne&&Se.render(e);for(let t=0,i=n.length;t<i;t++){const i=n[t];Je(y,e,i,i.viewport)}}else r.length>0&&et(i,r,e,t),ne&&Se.render(e),Je(y,e,t)}null!==U&&0===D&&(he.updateMultisampleRenderTarget(U),he.updateRenderTargetMipmap(U)),r&&M.end(E),!0===e.isScene&&e.onAfterRender(E,e,t),Ae.resetDefaultState(),I=-1,F=null,T.pop(),T.length>0?(x=T[T.length-1],he.setTextureUnits(x.state.textureUnits),!0===Q&&ye.setGlobalState(E.clippingPlanes,x.state.camera)):x=null,S.pop(),y=S.length>0?S[S.length-1]:null,null!==A&&A.renderEnd()},this.getActiveCubeFace=function(){return L},this.getActiveMipmapLevel=function(){return D},this.getRenderTarget=function(){return U},this.setRenderTargetTextures=function(e,t,i){const r=ce.get(e);r.__autoAllocateDepthBuffer=!1===e.resolveDepthBuffer,!1===r.__autoAllocateDepthBuffer&&(r.__useRenderToTexture=!1),ce.get(e.texture).__webglTexture=t,ce.get(e.depthTexture).__webglTexture=r.__autoAllocateDepthBuffer?void 0:i,r.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(e,t){const i=ce.get(e);i.__webglFramebuffer=t,i.__useDefaultFramebuffer=void 0===t},this.setRenderTarget=function(e,t=0,i=0){U=e,L=t,D=i;let r=null,n=!1,s=!1;if(e){const a=ce.get(e);if(void 0!==a.__useDefaultFramebuffer)return le.bindFramebuffer(Ce.FRAMEBUFFER,a.__webglFramebuffer),O.copy(e.viewport),B.copy(e.scissor),k=e.scissorTest,le.viewport(O),le.scissor(B),le.setScissorTest(k),void(I=-1);if(void 0===a.__webglFramebuffer)he.setupRenderTarget(e);else if(a.__hasExternalTextures)he.rebindTextures(e,ce.get(e.texture).__webglTexture,ce.get(e.depthTexture).__webglTexture);else if(e.depthBuffer){const t=e.depthTexture;if(a.__boundDepthTexture!==t){if(null!==t&&ce.has(t)&&(e.width!==t.image.width||e.height!==t.image.height))throw new Error("THREE.WebGLRenderer: Attached DepthTexture is initialized to the incorrect size.");he.setupDepthRenderbuffer(e)}}const o=e.texture;(o.isData3DTexture||o.isDataArrayTexture||o.isCompressedArrayTexture)&&(s=!0);const l=ce.get(e).__webglFramebuffer;e.isWebGLCubeRenderTarget?(r=Array.isArray(l[t])?l[t][i]:l[t],n=!0):r=e.samples>0&&!1===he.useMultisampledRTT(e)?ce.get(e).__webglMultisampledFramebuffer:Array.isArray(l)?l[i]:l,O.copy(e.viewport),B.copy(e.scissor),k=e.scissorTest}else O.copy(X).multiplyScalar(W).floor(),B.copy(q).multiplyScalar(W).floor(),k=Y;0!==i&&(r=R);if(le.bindFramebuffer(Ce.FRAMEBUFFER,r)&&le.drawBuffers(e,r),le.viewport(O),le.scissor(B),le.setScissorTest(k),n){const r=ce.get(e.texture);Ce.framebufferTexture2D(Ce.FRAMEBUFFER,Ce.COLOR_ATTACHMENT0,Ce.TEXTURE_CUBE_MAP_POSITIVE_X+t,r.__webglTexture,i)}else if(s){const r=t;for(let t=0;t<e.textures.length;t++){const n=ce.get(e.textures[t]);Ce.framebufferTextureLayer(Ce.FRAMEBUFFER,Ce.COLOR_ATTACHMENT0+t,n.__webglTexture,i,r)}}else if(null!==e&&0!==i){const t=ce.get(e.texture);Ce.framebufferTexture2D(Ce.FRAMEBUFFER,Ce.COLOR_ATTACHMENT0,Ce.TEXTURE_2D,t.__webglTexture,i)}I=-1},this.readRenderTargetPixels=function(e,t,i,r,n,s,a,o=0){if(!e||!e.isWebGLRenderTarget)return void Mi("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let l=ce.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&void 0!==a&&(l=l[a],Array.isArray(l)&&(l=l[0])),l){le.bindFramebuffer(Ce.FRAMEBUFFER,l);try{const a=e.textures[o],l=a.format,u=a.type;e.textures.length>1&&Ce.readBuffer(Ce.COLOR_ATTACHMENT0+o);const c=ht(a);if(!1===c.__formatReadable)return void Mi("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");if(!1===c.__typeReadable)return void Mi("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");t>=0&&t<=e.width-r&&i>=0&&i<=e.height-n&&Ce.readPixels(t,i,r,n,we.convert(l),we.convert(u),s)}finally{const e=null!==U?ce.get(U).__webglFramebuffer:null;le.bindFramebuffer(Ce.FRAMEBUFFER,e)}}},this.readRenderTargetPixelsAsync=async function(e,t,i,r,n,s,a,o=0){if(!e||!e.isWebGLRenderTarget)throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let l=ce.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&void 0!==a&&(l=l[a],Array.isArray(l)&&(l=l[0])),l){if(t>=0&&t<=e.width-r&&i>=0&&i<=e.height-n){le.bindFramebuffer(Ce.FRAMEBUFFER,l);const a=e.textures[o],u=a.format,c=a.type;e.textures.length>1&&Ce.readBuffer(Ce.COLOR_ATTACHMENT0+o);const h=ht(a);if(!1===h.__formatReadable)throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!1===h.__typeReadable)throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const d=Ce.createBuffer();Ce.bindBuffer(Ce.PIXEL_PACK_BUFFER,d),Ce.bufferData(Ce.PIXEL_PACK_BUFFER,s.byteLength,Ce.STREAM_READ),Ce.readPixels(t,i,r,n,we.convert(u),we.convert(c),0),Ce.bindBuffer(Ce.PIXEL_PACK_BUFFER,null);const p=null!==U?ce.get(U).__webglFramebuffer:null;le.bindFramebuffer(Ce.FRAMEBUFFER,p);const f=Ce.fenceSync(Ce.SYNC_GPU_COMMANDS_COMPLETE,0);return Ce.flush(),await function(e,t,i){return new Promise(function(r,n){setTimeout(function s(){switch(e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0)){case e.WAIT_FAILED:n();break;case e.TIMEOUT_EXPIRED:setTimeout(s,i);break;default:r()}},i)})}(Ce,f,4),Ce.bindBuffer(Ce.PIXEL_PACK_BUFFER,d),Ce.getBufferSubData(Ce.PIXEL_PACK_BUFFER,0,s),Ce.bindBuffer(Ce.PIXEL_PACK_BUFFER,null),Ce.deleteBuffer(d),Ce.deleteSync(f),s}throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")}},this.copyFramebufferToTexture=function(e,t=null,i=0){const r=Math.pow(2,-i),n=Math.floor(e.image.width*r),s=Math.floor(e.image.height*r),a=null!==t?t.x:0,o=null!==t?t.y:0;he.setTexture2D(e,0),Ce.copyTexSubImage2D(Ce.TEXTURE_2D,i,0,0,a,o,n,s),le.unbindTexture()},this.copyTextureToTexture=function(e,t,i=null,r=null,n=0,s=0){let a,o,l,u,c,h,d,p,f;const m=e.isCompressedTexture?e.mipmaps[s]:e.image;if(null!==i)a=i.max.x-i.min.x,o=i.max.y-i.min.y,l=i.isBox3?i.max.z-i.min.z:1,u=i.min.x,c=i.min.y,h=i.isBox3?i.min.z:0;else{const t=Math.pow(2,-n);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!==r?(d=r.x,p=r.y,f=r.z):(d=0,p=0,f=0);const g=we.convert(t.format),_=we.convert(t.type);let v;t.isData3DTexture?(he.setTexture3D(t,0),v=Ce.TEXTURE_3D):t.isDataArrayTexture||t.isCompressedArrayTexture?(he.setTexture2DArray(t,0),v=Ce.TEXTURE_2D_ARRAY):(he.setTexture2D(t,0),v=Ce.TEXTURE_2D),le.activeTexture(Ce.TEXTURE0),le.pixelStorei(Ce.UNPACK_FLIP_Y_WEBGL,t.flipY),le.pixelStorei(Ce.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),le.pixelStorei(Ce.UNPACK_ALIGNMENT,t.unpackAlignment);const b=le.getParameter(Ce.UNPACK_ROW_LENGTH),y=le.getParameter(Ce.UNPACK_IMAGE_HEIGHT),x=le.getParameter(Ce.UNPACK_SKIP_PIXELS),S=le.getParameter(Ce.UNPACK_SKIP_ROWS),T=le.getParameter(Ce.UNPACK_SKIP_IMAGES);le.pixelStorei(Ce.UNPACK_ROW_LENGTH,m.width),le.pixelStorei(Ce.UNPACK_IMAGE_HEIGHT,m.height),le.pixelStorei(Ce.UNPACK_SKIP_PIXELS,u),le.pixelStorei(Ce.UNPACK_SKIP_ROWS,c),le.pixelStorei(Ce.UNPACK_SKIP_IMAGES,h);const M=e.isDataArrayTexture||e.isData3DTexture,E=t.isDataArrayTexture||t.isData3DTexture;if(e.isDepthTexture){const i=ce.get(e),r=ce.get(t),m=ce.get(i.__renderTarget),g=ce.get(r.__renderTarget);le.bindFramebuffer(Ce.READ_FRAMEBUFFER,m.__webglFramebuffer),le.bindFramebuffer(Ce.DRAW_FRAMEBUFFER,g.__webglFramebuffer);for(let i=0;i<l;i++)M&&(Ce.framebufferTextureLayer(Ce.READ_FRAMEBUFFER,Ce.COLOR_ATTACHMENT0,ce.get(e).__webglTexture,n,h+i),Ce.framebufferTextureLayer(Ce.DRAW_FRAMEBUFFER,Ce.COLOR_ATTACHMENT0,ce.get(t).__webglTexture,s,f+i)),Ce.blitFramebuffer(u,c,u+a,c+o,d,p,d+a,p+o,Ce.DEPTH_BUFFER_BIT,Ce.NEAREST);le.bindFramebuffer(Ce.READ_FRAMEBUFFER,null),le.bindFramebuffer(Ce.DRAW_FRAMEBUFFER,null)}else if(0!==n||e.isRenderTargetTexture||ce.has(e)){const i=ce.get(e),r=ce.get(t);le.bindFramebuffer(Ce.READ_FRAMEBUFFER,C),le.bindFramebuffer(Ce.DRAW_FRAMEBUFFER,P);for(let e=0;e<l;e++)M?Ce.framebufferTextureLayer(Ce.READ_FRAMEBUFFER,Ce.COLOR_ATTACHMENT0,i.__webglTexture,n,h+e):Ce.framebufferTexture2D(Ce.READ_FRAMEBUFFER,Ce.COLOR_ATTACHMENT0,Ce.TEXTURE_2D,i.__webglTexture,n),E?Ce.framebufferTextureLayer(Ce.DRAW_FRAMEBUFFER,Ce.COLOR_ATTACHMENT0,r.__webglTexture,s,f+e):Ce.framebufferTexture2D(Ce.DRAW_FRAMEBUFFER,Ce.COLOR_ATTACHMENT0,Ce.TEXTURE_2D,r.__webglTexture,s),0!==n?Ce.blitFramebuffer(u,c,u+a,c+o,d,p,d+a,p+o,Ce.COLOR_BUFFER_BIT,Ce.NEAREST):E?Ce.copyTexSubImage3D(v,s,d,p,f+e,u,c,a,o):Ce.copyTexSubImage2D(v,s,d,p,u,c,a,o);le.bindFramebuffer(Ce.READ_FRAMEBUFFER,null),le.bindFramebuffer(Ce.DRAW_FRAMEBUFFER,null)}else E?e.isDataTexture||e.isData3DTexture?Ce.texSubImage3D(v,s,d,p,f,a,o,l,g,_,m.data):t.isCompressedArrayTexture?Ce.compressedTexSubImage3D(v,s,d,p,f,a,o,l,g,m.data):Ce.texSubImage3D(v,s,d,p,f,a,o,l,g,_,m):e.isDataTexture?Ce.texSubImage2D(Ce.TEXTURE_2D,s,d,p,a,o,g,_,m.data):e.isCompressedTexture?Ce.compressedTexSubImage2D(Ce.TEXTURE_2D,s,d,p,m.width,m.height,g,m.data):Ce.texSubImage2D(Ce.TEXTURE_2D,s,d,p,a,o,g,_,m);le.pixelStorei(Ce.UNPACK_ROW_LENGTH,b),le.pixelStorei(Ce.UNPACK_IMAGE_HEIGHT,y),le.pixelStorei(Ce.UNPACK_SKIP_PIXELS,x),le.pixelStorei(Ce.UNPACK_SKIP_ROWS,S),le.pixelStorei(Ce.UNPACK_SKIP_IMAGES,T),0===s&&!0===t.generateMipmaps&&!0===t.mipmapsAutoUpdate&&Ce.generateMipmap(v),le.unbindTexture()},this.initRenderTarget=function(e){void 0===ce.get(e).__webglFramebuffer&&he.setupRenderTarget(e)},this.initTexture=function(e){e.isCubeTexture?he.setTextureCube(e,0):e.isData3DTexture?he.setTexture3D(e,0):e.isDataArrayTexture||e.isCompressedArrayTexture?he.setTexture2DArray(e,0):he.setTexture2D(e,0),le.unbindTexture()},this.resetState=function(){L=0,D=0,U=null,le.reset(),Ae.reset()},"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return ui}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorSpace=Qi._getDrawingBufferColorSpace(e),t.unpackColorSpace=Qi._getUnpackColorSpace()}},Scene:Zr,PerspectiveCamera:za,Raycaster:class{constructor(e,t,i=0,r=1/0){this.ray=new ps(e,t),this.near=i,this.far=r,this.camera=null,this.layers=new Er,this.params={Mesh:{},Line:{threshold:1},LOD:{},Points:{threshold:1},Sprite:{}}}set(e,t){this.ray.set(e,t)}setFromCamera(e,t){t.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(t.matrixWorld),this.ray.direction.set(e.x,e.y,.5).unproject(t).sub(this.ray.origin).normalize(),this.camera=t):t.isOrthographicCamera?(this.ray.origin.set(e.x,e.y,t.projectionMatrix.elements[14]).unproject(t),this.ray.direction.set(0,0,-1).transformDirection(t.matrixWorld),this.camera=t):Mi("Raycaster: Unsupported camera type: "+t.type)}setFromXRController(e){return ro.identity().extractRotation(e.matrixWorld),this.ray.origin.setFromMatrixPosition(e.matrixWorld),this.ray.direction.set(0,0,-1).applyMatrix4(ro),this}intersectObject(e,t=!0,i=[]){return so(e,this,i,t),i.sort(no),i}intersectObjects(e,t=!0,i=[]){for(let r=0,n=e.length;r<n;r++)so(e[r],this,i,t);return i.sort(no),i}},SRGBColorSpace:Xt,TextureLoader:class extends Ma{constructor(e){super(e)}load(e,t,i,r){const n=new lr,s=new wa(this.manager);return s.setPriority(this.priority),s.setCache(this.cache),s.setCrossOrigin(this.crossOrigin),s.setPath(this.path),s.load(e,function(e){n.image=e,n.needsUpdate=!0,void 0!==t&&t(n)},i,r),n}},Vector2:Vi,Vector3:Wi,Box3:pn,Color:Yr,Mesh:ws,SphereGeometry:ta,MeshBasicMaterial:fs,BackSide:1,Timer:to};var YF=R({props:{width:{default:window.innerWidth,onChange(e,t,i){isNaN(e)&&(t.width=i)}},height:{default:window.innerHeight,onChange(e,t,i){isNaN(e)&&(t.height=i)}},viewOffset:{default:[0,0]},backgroundColor:{default:"#000011"},backgroundImageUrl:{},onBackgroundImageLoaded:{},showNavInfo:{default:!0},skyRadius:{default:5e4},objects:{default:[]},lights:{default:[]},enablePointerInteraction:{default:!0,onChange(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:()=>!0,triggerUpdate:!1},tooltipContent:{triggerUpdate:!1},hoverDuringDrag:{default:!1,triggerUpdate:!1},clickAfterDrag:{default:!1,triggerUpdate:!1},onHover:{default:()=>{},triggerUpdate:!1},onClick:{default:()=>{},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(t=>t.render(e.scene,e.camera));const t=+new Date;if(e.enablePointerInteraction&&t-e.lastRaycasterCheck>=e.pointerRaycasterThrottleMs){e.lastRaycasterCheck=t;let i=null;if(e.hoverDuringDrag||!e.isPointerDragging){const t=this.intersectingObjects(e.pointerPos.x,e.pointerPos.y);e.hoverOrderComparator&&t.sort((t,i)=>e.hoverOrderComparator(t.object,i.object));const r=t.find(t=>e.hoverFilter(t.object))||null;i=r?r.object:null,e.intersection=r||null}i!==e.hoverObj&&(e.onHover(i,e.hoverObj,e.intersection),e.tooltip.content(i&&C(e.tooltipContent)(i,e.intersection)||null),e.hoverObj=i)}e.tweenGroup.update()}return this},getPointerPos:function(e){const{x:t,y:i}=e.pointerPos;return{x:t,y:i}},cameraPosition:function(e,t,i,r){const n=e.camera;if(t&&e.initialised){const l=t,u=i||{x:0,y:0,z:0};if(e.povPosTween?.end(),e.povTgtTween?.end(),r){const t=Object.assign({},n.position),i=o();e.tweenGroup.add(e.povPosTween=new VU(t).to(l,r).easing(FU.Quadratic.Out).onUpdate(s).onComplete(function(){e.povPosTween=void 0,e.tweenGroup.remove(this)}).start()),e.tweenGroup.add(e.povTgtTween=new VU(i).to(u,r/3).easing(FU.Quadratic.Out).onUpdate(a).onComplete(function(){e.povTgtTween=void 0,e.tweenGroup.remove(this)}).start())}else s(l),a(u);return this}return Object.assign({},n.position,{lookAt:o()});function s(e){const{x:t,y:i,z:r}=e;void 0!==t&&(n.position.x=t),void 0!==i&&(n.position.y=i),void 0!==r&&(n.position.z=r)}function a(t){const i=new qF.Vector3(t.x,t.y,t.z);e.controls.enabled&&e.controls.target?e.controls.target=i:n.lookAt(i)}function o(){return Object.assign(new qF.Vector3(0,0,-1e3).applyQuaternion(n.quaternion).add(n.position))}},zoomToFit:function(e,t=0,i=10,r,n){return this.fitToBbox(this.getBbox(r),t,i,n)},fitToBbox:function(e,t,i=0,r=10,n=!1){const s=e.camera;if(t){s.updateMatrixWorld();const a=new qF.Vector3,o=new qF.Vector3,l=new qF.Vector3,u=new qF.Vector3;s.getWorldPosition(u),s.getWorldDirection(l),a.crossVectors(l,s.up).normalize(),o.crossVectors(a,l).normalize();const c=(1-2*r/e.height)*s.fov/2*(Math.PI/180),h=Math.atan(Math.tan(c)*s.aspect),d=new qF.Vector3((t.x[0]+t.x[1])/2,(t.y[0]+t.y[1])/2,(t.z[0]+t.z[1])/2),p=n?l.clone().multiplyScalar(u.distanceTo(d)).add(u):d,f=Math.max(0,...[new qF.Vector3(t.x[0],t.y[0],t.z[0]),new qF.Vector3(t.x[0],t.y[0],t.z[1]),new qF.Vector3(t.x[0],t.y[1],t.z[0]),new qF.Vector3(t.x[0],t.y[1],t.z[1]),new qF.Vector3(t.x[1],t.y[0],t.z[0]),new qF.Vector3(t.x[1],t.y[0],t.z[1]),new qF.Vector3(t.x[1],t.y[1],t.z[0]),new qF.Vector3(t.x[1],t.y[1],t.z[1])].map(e=>{const t=e.clone().sub(p);return Math.max(Math.abs(t.dot(o))/Math.tan(c),Math.abs(t.dot(a))/Math.tan(h))-t.dot(l)})),m=l.clone().negate(),g={x:p.x+m.x*f,y:p.y+m.y*f,z:p.z+m.z*f};this.cameraPosition(g,p,i)}return this},getBbox:function(e,t=()=>!0){const i=new qF.Box3,r=e.objects.filter(t);return r.length?(r.forEach(e=>i.expandByObject(e)),Object.assign(...["x","y","z"].map(e=>({[e]:[i.min[e],i.max[e]]})))):null},getScreenCoords:function(e,t,i,r){const n=new qF.Vector3(t,i,r);return n.project(this.camera()),{x:(n.x+1)*e.width/2,y:-(n.y-1)*e.height/2}},getSceneCoords:function(e,t,i,r=0){const n=new qF.Vector2(t/e.width*2-1,-i/e.height*2+1),s=new qF.Raycaster;return s.setFromCamera(n,e.camera),Object.assign({},s.ray.at(r,new qF.Vector3))},intersectingObjects:function(e,t,i){const r=new qF.Vector2(t/e.width*2-1,-i/e.height*2+1),n=new qF.Raycaster;return n.params.Line.threshold=e.lineHoverPrecision,n.params.Points.threshold=e.pointsHoverPrecision,n.setFromCamera(r,e.camera),n.intersectObjects(e.objects,!0)},renderer:e=>e.renderer,scene:e=>e.scene,camera:e=>e.camera,postProcessingComposer:e=>e.postProcessingComposer,controls:e=>e.controls,tbControls:e=>e.controls,_destructor:function(e){(e=>{for(;e.children.length;){const t=e.children[0];e.remove(t),XF(t)}})(e.scene),e.controls?.dispose(),e.renderer?.dispose(),e.postProcessingComposer?.dispose()}},stateInit:()=>({scene:new qF.Scene,camera:new qF.PerspectiveCamera,timer:new qF.Timer,tweenGroup:new BU,lastRaycasterCheck:0}),init(e,t,{controlType:i="trackball",useWebGPU:r=!1,rendererConfig:n={},extraRenderers:s=[],waitForLoadComplete:a=!0}={}){e.innerHTML="",e.appendChild(t.container=document.createElement("div")),t.container.className="scene-container",t.container.style.position="relative",t.container.appendChild(t.navInfo=document.createElement("div")),t.navInfo.className="scene-nav-info",t.navInfo.textContent={orbit:"Left-click: rotate, Mouse-wheel/middle-click: zoom, Right-click: pan",trackball:"Left-click: rotate, Mouse-wheel/middle-click: zoom, Right-click: pan",fly:"WASD: move, R|F: up | down, Q|E: roll, up|down: pitch, left|right: yaw"}[i]||"",t.navInfo.style.display=t.showNavInfo?null:"none",t.tooltip=new jF(t.container),t.pointerPos=new qF.Vector2,t.pointerPos.x=-2,t.pointerPos.y=-2,["pointermove","pointerdown"].forEach(e=>t.container.addEventListener(e,i=>{if("pointerdown"===e&&(t.isPointerPressed=!0),!t.isPointerDragging&&"pointermove"===i.type&&(i.pressure>0||t.isPointerPressed)&&("mouse"===i.pointerType||void 0===i.movementX||[i.movementX,i.movementY].some(e=>Math.abs(e)>1))&&(t.isPointerDragging=!0),t.enablePointerInteraction){const e=function(e){const t=e.getBoundingClientRect(),i=window.pageXOffset||document.documentElement.scrollLeft,r=window.pageYOffset||document.documentElement.scrollTop;return{top:t.top+r,left:t.left+i}}(t.container);t.pointerPos.x=i.pageX-e.left,t.pointerPos.y=i.pageY-e.top}},{passive:!0})),t.container.addEventListener("pointerup",e=>{t.isPointerPressed&&(t.isPointerPressed=!1,t.isPointerDragging&&(t.isPointerDragging=!1,!t.clickAfterDrag)||requestAnimationFrame(()=>{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",e=>{t.onRightClick&&e.preventDefault()}),t.renderer=new(r?yL:qF.WebGLRenderer)(Object.assign({antialias:!0,alpha:!0},n)),t.renderer.setPixelRatio(Math.min(2,window.devicePixelRatio)),t.container.appendChild(t.renderer.domElement),t.extraRenderers=s,t.extraRenderers.forEach(e=>{e.domElement.style.position="absolute",e.domElement.style.top="0px",e.domElement.style.pointerEvents="none",t.container.appendChild(e.domElement)}),t.postProcessingComposer=new ZD(t.renderer),t.postProcessingComposer.addPass(new QD(t.scene,t.camera)),t.controls=new{trackball:GL,orbit:bD,fly:ID}[i](t.camera,t.renderer.domElement),"fly"===i&&(t.controls.movementSpeed=300,t.controls.rollSpeed=Math.PI/6,t.controls.dragToLook=!0),"trackball"!==i&&"orbit"!==i||(t.controls.minDistance=.1,t.controls.maxDistance=t.skyRadius,t.controls.addEventListener("start",()=>{t.controlsEngaged=!0}),t.controls.addEventListener("change",()=>{t.controlsEngaged&&(t.controlsDragging=!0)}),t.controls.addEventListener("end",()=>{t.controlsEngaged=!1,t.controlsDragging=!1}),t.renderer.domElement.style.cursor=null),[t.renderer,t.postProcessingComposer,...t.extraRenderers].forEach(e=>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 qF.Mesh),t.skysphere.visible=!1,t.loadComplete=t.scene.visible=!a,window.scene=t.scene},update(e,t){if(e.width&&e.height&&(t.hasOwnProperty("width")||t.hasOwnProperty("height"))){const t=e.width,i=e.height;e.container.style.width=`${t}px`,e.container.style.height=`${i}px`,[e.renderer,e.postProcessingComposer,...e.extraRenderers].forEach(e=>e.setSize(t,i)),e.camera.aspect=t/i;const r=e.viewOffset.slice(0,2);r.some(e=>e)&&e.camera.setViewOffset(t,i,...r,t,i),e.camera.updateProjectionMatrix()}if(t.hasOwnProperty("viewOffset")){const t=e.width,i=e.height,r=e.viewOffset.slice(0,2);r.some(e=>e)?e.camera.setViewOffset(t,i,...r,t,i):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 qF.SphereGeometry(e.skyRadius)),t.hasOwnProperty("backgroundColor")){let t=bU(e.backgroundColor).alpha;void 0===t&&(t=1),e.renderer.setClearColor(new qF.Color(IU(1,e.backgroundColor)),t)}function i(){e.loadComplete=e.scene.visible=!0}t.hasOwnProperty("backgroundImageUrl")&&(e.backgroundImageUrl?(new qF.TextureLoader).load(e.backgroundImageUrl,t=>{t.colorSpace=qF.SRGBColorSpace,e.skysphere.material=new qF.MeshBasicMaterial({map:t,side:qF.BackSide}),e.skysphere.visible=!0,e.onBackgroundImageLoaded&&setTimeout(e.onBackgroundImageLoaded),!e.loadComplete&&i()}):(e.skysphere.visible=!1,e.skysphere.material.map=null,!e.loadComplete&&i())),t.hasOwnProperty("showNavInfo")&&(e.navInfo.style.display=e.showNavInfo?null:"none"),t.hasOwnProperty("lights")&&((t.lights||[]).forEach(t=>e.scene.remove(t)),e.lights.forEach(t=>e.scene.add(t))),t.hasOwnProperty("objects")&&((t.objects||[]).forEach(t=>e.scene.remove(t)),e.objects.forEach(t=>e.scene.add(t)))}});const KF=[[0,3,4,7,6,5,2,1],[0,7,6,1,2,5,4,3],[0,7,6,1,2,5,4,3],[2,3,0,1,6,7,4,5],[2,3,0,1,6,7,4,5],[4,3,2,5,6,1,0,7],[4,3,2,5,6,1,0,7],[6,5,2,1,0,3,4,7]],ZF=[[0,1,2,3,4,5,6,7]],QF=[],JF=new Map([[ZF[0].join(""),0]]);for(let e=0;e<ZF.length;e++){const t=ZF[e],i=[];for(const e of KF){const r=e.map(e=>t[e]),n=r.join("");let s=JF.get(n);void 0===s&&(s=ZF.length,ZF.push(r),JF.set(n,s)),i.push(s)}QF.push(i)}const eO=[0n,1n,2n,3n,4n,5n,6n,7n],tO=new Wi(0,0,0);function iO(e=tO,t=10,i=1,r=0,n,s=0,a=1,o=2,l=3,u=4,c=5,h=6,d=7){if(i<0)return[new Wi(0,0,0)];if(!Number.isInteger(i))throw new TypeError("Order must be an integer.");const p=[];if("bigint"==typeof r||"bigint"==typeof n){const f=aO(r),m=8n**BigInt(i+1),g=void 0===n?m:aO(n),_=f<0n?0n:f,v=_+(g>0n?g:0n),b=v>m?m:v;if(_>=b)return p;const y=[s,a,o,l,u,c,h,d];return b-_===1n?(sO(p,e.x,e.y,e.z,t,i,_,BigInt(3*i),0,y),p):(nO(p,e.x,e.y,e.z,t,i,0n,m/8n,0,_,b,y),p)}const f=8**(i+1),m=Math.floor(r),g=Math.max(0,m),_=void 0===n?f:Math.max(0,Math.floor(n)),v=Math.min(f,g+_);if(g>=v)return p;const b=[s,a,o,l,u,c,h,d];return rO(p,e.x,e.y,e.z,t,i,0,f/8,0,g,v,b),p}function rO(e,t,i,r,n,s,a,o,l,u,c,h){const d=ZF[l],p=QF[l],f=n/2;for(let n=0;n<8;n++){const l=a+n*o;if(l+o<=u||l>=c)continue;const m=h[d[n]],g=t+(m<4?-f:f),_=i+(m<2||m>5?f:-f),v=r+(m%4==1||m%4==2?f:-f);0===s?e.push(new Wi(g,_,v)):rO(e,g,_,v,f,s-1,l,o/8,p[n],u,c,h)}}function nO(e,t,i,r,n,s,a,o,l,u,c,h){const d=ZF[l],p=QF[l],f=n/2,m=o/8n,g=a+8n*o,_=u<=a?0:Number((u-a)/o),v=c>=g?7:Number((c-1n-a)/o);let b=a+eO[_]*o;for(let n=_;n<=v;n++,b+=o){const a=h[d[n]],o=t+(a<4?-f:f),l=i+(a<2||a>5?f:-f),g=r+(a%4==1||a%4==2?f:-f);0===s?e.push(new Wi(o,l,g)):nO(e,o,l,g,f,s-1,b,m,p[n],u,c,h)}}function sO(e,t,i,r,n,s,a,o,l,u){const c=ZF[l],h=Number(a>>o&7n),d=u[c[h]],p=n/2,f=t+(d<4?-p:p),m=i+(d<2||d>5?p:-p),g=r+(d%4==1||d%4==2?p:-p);0===s?e.push(new Wi(f,m,g)):sO(e,f,m,g,p,s-1,a,o-3n,QF[l][h],u)}function aO(e){if("bigint"==typeof e)return e;if(!Number.isSafeInteger(e))throw new TypeError("BigInt ranges require integer values.");return BigInt(e)}const oO=[[0,1,5,4],[1,2,6,5],[2,3,7,6],[3,0,4,7],[0,3,2,1],[4,5,6,7]],lO=[[-1,-1,-1],[1,-1,-1],[1,1,-1],[-1,1,-1],[-1,-1,1],[1,-1,1],[1,1,1],[-1,1,1]],uO=new Float32Array(48),cO=new Float32Array(72),hO=new Uint16Array(36),dO=[[0,-1,0],[1,0,0],[0,1,0],[-1,0,0],[0,0,-1],[0,0,1]];for(let e=0;e<oO.length;e++){const t=oO[e],i=dO[e];for(let r=0;r<4;r++){const n=4*e+r,s=t[r];uO[2*n]=s%2,uO[2*n+1]=Math.floor(s/2)%2,cO.set(i,3*n)}const r=4*e,n=6*e;hO.set([r,r+1,r+2,r,r+2,r+3],n)}class pO extends Zn{constructor(e=[],t=1){if(super(),!Array.isArray(e))throw new TypeError("points must be an array of Vector3 instances");if(!Number.isFinite(t)||t<0)throw new RangeError("width must be a non-negative finite number");if(this.type="SquareTubeGeometry",e.length<=1){const i=e[0];if(!(1!==e.length||i&&Number.isFinite(i.x)&&Number.isFinite(i.y)&&Number.isFinite(i.z)))throw new TypeError("points[0] must have finite x, y, and z coordinates");if(this.parameters={points:i?[new Wi(i.x,i.y,i.z)]:[],width:t},!i||0===t)return this.setIndex([]),this.setAttribute("position",new kn([],3)),void this.setAttribute("uv",new kn([],2));const r=t/2,n=i.x,s=i.y,a=i.z,o=new Float32Array(72);let l=0;for(const e of oO)for(const t of e){const e=lO[t];o[l++]=n+e[0]*r,o[l++]=s+e[1]*r,o[l++]=a+e[2]*r}return this.setIndex(new Fn(hO.slice(),1)),this.setAttribute("position",new kn(o,3)),this.setAttribute("uv",new kn(uO.slice(),2)),this.setAttribute("normal",new kn(cO.slice(),3)),this.boundingBox=new pn(new Wi(n-r,s-r,a-r),new Wi(n+r,s+r,a+r)),void(this.boundingSphere=new Hn(new Wi(n,s,a),Math.sqrt(3)*r))}const i=1e-6,r=[],n=new Wi,s=new Wi;for(let t=0;t<e.length;t++){const i=e[t];if(!(i&&Number.isFinite(i.x)&&Number.isFinite(i.y)&&Number.isFinite(i.z)))throw new TypeError(`points[${t}] must have finite x, y, and z coordinates`);const a=new Wi(i.x,i.y,i.z);if(!r.length||0!==a.distanceToSquared(r[r.length-1])){for(;r.length>=2;){n.subVectors(r[r.length-1],r[r.length-2]),s.subVectors(a,r[r.length-1]);if(n.dot(s)/Math.sqrt(n.lengthSq()*s.lengthSq())<.999999)break;r.pop()}r.push(a)}}if(this.parameters={points:r.map(e=>e.clone()),width:t},0===r.length||0===t)return this.setIndex([]),this.setAttribute("position",new kn([],3)),void this.setAttribute("uv",new kn([],2));if(1===r.length){const[e,i,n]=r[0].toArray(),s=t/2,a=new Float32Array(72);let o=0;for(const t of oO)for(const r of t){const t=lO[r];a[o++]=e+t[0]*s,a[o++]=i+t[1]*s,a[o++]=n+t[2]*s}return this.setIndex(new Fn(hO.slice(),1)),this.setAttribute("position",new kn(a,3)),this.setAttribute("uv",new kn(uO.slice(),2)),this.setAttribute("normal",new kn(cO.slice(),3)),this.computeBoundingBox(),void this.computeBoundingSphere()}const a=new Array(r.length-1);for(let e=0;e<a.length;e++)a[e]=r[e+1].clone().sub(r[e]).normalize();const o=r.length>2&&0===r[0].distanceToSquared(r[r.length-1]);for(let e=1;e<a.length;e++){const t=a[e-1].dot(a[e]);if(!(Math.abs(t)<=i)&&!(t>=.999999))throw new RangeError("path turns must be 90 degrees; straight segments are also allowed")}if(o){const e=a[a.length-1].dot(a[0]);if(Math.abs(e)>i&&e<.999999)throw new RangeError("path turns must be 90 degrees; straight segments are also allowed")}const l=new Float64Array(r.length);for(let e=1;e<r.length;e++)l[e]=l[e-1]+r[e].distanceTo(r[e-1]);const u=l[l.length-1],c=t/2,h=u+(o?0:t),d=new Array(a.length),p=new Wi,f=new Wi,m=new Hi;for(let e=0;e<a.length;e++){if(0===e){const t=a[e],i=Math.abs(t.x),r=Math.abs(t.y),n=Math.abs(t.z);p.set(i<=r&&i<=n?1:0,r<i&&r<=n?1:0,n<i&&n<r?1:0),p.addScaledVector(t,-p.dot(t)).normalize()}else m.setFromUnitVectors(a[e-1],a[e]),p.applyQuaternion(m),p.addScaledVector(a[e],-p.dot(a[e])).normalize();f.crossVectors(a[e],p).normalize(),d[e]={normal:p.clone(),binormal:f.clone()}}const g=4*a.length+(o?0:2),_=4*g,v=new Float32Array(3*_),b=new Float32Array(2*_),y=_>65535,x=y?On:Fn,S=y?new Uint32Array(6*g):new Uint16Array(6*g),T=[0,1,2,3],M=Array.from({length:4},()=>new Wi),E=Array.from({length:4},()=>new Wi),w=Array.from({length:4},()=>new Wi),A=new Wi,R=new Wi,C=new Wi,N=new Wi,P=new Wi,L=new Wi,D=new Wi,U=[null,null,null,null],I=new Float32Array(8),F=new Float32Array([0,0,.75,0,.5,0,.25,0]),O=new Float32Array([0,1,.25,1,.5,1,.75,1]);let B=0,k=0,z=0,G=0;function V(e,t,i,r,n,s=0){for(let r=0;r<4;r++){const a=0===r||3===r?1:-1,o=r<2?1:-1;n[r].copy(e).addScaledVector(i,s*c).addScaledVector(t.normal,a*c).addScaledVector(t.binormal,o*c)}if(r){P.copy(i).add(r).normalize();const t=P.dot(i);for(const r of n)L.copy(r).sub(e),r.addScaledVector(i,-P.dot(L)/t)}}function H(e,t,i,r,n,s){const a=void 0!==s;if(A.copy(t).sub(e),R.copy(i).sub(e),C.crossVectors(A,R).dot(n)<0){const e=t;if(t=r,r=e,a){const e=s[2],t=s[3];s[2]=s[6],s[3]=s[7],s[6]=e,s[7]=t}}U[0]=e,U[1]=t,U[2]=i,U[3]=r;for(let e=0;e<4;e++){const t=U[e];v[B++]=t.x,v[B++]=t.y,v[B++]=t.z,a?(b[k++]=s[2*e],b[k++]=1-s[2*e+1]):(b[k++]=1===e||2===e?1:0,b[k++]=e>=2?0:1)}S[G++]=z,S[G++]=z+1,S[G++]=z+2,S[G++]=z,S[G++]=z+2,S[G++]=z+3,z+=4}for(let e=0;e<a.length;e++){const t=a[e],n=e>0?a[e-1]:o?a[a.length-1]:void 0,s=e<a.length-1?a[e+1]:o?a[0]:void 0,u=n&&Math.abs(n.dot(t))<=i?n:void 0,p=s&&Math.abs(t.dot(s))<=i?s:void 0;if(V(r[e],d[e],t,u,M,0!==e||o?0:-1),V(r[e+1],d[e],t,p,E,e!==a.length-1||o?0:1),0===e)for(let e=0;e<4;e++)w[e].copy(M[e]);D.copy(r[e]).add(r[e+1]).multiplyScalar(.5);const f=0!==e||o?(l[e]+(o?0:c))/h:0,m=e!==a.length-1||o?(l[e+1]+(o?0:c))/h:1;for(const e of T){const t=(e+1)%4,i=0,r=1;I[0]=i,I[1]=f,I[2]=r,I[3]=f,I[4]=r,I[5]=m,I[6]=i,I[7]=m,N.copy(M[e]).add(M[t]).add(E[e]).add(E[t]).multiplyScalar(.25).sub(D),H(M[e],M[t],E[t],E[e],N,I)}}o||(L.copy(a[0]).negate(),H(w[0],w[3],w[2],w[1],L,F),H(E[0],E[1],E[2],E[3],a[a.length-1],O)),this.setIndex(new x(S,1)),this.setAttribute("position",new kn(v,3)),this.setAttribute("uv",new kn(b,2)),this.computeVertexNormals(),this.computeBoundingBox(),this.computeBoundingSphere()}copy(e){return super.copy(e),this.parameters={points:e.parameters.points.map(e=>e.clone()),width:e.parameters.width},this}}class fO extends pO{constructor(e,t,i,{padding:r=0,paddingAbsolute:n=0,simplifyCurves:s=!0}={}){super(...function(){if("bigint"!=typeof t&&(t=Math.round(t)),"bigint"!=typeof i&&(i=Math.round(i)),s){const r="bigint"==typeof t?8n:8;for(;!(t%r)&&!(i%r)&&e>0;)t/=r,i/=r,e-=1}const a=iO(void 0,1,e-1,t,i),o=2**(1-e),l=(o-Math.min(n,.5*o))*(1-Math.min(1,r));return[a,l]}()),this.type="HilbertGeometry";const a=this.parameters;this.parameters={...a,order:e,start:t,length:i,padding:r,paddingAbsolute:n,simplifyCurves:s}}clone(){return new this.constructor(0,1,0).copy(this)}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters,{points:e.parameters.points.map(e=>e.clone())}),this}}function mO(e,t){return null==e||null==t?NaN:e<t?-1:e>t?1:e>=t?0:NaN}function gO(e,t){return null==e||null==t?NaN:t<e?-1:t>e?1:t>=e?0:NaN}function _O(e){let t,i,r;function n(e,r,n=0,s=e.length){if(n<s){if(0!==t(r,r))return s;do{const t=n+s>>>1;i(e[t],r)<0?n=t+1:s=t}while(n<s)}return n}return 2!==e.length?(t=mO,i=(t,i)=>mO(e(t),i),r=(t,i)=>e(t)-i):(t=e===mO||e===gO?e:vO,i=e,r=e),{left:n,center:function(e,t,i=0,s=e.length){const a=n(e,t,i,s-1);return a>i&&r(e[a-1],t)>-r(e[a],t)?a-1:a},right:function(e,r,n=0,s=e.length){if(n<s){if(0!==t(r,r))return s;do{const t=n+s>>>1;i(e[t],r)<=0?n=t+1:s=t}while(n<s)}return n}}}function vO(){return 0}_O(mO),_O(function(e){return null===e?NaN:+e}).center;class bO extends Map{constructor(e,t=xO){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:t}}),null!=e)for(const[t,i]of e)this.set(t,i)}get(e){return super.get(yO(this,e))}has(e){return super.has(yO(this,e))}set(e,t){return super.set(function({_intern:e,_key:t},i){const r=t(i);return e.has(r)?e.get(r):(e.set(r,i),i)}(this,e),t)}delete(e){return super.delete(function({_intern:e,_key:t},i){const r=t(i);e.has(r)&&(i=e.get(r),e.delete(r));return i}(this,e))}}function yO({_intern:e,_key:t},i){const r=t(i);return e.has(r)?e.get(r):i}function xO(e){return null!==e&&"object"==typeof e?e.valueOf():e}function SO(e,t,i){e.prototype=t.prototype=i,i.constructor=e}function TO(e,t){var i=Object.create(e.prototype);for(var r in t)i[r]=t[r];return i}function MO(){}var EO=.7,wO=1/EO,AO="\\s*([+-]?\\d+)\\s*",RO="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",CO="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",NO=/^#([0-9a-f]{3,8})$/,PO=new RegExp(`^rgb\\(${AO},${AO},${AO}\\)$`),LO=new RegExp(`^rgb\\(${CO},${CO},${CO}\\)$`),DO=new RegExp(`^rgba\\(${AO},${AO},${AO},${RO}\\)$`),UO=new RegExp(`^rgba\\(${CO},${CO},${CO},${RO}\\)$`),IO=new RegExp(`^hsl\\(${RO},${CO},${CO}\\)$`),FO=new RegExp(`^hsla\\(${RO},${CO},${CO},${RO}\\)$`),OO={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};function BO(){return this.rgb().formatHex()}function kO(){return this.rgb().formatRgb()}function zO(e){var t,i;return e=(e+"").trim().toLowerCase(),(t=NO.exec(e))?(i=t[1].length,t=parseInt(t[1],16),6===i?GO(t):3===i?new jO(t>>8&15|t>>4&240,t>>4&15|240&t,(15&t)<<4|15&t,1):8===i?VO(t>>24&255,t>>16&255,t>>8&255,(255&t)/255):4===i?VO(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|240&t,((15&t)<<4|15&t)/255):null):(t=PO.exec(e))?new jO(t[1],t[2],t[3],1):(t=LO.exec(e))?new jO(255*t[1]/100,255*t[2]/100,255*t[3]/100,1):(t=DO.exec(e))?VO(t[1],t[2],t[3],t[4]):(t=UO.exec(e))?VO(255*t[1]/100,255*t[2]/100,255*t[3]/100,t[4]):(t=IO.exec(e))?ZO(t[1],t[2]/100,t[3]/100,1):(t=FO.exec(e))?ZO(t[1],t[2]/100,t[3]/100,t[4]):OO.hasOwnProperty(e)?GO(OO[e]):"transparent"===e?new jO(NaN,NaN,NaN,0):null}function GO(e){return new jO(e>>16&255,e>>8&255,255&e,1)}function VO(e,t,i,r){return r<=0&&(e=t=i=NaN),new jO(e,t,i,r)}function HO(e){return e instanceof MO||(e=zO(e)),e?new jO((e=e.rgb()).r,e.g,e.b,e.opacity):new jO}function WO(e,t,i,r){return 1===arguments.length?HO(e):new jO(e,t,i,null==r?1:r)}function jO(e,t,i,r){this.r=+e,this.g=+t,this.b=+i,this.opacity=+r}function $O(){return`#${KO(this.r)}${KO(this.g)}${KO(this.b)}`}function XO(){const e=qO(this.opacity);return`${1===e?"rgb(":"rgba("}${YO(this.r)}, ${YO(this.g)}, ${YO(this.b)}${1===e?")":`, ${e})`}`}function qO(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function YO(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function KO(e){return((e=YO(e))<16?"0":"")+e.toString(16)}function ZO(e,t,i,r){return r<=0?e=t=i=NaN:i<=0||i>=1?e=t=NaN:t<=0&&(e=NaN),new JO(e,t,i,r)}function QO(e){if(e instanceof JO)return new JO(e.h,e.s,e.l,e.opacity);if(e instanceof MO||(e=zO(e)),!e)return new JO;if(e instanceof JO)return e;var t=(e=e.rgb()).r/255,i=e.g/255,r=e.b/255,n=Math.min(t,i,r),s=Math.max(t,i,r),a=NaN,o=s-n,l=(s+n)/2;return o?(a=t===s?(i-r)/o+6*(i<r):i===s?(r-t)/o+2:(t-i)/o+4,o/=l<.5?s+n:2-s-n,a*=60):o=l>0&&l<1?0:a,new JO(a,o,l,e.opacity)}function JO(e,t,i,r){this.h=+e,this.s=+t,this.l=+i,this.opacity=+r}function eB(e){return(e=(e||0)%360)<0?e+360:e}function tB(e){return Math.max(0,Math.min(1,e||0))}function iB(e,t,i){return 255*(e<60?t+(i-t)*e/60:e<180?i:e<240?t+(i-t)*(240-e)/60:t)}SO(MO,zO,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:BO,formatHex:BO,formatHex8:function(){return this.rgb().formatHex8()},formatHsl:function(){return QO(this).formatHsl()},formatRgb:kO,toString:kO}),SO(jO,WO,TO(MO,{brighter(e){return e=null==e?wO:Math.pow(wO,e),new jO(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=null==e?EO:Math.pow(EO,e),new jO(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new jO(YO(this.r),YO(this.g),YO(this.b),qO(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:$O,formatHex:$O,formatHex8:function(){return`#${KO(this.r)}${KO(this.g)}${KO(this.b)}${KO(255*(isNaN(this.opacity)?1:this.opacity))}`},formatRgb:XO,toString:XO})),SO(JO,function(e,t,i,r){return 1===arguments.length?QO(e):new JO(e,t,i,null==r?1:r)},TO(MO,{brighter(e){return e=null==e?wO:Math.pow(wO,e),new JO(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=null==e?EO:Math.pow(EO,e),new JO(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+360*(this.h<0),t=isNaN(e)||isNaN(this.s)?0:this.s,i=this.l,r=i+(i<.5?i:1-i)*t,n=2*i-r;return new jO(iB(e>=240?e-240:e+120,n,r),iB(e,n,r),iB(e<120?e+240:e-120,n,r),this.opacity)},clamp(){return new JO(eB(this.h),tB(this.s),tB(this.l),qO(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=qO(this.opacity);return`${1===e?"hsl(":"hsla("}${eB(this.h)}, ${100*tB(this.s)}%, ${100*tB(this.l)}%${1===e?")":`, ${e})`}`}}));const rB=Math.PI/180,nB=180/Math.PI,sB=.96422,aB=.82521,oB=4/29,lB=6/29,uB=3*lB*lB,cB=lB*lB*lB;function hB(e){if(e instanceof dB)return new dB(e.l,e.a,e.b,e.opacity);if(e instanceof _B)return vB(e);e instanceof jO||(e=HO(e));var t,i,r=gB(e.r),n=gB(e.g),s=gB(e.b),a=pB((.2225045*r+.7168786*n+.0606169*s)/1);return r===n&&n===s?t=i=a:(t=pB((.4360747*r+.3850649*n+.1430804*s)/sB),i=pB((.0139322*r+.0971045*n+.7141733*s)/aB)),new dB(116*a-16,500*(t-a),200*(a-i),e.opacity)}function dB(e,t,i,r){this.l=+e,this.a=+t,this.b=+i,this.opacity=+r}function pB(e){return e>cB?Math.pow(e,1/3):e/uB+oB}function fB(e){return e>lB?e*e*e:uB*(e-oB)}function mB(e){return 255*(e<=.0031308?12.92*e:1.055*Math.pow(e,1/2.4)-.055)}function gB(e){return(e/=255)<=.04045?e/12.92:Math.pow((e+.055)/1.055,2.4)}function _B(e,t,i,r){this.h=+e,this.c=+t,this.l=+i,this.opacity=+r}function vB(e){if(isNaN(e.h))return new dB(e.l,0,0,e.opacity);var t=e.h*rB;return new dB(e.l,Math.cos(t)*e.c,Math.sin(t)*e.c,e.opacity)}SO(dB,function(e,t,i,r){return 1===arguments.length?hB(e):new dB(e,t,i,null==r?1:r)},TO(MO,{brighter(e){return new dB(this.l+18*(null==e?1:e),this.a,this.b,this.opacity)},darker(e){return new dB(this.l-18*(null==e?1:e),this.a,this.b,this.opacity)},rgb(){var e=(this.l+16)/116,t=isNaN(this.a)?e:e+this.a/500,i=isNaN(this.b)?e:e-this.b/200;return new jO(mB(3.1338561*(t=sB*fB(t))-1.6168667*(e=1*fB(e))-.4906146*(i=aB*fB(i))),mB(-.9787684*t+1.9161415*e+.033454*i),mB(.0719453*t-.2289914*e+1.4052427*i),this.opacity)}})),SO(_B,function(e,t,i,r){return 1===arguments.length?function(e){if(e instanceof _B)return new _B(e.h,e.c,e.l,e.opacity);if(e instanceof dB||(e=hB(e)),0===e.a&&0===e.b)return new _B(NaN,0<e.l&&e.l<100?0:NaN,e.l,e.opacity);var t=Math.atan2(e.b,e.a)*nB;return new _B(t<0?t+360:t,Math.sqrt(e.a*e.a+e.b*e.b),e.l,e.opacity)}(e):new _B(e,t,i,null==r?1:r)},TO(MO,{brighter(e){return new _B(this.h,this.c,this.l+18*(null==e?1:e),this.opacity)},darker(e){return new _B(this.h,this.c,this.l-18*(null==e?1:e),this.opacity)},rgb(){return vB(this).rgb()}}));var bB=-.14861,yB=1.78277,xB=-.29227,SB=-.90649,TB=1.97294,MB=TB*SB,EB=TB*yB,wB=yB*xB-SB*bB;function AB(e,t,i,r){return 1===arguments.length?function(e){if(e instanceof RB)return new RB(e.h,e.s,e.l,e.opacity);e instanceof jO||(e=HO(e));var t=e.r/255,i=e.g/255,r=e.b/255,n=(wB*r+MB*t-EB*i)/(wB+MB-EB),s=r-n,a=(TB*(i-n)-xB*s)/SB,o=Math.sqrt(a*a+s*s)/(TB*n*(1-n)),l=o?Math.atan2(a,s)*nB-120:NaN;return new RB(l<0?l+360:l,o,n,e.opacity)}(e):new RB(e,t,i,null==r?1:r)}function RB(e,t,i,r){this.h=+e,this.s=+t,this.l=+i,this.opacity=+r}SO(RB,AB,TO(MO,{brighter(e){return e=null==e?wO:Math.pow(wO,e),new RB(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=null==e?EO:Math.pow(EO,e),new RB(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=isNaN(this.h)?0:(this.h+120)*rB,t=+this.l,i=isNaN(this.s)?0:this.s*t*(1-t),r=Math.cos(e),n=Math.sin(e);return new jO(255*(t+i*(bB*r+yB*n)),255*(t+i*(xB*r+SB*n)),255*(t+i*(TB*r)),this.opacity)}}));var CB=e=>()=>e;function NB(e,t){return function(i){return e+i*t}}function PB(e){return 1===(e=+e)?LB:function(t,i){return i-t?function(e,t,i){return e=Math.pow(e,i),t=Math.pow(t,i)-e,i=1/i,function(r){return Math.pow(e+r*t,i)}}(t,i,e):CB(isNaN(t)?i:t)}}function LB(e,t){var i=t-e;return i?NB(e,i):CB(isNaN(e)?t:e)}!function e(t){var i=PB(t);function r(e,t){var r=i((e=WO(e)).r,(t=WO(t)).r),n=i(e.g,t.g),s=i(e.b,t.b),a=LB(e.opacity,t.opacity);return function(t){return e.r=r(t),e.g=n(t),e.b=s(t),e.opacity=a(t),e+""}}return r.gamma=e,r}(1);var DB,UB=(DB=function(e){var t=e.length-1;return function(i){var r=i<=0?i=0:i>=1?(i=1,t-1):Math.floor(i*t),n=e[r],s=e[r+1],a=r>0?e[r-1]:2*n-s,o=r<t-1?e[r+2]:2*s-n;return function(e,t,i,r,n){var s=e*e,a=s*e;return((1-3*e+3*s-a)*t+(4-6*s+3*a)*i+(1+3*e+3*s-3*a)*r+a*n)/6}((i-r/t)*t,a,n,s,o)}},function(e){var t,i,r=e.length,n=new Array(r),s=new Array(r),a=new Array(r);for(t=0;t<r;++t)i=WO(e[t]),n[t]=i.r||0,s[t]=i.g||0,a[t]=i.b||0;return n=DB(n),s=DB(s),a=DB(a),i.opacity=1,function(e){return i.r=n(e),i.g=s(e),i.b=a(e),i+""}});function IB(e){return((e=Math.exp(e))+1/e)/2}function FB(e){return function t(i){function r(t,r){var n=e((t=AB(t)).h,(r=AB(r)).h),s=LB(t.s,r.s),a=LB(t.l,r.l),o=LB(t.opacity,r.opacity);return function(e){return t.h=n(e),t.s=s(e),t.l=a(Math.pow(e,i)),t.opacity=o(e),t+""}}return i=+i,r.gamma=t,r}(1)}!function e(t,i,r){function n(e,n){var s,a,o=e[0],l=e[1],u=e[2],c=n[0],h=n[1],d=n[2],p=c-o,f=h-l,m=p*p+f*f;if(m<1e-12)a=Math.log(d/u)/t,s=function(e){return[o+e*p,l+e*f,u*Math.exp(t*e*a)]};else{var g=Math.sqrt(m),_=(d*d-u*u+r*m)/(2*u*i*g),v=(d*d-u*u-r*m)/(2*d*i*g),b=Math.log(Math.sqrt(_*_+1)-_),y=Math.log(Math.sqrt(v*v+1)-v);a=(y-b)/t,s=function(e){var r=e*a,n=IB(b),s=u/(i*g)*(n*function(e){return((e=Math.exp(2*e))-1)/(e+1)}(t*r+b)-function(e){return((e=Math.exp(e))-1/e)/2}(b));return[o+s*p,l+s*f,u*n/IB(t*r+b)]}}return s.duration=1e3*Math.abs(a)*t/Math.SQRT2,s}return n.rho=function(t){var i=Math.max(.001,+t),r=i*i;return e(i,r,r*r)},n}(Math.SQRT2,2,4),FB(function(e,t){var i=t-e;return i?NB(e,i>180||i<-180?i-360*Math.round(i/360):i):CB(isNaN(e)?t:e)});var OB=FB(LB);function BB(e,t){switch(arguments.length){case 0:break;case 1:this.range(e);break;default:this.range(t).domain(e)}return this}const kB=Symbol("implicit");function zB(){var e=new bO,t=[],i=[],r=kB;function n(n){let s=e.get(n);if(void 0===s){if(r!==kB)return r;e.set(n,s=t.push(n)-1)}return i[s%i.length]}return n.domain=function(i){if(!arguments.length)return t.slice();t=[],e=new bO;for(const r of i)e.has(r)||e.set(r,t.push(r)-1);return n},n.range=function(e){return arguments.length?(i=Array.from(e),n):i.slice()},n.unknown=function(e){return arguments.length?(r=e,n):r},n.copy=function(){return zB(t,i).unknown(r)},BB.apply(n,arguments),n}function GB(e){for(var t=e.length/6|0,i=new Array(t),r=0;r<t;)i[r]="#"+e.slice(6*r,6*++r);return i}GB("1f77b4ff7f0e2ca02cd627289467bd8c564be377c27f7f7fbcbd2217becf"),GB("7fc97fbeaed4fdc086ffff99386cb0f0027fbf5b17666666"),GB("1b9e77d95f027570b3e7298a66a61ee6ab02a6761d666666"),GB("4269d0efb118ff725c6cc5b03ca951ff8ab7a463f297bbf59c6b4e9498a0");var VB=GB("a6cee31f78b4b2df8a33a02cfb9a99e31a1cfdbf6fff7f00cab2d66a3d9affff99b15928");GB("fbb4aeb3cde3ccebc5decbe4fed9a6ffffcce5d8bdfddaecf2f2f2"),GB("b3e2cdfdcdaccbd5e8f4cae4e6f5c9fff2aef1e2cccccccc"),GB("e41a1c377eb84daf4a984ea3ff7f00ffff33a65628f781bf999999"),GB("66c2a5fc8d628da0cbe78ac3a6d854ffd92fe5c494b3b3b3"),GB("8dd3c7ffffb3bebadafb807280b1d3fdb462b3de69fccde5d9d9d9bc80bdccebc5ffed6f"),GB("4e79a7f28e2ce1575976b7b259a14fedc949af7aa1ff9da79c755fbab0ab");var HB=e=>UB(e[e.length-1]);function WB(e){var t=e.length;return function(i){return e[Math.max(0,Math.min(t-1,Math.floor(i*t)))]}}function jB(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,r=Array(t);i<t;i++)r[i]=e[i];return r}function $B(e,t,i){if("function"==typeof e?e===t:e.has(t))return arguments.length<3?t:i;throw new TypeError("Private element is not present on this object")}function XB(e,t){return e.get($B(e,t))}function qB(e,t,i){(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,i)}function YB(e,t,i){return e.set($B(e,t),i),i}function KB(e,t,i){return t&&function(e,t){for(var i=0;i<t.length;i++){var r=t[i];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,JB(r.key),r)}}(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function ZB(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var i=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=i){var r,n,s,a,o=[],l=!0,u=!1;try{if(s=(i=i.call(e)).next,0===t);else for(;!(l=(r=s.call(i)).done)&&(o.push(r.value),o.length!==t);l=!0);}catch(e){u=!0,n=e}finally{try{if(!l&&null!=i.return&&(a=i.return(),Object(a)!==a))return}finally{if(u)throw n}}return o}}(e,t)||ek(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 QB(e){return function(e){if(Array.isArray(e))return jB(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||ek(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 JB(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.call(e,t);if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==typeof t?t:t+""}function ek(e,t){if(e){if("string"==typeof e)return jB(e,t);var i={}.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?jB(e,t):void 0}}HB(new Array(3).concat("d8b365f5f5f55ab4ac","a6611adfc27d80cdc1018571","a6611adfc27df5f5f580cdc1018571","8c510ad8b365f6e8c3c7eae55ab4ac01665e","8c510ad8b365f6e8c3f5f5f5c7eae55ab4ac01665e","8c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e","8c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e","5430058c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e003c30","5430058c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e003c30").map(GB)),HB(new Array(3).concat("af8dc3f7f7f77fbf7b","7b3294c2a5cfa6dba0008837","7b3294c2a5cff7f7f7a6dba0008837","762a83af8dc3e7d4e8d9f0d37fbf7b1b7837","762a83af8dc3e7d4e8f7f7f7d9f0d37fbf7b1b7837","762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b7837","762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b7837","40004b762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b783700441b","40004b762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b783700441b").map(GB)),HB(new Array(3).concat("e9a3c9f7f7f7a1d76a","d01c8bf1b6dab8e1864dac26","d01c8bf1b6daf7f7f7b8e1864dac26","c51b7de9a3c9fde0efe6f5d0a1d76a4d9221","c51b7de9a3c9fde0eff7f7f7e6f5d0a1d76a4d9221","c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221","c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221","8e0152c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221276419","8e0152c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221276419").map(GB)),HB(new Array(3).concat("998ec3f7f7f7f1a340","5e3c99b2abd2fdb863e66101","5e3c99b2abd2f7f7f7fdb863e66101","542788998ec3d8daebfee0b6f1a340b35806","542788998ec3d8daebf7f7f7fee0b6f1a340b35806","5427888073acb2abd2d8daebfee0b6fdb863e08214b35806","5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b35806","2d004b5427888073acb2abd2d8daebfee0b6fdb863e08214b358067f3b08","2d004b5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b358067f3b08").map(GB)),HB(new Array(3).concat("ef8a62f7f7f767a9cf","ca0020f4a58292c5de0571b0","ca0020f4a582f7f7f792c5de0571b0","b2182bef8a62fddbc7d1e5f067a9cf2166ac","b2182bef8a62fddbc7f7f7f7d1e5f067a9cf2166ac","b2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac","b2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac","67001fb2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac053061","67001fb2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac053061").map(GB)),HB(new Array(3).concat("ef8a62ffffff999999","ca0020f4a582bababa404040","ca0020f4a582ffffffbababa404040","b2182bef8a62fddbc7e0e0e09999994d4d4d","b2182bef8a62fddbc7ffffffe0e0e09999994d4d4d","b2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d","b2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d","67001fb2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d1a1a1a","67001fb2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d1a1a1a").map(GB)),HB(new Array(3).concat("fc8d59ffffbf91bfdb","d7191cfdae61abd9e92c7bb6","d7191cfdae61ffffbfabd9e92c7bb6","d73027fc8d59fee090e0f3f891bfdb4575b4","d73027fc8d59fee090ffffbfe0f3f891bfdb4575b4","d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4","d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4","a50026d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4313695","a50026d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4313695").map(GB)),HB(new Array(3).concat("fc8d59ffffbf91cf60","d7191cfdae61a6d96a1a9641","d7191cfdae61ffffbfa6d96a1a9641","d73027fc8d59fee08bd9ef8b91cf601a9850","d73027fc8d59fee08bffffbfd9ef8b91cf601a9850","d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850","d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850","a50026d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850006837","a50026d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850006837").map(GB)),HB(new Array(3).concat("fc8d59ffffbf99d594","d7191cfdae61abdda42b83ba","d7191cfdae61ffffbfabdda42b83ba","d53e4ffc8d59fee08be6f59899d5943288bd","d53e4ffc8d59fee08bffffbfe6f59899d5943288bd","d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd","d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd","9e0142d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd5e4fa2","9e0142d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd5e4fa2").map(GB)),HB(new Array(3).concat("e5f5f999d8c92ca25f","edf8fbb2e2e266c2a4238b45","edf8fbb2e2e266c2a42ca25f006d2c","edf8fbccece699d8c966c2a42ca25f006d2c","edf8fbccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45006d2c00441b").map(GB)),HB(new Array(3).concat("e0ecf49ebcda8856a7","edf8fbb3cde38c96c688419d","edf8fbb3cde38c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d810f7c4d004b").map(GB)),HB(new Array(3).concat("e0f3dba8ddb543a2ca","f0f9e8bae4bc7bccc42b8cbe","f0f9e8bae4bc7bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe0868ac084081").map(GB)),HB(new Array(3).concat("fee8c8fdbb84e34a33","fef0d9fdcc8afc8d59d7301f","fef0d9fdcc8afc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301fb300007f0000").map(GB)),HB(new Array(3).concat("ece2f0a6bddb1c9099","f6eff7bdc9e167a9cf02818a","f6eff7bdc9e167a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016c59014636").map(GB)),HB(new Array(3).concat("ece7f2a6bddb2b8cbe","f1eef6bdc9e174a9cf0570b0","f1eef6bdc9e174a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0045a8d023858").map(GB)),HB(new Array(3).concat("e7e1efc994c7dd1c77","f1eef6d7b5d8df65b0ce1256","f1eef6d7b5d8df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125698004367001f").map(GB)),HB(new Array(3).concat("fde0ddfa9fb5c51b8a","feebe2fbb4b9f768a1ae017e","feebe2fbb4b9f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a017749006a").map(GB)),HB(new Array(3).concat("edf8b17fcdbb2c7fb8","ffffcca1dab441b6c4225ea8","ffffcca1dab441b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea8253494081d58").map(GB)),HB(new Array(3).concat("f7fcb9addd8e31a354","ffffccc2e69978c679238443","ffffccc2e69978c67931a354006837","ffffccd9f0a3addd8e78c67931a354006837","ffffccd9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443006837004529").map(GB)),HB(new Array(3).concat("fff7bcfec44fd95f0e","ffffd4fed98efe9929cc4c02","ffffd4fed98efe9929d95f0e993404","ffffd4fee391fec44ffe9929d95f0e993404","ffffd4fee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c02993404662506").map(GB)),HB(new Array(3).concat("ffeda0feb24cf03b20","ffffb2fecc5cfd8d3ce31a1c","ffffb2fecc5cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cbd0026800026").map(GB)),HB(new Array(3).concat("deebf79ecae13182bd","eff3ffbdd7e76baed62171b5","eff3ffbdd7e76baed63182bd08519c","eff3ffc6dbef9ecae16baed63182bd08519c","eff3ffc6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b508519c08306b").map(GB)),HB(new Array(3).concat("e5f5e0a1d99b31a354","edf8e9bae4b374c476238b45","edf8e9bae4b374c47631a354006d2c","edf8e9c7e9c0a1d99b74c47631a354006d2c","edf8e9c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45006d2c00441b").map(GB)),HB(new Array(3).concat("f0f0f0bdbdbd636363","f7f7f7cccccc969696525252","f7f7f7cccccc969696636363252525","f7f7f7d9d9d9bdbdbd969696636363252525","f7f7f7d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525000000").map(GB)),HB(new Array(3).concat("efedf5bcbddc756bb1","f2f0f7cbc9e29e9ac86a51a3","f2f0f7cbc9e29e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a354278f3f007d").map(GB)),HB(new Array(3).concat("fee0d2fc9272de2d26","fee5d9fcae91fb6a4acb181d","fee5d9fcae91fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181da50f1567000d").map(GB)),HB(new Array(3).concat("fee6cefdae6be6550d","feeddefdbe85fd8d3cd94701","feeddefdbe85fd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d94801a636037f2704").map(GB)),OB(AB(300,.5,0),AB(-240,.5,1)),OB(AB(-100,.75,.35),AB(80,1.5,.8)),OB(AB(260,.75,.35),AB(80,1.5,.8)),AB(),WO(),WB(GB("44015444025645045745055946075a46085c460a5d460b5e470d60470e6147106347116447136548146748166848176948186a481a6c481b6d481c6e481d6f481f70482071482173482374482475482576482677482878482979472a7a472c7a472d7b472e7c472f7d46307e46327e46337f463480453581453781453882443983443a83443b84433d84433e85423f854240864241864142874144874045884046883f47883f48893e49893e4a893e4c8a3d4d8a3d4e8a3c4f8a3c508b3b518b3b528b3a538b3a548c39558c39568c38588c38598c375a8c375b8d365c8d365d8d355e8d355f8d34608d34618d33628d33638d32648e32658e31668e31678e31688e30698e306a8e2f6b8e2f6c8e2e6d8e2e6e8e2e6f8e2d708e2d718e2c718e2c728e2c738e2b748e2b758e2a768e2a778e2a788e29798e297a8e297b8e287c8e287d8e277e8e277f8e27808e26818e26828e26828e25838e25848e25858e24868e24878e23888e23898e238a8d228b8d228c8d228d8d218e8d218f8d21908d21918c20928c20928c20938c1f948c1f958b1f968b1f978b1f988b1f998a1f9a8a1e9b8a1e9c891e9d891f9e891f9f881fa0881fa1881fa1871fa28720a38620a48621a58521a68522a78522a88423a98324aa8325ab8225ac8226ad8127ad8128ae8029af7f2ab07f2cb17e2db27d2eb37c2fb47c31b57b32b67a34b67935b77937b87838b9773aba763bbb753dbc743fbc7340bd7242be7144bf7046c06f48c16e4ac16d4cc26c4ec36b50c46a52c56954c56856c66758c7655ac8645cc8635ec96260ca6063cb5f65cb5e67cc5c69cd5b6ccd5a6ece5870cf5773d05675d05477d1537ad1517cd2507fd34e81d34d84d44b86d54989d5488bd6468ed64590d74393d74195d84098d83e9bd93c9dd93ba0da39a2da37a5db36a8db34aadc32addc30b0dd2fb2dd2db5de2bb8de29bade28bddf26c0df25c2df23c5e021c8e020cae11fcde11dd0e11cd2e21bd5e21ad8e219dae319dde318dfe318e2e418e5e419e7e419eae51aece51befe51cf1e51df4e61ef6e620f8e621fbe723fde725")),WB(GB("00000401000501010601010802010902020b02020d03030f03031204041405041606051806051a07061c08071e0907200a08220b09240c09260d0a290e0b2b100b2d110c2f120d31130d34140e36150e38160f3b180f3d19103f1a10421c10441d11471e114920114b21114e22115024125325125527125829115a2a115c2c115f2d11612f116331116533106734106936106b38106c390f6e3b0f703d0f713f0f72400f74420f75440f764510774710784910784a10794c117a4e117b4f127b51127c52137c54137d56147d57157e59157e5a167e5c167f5d177f5f187f601880621980641a80651a80671b80681c816a1c816b1d816d1d816e1e81701f81721f817320817521817621817822817922827b23827c23827e24828025828125818326818426818627818827818928818b29818c29818e2a81902a81912b81932b80942c80962c80982d80992d809b2e7f9c2e7f9e2f7fa02f7fa1307ea3307ea5317ea6317da8327daa337dab337cad347cae347bb0357bb2357bb3367ab5367ab73779b83779ba3878bc3978bd3977bf3a77c03a76c23b75c43c75c53c74c73d73c83e73ca3e72cc3f71cd4071cf4070d0416fd2426fd3436ed5446dd6456cd8456cd9466bdb476adc4869de4968df4a68e04c67e24d66e34e65e44f64e55064e75263e85362e95462ea5661eb5760ec5860ed5a5fee5b5eef5d5ef05f5ef1605df2625df2645cf3655cf4675cf4695cf56b5cf66c5cf66e5cf7705cf7725cf8745cf8765cf9785df9795df97b5dfa7d5efa7f5efa815ffb835ffb8560fb8761fc8961fc8a62fc8c63fc8e64fc9065fd9266fd9467fd9668fd9869fd9a6afd9b6bfe9d6cfe9f6dfea16efea36ffea571fea772fea973feaa74feac76feae77feb078feb27afeb47bfeb67cfeb77efeb97ffebb81febd82febf84fec185fec287fec488fec68afec88cfeca8dfecc8ffecd90fecf92fed194fed395fed597fed799fed89afdda9cfddc9efddea0fde0a1fde2a3fde3a5fde5a7fde7a9fde9aafdebacfcecaefceeb0fcf0b2fcf2b4fcf4b6fcf6b8fcf7b9fcf9bbfcfbbdfcfdbf")),WB(GB("00000401000501010601010802010a02020c02020e03021004031204031405041706041907051b08051d09061f0a07220b07240c08260d08290e092b10092d110a30120a32140b34150b37160b39180c3c190c3e1b0c411c0c431e0c451f0c48210c4a230c4c240c4f260c51280b53290b552b0b572d0b592f0a5b310a5c320a5e340a5f3609613809623909633b09643d09653e0966400a67420a68440a68450a69470b6a490b6a4a0c6b4c0c6b4d0d6c4f0d6c510e6c520e6d540f6d550f6d57106e59106e5a116e5c126e5d126e5f136e61136e62146e64156e65156e67166e69166e6a176e6c186e6d186e6f196e71196e721a6e741a6e751b6e771c6d781c6d7a1d6d7c1d6d7d1e6d7f1e6c801f6c82206c84206b85216b87216b88226a8a226a8c23698d23698f24699025689225689326679526679727669827669a28659b29649d29649f2a63a02a63a22b62a32c61a52c60a62d60a82e5fa92e5eab2f5ead305dae305cb0315bb1325ab3325ab43359b63458b73557b93556ba3655bc3754bd3853bf3952c03a51c13a50c33b4fc43c4ec63d4dc73e4cc83f4bca404acb4149cc4248ce4347cf4446d04545d24644d34743d44842d54a41d74b3fd84c3ed94d3dda4e3cdb503bdd513ade5238df5337e05536e15635e25734e35933e45a31e55c30e65d2fe75e2ee8602de9612bea632aeb6429eb6628ec6726ed6925ee6a24ef6c23ef6e21f06f20f1711ff1731df2741cf3761bf37819f47918f57b17f57d15f67e14f68013f78212f78410f8850ff8870ef8890cf98b0bf98c0af98e09fa9008fa9207fa9407fb9606fb9706fb9906fb9b06fb9d07fc9f07fca108fca309fca50afca60cfca80dfcaa0ffcac11fcae12fcb014fcb216fcb418fbb61afbb81dfbba1ffbbc21fbbe23fac026fac228fac42afac62df9c72ff9c932f9cb35f8cd37f8cf3af7d13df7d340f6d543f6d746f5d949f5db4cf4dd4ff4df53f4e156f3e35af3e55df2e661f2e865f2ea69f1ec6df1ed71f1ef75f1f179f2f27df2f482f3f586f3f68af4f88ef5f992f6fa96f8fb9af9fc9dfafda1fcffa4")),WB(GB("0d088710078813078916078a19068c1b068d1d068e20068f2206902406912605912805922a05932c05942e05952f059631059733059735049837049938049a3a049a3c049b3e049c3f049c41049d43039e44039e46039f48039f4903a04b03a14c02a14e02a25002a25102a35302a35502a45601a45801a45901a55b01a55c01a65e01a66001a66100a76300a76400a76600a76700a86900a86a00a86c00a86e00a86f00a87100a87201a87401a87501a87701a87801a87a02a87b02a87d03a87e03a88004a88104a78305a78405a78606a68707a68808a68a09a58b0aa58d0ba58e0ca48f0da4910ea3920fa39410a29511a19613a19814a099159f9a169f9c179e9d189d9e199da01a9ca11b9ba21d9aa31e9aa51f99a62098a72197a82296aa2395ab2494ac2694ad2793ae2892b02991b12a90b22b8fb32c8eb42e8db52f8cb6308bb7318ab83289ba3388bb3488bc3587bd3786be3885bf3984c03a83c13b82c23c81c33d80c43e7fc5407ec6417dc7427cc8437bc9447aca457acb4679cc4778cc4977cd4a76ce4b75cf4c74d04d73d14e72d24f71d35171d45270d5536fd5546ed6556dd7566cd8576bd9586ada5a6ada5b69db5c68dc5d67dd5e66de5f65de6164df6263e06363e16462e26561e26660e3685fe4695ee56a5de56b5de66c5ce76e5be76f5ae87059e97158e97257ea7457eb7556eb7655ec7754ed7953ed7a52ee7b51ef7c51ef7e50f07f4ff0804ef1814df1834cf2844bf3854bf3874af48849f48948f58b47f58c46f68d45f68f44f79044f79143f79342f89441f89540f9973ff9983ef99a3efa9b3dfa9c3cfa9e3bfb9f3afba139fba238fca338fca537fca636fca835fca934fdab33fdac33fdae32fdaf31fdb130fdb22ffdb42ffdb52efeb72dfeb82cfeba2cfebb2bfebd2afebe2afec029fdc229fdc328fdc527fdc627fdc827fdca26fdcb26fccd25fcce25fcd025fcd225fbd324fbd524fbd724fad824fada24f9dc24f9dd25f8df25f8e125f7e225f7e425f6e626f6e826f5e926f5eb27f4ed27f3ee27f3f027f2f227f1f426f1f525f0f724f0f921"));var tk=new WeakMap,ik=new WeakMap,rk=new WeakMap,nk=new WeakMap,sk=new WeakMap,ak=new WeakMap,ok=function(){return KB(function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),qB(this,tk,new Map),qB(this,ik,new Map),qB(this,rk,function(e){return e}),qB(this,nk,function(){return{}}),qB(this,sk,function(){}),qB(this,ak,function(){})},[{key:"getObj",value:function(e){return XB(tk,this).get(XB(rk,this).call(this,e))}},{key:"getData",value:function(e){return XB(ik,this).get(e)}},{key:"entries",value:function(){return QB(XB(ik,this).entries()).map(function(e){var t=ZB(e,2),i=t[0];return[t[1],i]})}},{key:"id",value:function(e){return YB(rk,this,C(e)),this}},{key:"onCreateObj",value:function(e){return YB(nk,this,e),this}},{key:"onUpdateObj",value:function(e){return YB(sk,this,e),this}},{key:"onRemoveObj",value:function(e){return YB(ak,this,e),this}},{key:"digest",value:function(e){var t=this;e.filter(function(e){return!XB(tk,t).has(XB(rk,t).call(t,e))}).forEach(function(e){var i=XB(nk,t).call(t,e);XB(tk,t).set(XB(rk,t).call(t,e),i),XB(ik,t).set(i,e)});var i=new Map(e.map(function(e){return[XB(rk,t).call(t,e),e]}));return XB(tk,this).forEach(function(e,r){i.has(r)?XB(sk,t).call(t,e,i.get(r)):(XB(ak,t).call(t,e,r),XB(tk,t).delete(r),XB(ik,t).delete(e))}),this}},{key:"clear",value:function(){return this.digest([]),this}}])}();function lk(e){return lk="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},lk(e)}var uk=/^\s+/,ck=/\s+$/;function hk(e,t){if(t=t||{},(e=e||"")instanceof hk)return e;if(!(this instanceof hk))return new hk(e,t);var i=function(e){var t={r:0,g:0,b:0},i=1,r=null,n=null,s=null,a=!1,o=!1;"string"==typeof e&&(e=function(e){e=e.replace(uk,"").replace(ck,"").toLowerCase();var t,i=!1;if(Rk[e])e=Rk[e],i=!0;else if("transparent"==e)return{r:0,g:0,b:0,a:0,format:"name"};if(t=Gk.rgb.exec(e))return{r:t[1],g:t[2],b:t[3]};if(t=Gk.rgba.exec(e))return{r:t[1],g:t[2],b:t[3],a:t[4]};if(t=Gk.hsl.exec(e))return{h:t[1],s:t[2],l:t[3]};if(t=Gk.hsla.exec(e))return{h:t[1],s:t[2],l:t[3],a:t[4]};if(t=Gk.hsv.exec(e))return{h:t[1],s:t[2],v:t[3]};if(t=Gk.hsva.exec(e))return{h:t[1],s:t[2],v:t[3],a:t[4]};if(t=Gk.hex8.exec(e))return{r:Dk(t[1]),g:Dk(t[2]),b:Dk(t[3]),a:Ok(t[4]),format:i?"name":"hex8"};if(t=Gk.hex6.exec(e))return{r:Dk(t[1]),g:Dk(t[2]),b:Dk(t[3]),format:i?"name":"hex"};if(t=Gk.hex4.exec(e))return{r:Dk(t[1]+""+t[1]),g:Dk(t[2]+""+t[2]),b:Dk(t[3]+""+t[3]),a:Ok(t[4]+""+t[4]),format:i?"name":"hex8"};if(t=Gk.hex3.exec(e))return{r:Dk(t[1]+""+t[1]),g:Dk(t[2]+""+t[2]),b:Dk(t[3]+""+t[3]),format:i?"name":"hex"};return!1}(e));"object"==lk(e)&&(Vk(e.r)&&Vk(e.g)&&Vk(e.b)?(t=function(e,t,i){return{r:255*Pk(e,255),g:255*Pk(t,255),b:255*Pk(i,255)}}(e.r,e.g,e.b),a=!0,o="%"===String(e.r).substr(-1)?"prgb":"rgb"):Vk(e.h)&&Vk(e.s)&&Vk(e.v)?(r=Ik(e.s),n=Ik(e.v),t=function(e,t,i){e=6*Pk(e,360),t=Pk(t,100),i=Pk(i,100);var r=Math.floor(e),n=e-r,s=i*(1-t),a=i*(1-n*t),o=i*(1-(1-n)*t),l=r%6,u=[i,a,s,s,o,i][l],c=[o,i,i,a,s,s][l],h=[s,s,o,i,i,a][l];return{r:255*u,g:255*c,b:255*h}}(e.h,r,n),a=!0,o="hsv"):Vk(e.h)&&Vk(e.s)&&Vk(e.l)&&(r=Ik(e.s),s=Ik(e.l),t=function(e,t,i){var r,n,s;function a(e,t,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?e+6*(t-e)*i:i<.5?t:i<2/3?e+(t-e)*(2/3-i)*6:e}if(e=Pk(e,360),t=Pk(t,100),i=Pk(i,100),0===t)r=n=s=i;else{var o=i<.5?i*(1+t):i+t-i*t,l=2*i-o;r=a(l,o,e+1/3),n=a(l,o,e),s=a(l,o,e-1/3)}return{r:255*r,g:255*n,b:255*s}}(e.h,r,s),a=!0,o="hsl"),e.hasOwnProperty("a")&&(i=e.a));return i=Nk(i),{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:i}}(e);this._originalInput=e,this._r=i.r,this._g=i.g,this._b=i.b,this._a=i.a,this._roundA=Math.round(100*this._a)/100,this._format=t.format||i.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=i.ok}function dk(e,t,i){e=Pk(e,255),t=Pk(t,255),i=Pk(i,255);var r,n,s=Math.max(e,t,i),a=Math.min(e,t,i),o=(s+a)/2;if(s==a)r=n=0;else{var l=s-a;switch(n=o>.5?l/(2-s-a):l/(s+a),s){case e:r=(t-i)/l+(t<i?6:0);break;case t:r=(i-e)/l+2;break;case i:r=(e-t)/l+4}r/=6}return{h:r,s:n,l:o}}function pk(e,t,i){e=Pk(e,255),t=Pk(t,255),i=Pk(i,255);var r,n,s=Math.max(e,t,i),a=Math.min(e,t,i),o=s,l=s-a;if(n=0===s?0:l/s,s==a)r=0;else{switch(s){case e:r=(t-i)/l+(t<i?6:0);break;case t:r=(i-e)/l+2;break;case i:r=(e-t)/l+4}r/=6}return{h:r,s:n,v:o}}function fk(e,t,i,r){var n=[Uk(Math.round(e).toString(16)),Uk(Math.round(t).toString(16)),Uk(Math.round(i).toString(16))];return r&&n[0].charAt(0)==n[0].charAt(1)&&n[1].charAt(0)==n[1].charAt(1)&&n[2].charAt(0)==n[2].charAt(1)?n[0].charAt(0)+n[1].charAt(0)+n[2].charAt(0):n.join("")}function mk(e,t,i,r){return[Uk(Fk(r)),Uk(Math.round(e).toString(16)),Uk(Math.round(t).toString(16)),Uk(Math.round(i).toString(16))].join("")}function gk(e,t){t=0===t?0:t||10;var i=hk(e).toHsl();return i.s-=t/100,i.s=Lk(i.s),hk(i)}function _k(e,t){t=0===t?0:t||10;var i=hk(e).toHsl();return i.s+=t/100,i.s=Lk(i.s),hk(i)}function vk(e){return hk(e).desaturate(100)}function bk(e,t){t=0===t?0:t||10;var i=hk(e).toHsl();return i.l+=t/100,i.l=Lk(i.l),hk(i)}function yk(e,t){t=0===t?0:t||10;var i=hk(e).toRgb();return i.r=Math.max(0,Math.min(255,i.r-Math.round(-t/100*255))),i.g=Math.max(0,Math.min(255,i.g-Math.round(-t/100*255))),i.b=Math.max(0,Math.min(255,i.b-Math.round(-t/100*255))),hk(i)}function xk(e,t){t=0===t?0:t||10;var i=hk(e).toHsl();return i.l-=t/100,i.l=Lk(i.l),hk(i)}function Sk(e,t){var i=hk(e).toHsl(),r=(i.h+t)%360;return i.h=r<0?360+r:r,hk(i)}function Tk(e){var t=hk(e).toHsl();return t.h=(t.h+180)%360,hk(t)}function Mk(e,t){if(isNaN(t)||t<=0)throw new Error("Argument to polyad must be a positive number");for(var i=hk(e).toHsl(),r=[hk(e)],n=360/t,s=1;s<t;s++)r.push(hk({h:(i.h+s*n)%360,s:i.s,l:i.l}));return r}function Ek(e){var t=hk(e).toHsl(),i=t.h;return[hk(e),hk({h:(i+72)%360,s:t.s,l:t.l}),hk({h:(i+216)%360,s:t.s,l:t.l})]}function wk(e,t,i){t=t||6,i=i||30;var r=hk(e).toHsl(),n=360/i,s=[hk(e)];for(r.h=(r.h-(n*t>>1)+720)%360;--t;)r.h=(r.h+n)%360,s.push(hk(r));return s}function Ak(e,t){t=t||6;for(var i=hk(e).toHsv(),r=i.h,n=i.s,s=i.v,a=[],o=1/t;t--;)a.push(hk({h:r,s:n,v:s})),s=(s+o)%1;return a}hk.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,i,r=this.toRgb();return e=r.r/255,t=r.g/255,i=r.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*(i<=.03928?i/12.92:Math.pow((i+.055)/1.055,2.4))},setAlpha:function(e){return this._a=Nk(e),this._roundA=Math.round(100*this._a)/100,this},toHsv:function(){var e=pk(this._r,this._g,this._b);return{h:360*e.h,s:e.s,v:e.v,a:this._a}},toHsvString:function(){var e=pk(this._r,this._g,this._b),t=Math.round(360*e.h),i=Math.round(100*e.s),r=Math.round(100*e.v);return 1==this._a?"hsv("+t+", "+i+"%, "+r+"%)":"hsva("+t+", "+i+"%, "+r+"%, "+this._roundA+")"},toHsl:function(){var e=dk(this._r,this._g,this._b);return{h:360*e.h,s:e.s,l:e.l,a:this._a}},toHslString:function(){var e=dk(this._r,this._g,this._b),t=Math.round(360*e.h),i=Math.round(100*e.s),r=Math.round(100*e.l);return 1==this._a?"hsl("+t+", "+i+"%, "+r+"%)":"hsla("+t+", "+i+"%, "+r+"%, "+this._roundA+")"},toHex:function(e){return fk(this._r,this._g,this._b,e)},toHexString:function(e){return"#"+this.toHex(e)},toHex8:function(e){return function(e,t,i,r,n){var s=[Uk(Math.round(e).toString(16)),Uk(Math.round(t).toString(16)),Uk(Math.round(i).toString(16)),Uk(Fk(r))];if(n&&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*Pk(this._r,255))+"%",g:Math.round(100*Pk(this._g,255))+"%",b:Math.round(100*Pk(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+Math.round(100*Pk(this._r,255))+"%, "+Math.round(100*Pk(this._g,255))+"%, "+Math.round(100*Pk(this._b,255))+"%)":"rgba("+Math.round(100*Pk(this._r,255))+"%, "+Math.round(100*Pk(this._g,255))+"%, "+Math.round(100*Pk(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":!(this._a<1)&&(Ck[fk(this._r,this._g,this._b,!0)]||!1)},toFilter:function(e){var t="#"+mk(this._r,this._g,this._b,this._a),i=t,r=this._gradientType?"GradientType = 1, ":"";if(e){var n=hk(e);i="#"+mk(n._r,n._g,n._b,n._a)}return"progid:DXImageTransform.Microsoft.gradient("+r+"startColorstr="+t+",endColorstr="+i+")"},toString:function(e){var t=!!e;e=e||this._format;var i=!1,r=this._a<1&&this._a>=0;return t||!r||"hex"!==e&&"hex6"!==e&&"hex3"!==e&&"hex4"!==e&&"hex8"!==e&&"name"!==e?("rgb"===e&&(i=this.toRgbString()),"prgb"===e&&(i=this.toPercentageRgbString()),"hex"!==e&&"hex6"!==e||(i=this.toHexString()),"hex3"===e&&(i=this.toHexString(!0)),"hex4"===e&&(i=this.toHex8String(!0)),"hex8"===e&&(i=this.toHex8String()),"name"===e&&(i=this.toName()),"hsl"===e&&(i=this.toHslString()),"hsv"===e&&(i=this.toHsvString()),i||this.toHexString()):"name"===e&&0===this._a?this.toName():this.toRgbString()},clone:function(){return hk(this.toString())},_applyModification:function(e,t){var i=e.apply(null,[this].concat([].slice.call(t)));return this._r=i._r,this._g=i._g,this._b=i._b,this.setAlpha(i._a),this},lighten:function(){return this._applyModification(bk,arguments)},brighten:function(){return this._applyModification(yk,arguments)},darken:function(){return this._applyModification(xk,arguments)},desaturate:function(){return this._applyModification(gk,arguments)},saturate:function(){return this._applyModification(_k,arguments)},greyscale:function(){return this._applyModification(vk,arguments)},spin:function(){return this._applyModification(Sk,arguments)},_applyCombination:function(e,t){return e.apply(null,[this].concat([].slice.call(t)))},analogous:function(){return this._applyCombination(wk,arguments)},complement:function(){return this._applyCombination(Tk,arguments)},monochromatic:function(){return this._applyCombination(Ak,arguments)},splitcomplement:function(){return this._applyCombination(Ek,arguments)},triad:function(){return this._applyCombination(Mk,[3])},tetrad:function(){return this._applyCombination(Mk,[4])}},hk.fromRatio=function(e,t){if("object"==lk(e)){var i={};for(var r in e)e.hasOwnProperty(r)&&(i[r]="a"===r?e[r]:Ik(e[r]));e=i}return hk(e,t)},hk.equals=function(e,t){return!(!e||!t)&&hk(e).toRgbString()==hk(t).toRgbString()},hk.random=function(){return hk.fromRatio({r:Math.random(),g:Math.random(),b:Math.random()})},hk.mix=function(e,t,i){i=0===i?0:i||50;var r=hk(e).toRgb(),n=hk(t).toRgb(),s=i/100;return hk({r:(n.r-r.r)*s+r.r,g:(n.g-r.g)*s+r.g,b:(n.b-r.b)*s+r.b,a:(n.a-r.a)*s+r.a})},
|
|
3
3
|
// <http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef (WCAG Version 2)
|
|
4
4
|
// Analyze the 2 colors and returns the color contrast defined by (WCAG Version 2)
|
|
5
|
-
hk.readability=function(e,t){var i=hk(e),r=hk(t);return(Math.max(i.getLuminance(),r.getLuminance())+.05)/(Math.min(i.getLuminance(),r.getLuminance())+.05)},hk.isReadable=function(e,t,i){var r,n,s=hk.readability(e,t);switch(n=!1,(r=function(e){var t,i;t=((e=e||{level:"AA",size:"small"}).level||"AA").toUpperCase(),i=(e.size||"small").toLowerCase(),"AA"!==t&&"AAA"!==t&&(t="AA");"small"!==i&&"large"!==i&&(i="small");return{level:t,size:i}}(i)).level+r.size){case"AAsmall":case"AAAlarge":n=s>=4.5;break;case"AAlarge":n=s>=3;break;case"AAAsmall":n=s>=7}return n},hk.mostReadable=function(e,t,i){var r,n,s,a,o=null,l=0;n=(i=i||{}).includeFallbackColors,s=i.level,a=i.size;for(var u=0;u<t.length;u++)(r=hk.readability(e,t[u]))>l&&(l=r,o=hk(t[u]));return hk.isReadable(e,o,{level:s,size:a})||!n?o:(i.includeFallbackColors=!1,hk.mostReadable(e,["#fff","#000"],i))};var Rk=hk.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"},Ck=hk.hexNames=function(e){var t={};for(var i in e)e.hasOwnProperty(i)&&(t[e[i]]=i);return t}(Rk);function Nk(e){return e=parseFloat(e),(isNaN(e)||e<0||e>1)&&(e=1),e}function Pk(e,t){(function(e){return"string"==typeof e&&-1!=e.indexOf(".")&&1===parseFloat(e)})(e)&&(e="100%");var i=function(e){return"string"==typeof e&&-1!=e.indexOf("%")}(e);return e=Math.min(t,Math.max(0,parseFloat(e))),i&&(e=parseInt(e*t,10)/100),Math.abs(e-t)<1e-6?1:e%t/parseFloat(t)}function Lk(e){return Math.min(1,Math.max(0,e))}function Dk(e){return parseInt(e,16)}function Uk(e){return 1==e.length?"0"+e:""+e}function Ik(e){return e<=1&&(e=100*e+"%"),e}function Fk(e){return Math.round(255*parseFloat(e)).toString(16)}function Ok(e){return Dk(e)/255}var Bk,kk,zk,Gk=(kk="[\\s|\\(]+("+(Bk="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+Bk+")[,|\\s]+("+Bk+")\\s*\\)?",zk="[\\s|\\(]+("+Bk+")[,|\\s]+("+Bk+")[,|\\s]+("+Bk+")[,|\\s]+("+Bk+")\\s*\\)?",{CSS_UNIT:new RegExp(Bk),rgb:new RegExp("rgb"+kk),rgba:new RegExp("rgba"+zk),hsl:new RegExp("hsl"+kk),hsla:new RegExp("hsla"+zk),hsv:new RegExp("hsv"+kk),hsva:new RegExp("hsva"+zk),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 Vk(e){return!!Gk.CSS_UNIT.exec(e)}const Hk=e=>{e instanceof Array?e.forEach(Hk):(e.map&&e.map.dispose(),e.dispose())},Wk=e=>{e.geometry&&e.geometry.dispose(),e.material&&Hk(e.material),e.texture&&e.texture.dispose(),e.children&&e.children.forEach(Wk)};class jk extends ok{constructor(e,{dataBindAttr:t="__data",objBindAttr:i="__threeObj",removeDelay:r=0}={}){super(),this.scene=e,this.#e=t,this.#t=i,this.#i=r,this.onRemoveObj(()=>{})}onCreateObj(e){return super.onCreateObj(t=>{const i=e(t);return t[this.#t]=i,i[this.#e]=t,this.scene.add(i),i}),this}onRemoveObj(e){return super.onRemoveObj((t,i)=>{const r=super.getData(t);e(t,i);const n=()=>{this.scene.remove(t),Wk(t),delete r[this.#t]};this.#i?setTimeout(n,this.#i):n()}),this}scene;#e;#t;#i}const $k=e=>isNaN(e)?parseInt(hk(e).toHex(),16):e,Xk=e=>e&&isNaN(e)?zO(e).opacity:1,qk=32,Yk=64,Kk=.92,Zk=.8;function Qk(e,t){const i=new ma,r=Xk(e);return i.color.set($k(e)),i.transparent=r<1,i.opacity=r,t&&(i.onBeforeCompile=e=>{e.uniforms.labelGlyphTexture={value:t.glyphTexture},e.uniforms.labelDataTexture={value:t.labelTexture},e.uniforms.labelDataTextureSize={value:new Vi(t.labelTexture.image.width,t.labelTexture.image.height)},e.uniforms.labelLabelsPerRow={value:t.labelsPerRow},e.vertexShader=e.vertexShader.replace("#include <common>","#include <common>\n attribute float hilbertLabelId;\n attribute float hilbertLabelLength;\n attribute float hilbertLabelAspect;\n attribute float hilbertLabelMaxFontSize;\n attribute float hilbertLabelReverse;\n attribute vec4 hilbertLabelColor;\n varying vec2 vHilbertLabelUv;\n varying float vHilbertLabelId;\n varying float vHilbertLabelLength;\n varying float vHilbertLabelAspect;\n varying float vHilbertLabelMaxFontSize;\n varying float vHilbertLabelReverse;\n varying vec4 vHilbertLabelColor;").replace("#include <begin_vertex>","#include <begin_vertex>\n vHilbertLabelUv = uv;\n vHilbertLabelId = hilbertLabelId;\n vHilbertLabelLength = hilbertLabelLength;\n vHilbertLabelAspect = hilbertLabelAspect;\n vHilbertLabelMaxFontSize = hilbertLabelMaxFontSize;\n vHilbertLabelReverse = hilbertLabelReverse;\n vHilbertLabelColor = hilbertLabelColor;"),e.fragmentShader=e.fragmentShader.replace("#include <common>","#include <common>\n uniform sampler2D labelGlyphTexture;\n uniform sampler2D labelDataTexture;\n uniform vec2 labelDataTextureSize;\n uniform float labelLabelsPerRow;\n varying vec2 vHilbertLabelUv;\n varying float vHilbertLabelId;\n varying float vHilbertLabelLength;\n varying float vHilbertLabelAspect;\n varying float vHilbertLabelMaxFontSize;\n varying float vHilbertLabelReverse;\n varying vec4 vHilbertLabelColor;").replace("#include <map_fragment>",`#include <map_fragment>\n if (vHilbertLabelId >= 0.0 && vHilbertLabelUv.x >= 0.0 && vHilbertLabelUv.x <= 1.0) {\n float aspect = max(vHilbertLabelAspect, 0.001);\n float visibleLength = vHilbertLabelLength;\n float textUnits = 1.0 + max(visibleLength - 1.0, 0.0) * ${Zk.toFixed(2)};\n float maxFontSize = min(${.8.toFixed(2)}, vHilbertLabelMaxFontSize);\n float fontSize = min(maxFontSize, aspect * ${Kk.toFixed(2)} / textUnits);\n bool isTruncated = fontSize < ${.05.toFixed(2)};\n if (isTruncated) visibleLength = min(visibleLength, max(3.0, floor((aspect * ${Kk.toFixed(2)} / ${.05.toFixed(2)} - 1.0) / ${Zk.toFixed(2)}) + 1.0));\n textUnits = 1.0 + max(visibleLength - 1.0, 0.0) * ${Zk.toFixed(2)};\n fontSize = min(maxFontSize, aspect * ${Kk.toFixed(2)} / textUnits);\n float characterSize = fontSize / aspect;\n float characterAdvance = characterSize * ${Zk.toFixed(2)};\n float textWidth = characterSize + characterAdvance * max(visibleLength - 1.0, 0.0);\n float textStart = (1.0 - textWidth) * 0.5;\n float textPosition = vHilbertLabelUv.x - textStart;\n if (textPosition >= 0.0 && textPosition < textWidth) {\n float glyphVerticalPosition = (vHilbertLabelUv.y - 0.5) / max(fontSize, 0.001) + 0.5;\n if (glyphVerticalPosition >= 0.0 && glyphVerticalPosition <= 1.0) {\n float charPosition = textPosition / max(characterAdvance, 0.001);\n float charSlot = floor(charPosition);\n float charIndex = mix(charSlot, visibleLength - 1.0 - charSlot, vHilbertLabelReverse);\n float glyphHorizontalPosition = (textPosition - charSlot * characterAdvance) / max(characterSize, 0.001);\n glyphHorizontalPosition = mix(glyphHorizontalPosition, 1.0 - glyphHorizontalPosition, vHilbertLabelReverse);\n float labelRow = floor(vHilbertLabelId / labelLabelsPerRow);\n float labelColumn = mod(vHilbertLabelId, labelLabelsPerRow);\n vec2 dataUv = (vec2(labelColumn * 32.0 + charIndex, labelRow) + 0.5) / labelDataTextureSize;\n float charCode = floor(texture2D(labelDataTexture, dataUv).r * 255.0 + 0.5);\n if (isTruncated && charIndex >= visibleLength - 3.0) charCode = 46.0;\n vec2 glyphCell = vec2(mod(charCode, 16.0), floor(charCode / 16.0));\n vec2 glyphUv = vec2(0.015625 + clamp(glyphHorizontalPosition, 0.0, 1.0) * 0.96875, 0.015625 + (1.0 - glyphVerticalPosition) * 0.96875);\n vec2 glyphAtlasUv = vec2(glyphCell.x + glyphUv.x, 16.0 - glyphCell.y - glyphUv.y) / 16.0;\n float glyphCoverage = texture2D(labelGlyphTexture, glyphAtlasUv).a;\n float previousCharSlot = charSlot - 1.0;\n float previousCharIndex = mix(previousCharSlot, visibleLength - 1.0 - previousCharSlot, vHilbertLabelReverse);\n float previousGlyphPosition = (textPosition - previousCharSlot * characterAdvance) / max(characterSize, 0.001);\n previousGlyphPosition = mix(previousGlyphPosition, 1.0 - previousGlyphPosition, vHilbertLabelReverse);\n if (charSlot > 0.0 && previousGlyphPosition < 1.0) {\n vec2 previousDataUv = (vec2(labelColumn * 32.0 + previousCharIndex, labelRow) + 0.5) / labelDataTextureSize;\n float previousCharCode = floor(texture2D(labelDataTexture, previousDataUv).r * 255.0 + 0.5);\n if (isTruncated && previousCharIndex >= visibleLength - 3.0) previousCharCode = 46.0;\n vec2 previousGlyphCell = vec2(mod(previousCharCode, 16.0), floor(previousCharCode / 16.0));\n vec2 previousGlyphAtlasUv = vec2(\n previousGlyphCell.x + 0.015625 + clamp(previousGlyphPosition, 0.0, 1.0) * 0.96875,\n 16.0 - previousGlyphCell.y - glyphUv.y\n ) / 16.0;\n glyphCoverage = max(glyphCoverage, texture2D(labelGlyphTexture, previousGlyphAtlasUv).a);\n }\n float glyphAlpha = glyphCoverage * vHilbertLabelColor.a;\n diffuseColor.rgb = mix(diffuseColor.rgb, vHilbertLabelColor.rgb, glyphAlpha);\n }\n }\n }`)},i.customProgramCacheKey=()=>"three-hilbert-label-glyph-atlas"),i}function Jk(e,t,i=!1){const r=e.getAttribute("position").count,n=i?t.length:r,s=(e,t)=>i?new Cs(e,t):new kn(e,t),a=new Float32Array(n),o=new Float32Array(n),l=new Float32Array(4*n);t.forEach(({info:e},t)=>{const r=e?.color,s=new Yr(r?$k(r):16777215),u=i?t+1:n;for(let n=i?t:0;n<u;n++)a[n]=e?e.id:-1,o[n]=e?e.length:0,l[4*n]=s.r,l[4*n+1]=s.g,l[4*n+2]=s.b,l[4*n+3]=r?Xk(r):0}),e.setAttribute("hilbertLabelId",s(a,1)),e.setAttribute("hilbertLabelLength",s(o,1)),e.setAttribute("hilbertLabelColor",s(l,4))}function ez(e){const t=e.getAttribute("uv");if(!t)return;const i=e.getAttribute("position"),r=e.parameters?.points,n=new Float32Array(t.count),s=new Float32Array(t.count).fill(.8),a=new Float32Array(t.count),o=function(e,t){const i=new Set;if(!e||e.length<4||!t)return i;const r=e.slice(1).map((t,i)=>t.clone().sub(e[i]).normalize());for(let n=1;n<r.length-1;n++){const s=r[n-1],a=r[n],o=r[n+1];if(s.dot(o)>-.999999||Math.abs(s.dot(a))>1e-6)continue;[{segment:n-1,normal:a},{segment:n,normal:s.clone().negate()},{segment:n+1,normal:a}].forEach(({segment:n,normal:s})=>{const a=e[n].clone().add(e[n+1]).multiplyScalar(.5);for(let e=0;e<4;e++){const o=4*(4*n+e),l=new Wi;for(let e=0;e<4;e++)l.add((new Wi).fromBufferAttribute(t,o+e));l.multiplyScalar(.25).sub(a),l.addScaledVector(r[n],-l.dot(r[n])),l.lengthSq()>0&&l.normalize().dot(s)>.9&&i.add(o)}})}return i}(r,i),l=[];if(r?.length>1){const e=4*(r.length-1);for(let i=0;i+3<t.count&&i/4<e;i+=4){let e=1/0,r=-1/0,n=1/0,s=-1/0;for(let a=0;a<4;a++)e=Math.min(e,t.getX(i+a)),r=Math.max(r,t.getX(i+a)),n=Math.min(n,t.getY(i+a)),s=Math.max(s,t.getY(i+a));r<=e||s===n||l.push({vertex:i,minU:e,maxU:r,minV:n,maxV:s})}}else for(let e=0;e+3<t.count;e+=4){let i=1/0,r=-1/0,n=1/0,s=-1/0;for(let a=0;a<4;a++)i=Math.min(i,t.getX(e+a)),r=Math.max(r,t.getX(e+a)),n=Math.min(n,t.getY(e+a)),s=Math.max(s,t.getY(e+a));Math.abs(r-i-.25)>.01||s<=n||l.push({vertex:e,minU:i,maxU:r,minV:n,maxV:s})}const u=new Set(l.map(({vertex:e})=>e));if(l.forEach(({vertex:e,minU:s,maxU:l,minV:u,maxV:c},h)=>{for(let t=0;t<4;t++)a[e+t]=1;if(o.has(e)){for(let i=0;i<4;i++)t.setX(e+i,-1);return}if(i&&!function(e,t){const i=Array.from({length:4},(i,r)=>(new Wi).fromBufferAttribute(e,t+r)),r=i.map((e,t)=>i[(t+1)%4].clone().sub(e)),n=Math.max(...r.map(e=>e.length())),s=1e-4*n,a=r[0].clone().add(r[2]).length()<=s&&r[1].clone().add(r[3]).length()<=s,o=Math.abs(r[0].dot(r[1]))<=r[0].length()*r[1].length()*1e-4;return a&&o}(i,e)){for(let i=0;i<4;i++)t.setX(e+i,-1);return}const d=Math.floor(h/4),p=r?.[d],f=r?.[d+1],m=f?f.x-p.x:0,g=f?f.y-p.y:0,_=f?f.z-p.z:0,v=Math.hypot(m,g,_),b=Array.from({length:4},(r,n)=>{const s=e+n;return i&&p&&v?((i.getX(s)-p.x)*m+(i.getY(s)-p.y)*g+(i.getZ(s)-p.z)*_)/v:v*(t.getY(s)-u)/(c-u)}),y=Math.min(...b),x=Math.max(...b)-y,S=i?(new Wi).fromBufferAttribute(i,e).distanceTo((new Wi).fromBufferAttribute(i,e+1)):0;if(S>0)for(let t=0;t<4;t++)n[e+t]=x/S;if(x<1e-6)for(let i=0;i<4;i++)t.setX(e+i,-1);else for(let i=0;i<4;i++){const r=e+i,n=(b[i]-y)/x,a=t.getX(r);t.setXY(r,1-n,1-(a-s)/(l-s))}}),l.length){for(let e=0;e+3<t.count;e+=4)if(!u.has(e))for(let i=0;i<4;i++)t.setX(e+i,-1)}else!function(e,t,i,r){const n=e.getAttribute("position"),s=e.getAttribute("normal");if(!n||!s||24!==n.count)return;for(let e=0;e+3<n.count;e+=4){const a=s.getX(e),o=s.getY(e),l=s.getZ(e),u=Math.abs(o)>.9||l>.9?1:l<-.9?-1:0,c=Math.abs(o)>.9?0:a>.9?-1:a<-.9?1:0,h=Math.abs(o)>.9?0:1,d=Math.abs(o)>.9?o>0?-1:1:0;let p=1/0,f=-1/0,m=1/0,g=-1/0;for(let t=0;t<4;t++){const i=e+t,r=n.getX(i)*u+n.getZ(i)*c,s=n.getY(i)*h+n.getZ(i)*d;p=Math.min(p,r),f=Math.max(f,r),m=Math.min(m,s),g=Math.max(g,s)}for(let s=0;s<4;s++){const a=e+s,o=n.getX(a)*u+n.getZ(a)*c,l=n.getY(a)*h+n.getZ(a)*d;t.setXY(a,(o-p)/(f-p),(l-m)/(g-m)),i[a]=(f-p)/(g-m),r[a]=.5}}}(e,t,n,s);e.setAttribute("hilbertLabelAspect",new kn(n,1)),e.setAttribute("hilbertLabelMaxFontSize",new kn(s,1)),e.setAttribute("hilbertLabelReverse",new kn(a,1)),t.needsUpdate=!0}const tz=[[0,3,4,7,6,5,2,1],[0,7,6,1,2,5,4,3],[0,7,6,1,2,5,4,3],[2,3,0,1,6,7,4,5],[2,3,0,1,6,7,4,5],[4,3,2,5,6,1,0,7],[4,3,2,5,6,1,0,7],[6,5,2,1,0,3,4,7]],{orientations:iz,transitions:rz}=function(){const e=[[0,1,2,3,4,5,6,7]],t=[],i=new Map([[e[0].join(""),0]]);for(let r=0;r<e.length;r++){const n=e[r],s=[];for(const t of tz){const r=t.map(e=>n[e]),a=r.join("");let o=i.get(a);void 0===o&&(o=e.length,e.push(r),i.set(a,o)),s.push(o)}t.push(s)}return{orientations:e,transitions:t}}();function nz({useInstancing:e=!0,data:t,order:i,paddingAccessor:r,paddingAbsoluteAccessor:n,colorAccessor:s,labelAccessor:a,labelAtlas:o,defaultColorScale:l,simplifyCurves:u,SCALE:c}){const h=new Map,d=new Map,p=new WeakMap,f=[],m=new Map,g=new Set;t.forEach(t=>{const _=r(t),v=n(t),b=o?.labels.get(t),y=b?.text??a(t);if(!e){const e=sz(i,t,_,v,u,Boolean(o));return o&&Jk(e,[{info:b}]),p.set(t,e),void f.push(t)}const x=function(e,t,i,r,n,s){const a="bigint"==typeof t&&"bigint"==typeof i;if(!Number.isInteger(e)||"bigint"==typeof t!=("bigint"==typeof i))return null;if(!(a||Number.isFinite(t)&&Number.isFinite(i)))return null;let o=e,l=a?t:Math.round(t),u=a?i:Math.round(i);const c=a?8n:8,h=a?0n:0;if(s)for(;o>0&&l%c===h&&u%c===h;)l/=c,u/=c,o--;const d=1/2**(o-1),p=(d-Math.min(n,.5*d))*(1-Math.min(1,r));if(!(p>0&&Number.isFinite(p)))return null;if(o<=0){return{points:[{x:0,y:0,z:0}],width:p,scale:p}}let f,m;if(a){const e=8n**BigInt(o);if(f=l<0n?0n:l,m=f+(u>0n?u:0n),m>e&&(m=e),f>=m||m-f>4n)return null}else{const e=8**o;if(!Number.isSafeInteger(l)||!Number.isSafeInteger(u)||!Number.isFinite(e))return null;if(f=Math.max(0,l),m=Math.min(e,f+Math.max(0,u)),f>=m||m-f>4)return null}const g=[];for(let e=f;e<m;e=a?e+1n:e+1)g.push(az(e,o));const _=1===g.length?p:Math.abs(g[1].x-g[0].x)+Math.abs(g[1].y-g[0].y)+Math.abs(g[1].z-g[0].z);return{points:g,width:p,scale:_}}(i,t.start,t.length,_,v,u);if(!x){const e=sz(i,t,_,v,u,Boolean(o));return o&&Jk(e,[{info:b}]),p.set(t,e),void f.push(t)}const S=s?.(t)||l(y||""),{points:T,width:M,scale:E}=x,w=function(e){const t=[];let i=e[0];for(let r=1;r<e.length;r++){const n=e[r];for(const e of["x","y","z"]){const r=n[e]-i[e];if(r){t.push("x"===e?r>0?"R":"L":"y"===e?r>0?"U":"D":r>0?"B":"F");break}}i=n}return t.join("")}(T),A=`${w}|${M/E}|${Boolean(o)}`;g.add(A);let R=d.get(A);if(!R){const e=sz(i,t,_,v,u,Boolean(o));R=function(e,t,i){const r=new Zn;Object.entries(e.attributes).forEach(([e,t])=>{r.setAttribute(e,t.clone())}),e.index&&r.setIndex(e.index.clone());e.groups.forEach(e=>r.addGroup(e.start,e.count,e.materialIndex)),r.setDrawRange(e.drawRange.start,e.drawRange.count);const n=r.getAttribute("position");for(let e=0;e<n.count;e++)n.setXYZ(e,(n.getX(e)-t.x)/i,(n.getY(e)-t.y)/i,(n.getZ(e)-t.z)/i);return n.needsUpdate=!0,r.computeBoundingBox(),r.computeBoundingSphere(),r}(e,T[0],E),d.set(A,R),e.dispose()}const C=S;let N=h.get(C);if(!N){if(o)N=Qk(S,o);else{const e=Xk(S);N=new ma,N.color.set($k(S)),N.transparent=e<1,N.opacity=e}h.set(C,N)}let P=m.get(A);P||(P=new Map,m.set(A,P));let L=P.get(C);L||(L={geometry:R,material:N,transforms:new Float32Array(256),count:0,data:[],labelRecords:[]},P.set(C,L));const D=E*c;let U=L.transforms;if(4*L.count===U.length){const e=new Float32Array(2*U.length);e.set(U),U=L.transforms=e}const I=4*L.count;U[I]=D,U[I+1]=T[0].x*c,U[I+2]=T[0].y*c,U[I+3]=T[0].z*c,L.count++,L.data.push(t),o&&L.labelRecords.push({info:b})}),d.forEach((e,t)=>{g.has(t)||(e.dispose(),d.delete(t))});const _=[];return m.forEach(e=>{e.forEach(e=>{const t=e.geometry.clone();o&&Jk(t,e.labelRecords,!0);const i=new Os(t,e.material,e.count),r=i.instanceMatrix.array;for(let t=0;t<e.count;t++){const i=4*t,n=16*t,s=e.transforms[i];r[n]=s,r[n+5]=s,r[n+10]=s,r[n+12]=e.transforms[i+1],r[n+13]=e.transforms[i+2],r[n+14]=e.transforms[i+3],r[n+15]=1}i.instanceMatrix.needsUpdate=!0,i.computeBoundingSphere(),i.userData.data=e.data,_.push(i)})}),d.forEach(e=>e.dispose()),{fallbackData:f,geometries:p,meshes:_}}function sz(e,t,i,r,n,s){const a=new fO(e,t.start,t.length,{padding:i,paddingAbsolute:r,simplifyCurves:n});return s&&ez(a),a}function az(e,t){const i="bigint"==typeof e;let r=i?8n**BigInt(t-1):8**(t-1),n=0,s=0,a=0,o=1,l=0;for(let u=0;u<t;u++){const t=i?Number(e/r%8n):Math.floor(e/r)%8,u=iz[l][t],c=o/2;n+=u<4?-c:c,s+=u<2||u>5?c:-c,a+=u%4==1||u%4==2?c:-c,o=c,l=rz[l][t],r=i?r/8n:r/8}return{x:n,y:s,z:a}}const oz=100,lz=R({props:{order:{default:4},data:{default:[]},padding:{default:0},paddingAbsolute:{default:0},color:{},label:{default:"name"},labelColor:{default:()=>"lavender"},simplifyCurves:{default:!0},useInstancedMeshes:{default:!1}},methods:{getPositionAtVal:(e,t)=>{const i=new fO(e.order,t,1);return i.computeBoundingSphere(),i.boundingSphere.center.clone().multiplyScalar(oz)},getRangeBbox:(e,t,i)=>{const r=new fO(e.order,t,i);r.computeBoundingBox();const n=r.boundingBox.clone();return r.dispose(),n.min.multiplyScalar(oz),n.max.multiplyScalar(oz),n}},stateInit:()=>({defaultColorScale:zB(VB),instancedMeshes:[],labelAtlas:null}),init:function(e,t){(e=>{if(e&&e.children)for(;e.children.length;){const t=e.children[0];e.remove(t),Wk(t)}})(e),t.scene=e,t.dataMapper=new jk(e,{objBindAttr:"__threeObjHilbert"}).onCreateObj(()=>{const e=new Vr;return e.add(new ws),e.scale.set(oz,oz,oz),e})},update:function(e,t){const i=C(e.padding),r=C(e.paddingAbsolute),n=C(e.color),s=C(e.label),a=C(e.labelColor),o=e.labelAtlas,l=function(e,t,i){const r=new Map,n=new WeakMap;if(e.forEach(e=>{const s=t(e),a=i(e);if(!s||!a)return;const o=Array.from(String(s)),l=o.length>qk?`${o.slice(0,29).join("")}...`:o.join("");let u=r.get(l);void 0===u&&(u=r.size,r.set(l,u)),n.set(e,{id:u,length:Array.from(l).length,text:l,color:a})}),!r.size)return null;const s=document.createElement("canvas");s.width=1024,s.height=1024;const a=s.getContext("2d");if(!a)throw new Error("Unable to create canvas context for label glyphs");a.font="bold 64px monospace",a.textAlign="center",a.textBaseline="middle";for(let e=0;e<256;e++){const t=String.fromCharCode(e);if(e<32||127===e)continue;const i=e%16*Yk+32,r=Math.floor(e/16)*Yk+32;a.fillStyle="#fff",a.fillText(t,i,r)}const o=new qs(s);o.magFilter=Oe,o.minFilter=Oe,o.colorSpace=Xt;const l=128,u=4096,c=Math.ceil(r.size/l),h=new Uint8Array(u*c*4);r.forEach((e,t)=>{Array.from(t).forEach((t,i)=>{const r=t.codePointAt(0),n=e%l*qk+i,s=Math.floor(e/l),a=r>=32&&r<=255&&(r<127||r>=160);h[4*(s*u+n)]=a?r:63})});const d=new Rs(h,u,c,tt,ze);return d.magFilter=Ue,d.minFilter=Ue,d.generateMipmaps=!1,d.needsUpdate=!0,{labels:n,glyphTexture:o,labelTexture:d,labelsPerRow:l,labelCount:r.size}}(e.data,s,a);e.labelAtlas=l;const{fallbackData:u,geometries:c,meshes:h}=nz({useInstancing:e.useInstancedMeshes,data:e.data,order:e.order,paddingAccessor:i,paddingAbsoluteAccessor:r,colorAccessor:n,labelAccessor:s,labelAtlas:l,defaultColorScale:e.defaultColorScale,simplifyCurves:e.simplifyCurves,SCALE:oz});e.instancedMeshes.forEach(t=>{e.scene.remove(t),Wk(t)}),e.instancedMeshes=h,h.forEach(t=>e.scene.add(t));const d=new Map;e.dataMapper.onUpdateObj((t,i)=>{const[r]=t.children,a=l?.labels.get(i)?.text??s(i),o=n?.(i)||e.defaultColorScale(a||""),u=o;let h=d.get(u);if(!h&&l)h=Qk(o,l),d.set(u,h);else if(!h){const e=Xk(o);h=new ma,h.color.set($k(o)),h.transparent=e<1,h.opacity=e,d.set(u,h)}r.material=h,r.geometry?.dispose(),r.geometry=c.get(i)}).digest(u),o&&(o.glyphTexture.dispose(),o.labelTexture.dispose())}});var uz=function(e,t=Object,i=!1){class r extends t{constructor(...t){super(...t),this.__kapsuleInstance=new e(...[...i?[this]:[],...t])}}const n=e();return n._destructor?.(),Object.keys(n).forEach(e=>r.prototype[e]=function(...t){const i=this.__kapsuleInstance[e](...t);return i===this.__kapsuleInstance?this:i}),r}(lz,Vr,!0);!function(e,t){void 0===t&&(t={});var i=t.insertAt;if("undefined"!=typeof document){var r=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css","top"===i&&r.firstChild?r.insertBefore(n,r.firstChild):r.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}}(".hilbert-scene-container .clickable {\n cursor: pointer;\n}");var cz=R({props:{width:{default:window.innerWidth,onChange(e,t){t.renderObjs.width(e)},triggerUpdate:!1},height:{default:window.innerHeight,onChange(e,t){t.renderObjs.height(e)},triggerUpdate:!1},hilbertOrder:{default:3,onChange(e,t){t.hilbert.order(e)},triggerUpdate:!1},data:{default:[],onChange(e,t){t.hilbert.data(e)},triggerUpdate:!1},padding:{default:0,onChange(e,t){t.hilbert.padding(e)},triggerUpdate:!1},paddingAbsolute:{default:0,onChange(e,t){t.hilbert.paddingAbsolute(e)},triggerUpdate:!1},color:{onChange(e,t){t.hilbert.color(e)},triggerUpdate:!1},label:{default:"name",onChange(e,t){t.hilbert.label(e)},triggerUpdate:!1},labelColor:{default:()=>"white",onChange(e,t){t.hilbert.labelColor(e)},triggerUpdate:!1},simplifyCurves:{default:!0,onChange(e,t){t.hilbert.simplifyCurves(e)},triggerUpdate:!1},useInstancedMeshes:{default:!1,onChange(e,t){t.hilbert.useInstancedMeshes(e)},triggerUpdate:!1},valFormatter:{default:e=>e},tooltipContent:{triggerUpdate:!1},onHover:{triggerUpdate:!1},onClick:{triggerUpdate:!1},onBackgroundClick:{triggerUpdate:!1}},methods:{focusOn:function(e,t,i,r){setTimeout(()=>{const n=e.hilbert.getRangeBbox(t,i),s={x:[n.min.x,n.max.x],y:[n.min.y,n.max.y],z:[n.min.z,n.max.z]};e.renderObjs.fitToBbox(s,r)})},zoomToFit:function(e,t,i){return e.renderObjs.zoomTofit(t,i),this},_animationCycle(e){e.renderObjs.tick(),e.animationFrameRequestId=requestAnimationFrame(this._animationCycle)},scene:e=>e.renderObjs.scene(),camera:e=>e.renderObjs.camera(),renderer:e=>e.renderObjs.renderer(),controls:e=>e.renderObjs.controls(),_destructor:function(e){cancelAnimationFrame(e.animationFrameRequestId),this.data([]),e.hilbert._destructor?.(),e.renderObjs._destructor?.()}},stateInit({controlType:e="orbit"}){const t=new uz;return{hilbert:t,renderObjs:YF({controlType:e}).objects([t]).lights([new qa(13421772,Math.PI),new Xa(16777215,.6*Math.PI)])}},init:function(e,t){e.innerHTML="",e.style.position="relative";const i=document.createElement("div");i.className="hilbert-scene-container",e.appendChild(i);const r=(e,t)=>{if(!e)return null;if(t&&e.isInstancedMesh)return e.userData.data?.[t.instanceId]||null;const i=function(e){let t=e;for(;t&&!t.hasOwnProperty("__data");)t=t.parent;return t}(e);return i?.__data||null};t.renderObjs(i).tooltipContent((e,i)=>{const n=r(e,i);return n?t.tooltipContent?C(t.tooltipContent)(n)||"":(()=>{const e=C(t.label)(n);return`${e?`<b>${e}</b>: `:""}${t.valFormatter(n.start)+(n.length>1?" - "+t.valFormatter(n.start+n.length-("bigint"==typeof n.start?1n:1)):"")}`})():""}).onHover((e,i,n)=>{const s=r(e,n);s!==t.hoverD&&(t.onHover?.(s,t.hoverD||null),t.renderObjs.renderer().domElement.classList[s&&t.onClick||!s&&t.onBackgroundClick?"add":"remove"]("clickable"),t.hoverD=s)}).onClick((e,i,n)=>{const s=r(e,n);s?t.onClick?.(s,i):t.onBackgroundClick?.(i)}),t.renderObjs.camera().position.z=500,this._animationCycle()}});return cz});
|
|
5
|
+
hk.readability=function(e,t){var i=hk(e),r=hk(t);return(Math.max(i.getLuminance(),r.getLuminance())+.05)/(Math.min(i.getLuminance(),r.getLuminance())+.05)},hk.isReadable=function(e,t,i){var r,n,s=hk.readability(e,t);switch(n=!1,(r=function(e){var t,i;t=((e=e||{level:"AA",size:"small"}).level||"AA").toUpperCase(),i=(e.size||"small").toLowerCase(),"AA"!==t&&"AAA"!==t&&(t="AA");"small"!==i&&"large"!==i&&(i="small");return{level:t,size:i}}(i)).level+r.size){case"AAsmall":case"AAAlarge":n=s>=4.5;break;case"AAlarge":n=s>=3;break;case"AAAsmall":n=s>=7}return n},hk.mostReadable=function(e,t,i){var r,n,s,a,o=null,l=0;n=(i=i||{}).includeFallbackColors,s=i.level,a=i.size;for(var u=0;u<t.length;u++)(r=hk.readability(e,t[u]))>l&&(l=r,o=hk(t[u]));return hk.isReadable(e,o,{level:s,size:a})||!n?o:(i.includeFallbackColors=!1,hk.mostReadable(e,["#fff","#000"],i))};var Rk=hk.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"},Ck=hk.hexNames=function(e){var t={};for(var i in e)e.hasOwnProperty(i)&&(t[e[i]]=i);return t}(Rk);function Nk(e){return e=parseFloat(e),(isNaN(e)||e<0||e>1)&&(e=1),e}function Pk(e,t){(function(e){return"string"==typeof e&&-1!=e.indexOf(".")&&1===parseFloat(e)})(e)&&(e="100%");var i=function(e){return"string"==typeof e&&-1!=e.indexOf("%")}(e);return e=Math.min(t,Math.max(0,parseFloat(e))),i&&(e=parseInt(e*t,10)/100),Math.abs(e-t)<1e-6?1:e%t/parseFloat(t)}function Lk(e){return Math.min(1,Math.max(0,e))}function Dk(e){return parseInt(e,16)}function Uk(e){return 1==e.length?"0"+e:""+e}function Ik(e){return e<=1&&(e=100*e+"%"),e}function Fk(e){return Math.round(255*parseFloat(e)).toString(16)}function Ok(e){return Dk(e)/255}var Bk,kk,zk,Gk=(kk="[\\s|\\(]+("+(Bk="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+Bk+")[,|\\s]+("+Bk+")\\s*\\)?",zk="[\\s|\\(]+("+Bk+")[,|\\s]+("+Bk+")[,|\\s]+("+Bk+")[,|\\s]+("+Bk+")\\s*\\)?",{CSS_UNIT:new RegExp(Bk),rgb:new RegExp("rgb"+kk),rgba:new RegExp("rgba"+zk),hsl:new RegExp("hsl"+kk),hsla:new RegExp("hsla"+zk),hsv:new RegExp("hsv"+kk),hsva:new RegExp("hsva"+zk),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 Vk(e){return!!Gk.CSS_UNIT.exec(e)}const Hk=e=>{e instanceof Array?e.forEach(Hk):(e.map&&e.map.dispose(),e.dispose())},Wk=e=>{e.geometry&&e.geometry.dispose(),e.material&&Hk(e.material),e.texture&&e.texture.dispose(),e.children&&e.children.forEach(Wk)};class jk extends ok{constructor(e,{dataBindAttr:t="__data",objBindAttr:i="__threeObj",removeDelay:r=0}={}){super(),this.scene=e,this.#e=t,this.#t=i,this.#i=r,this.onRemoveObj(()=>{})}onCreateObj(e){return super.onCreateObj(t=>{const i=e(t);return t[this.#t]=i,i[this.#e]=t,this.scene.add(i),i}),this}onRemoveObj(e){return super.onRemoveObj((t,i)=>{const r=super.getData(t);e(t,i);const n=()=>{this.scene.remove(t),Wk(t),delete r[this.#t]};this.#i?setTimeout(n,this.#i):n()}),this}scene;#e;#t;#i}const $k=e=>isNaN(e)?parseInt(hk(e).toHex(),16):e,Xk=e=>e&&isNaN(e)?zO(e).opacity:1,qk=32,Yk=64,Kk=.92,Zk=.8;function Qk(e,t){const i=new ma,r=Xk(e);return i.color.set($k(e)),i.transparent=r<1,i.opacity=r,t&&(i.onBeforeCompile=e=>{e.uniforms.labelGlyphTexture={value:t.glyphTexture},e.uniforms.labelDataTexture={value:t.labelTexture},e.uniforms.labelDataTextureSize={value:new Vi(t.labelTexture.image.width,t.labelTexture.image.height)},e.uniforms.labelLabelsPerRow={value:t.labelsPerRow},e.vertexShader=e.vertexShader.replace("#include <common>","#include <common>\n attribute float hilbertLabelId;\n attribute float hilbertLabelLength;\n attribute float hilbertLabelAspect;\n attribute float hilbertLabelMaxFontSize;\n attribute float hilbertLabelReverse;\n attribute vec4 hilbertLabelColor;\n varying vec2 vHilbertLabelUv;\n varying float vHilbertLabelId;\n varying float vHilbertLabelLength;\n varying float vHilbertLabelAspect;\n varying float vHilbertLabelMaxFontSize;\n varying float vHilbertLabelReverse;\n varying vec4 vHilbertLabelColor;").replace("#include <begin_vertex>","#include <begin_vertex>\n vHilbertLabelUv = uv;\n vHilbertLabelId = hilbertLabelId;\n vHilbertLabelLength = hilbertLabelLength;\n vHilbertLabelAspect = hilbertLabelAspect;\n vHilbertLabelMaxFontSize = hilbertLabelMaxFontSize;\n vHilbertLabelReverse = hilbertLabelReverse;\n vHilbertLabelColor = hilbertLabelColor;"),e.fragmentShader=e.fragmentShader.replace("#include <common>","#include <common>\n uniform sampler2D labelGlyphTexture;\n uniform sampler2D labelDataTexture;\n uniform vec2 labelDataTextureSize;\n uniform float labelLabelsPerRow;\n varying vec2 vHilbertLabelUv;\n varying float vHilbertLabelId;\n varying float vHilbertLabelLength;\n varying float vHilbertLabelAspect;\n varying float vHilbertLabelMaxFontSize;\n varying float vHilbertLabelReverse;\n varying vec4 vHilbertLabelColor;").replace("#include <map_fragment>",`#include <map_fragment>\n if (vHilbertLabelId >= 0.0 && vHilbertLabelUv.x >= 0.0 && vHilbertLabelUv.x <= 1.0) {\n float aspect = max(vHilbertLabelAspect, 0.001);\n float visibleLength = vHilbertLabelLength;\n float textUnits = 1.0 + max(visibleLength - 1.0, 0.0) * ${Zk.toFixed(2)};\n float maxFontSize = min(${.8.toFixed(2)}, vHilbertLabelMaxFontSize);\n float fontSize = min(maxFontSize, aspect * ${Kk.toFixed(2)} / textUnits);\n bool isTruncated = fontSize < ${.05.toFixed(2)};\n if (isTruncated) visibleLength = min(visibleLength, max(3.0, floor((aspect * ${Kk.toFixed(2)} / ${.05.toFixed(2)} - 1.0) / ${Zk.toFixed(2)}) + 1.0));\n textUnits = 1.0 + max(visibleLength - 1.0, 0.0) * ${Zk.toFixed(2)};\n fontSize = min(maxFontSize, aspect * ${Kk.toFixed(2)} / textUnits);\n float characterSize = fontSize / aspect;\n float characterAdvance = characterSize * ${Zk.toFixed(2)};\n float textWidth = characterSize + characterAdvance * max(visibleLength - 1.0, 0.0);\n float textStart = (1.0 - textWidth) * 0.5;\n float textPosition = vHilbertLabelUv.x - textStart;\n if (textPosition >= 0.0 && textPosition < textWidth) {\n float glyphVerticalPosition = (vHilbertLabelUv.y - 0.5) / max(fontSize, 0.001) + 0.5;\n if (glyphVerticalPosition >= 0.0 && glyphVerticalPosition <= 1.0) {\n float charPosition = textPosition / max(characterAdvance, 0.001);\n float charSlot = floor(charPosition);\n float charIndex = mix(charSlot, visibleLength - 1.0 - charSlot, vHilbertLabelReverse);\n float glyphHorizontalPosition = (textPosition - charSlot * characterAdvance) / max(characterSize, 0.001);\n glyphHorizontalPosition = mix(glyphHorizontalPosition, 1.0 - glyphHorizontalPosition, vHilbertLabelReverse);\n float labelRow = floor(vHilbertLabelId / labelLabelsPerRow);\n float labelColumn = mod(vHilbertLabelId, labelLabelsPerRow);\n vec2 dataUv = (vec2(labelColumn * 32.0 + charIndex, labelRow) + 0.5) / labelDataTextureSize;\n float charCode = floor(texture2D(labelDataTexture, dataUv).r * 255.0 + 0.5);\n if (isTruncated && charIndex >= visibleLength - 3.0) charCode = 46.0;\n vec2 glyphCell = vec2(mod(charCode, 16.0), floor(charCode / 16.0));\n vec2 glyphUv = vec2(0.015625 + clamp(glyphHorizontalPosition, 0.0, 1.0) * 0.96875, 0.015625 + (1.0 - glyphVerticalPosition) * 0.96875);\n vec2 glyphAtlasUv = vec2(glyphCell.x + glyphUv.x, 16.0 - glyphCell.y - glyphUv.y) / 16.0;\n float glyphCoverage = texture2D(labelGlyphTexture, glyphAtlasUv).a;\n float previousCharSlot = charSlot - 1.0;\n float previousCharIndex = mix(previousCharSlot, visibleLength - 1.0 - previousCharSlot, vHilbertLabelReverse);\n float previousGlyphPosition = (textPosition - previousCharSlot * characterAdvance) / max(characterSize, 0.001);\n previousGlyphPosition = mix(previousGlyphPosition, 1.0 - previousGlyphPosition, vHilbertLabelReverse);\n if (charSlot > 0.0 && previousGlyphPosition < 1.0) {\n vec2 previousDataUv = (vec2(labelColumn * 32.0 + previousCharIndex, labelRow) + 0.5) / labelDataTextureSize;\n float previousCharCode = floor(texture2D(labelDataTexture, previousDataUv).r * 255.0 + 0.5);\n if (isTruncated && previousCharIndex >= visibleLength - 3.0) previousCharCode = 46.0;\n vec2 previousGlyphCell = vec2(mod(previousCharCode, 16.0), floor(previousCharCode / 16.0));\n vec2 previousGlyphAtlasUv = vec2(\n previousGlyphCell.x + 0.015625 + clamp(previousGlyphPosition, 0.0, 1.0) * 0.96875,\n 16.0 - previousGlyphCell.y - glyphUv.y\n ) / 16.0;\n glyphCoverage = max(glyphCoverage, texture2D(labelGlyphTexture, previousGlyphAtlasUv).a);\n }\n float glyphAlpha = glyphCoverage * vHilbertLabelColor.a;\n diffuseColor.rgb = mix(diffuseColor.rgb, vHilbertLabelColor.rgb, glyphAlpha);\n }\n }\n }`)},i.customProgramCacheKey=()=>"three-hilbert-label-glyph-atlas"),i}function Jk(e,t,i=!1){const r=e.getAttribute("position").count,n=i?t.length:r,s=(e,t)=>i?new Cs(e,t):new kn(e,t),a=new Float32Array(n),o=new Float32Array(n),l=new Float32Array(4*n);t.forEach(({info:e},t)=>{const r=e?.color,s=new Yr(r?$k(r):16777215),u=i?t+1:n;for(let n=i?t:0;n<u;n++)a[n]=e?e.id:-1,o[n]=e?e.length:0,l[4*n]=s.r,l[4*n+1]=s.g,l[4*n+2]=s.b,l[4*n+3]=r?Xk(r):0}),e.setAttribute("hilbertLabelId",s(a,1)),e.setAttribute("hilbertLabelLength",s(o,1)),e.setAttribute("hilbertLabelColor",s(l,4))}function ez(e){const t=e.getAttribute("uv");if(!t)return;const i=e.getAttribute("position"),r=e.parameters?.points,n=new Float32Array(t.count),s=new Float32Array(t.count).fill(.8),a=new Float32Array(t.count),o=function(e,t){const i=new Set;if(!e||e.length<4||!t)return i;const r=e.slice(1).map((t,i)=>t.clone().sub(e[i]).normalize());for(let n=1;n<r.length-1;n++){const s=r[n-1],a=r[n],o=r[n+1];if(s.dot(o)>-.999999||Math.abs(s.dot(a))>1e-6)continue;[{segment:n-1,normal:a},{segment:n,normal:s.clone().negate()},{segment:n+1,normal:a}].forEach(({segment:n,normal:s})=>{const a=e[n].clone().add(e[n+1]).multiplyScalar(.5);for(let e=0;e<4;e++){const o=4*(4*n+e),l=new Wi;for(let e=0;e<4;e++)l.add((new Wi).fromBufferAttribute(t,o+e));l.multiplyScalar(.25).sub(a),l.addScaledVector(r[n],-l.dot(r[n])),l.lengthSq()>0&&l.normalize().dot(s)>.9&&i.add(o)}})}return i}(r,i),l=[];if(r?.length>1){const e=4*(r.length-1);for(let i=0;i+3<t.count&&i/4<e;i+=4){let e=1/0,r=-1/0,n=1/0,s=-1/0;for(let a=0;a<4;a++)e=Math.min(e,t.getX(i+a)),r=Math.max(r,t.getX(i+a)),n=Math.min(n,t.getY(i+a)),s=Math.max(s,t.getY(i+a));r<=e||s===n||l.push({vertex:i,minU:e,maxU:r,minV:n,maxV:s})}}else for(let e=0;e+3<t.count;e+=4){let i=1/0,r=-1/0,n=1/0,s=-1/0;for(let a=0;a<4;a++)i=Math.min(i,t.getX(e+a)),r=Math.max(r,t.getX(e+a)),n=Math.min(n,t.getY(e+a)),s=Math.max(s,t.getY(e+a));Math.abs(r-i-.25)>.01||s<=n||l.push({vertex:e,minU:i,maxU:r,minV:n,maxV:s})}const u=new Set(l.map(({vertex:e})=>e));if(l.forEach(({vertex:e,minU:s,maxU:l,minV:u,maxV:c},h)=>{for(let t=0;t<4;t++)a[e+t]=1;if(o.has(e)){for(let i=0;i<4;i++)t.setX(e+i,-1);return}if(i&&!function(e,t){const i=Array.from({length:4},(i,r)=>(new Wi).fromBufferAttribute(e,t+r)),r=i.map((e,t)=>i[(t+1)%4].clone().sub(e)),n=Math.max(...r.map(e=>e.length())),s=1e-4*n,a=r[0].clone().add(r[2]).length()<=s&&r[1].clone().add(r[3]).length()<=s,o=Math.abs(r[0].dot(r[1]))<=r[0].length()*r[1].length()*1e-4;return a&&o}(i,e)){for(let i=0;i<4;i++)t.setX(e+i,-1);return}const d=Math.floor(h/4),p=r?.[d],f=r?.[d+1],m=f?f.x-p.x:0,g=f?f.y-p.y:0,_=f?f.z-p.z:0,v=Math.hypot(m,g,_),b=Array.from({length:4},(r,n)=>{const s=e+n;return i&&p&&v?((i.getX(s)-p.x)*m+(i.getY(s)-p.y)*g+(i.getZ(s)-p.z)*_)/v:v*(t.getY(s)-u)/(c-u)}),y=Math.min(...b),x=Math.max(...b)-y,S=i?(new Wi).fromBufferAttribute(i,e).distanceTo((new Wi).fromBufferAttribute(i,e+1)):0;if(S>0)for(let t=0;t<4;t++)n[e+t]=x/S;if(x<1e-6)for(let i=0;i<4;i++)t.setX(e+i,-1);else for(let i=0;i<4;i++){const r=e+i,n=(b[i]-y)/x,a=t.getX(r);t.setXY(r,1-n,1-(a-s)/(l-s))}}),l.length){for(let e=0;e+3<t.count;e+=4)if(!u.has(e))for(let i=0;i<4;i++)t.setX(e+i,-1)}else!function(e,t,i,r){const n=e.getAttribute("position"),s=e.getAttribute("normal");if(!n||!s||24!==n.count)return;for(let e=0;e+3<n.count;e+=4){const a=s.getX(e),o=s.getY(e),l=s.getZ(e),u=Math.abs(o)>.9||l>.9?1:l<-.9?-1:0,c=Math.abs(o)>.9?0:a>.9?-1:a<-.9?1:0,h=Math.abs(o)>.9?0:1,d=Math.abs(o)>.9?o>0?-1:1:0;let p=1/0,f=-1/0,m=1/0,g=-1/0;for(let t=0;t<4;t++){const i=e+t,r=n.getX(i)*u+n.getZ(i)*c,s=n.getY(i)*h+n.getZ(i)*d;p=Math.min(p,r),f=Math.max(f,r),m=Math.min(m,s),g=Math.max(g,s)}for(let s=0;s<4;s++){const a=e+s,o=n.getX(a)*u+n.getZ(a)*c,l=n.getY(a)*h+n.getZ(a)*d;t.setXY(a,(o-p)/(f-p),(l-m)/(g-m)),i[a]=(f-p)/(g-m),r[a]=.5}}}(e,t,n,s);e.setAttribute("hilbertLabelAspect",new kn(n,1)),e.setAttribute("hilbertLabelMaxFontSize",new kn(s,1)),e.setAttribute("hilbertLabelReverse",new kn(a,1)),t.needsUpdate=!0}const tz=[[0,3,4,7,6,5,2,1],[0,7,6,1,2,5,4,3],[0,7,6,1,2,5,4,3],[2,3,0,1,6,7,4,5],[2,3,0,1,6,7,4,5],[4,3,2,5,6,1,0,7],[4,3,2,5,6,1,0,7],[6,5,2,1,0,3,4,7]],{orientations:iz,transitions:rz}=function(){const e=[[0,1,2,3,4,5,6,7]],t=[],i=new Map([[e[0].join(""),0]]);for(let r=0;r<e.length;r++){const n=e[r],s=[];for(const t of tz){const r=t.map(e=>n[e]),a=r.join("");let o=i.get(a);void 0===o&&(o=e.length,e.push(r),i.set(a,o)),s.push(o)}t.push(s)}return{orientations:e,transitions:t}}();function nz({useInstancing:e=!0,data:t,order:i,paddingAccessor:r,paddingAbsoluteAccessor:n,colorAccessor:s,labelAccessor:a,labelAtlas:o,defaultColorScale:l,simplifyCurves:u,SCALE:c}){const h=new Map,d=new Map,p=new WeakMap,f=[],m=new Map,g=new Set;t.forEach(t=>{const _=r(t),v=n(t),b=o?.labels.get(t),y=b?.text??a(t);if(!e){const e=sz(i,t,_,v,u,Boolean(o));return o&&Jk(e,[{info:b}]),p.set(t,e),void f.push(t)}const x=function(e,t,i,r,n,s){const a="bigint"==typeof t&&"bigint"==typeof i;if(!Number.isInteger(e)||"bigint"==typeof t!=("bigint"==typeof i))return null;if(!(a||Number.isFinite(t)&&Number.isFinite(i)))return null;let o=e,l=a?t:Math.round(t),u=a?i:Math.round(i);const c=a?8n:8,h=a?0n:0;if(s)for(;o>0&&l%c===h&&u%c===h;)l/=c,u/=c,o--;const d=1/2**(o-1),p=(d-Math.min(n,.5*d))*(1-Math.min(1,r));if(!(p>0&&Number.isFinite(p)))return null;if(o<=0){return{points:[{x:0,y:0,z:0}],width:p,scale:p}}let f,m;if(a){const e=8n**BigInt(o);if(f=l<0n?0n:l,m=f+(u>0n?u:0n),m>e&&(m=e),f>=m||m-f>4n)return null}else{const e=8**o;if(!Number.isSafeInteger(l)||!Number.isSafeInteger(u)||!Number.isFinite(e))return null;if(f=Math.max(0,l),m=Math.min(e,f+Math.max(0,u)),f>=m||m-f>4)return null}const g=[];for(let e=f;e<m;e=a?e+1n:e+1)g.push(az(e,o));const _=1===g.length?p:Math.abs(g[1].x-g[0].x)+Math.abs(g[1].y-g[0].y)+Math.abs(g[1].z-g[0].z);return{points:g,width:p,scale:_}}(i,t.start,t.length,_,v,u);if(!x){const e=sz(i,t,_,v,u,Boolean(o));return o&&Jk(e,[{info:b}]),p.set(t,e),void f.push(t)}const S=s?.(t)||l(y||""),{points:T,width:M,scale:E}=x,w=function(e){const t=[];let i=e[0];for(let r=1;r<e.length;r++){const n=e[r];for(const e of["x","y","z"]){const r=n[e]-i[e];if(r){t.push("x"===e?r>0?"R":"L":"y"===e?r>0?"U":"D":r>0?"B":"F");break}}i=n}return t.join("")}(T),A=`${w}|${M/E}|${Boolean(o)}`;g.add(A);let R=d.get(A);if(!R){const e=sz(i,t,_,v,u,Boolean(o));R=function(e,t,i){const r=new Zn;Object.entries(e.attributes).forEach(([e,t])=>{r.setAttribute(e,t.clone())}),e.index&&r.setIndex(e.index.clone());e.groups.forEach(e=>r.addGroup(e.start,e.count,e.materialIndex)),r.setDrawRange(e.drawRange.start,e.drawRange.count);const n=r.getAttribute("position");for(let e=0;e<n.count;e++)n.setXYZ(e,(n.getX(e)-t.x)/i,(n.getY(e)-t.y)/i,(n.getZ(e)-t.z)/i);return n.needsUpdate=!0,r.computeBoundingBox(),r.computeBoundingSphere(),r}(e,T[0],E),d.set(A,R),e.dispose()}const C=S;let N=h.get(C);if(!N){if(o)N=Qk(S,o);else{const e=Xk(S);N=new ma,N.color.set($k(S)),N.transparent=e<1,N.opacity=e}h.set(C,N)}let P=m.get(A);P||(P=new Map,m.set(A,P));let L=P.get(C);L||(L={geometry:R,material:N,transforms:new Float32Array(256),count:0,data:[],labelRecords:[]},P.set(C,L));const D=E*c;let U=L.transforms;if(4*L.count===U.length){const e=new Float32Array(2*U.length);e.set(U),U=L.transforms=e}const I=4*L.count;U[I]=D,U[I+1]=T[0].x*c,U[I+2]=T[0].y*c,U[I+3]=T[0].z*c,L.count++,L.data.push(t),o&&L.labelRecords.push({info:b})}),d.forEach((e,t)=>{g.has(t)||(e.dispose(),d.delete(t))});const _=[];return m.forEach(e=>{e.forEach(e=>{const t=e.geometry.clone();o&&Jk(t,e.labelRecords,!0);const i=new Os(t,e.material,e.count),r=i.instanceMatrix.array;for(let t=0;t<e.count;t++){const i=4*t,n=16*t,s=e.transforms[i];r[n]=s,r[n+5]=s,r[n+10]=s,r[n+12]=e.transforms[i+1],r[n+13]=e.transforms[i+2],r[n+14]=e.transforms[i+3],r[n+15]=1}i.instanceMatrix.needsUpdate=!0,i.computeBoundingSphere(),i.userData.data=e.data,_.push(i)})}),d.forEach(e=>e.dispose()),{fallbackData:f,geometries:p,meshes:_}}function sz(e,t,i,r,n,s){const a=new fO(e,t.start,t.length,{padding:i,paddingAbsolute:r,simplifyCurves:n});return s&&ez(a),a}function az(e,t){const i="bigint"==typeof e;let r=i?8n**BigInt(t-1):8**(t-1),n=0,s=0,a=0,o=1,l=0;for(let u=0;u<t;u++){const t=i?Number(e/r%8n):Math.floor(e/r)%8,u=iz[l][t],c=o/2;n+=u<4?-c:c,s+=u<2||u>5?c:-c,a+=u%4==1||u%4==2?c:-c,o=c,l=rz[l][t],r=i?r/8n:r/8}return{x:n,y:s,z:a}}const oz=100,lz=R({props:{order:{default:4},data:{default:[]},padding:{default:0},paddingAbsolute:{default:0},color:{},label:{default:"name"},labelColor:{default:()=>"lavender"},simplifyCurves:{default:!0},useInstancedMeshes:{default:!1}},methods:{getPositionAtVal:(e,t)=>{const i=new fO(e.order,t,1);return i.computeBoundingSphere(),i.boundingSphere.center.clone().multiplyScalar(oz)},getRangeBbox:(e,t,i)=>{const r=new fO(e.order,t,i);r.computeBoundingBox();const n=r.boundingBox.clone();return r.dispose(),n.min.multiplyScalar(oz),n.max.multiplyScalar(oz),n}},stateInit:()=>({defaultColorScale:zB(VB),instancedMeshes:[],labelAtlas:null}),init:function(e,t){(e=>{if(e&&e.children)for(;e.children.length;){const t=e.children[0];e.remove(t),Wk(t)}})(e),t.scene=e,t.dataMapper=new jk(e,{objBindAttr:"__threeObjHilbert"}).onCreateObj(()=>{const e=new Vr;return e.add(new ws),e.scale.set(oz,oz,oz),e})},update:function(e,t){const i=C(e.padding),r=C(e.paddingAbsolute),n=C(e.color),s=C(e.label),a=C(e.labelColor),o=e.labelAtlas,l=function(e,t,i){const r=new Map,n=new WeakMap;if(e.forEach(e=>{const s=t(e),a=i(e);if(!s||!a)return;const o=Array.from(String(s)),l=o.length>qk?`${o.slice(0,29).join("")}...`:o.join("");let u=r.get(l);void 0===u&&(u=r.size,r.set(l,u)),n.set(e,{id:u,length:Array.from(l).length,text:l,color:a})}),!r.size)return null;const s=document.createElement("canvas");s.width=1024,s.height=1024;const a=s.getContext("2d");if(!a)throw new Error("Unable to create canvas context for label glyphs");a.font="bold 64px monospace",a.textAlign="center",a.textBaseline="middle";for(let e=0;e<256;e++){const t=String.fromCharCode(e);if(e<32||127===e)continue;const i=e%16*Yk+32,r=Math.floor(e/16)*Yk+32;a.fillStyle="#fff",a.fillText(t,i,r)}const o=new qs(s);o.magFilter=Oe,o.minFilter=Oe,o.colorSpace=Xt;const l=128,u=4096,c=Math.ceil(r.size/l),h=new Uint8Array(u*c*4);r.forEach((e,t)=>{Array.from(t).forEach((t,i)=>{const r=t.codePointAt(0),n=e%l*qk+i,s=Math.floor(e/l),a=r>=32&&r<=255&&(r<127||r>=160);h[4*(s*u+n)]=a?r:63})});const d=new Rs(h,u,c,tt,ze);return d.magFilter=Ue,d.minFilter=Ue,d.generateMipmaps=!1,d.needsUpdate=!0,{labels:n,glyphTexture:o,labelTexture:d,labelsPerRow:l,labelCount:r.size}}(e.data,s,a);e.labelAtlas=l;const{fallbackData:u,geometries:c,meshes:h}=nz({useInstancing:e.useInstancedMeshes,data:e.data,order:e.order,paddingAccessor:i,paddingAbsoluteAccessor:r,colorAccessor:n,labelAccessor:s,labelAtlas:l,defaultColorScale:e.defaultColorScale,simplifyCurves:e.simplifyCurves,SCALE:oz});e.instancedMeshes.forEach(t=>{e.scene.remove(t),Wk(t)}),e.instancedMeshes=h,h.forEach(t=>e.scene.add(t));const d=new Map;e.dataMapper.onUpdateObj((t,i)=>{const[r]=t.children,a=l?.labels.get(i)?.text??s(i),o=n?.(i)||e.defaultColorScale(a||""),u=o;let h=d.get(u);if(!h&&l)h=Qk(o,l),d.set(u,h);else if(!h){const e=Xk(o);h=new ma,h.color.set($k(o)),h.transparent=e<1,h.opacity=e,d.set(u,h)}r.material=h,r.geometry?.dispose(),r.geometry=c.get(i)}).digest(u),o&&(o.glyphTexture.dispose(),o.labelTexture.dispose())}});var uz=function(e,t=Object,i=!1){class r extends t{constructor(...t){super(...t),this.__kapsuleInstance=new e(...[...i?[this]:[],...t])}}const n=e();return n._destructor?.(),Object.keys(n).forEach(e=>r.prototype[e]=function(...t){const i=this.__kapsuleInstance[e](...t);return i===this.__kapsuleInstance?this:i}),r}(lz,Vr,!0);!function(e,t){void 0===t&&(t={});var i=t.insertAt;if("undefined"!=typeof document){var r=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css","top"===i&&r.firstChild?r.insertBefore(n,r.firstChild):r.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}}(".hilbert-scene-container .clickable {\n cursor: pointer;\n}");var cz=R({props:{width:{default:window.innerWidth,onChange(e,t){t.renderObjs.width(e)},triggerUpdate:!1},height:{default:window.innerHeight,onChange(e,t){t.renderObjs.height(e)},triggerUpdate:!1},hilbertOrder:{default:3,onChange(e,t){t.hilbert.order(e)},triggerUpdate:!1},data:{default:[],onChange(e,t){t.hilbert.data(e)},triggerUpdate:!1},padding:{default:0,onChange(e,t){t.hilbert.padding(e)},triggerUpdate:!1},paddingAbsolute:{default:0,onChange(e,t){t.hilbert.paddingAbsolute(e)},triggerUpdate:!1},color:{onChange(e,t){t.hilbert.color(e)},triggerUpdate:!1},label:{default:"name",onChange(e,t){t.hilbert.label(e)},triggerUpdate:!1},labelColor:{default:()=>"lavender",onChange(e,t){t.hilbert.labelColor(e)},triggerUpdate:!1},simplifyCurves:{default:!0,onChange(e,t){t.hilbert.simplifyCurves(e)},triggerUpdate:!1},useInstancedMeshes:{default:!1,onChange(e,t){t.hilbert.useInstancedMeshes(e)},triggerUpdate:!1},valFormatter:{default:e=>e},tooltipContent:{triggerUpdate:!1},onHover:{triggerUpdate:!1},onClick:{triggerUpdate:!1},onBackgroundClick:{triggerUpdate:!1}},methods:{focusOn:function(e,t,i,r){setTimeout(()=>{const n=e.hilbert.getRangeBbox(t,i),s={x:[n.min.x,n.max.x],y:[n.min.y,n.max.y],z:[n.min.z,n.max.z]};e.renderObjs.fitToBbox(s,r)})},zoomToFit:function(e,t,i){return e.renderObjs.zoomTofit(t,i),this},_animationCycle(e){e.renderObjs.tick(),e.animationFrameRequestId=requestAnimationFrame(this._animationCycle)},scene:e=>e.renderObjs.scene(),camera:e=>e.renderObjs.camera(),renderer:e=>e.renderObjs.renderer(),controls:e=>e.renderObjs.controls(),_destructor:function(e){cancelAnimationFrame(e.animationFrameRequestId),this.data([]),e.hilbert._destructor?.(),e.renderObjs._destructor?.()}},stateInit({controlType:e="orbit"}){const t=new uz;return{hilbert:t,renderObjs:YF({controlType:e}).objects([t]).lights([new qa(13421772,Math.PI),new Xa(16777215,.6*Math.PI)])}},init:function(e,t){e.innerHTML="",e.style.position="relative";const i=document.createElement("div");i.className="hilbert-scene-container",e.appendChild(i);const r=(e,t)=>{if(!e)return null;if(t&&e.isInstancedMesh)return e.userData.data?.[t.instanceId]||null;const i=function(e){let t=e;for(;t&&!t.hasOwnProperty("__data");)t=t.parent;return t}(e);return i?.__data||null};t.renderObjs(i).tooltipContent((e,i)=>{const n=r(e,i);return n?t.tooltipContent?C(t.tooltipContent)(n)||"":(()=>{const e=C(t.label)(n);return`${e?`<b>${e}</b>: `:""}${t.valFormatter(n.start)+(n.length>1?" - "+t.valFormatter(n.start+n.length-("bigint"==typeof n.start?1n:1)):"")}`})():""}).onHover((e,i,n)=>{const s=r(e,n);s!==t.hoverD&&(t.onHover?.(s,t.hoverD||null),t.renderObjs.renderer().domElement.classList[s&&t.onClick||!s&&t.onBackgroundClick?"add":"remove"]("clickable"),t.hoverD=s)}).onClick((e,i,n)=>{const s=r(e,n);s?t.onClick?.(s,i):t.onBackgroundClick?.(i)}),t.renderObjs.camera().position.z=500,this._animationCycle()}});return cz});
|