hilbert-chart-3d 0.9.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/dist/hilbert-chart-3d.js +22 -24
- package/dist/hilbert-chart-3d.js.map +1 -1
- package/dist/hilbert-chart-3d.min.js +2 -2
- package/dist/hilbert-chart-3d.mjs +14 -23
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
// Version 0.
|
|
1
|
+
// Version 0.10.0 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,n=t||i||Function("return this")(),r=function(){return n.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=n.Symbol,c=Object.prototype,u=c.hasOwnProperty,h=c.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=u.call(e,d),i=e[d];try{e[d]=void 0;var n=!0}catch(e){}var r=h.call(e);return n&&(t?e[d]=i:delete e[d]),r}(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 n=_.test(t);return n||v.test(t)?b(t.slice(2),n?2:8):g.test(t)?NaN:+t}var x=Math.max,S=Math.min;function T(t,i,n){var s,a,o,l,c,u,h=0,d=!1,p=!1,f=!0;if("function"!=typeof t)throw new TypeError("Expected a function");function m(e){var i=s,n=a;return s=a=void 0,h=e,l=t.apply(n,i)}function g(e){var t=e-u;return void 0===u||t>=i||t<0||p&&e-h>=o}function _(){var e=r();if(g(e))return v(e);c=setTimeout(_,function(e){var t=i-(e-u);return p?S(t,o-(e-h)):t}(e))}function v(e){return c=void 0,f&&s?m(e):(s=a=void 0,l)}function b(){var e=r(),t=g(e);if(s=arguments,a=this,u=e,t){if(void 0===c)return function(e){return h=e,c=setTimeout(_,i),d?m(e):l}(u);if(p)return clearTimeout(c),c=setTimeout(_,i),m(u)}return void 0===c&&(c=setTimeout(_,i)),l}return i=y(i)||0,e(n)&&(d=!!n.leading,o=(p="maxWait"in n)?x(y(n.maxWait)||0,i):o,f="trailing"in n?!!n.trailing:f),b.cancel=function(){void 0!==c&&clearTimeout(c),h=0,s=u=a=c=void 0},b.flush=function(){return void 0===c?l:v(r())},b}function M(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,n=Array(t);i<t;i++)n[i]=e[i];return n}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 n,r,s,a,o=[],l=!0,c=!1;try{if(s=(i=i.call(e)).next,0===t);else for(;!(l=(n=s.call(i)).done)&&(o.push(n.value),o.length!==t);l=!0);}catch(e){c=!0,r=e}finally{try{if(!l&&null!=i.return&&(a=i.return(),Object(a)!==a))return}finally{if(c)throw r}}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 n=i.default,r=void 0===n?null:n,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=r,this.triggerUpdate=a,this.onChange=l});function R(e){var t=e.stateInit,i=void 0===t?function(){return{}}:t,n=e.props,r=void 0===n?{}:n,s=e.methods,a=void 0===s?{}:s,o=e.aliases,l=void 0===o?{}:o,c=e.init,u=void 0===c?function(){}:c,h=e.update,d=void 0===h?function(){}:h,p=Object.keys(r).map(function(e){return new A(e,r[e])});return function e(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];var s=!!(this instanceof e?this.constructor:void 0),o=s?n.shift():void 0,c=n[0],h=void 0===c?{}:c,f=Object.assign({},i instanceof Function?i(h):i,{initialised:!1}),m={};function g(e){return _(e,h),v(),g}var _=function(e,t){u.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,n=void 0!==i&&i,r=e.onChange,s=void 0===r?function(e,t){}:r,a=e.defaultVal,o=void 0===a?null:a;return function(e){var i=f[t];if(!arguments.length)return i;var r=void 0===e?o:e;return f[t]=r,s.call(g,r,f,i),!m.hasOwnProperty(t)&&(m[t]=i),n&&v(),g}}(e)}),Object.keys(a).forEach(function(e){g[e]=function(){for(var t,i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];return(t=a[e]).call.apply(t,[g,f].concat(n))}}),Object.entries(l).forEach(function(e){var t=w(e,2),i=t[0],n=t[1];return g[i]=g[n]}),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,I=0,F=1,U=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,ne=209,re=210,se=211,ae=212,oe=213,le=214,ce=0,ue=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,Ie=1003,Fe=1004,Ue=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,nt=1027,rt=1028,st=1029,at=1030,ot=1031,lt=1032,ct=1033,ut=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,It=37817,Ft=37818,Ut=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,ni=517,ri=518,si=519,ai=35044,oi=35048,li="300 es",ci=2e3,ui=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={[ce]:0,[he]:6,[pe]:4,[de]:5,[ue]: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 n=i[e];if(void 0!==n){const e=n.indexOf(t);-1!==e&&n.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,n=t.length;i<n;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,n=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&n]+Ci[n>>8&255]+Ci[n>>16&255]+Ci[n>>24&255]).toLowerCase()}function Ii(e,t,i){return Math.max(t,Math.min(i,e))}function Fi(e,t){return(e%t+t)%t}function Ui(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:Ii,euclideanModulo:Fi,mapLinear:function(e,t,i,n,r){return n+(e-t)*(r-n)/(i-t)},inverseLerp:function(e,t,i){return e!==t?(i-e)/(t-e):0},lerp:Ui,damp:function(e,t,i,n){return Ui(e,t,1-Math.exp(-i*n))},pingpong:function(e,t=1){return t-Math.abs(Fi(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,n,r){const s=Math.cos,a=Math.sin,o=s(i/2),l=a(i/2),c=s((t+n)/2),u=a((t+n)/2),h=s((t-n)/2),d=a((t-n)/2),p=s((n-t)/2),f=a((n-t)/2);switch(r){case"XYX":e.set(o*u,l*h,l*d,o*c);break;case"YZY":e.set(l*d,o*u,l*h,o*c);break;case"ZXZ":e.set(l*h,l*d,o*u,o*c);break;case"XZX":e.set(o*u,l*f,l*p,o*c);break;case"YXY":e.set(l*p,o*u,l*f,o*c);break;case"ZYZ":e.set(l*f,l*p,o*u,o*c);break;default:Ti("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}},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,n=e.elements;return this.x=n[0]*t+n[3]*i+n[6],this.y=n[1]*t+n[4]*i+n[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Ii(this.x,e.x,t.x),this.y=Ii(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=Ii(this.x,e,t),this.y=Ii(this.y,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Ii(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(Ii(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y;return t*t+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const i=Math.cos(t),n=Math.sin(t),r=this.x-e.x,s=this.y-e.y;return this.x=r*i-s*n+e.x,this.y=r*n+s*i+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class Hi{constructor(e=0,t=0,i=0,n=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=i,this._w=n}static slerpFlat(e,t,i,n,r,s,a){let o=i[n+0],l=i[n+1],c=i[n+2],u=i[n+3],h=r[s+0],d=r[s+1],p=r[s+2],f=r[s+3];if(u!==f||o!==h||l!==d||c!==p){let e=o*h+l*d+c*p+u*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),n=Math.sin(i);t=Math.sin(t*i)/n,o=o*t+h*(a=Math.sin(a*i)/n),l=l*t+d*a,c=c*t+p*a,u=u*t+f*a}else{o=o*t+h*a,l=l*t+d*a,c=c*t+p*a,u=u*t+f*a;const e=1/Math.sqrt(o*o+l*l+c*c+u*u);o*=e,l*=e,c*=e,u*=e}}e[t]=o,e[t+1]=l,e[t+2]=c,e[t+3]=u}static multiplyQuaternionsFlat(e,t,i,n,r,s){const a=i[n],o=i[n+1],l=i[n+2],c=i[n+3],u=r[s],h=r[s+1],d=r[s+2],p=r[s+3];return e[t]=a*p+c*u+o*d-l*h,e[t+1]=o*p+c*h+l*u-a*d,e[t+2]=l*p+c*d+a*h-o*u,e[t+3]=c*p-a*u-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,n){return this._x=e,this._y=t,this._z=i,this._w=n,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const i=e._x,n=e._y,r=e._z,s=e._order,a=Math.cos,o=Math.sin,l=a(i/2),c=a(n/2),u=a(r/2),h=o(i/2),d=o(n/2),p=o(r/2);switch(s){case"XYZ":this._x=h*c*u+l*d*p,this._y=l*d*u-h*c*p,this._z=l*c*p+h*d*u,this._w=l*c*u-h*d*p;break;case"YXZ":this._x=h*c*u+l*d*p,this._y=l*d*u-h*c*p,this._z=l*c*p-h*d*u,this._w=l*c*u+h*d*p;break;case"ZXY":this._x=h*c*u-l*d*p,this._y=l*d*u+h*c*p,this._z=l*c*p+h*d*u,this._w=l*c*u-h*d*p;break;case"ZYX":this._x=h*c*u-l*d*p,this._y=l*d*u+h*c*p,this._z=l*c*p-h*d*u,this._w=l*c*u+h*d*p;break;case"YZX":this._x=h*c*u+l*d*p,this._y=l*d*u+h*c*p,this._z=l*c*p-h*d*u,this._w=l*c*u-h*d*p;break;case"XZY":this._x=h*c*u-l*d*p,this._y=l*d*u-h*c*p,this._z=l*c*p+h*d*u,this._w=l*c*u+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,n=Math.sin(i);return this._x=e.x*n,this._y=e.y*n,this._z=e.z*n,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,i=t[0],n=t[4],r=t[8],s=t[1],a=t[5],o=t[9],l=t[2],c=t[6],u=t[10],h=i+a+u;if(h>0){const e=.5/Math.sqrt(h+1);this._w=.25/e,this._x=(c-o)*e,this._y=(r-l)*e,this._z=(s-n)*e}else if(i>a&&i>u){const e=2*Math.sqrt(1+i-a-u);this._w=(c-o)/e,this._x=.25*e,this._y=(n+s)/e,this._z=(r+l)/e}else if(a>u){const e=2*Math.sqrt(1+a-i-u);this._w=(r-l)/e,this._x=(n+s)/e,this._y=.25*e,this._z=(o+c)/e}else{const e=2*Math.sqrt(1+u-i-a);this._w=(s-n)/e,this._x=(r+l)/e,this._y=(o+c)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let i=e.dot(t)+1;return i<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(Ii(this.dot(e),-1,1)))}rotateTowards(e,t){const i=this.angleTo(e);if(0===i)return this;const n=Math.min(1,t/i);return this.slerp(e,n),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return 0===e?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const i=e._x,n=e._y,r=e._z,s=e._w,a=t._x,o=t._y,l=t._z,c=t._w;return this._x=i*c+s*a+n*l-r*o,this._y=n*c+s*o+r*a-i*l,this._z=r*c+s*l+i*o-n*a,this._w=s*c-i*a-n*o-r*l,this._onChangeCallback(),this}slerp(e,t){let i=e._x,n=e._y,r=e._z,s=e._w,a=this.dot(e);a<0&&(i=-i,n=-n,r=-r,s=-s,a=-a);let o=1-t;if(a<.9995){const e=Math.acos(a),l=Math.sin(e);o=Math.sin(o*e)/l,t=Math.sin(t*e)/l,this._x=this._x*o+i*t,this._y=this._y*o+n*t,this._z=this._z*o+r*t,this._w=this._w*o+s*t,this._onChangeCallback()}else this._x=this._x*o+i*t,this._y=this._y*o+n*t,this._z=this._z*o+r*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(),n=Math.sqrt(1-i),r=Math.sqrt(i);return this.set(n*Math.sin(e),n*Math.cos(e),r*Math.sin(t),r*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class Wi{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,n=this.z,r=e.elements;return this.x=r[0]*t+r[3]*i+r[6]*n,this.y=r[1]*t+r[4]*i+r[7]*n,this.z=r[2]*t+r[5]*i+r[8]*n,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,i=this.y,n=this.z,r=e.elements,s=1/(r[3]*t+r[7]*i+r[11]*n+r[15]);return this.x=(r[0]*t+r[4]*i+r[8]*n+r[12])*s,this.y=(r[1]*t+r[5]*i+r[9]*n+r[13])*s,this.z=(r[2]*t+r[6]*i+r[10]*n+r[14])*s,this}applyQuaternion(e){const t=this.x,i=this.y,n=this.z,r=e.x,s=e.y,a=e.z,o=e.w,l=2*(s*n-a*i),c=2*(a*t-r*n),u=2*(r*i-s*t);return this.x=t+o*l+s*u-a*c,this.y=i+o*c+a*l-r*u,this.z=n+o*u+r*c-s*l,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,i=this.y,n=this.z,r=e.elements;return this.x=r[0]*t+r[4]*i+r[8]*n,this.y=r[1]*t+r[5]*i+r[9]*n,this.z=r[2]*t+r[6]*i+r[10]*n,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Ii(this.x,e.x,t.x),this.y=Ii(this.y,e.y,t.y),this.z=Ii(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=Ii(this.x,e,t),this.y=Ii(this.y,e,t),this.z=Ii(this.z,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Ii(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,n=e.y,r=e.z,s=t.x,a=t.y,o=t.z;return this.x=n*o-r*a,this.y=r*s-i*o,this.z=i*a-n*s,this}projectOnVector(e){const t=e.lengthSq();if(0===t)return this.set(0,0,0);const i=e.dot(this)/t;return this.copy(e).multiplyScalar(i)}projectOnPlane(e){return 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(Ii(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y,n=this.z-e.z;return t*t+i*i+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,i){const n=Math.sin(t)*e;return this.x=n*Math.sin(i),this.y=Math.cos(t)*e,this.z=n*Math.cos(i),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,i){return this.x=e*Math.sin(t),this.y=i,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),i=this.setFromMatrixColumn(e,1).length(),n=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=i,this.z=n,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,4*t)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,3*t)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=2*Math.random()-1,i=Math.sqrt(1-t*t);return this.x=i*Math.cos(e),this.y=t,this.z=i*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const ji=new Wi,$i=new Hi;class Xi{static{this.prototype.isMatrix3=!0}constructor(e,t,i,n,r,s,a,o,l){this.elements=[1,0,0,0,1,0,0,0,1],void 0!==e&&this.set(e,t,i,n,r,s,a,o,l)}set(e,t,i,n,r,s,a,o,l){const c=this.elements;return c[0]=e,c[1]=n,c[2]=a,c[3]=t,c[4]=r,c[5]=o,c[6]=i,c[7]=s,c[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],this}extractBasis(e,t,i){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,n=t.elements,r=this.elements,s=i[0],a=i[3],o=i[6],l=i[1],c=i[4],u=i[7],h=i[2],d=i[5],p=i[8],f=n[0],m=n[3],g=n[6],_=n[1],v=n[4],b=n[7],y=n[2],x=n[5],S=n[8];return r[0]=s*f+a*_+o*y,r[3]=s*m+a*v+o*x,r[6]=s*g+a*b+o*S,r[1]=l*f+c*_+u*y,r[4]=l*m+c*v+u*x,r[7]=l*g+c*b+u*S,r[2]=h*f+d*_+p*y,r[5]=h*m+d*v+p*x,r[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],n=e[2],r=e[3],s=e[4],a=e[5],o=e[6],l=e[7],c=e[8];return t*s*c-t*a*l-i*r*c+i*a*o+n*r*l-n*s*o}invert(){const e=this.elements,t=e[0],i=e[1],n=e[2],r=e[3],s=e[4],a=e[5],o=e[6],l=e[7],c=e[8],u=c*s-a*l,h=a*o-c*r,d=l*r-s*o,p=t*u+i*h+n*d;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const f=1/p;return e[0]=u*f,e[1]=(n*l-c*i)*f,e[2]=(a*i-n*s)*f,e[3]=h*f,e[4]=(c*t-n*o)*f,e[5]=(n*r-a*t)*f,e[6]=d*f,e[7]=(i*o-l*t)*f,e[8]=(s*t-i*r)*f,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,i,n,r,s,a){const o=Math.cos(r),l=Math.sin(r);return this.set(i*o,i*l,-i*(o*s+l*a)+s+e,-n*l,n*o,-n*(-l*s+o*a)+a+t,0,0,1),this}scale(e,t){return 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=en(e.r),e.g=en(e.g),e.b=en(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],n=[.3127,.329];return e.define({[qt]:{primaries:t,whitePoint:n,transfer:Yt,toXYZ:Yi,fromXYZ:Ki,luminanceCoefficients:i,workingColorSpaceConfig:{unpackColorSpace:Xt},outputColorSpaceConfig:{drawingBufferColorSpace:Xt}},[Xt]:{primaries:t,whitePoint:n,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 en(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}let tn;class nn{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===tn&&(tn=vi("canvas")),tn.width=e.width,tn.height=e.height;const t=tn.getContext("2d");e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),i=tn}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 n=i.getImageData(0,0,e.width,e.height),r=n.data;for(let e=0;e<r.length;e++)r[e]=255*Ji(r[e]/255);return i.putImageData(n,0,0),t}if(e.data){const t=e.data.slice(0);for(let e=0;e<t.length;e++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[e]=Math.floor(255*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 rn=0;class sn{constructor(e=null){this.isTextureSource=!0,Object.defineProperty(this,"id",{value:rn++}),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:""},n=this.data;if(null!==n){let e;if(Array.isArray(n)){e=[];for(let t=0,i=n.length;t<i;t++)n[t].isDataTexture?e.push(an(n[t].image)):e.push(an(n[t]))}else e=an(n);i.url=e}return t||(e.images[this.uuid]=i),i}}function an(e){return"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?nn.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 on=0;const ln=new Wi;class cn extends Ri{constructor(e=cn.DEFAULT_IMAGE,t=cn.DEFAULT_MAPPING,i=1001,n=1001,r=1006,s=1008,a=1023,o=ze,l=cn.DEFAULT_ANISOTROPY,c=""){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:on++}),this.uuid=Di(),this.name="",this.source=new sn(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=i,this.wrapT=n,this.magFilter=r,this.minFilter=s,this.anisotropy=l,this.format=a,this.internalFormat=null,this.type=o,this.offset=new 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=c,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(ln).x}get height(){return this.source.getSize(ln).y}get depth(){return this.source.getSize(ln).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 n=this[t];void 0!==n?n&&i&&n.isVector2&&i.isVector2||n&&i&&n.isVector3&&i.isVector3||n&&i&&n.isMatrix3&&i.isMatrix3?n.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++}}cn.DEFAULT_IMAGE=null,cn.DEFAULT_MAPPING=300,cn.DEFAULT_ANISOTROPY=1;class un{static{this.prototype.isVector4=!0}constructor(e=0,t=0,i=0,n=1){this.x=e,this.y=t,this.z=i,this.w=n}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,i,n){return this.x=e,this.y=t,this.z=i,this.w=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("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,n=this.z,r=this.w,s=e.elements;return this.x=s[0]*t+s[4]*i+s[8]*n+s[12]*r,this.y=s[1]*t+s[5]*i+s[9]*n+s[13]*r,this.z=s[2]*t+s[6]*i+s[10]*n+s[14]*r,this.w=s[3]*t+s[7]*i+s[11]*n+s[15]*r,this}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,n,r;const s=.01,a=.1,o=e.elements,l=o[0],c=o[4],u=o[8],h=o[1],d=o[5],p=o[9],f=o[2],m=o[6],g=o[10];if(Math.abs(c-h)<s&&Math.abs(u-f)<s&&Math.abs(p-m)<s){if(Math.abs(c+h)<a&&Math.abs(u+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=(c+h)/4,b=(u+f)/4,y=(p+m)/4;return e>o&&e>_?e<s?(i=0,n=.707106781,r=.707106781):(i=Math.sqrt(e),n=v/i,r=b/i):o>_?o<s?(i=.707106781,n=0,r=.707106781):(n=Math.sqrt(o),i=v/n,r=y/n):_<s?(i=.707106781,n=.707106781,r=0):(r=Math.sqrt(_),i=b/r,n=y/r),this.set(i,n,r,t),this}let _=Math.sqrt((m-p)*(m-p)+(u-f)*(u-f)+(h-c)*(h-c));return Math.abs(_)<.001&&(_=1),this.x=(m-p)/_,this.y=(u-f)/_,this.z=(h-c)/_,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=Ii(this.x,e.x,t.x),this.y=Ii(this.y,e.y,t.y),this.z=Ii(this.z,e.z,t.z),this.w=Ii(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=Ii(this.x,e,t),this.y=Ii(this.y,e,t),this.z=Ii(this.z,e,t),this.w=Ii(this.w,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Ii(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 hn 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 un(0,0,e,t),this.scissorTest=!1,this.viewport=new un(0,0,e,t),this.textures=[];const n=i.count;for(let r=0;r<n;r++)this.textures[r]=new cn({width:e,height:t,depth:i.depth}),this.textures[r].isRenderTargetTexture=!0,this.textures[r].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 n=0,r=this.textures.length;n<r;n++)this.textures[n].image.width=e,this.textures[n].image.height=t,this.textures[n].image.depth=i,!0!==this.textures[n].isData3DTexture&&(this.textures[n].isArrayTexture=this.textures[n].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 sn(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 dn extends hn{constructor(e=1,t=1,i={}){super(e,t,i),this.isWebGLRenderTarget=!0}}class pn extends cn{constructor(e=null,t=1,i=1,n=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:i,depth:n},this.magFilter=Ie,this.minFilter=Ie,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 fn extends cn{constructor(e=null,t=1,i=1,n=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:i,depth:n},this.magFilter=Ie,this.minFilter=Ie,this.wrapR=Le,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}copy(e){return super.copy(e),this.wrapR=e.wrapR,this}}class mn{static{this.prototype.isMatrix4=!0}constructor(e,t,i,n,r,s,a,o,l,c,u,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,n,r,s,a,o,l,c,u,h,d,p,f,m)}set(e,t,i,n,r,s,a,o,l,c,u,h,d,p,f,m){const g=this.elements;return g[0]=e,g[4]=t,g[8]=i,g[12]=n,g[1]=r,g[5]=s,g[9]=a,g[13]=o,g[2]=l,g[6]=c,g[10]=u,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 mn).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,n=1/gn.setFromMatrixColumn(e,0).length(),r=1/gn.setFromMatrixColumn(e,1).length(),s=1/gn.setFromMatrixColumn(e,2).length();return t[0]=i[0]*n,t[1]=i[1]*n,t[2]=i[2]*n,t[3]=0,t[4]=i[4]*r,t[5]=i[5]*r,t[6]=i[6]*r,t[7]=0,t[8]=i[8]*s,t[9]=i[9]*s,t[10]=i[10]*s,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,i=e.x,n=e.y,r=e.z,s=Math.cos(i),a=Math.sin(i),o=Math.cos(n),l=Math.sin(n),c=Math.cos(r),u=Math.sin(r);if("XYZ"===e.order){const e=s*c,i=s*u,n=a*c,r=a*u;t[0]=o*c,t[4]=-o*u,t[8]=l,t[1]=i+n*l,t[5]=e-r*l,t[9]=-a*o,t[2]=r-e*l,t[6]=n+i*l,t[10]=s*o}else if("YXZ"===e.order){const e=o*c,i=o*u,n=l*c,r=l*u;t[0]=e+r*a,t[4]=n*a-i,t[8]=s*l,t[1]=s*u,t[5]=s*c,t[9]=-a,t[2]=i*a-n,t[6]=r+e*a,t[10]=s*o}else if("ZXY"===e.order){const e=o*c,i=o*u,n=l*c,r=l*u;t[0]=e-r*a,t[4]=-s*u,t[8]=n+i*a,t[1]=i+n*a,t[5]=s*c,t[9]=r-e*a,t[2]=-s*l,t[6]=a,t[10]=s*o}else if("ZYX"===e.order){const e=s*c,i=s*u,n=a*c,r=a*u;t[0]=o*c,t[4]=n*l-i,t[8]=e*l+r,t[1]=o*u,t[5]=r*l+e,t[9]=i*l-n,t[2]=-l,t[6]=a*o,t[10]=s*o}else if("YZX"===e.order){const e=s*o,i=s*l,n=a*o,r=a*l;t[0]=o*c,t[4]=r-e*u,t[8]=n*u+i,t[1]=u,t[5]=s*c,t[9]=-a*c,t[2]=-l*c,t[6]=i*u+n,t[10]=e-r*u}else if("XZY"===e.order){const e=s*o,i=s*l,n=a*o,r=a*l;t[0]=o*c,t[4]=-u,t[8]=l*c,t[1]=e*u+r,t[5]=s*c,t[9]=i*u-n,t[2]=n*u-i,t[6]=a*c,t[10]=r*u+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(vn,e,bn)}lookAt(e,t,i){const n=this.elements;return Sn.subVectors(e,t),0===Sn.lengthSq()&&(Sn.z=1),Sn.normalize(),yn.crossVectors(i,Sn),0===yn.lengthSq()&&(1===Math.abs(i.z)?Sn.x+=1e-4:Sn.z+=1e-4,Sn.normalize(),yn.crossVectors(i,Sn)),yn.normalize(),xn.crossVectors(Sn,yn),n[0]=yn.x,n[4]=xn.x,n[8]=Sn.x,n[1]=yn.y,n[5]=xn.y,n[9]=Sn.y,n[2]=yn.z,n[6]=xn.z,n[10]=Sn.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,n=t.elements,r=this.elements,s=i[0],a=i[4],o=i[8],l=i[12],c=i[1],u=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=n[0],S=n[4],T=n[8],M=n[12],E=n[1],w=n[5],A=n[9],R=n[13],C=n[2],N=n[6],P=n[10],L=n[14],D=n[3],I=n[7],F=n[11],U=n[15];return r[0]=s*x+a*E+o*C+l*D,r[4]=s*S+a*w+o*N+l*I,r[8]=s*T+a*A+o*P+l*F,r[12]=s*M+a*R+o*L+l*U,r[1]=c*x+u*E+h*C+d*D,r[5]=c*S+u*w+h*N+d*I,r[9]=c*T+u*A+h*P+d*F,r[13]=c*M+u*R+h*L+d*U,r[2]=p*x+f*E+m*C+g*D,r[6]=p*S+f*w+m*N+g*I,r[10]=p*T+f*A+m*P+g*F,r[14]=p*M+f*R+m*L+g*U,r[3]=_*x+v*E+b*C+y*D,r[7]=_*S+v*w+b*N+y*I,r[11]=_*T+v*A+b*P+y*F,r[15]=_*M+v*R+b*L+y*U,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[4],n=e[8],r=e[12],s=e[1],a=e[5],o=e[9],l=e[13],c=e[2],u=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*u,b=a*h-o*u,y=s*d-l*c,x=s*h-o*c,S=s*u-a*c;return t*(f*_-m*v+g*b)-i*(p*_-m*y+g*x)+n*(p*v-f*y+g*S)-r*(p*b-f*x+m*S)}determinantAffine(){const e=this.elements,t=e[0],i=e[4],n=e[8],r=e[1],s=e[5],a=e[9],o=e[2],l=e[6],c=e[10];return t*(s*c-a*l)-i*(r*c-a*o)+n*(r*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 n=this.elements;return e.isVector3?(n[12]=e.x,n[13]=e.y,n[14]=e.z):(n[12]=e,n[13]=t,n[14]=i),this}invert(){const e=this.elements,t=e[0],i=e[1],n=e[2],r=e[3],s=e[4],a=e[5],o=e[6],l=e[7],c=e[8],u=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-n*s,b=t*l-r*s,y=i*o-n*a,x=i*l-r*a,S=n*l-r*o,T=c*f-u*p,M=c*m-h*p,E=c*g-d*p,w=u*m-h*f,A=u*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]=(n*A-i*R-r*w)*N,e[2]=(f*S-m*x+g*y)*N,e[3]=(h*x-u*S-d*y)*N,e[4]=(o*E-s*R-l*M)*N,e[5]=(t*R-n*E+r*M)*N,e[6]=(m*b-p*S-g*v)*N,e[7]=(c*S-h*b+d*v)*N,e[8]=(s*A-a*E+l*T)*N,e[9]=(i*E-t*A-r*T)*N,e[10]=(p*x-f*b+g*_)*N,e[11]=(u*b-c*x-d*_)*N,e[12]=(a*M-s*w-o*T)*N,e[13]=(t*w-i*M+n*T)*N,e[14]=(f*v-p*y-m*_)*N,e[15]=(c*y-u*v+h*_)*N,this}scale(e){const t=this.elements,i=e.x,n=e.y,r=e.z;return t[0]*=i,t[4]*=n,t[8]*=r,t[1]*=i,t[5]*=n,t[9]*=r,t[2]*=i,t[6]*=n,t[10]*=r,t[3]*=i,t[7]*=n,t[11]*=r,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],i=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],n=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,i,n))}makeTranslation(e,t,i){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,i,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),i=Math.sin(e);return this.set(1,0,0,0,0,t,-i,0,0,i,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,0,i,0,0,1,0,0,-i,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,0,i,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const i=Math.cos(t),n=Math.sin(t),r=1-i,s=e.x,a=e.y,o=e.z,l=r*s,c=r*a;return this.set(l*s+i,l*a-n*o,l*o+n*a,0,l*a+n*o,c*a+i,c*o-n*s,0,l*o-n*a,c*o+n*s,r*o*o+i,0,0,0,0,1),this}makeScale(e,t,i){return this.set(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1),this}makeShear(e,t,i,n,r,s){return this.set(1,i,r,0,e,1,s,0,t,n,1,0,0,0,0,1),this}compose(e,t,i){const n=this.elements,r=t._x,s=t._y,a=t._z,o=t._w,l=r+r,c=s+s,u=a+a,h=r*l,d=r*c,p=r*u,f=s*c,m=s*u,g=a*u,_=o*l,v=o*c,b=o*u,y=i.x,x=i.y,S=i.z;return n[0]=(1-(f+g))*y,n[1]=(d+b)*y,n[2]=(p-v)*y,n[3]=0,n[4]=(d-b)*x,n[5]=(1-(h+g))*x,n[6]=(m+_)*x,n[7]=0,n[8]=(p+v)*S,n[9]=(m-_)*S,n[10]=(1-(h+f))*S,n[11]=0,n[12]=e.x,n[13]=e.y,n[14]=e.z,n[15]=1,this}decompose(e,t,i){const n=this.elements;e.x=n[12],e.y=n[13],e.z=n[14];const r=this.determinantAffine();if(0===r)return i.set(1,1,1),t.identity(),this;let s=gn.set(n[0],n[1],n[2]).length();const a=gn.set(n[4],n[5],n[6]).length(),o=gn.set(n[8],n[9],n[10]).length();r<0&&(s=-s),_n.copy(this);const l=1/s,c=1/a,u=1/o;return _n.elements[0]*=l,_n.elements[1]*=l,_n.elements[2]*=l,_n.elements[4]*=c,_n.elements[5]*=c,_n.elements[6]*=c,_n.elements[8]*=u,_n.elements[9]*=u,_n.elements[10]*=u,t.setFromRotationMatrix(_n),i.x=s,i.y=a,i.z=o,this}makePerspective(e,t,i,n,r,s,a=2e3,o=!1){const l=this.elements,c=2*r/(t-e),u=2*r/(i-n),h=(t+e)/(t-e),d=(i+n)/(i-n);let p,f;if(o)p=r/(s-r),f=s*r/(s-r);else if(a===ci)p=-(s+r)/(s-r),f=-2*s*r/(s-r);else{if(a!==ui)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);p=-s/(s-r),f=-s*r/(s-r)}return l[0]=c,l[4]=0,l[8]=h,l[12]=0,l[1]=0,l[5]=u,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,n,r,s,a=2e3,o=!1){const l=this.elements,c=2/(t-e),u=2/(i-n),h=-(t+e)/(t-e),d=-(i+n)/(i-n);let p,f;if(o)p=1/(s-r),f=s/(s-r);else if(a===ci)p=-2/(s-r),f=-(s+r)/(s-r);else{if(a!==ui)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);p=-1/(s-r),f=-r/(s-r)}return l[0]=c,l[4]=0,l[8]=0,l[12]=h,l[1]=0,l[5]=u,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 gn=new Wi,_n=new mn,vn=new Wi(0,0,0),bn=new Wi(1,1,1),yn=new Wi,xn=new Wi,Sn=new Wi,Tn=new mn,Mn=new Hi;class En{constructor(e=0,t=0,i=0,n=En.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=i,this._order=n}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,i,n=this._order){return this._x=e,this._y=t,this._z=i,this._order=n,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,i=!0){const n=e.elements,r=n[0],s=n[4],a=n[8],o=n[1],l=n[5],c=n[9],u=n[2],h=n[6],d=n[10];switch(t){case"XYZ":this._y=Math.asin(Ii(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-c,d),this._z=Math.atan2(-s,r)):(this._x=Math.atan2(h,l),this._z=0);break;case"YXZ":this._x=Math.asin(-Ii(c,-1,1)),Math.abs(c)<.9999999?(this._y=Math.atan2(a,d),this._z=Math.atan2(o,l)):(this._y=Math.atan2(-u,r),this._z=0);break;case"ZXY":this._x=Math.asin(Ii(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(-u,d),this._z=Math.atan2(-s,l)):(this._y=0,this._z=Math.atan2(o,r));break;case"ZYX":this._y=Math.asin(-Ii(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(h,d),this._z=Math.atan2(o,r)):(this._x=0,this._z=Math.atan2(-s,l));break;case"YZX":this._z=Math.asin(Ii(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-c,l),this._y=Math.atan2(-u,r)):(this._x=0,this._y=Math.atan2(a,d));break;case"XZY":this._z=Math.asin(-Ii(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(h,l),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-c,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 Tn.makeRotationFromQuaternion(e),this.setFromRotationMatrix(Tn,t,i)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return Mn.setFromEuler(this),this.setFromQuaternion(Mn,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}}En.DEFAULT_ORDER="XYZ";class wn{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 An=0;const Rn=new Wi,Cn=new Hi,Nn=new mn,Pn=new Wi,Ln=new Wi,Dn=new Wi,In=new Hi,Fn=new Wi(1,0,0),Un=new Wi(0,1,0),On=new Wi(0,0,1),Bn={type:"added"},kn={type:"removed"},zn={type:"childadded",child:null},Gn={type:"childremoved",child:null};class Vn extends Ri{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:An++}),this.uuid=Di(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Vn.DEFAULT_UP.clone();const e=new Wi,t=new En,i=new Hi,n=new Wi(1,1,1);t._onChange(function(){i.setFromEuler(t,!1)}),i._onChange(function(){t.setFromQuaternion(i,void 0,!1)}),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:i},scale:{configurable:!0,enumerable:!0,value:n},modelViewMatrix:{value:new mn},normalMatrix:{value:new Xi}}),this.matrix=new mn,this.matrixWorld=new mn,this.matrixAutoUpdate=Vn.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Vn.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new wn,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 Cn.setFromAxisAngle(e,t),this.quaternion.multiply(Cn),this}rotateOnWorldAxis(e,t){return Cn.setFromAxisAngle(e,t),this.quaternion.premultiply(Cn),this}rotateX(e){return this.rotateOnAxis(Fn,e)}rotateY(e){return this.rotateOnAxis(Un,e)}rotateZ(e){return this.rotateOnAxis(On,e)}translateOnAxis(e,t){return Rn.copy(e).applyQuaternion(this.quaternion),this.position.add(Rn.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(Fn,e)}translateY(e){return this.translateOnAxis(Un,e)}translateZ(e){return this.translateOnAxis(On,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(Nn.copy(this.matrixWorld).invert())}lookAt(e,t,i){e.isVector3?Pn.copy(e):Pn.set(e,t,i);const n=this.parent;this.updateWorldMatrix(!0,!1),Ln.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Nn.lookAt(Ln,Pn,this.up):Nn.lookAt(Pn,Ln,this.up),this.quaternion.setFromRotationMatrix(Nn),n&&(Nn.extractRotation(n.matrixWorld),Cn.setFromRotationMatrix(Nn),this.quaternion.premultiply(Cn.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(Bn),zn.child=e,this.dispatchEvent(zn),zn.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(kn),Gn.child=e,this.dispatchEvent(Gn),Gn.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),Nn.copy(this.matrixWorld).invert(),null!==e.parent&&(e.parent.updateWorldMatrix(!0,!1),Nn.multiply(e.parent.matrixWorld)),e.applyMatrix4(Nn),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(Bn),zn.child=e,this.dispatchEvent(zn),zn.child=null,this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let i=0,n=this.children.length;i<n;i++){const n=this.children[i].getObjectByProperty(e,t);if(void 0!==n)return n}}getObjectsByProperty(e,t,i=[]){this[e]===t&&i.push(this);const n=this.children;for(let r=0,s=n.length;r<s;r++)n[r].getObjectsByProperty(e,t,i);return i}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Ln,e,Dn),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Ln,In,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,n=t.length;i<n;i++)t[i].traverse(e)}traverseVisible(e){if(!1===this.visible)return;e(this);const t=this.children;for(let i=0,n=t.length;i<n;i++)t[i].traverseVisible(e)}traverseAncestors(e){const t=this.parent;null!==t&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale);const e=this.pivot;if(null!==e){const t=e.x,i=e.y,n=e.z,r=this.matrix.elements;r[12]+=t-r[0]*t-r[4]*i-r[8]*n,r[13]+=i-r[1]*t-r[5]*i-r[9]*n,r[14]+=n-r[2]*t-r[6]*i-r[10]*n}this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(!0===this.matrixWorldAutoUpdate&&(null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);const t=this.children;for(let i=0,n=t.length;i<n;i++){t[i].updateMatrixWorld(e)}}updateWorldMatrix(e,t,i=!1){const n=this.parent;if(!0===e&&null!==n&&n.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,n=e.length;t<n;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 n={};function r(t,i){return void 0===t[i.uuid]&&(t[i.uuid]=i.toJSON(e)),i.uuid}if(n.uuid=this.uuid,n.type=this.type,n.name=this.name,n.castShadow=this.castShadow,n.receiveShadow=this.receiveShadow,n.visible=this.visible,n.frustumCulled=this.frustumCulled,n.renderOrder=this.renderOrder,n.static=this.static,n.matrixAutoUpdate=this.matrixAutoUpdate,Object.keys(this.userData).length>0&&(n.userData=this.userData),n.layers=this.layers.mask,n.matrix=this.matrix.toArray(),n.up=this.up.toArray(),null!==this.pivot&&(n.pivot=this.pivot.toArray()),void 0!==this.morphTargetDictionary&&(n.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),void 0!==this.morphTargetInfluences&&(n.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(n.type="InstancedMesh",n.count=this.count,n.instanceMatrix=this.instanceMatrix.toJSON(),null!==this.instanceColor&&(n.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(n.type="BatchedMesh",n.perObjectFrustumCulled=this.perObjectFrustumCulled,n.sortObjects=this.sortObjects,n.drawRanges=this._drawRanges,n.reservedRanges=this._reservedRanges,n.geometryInfo=this._geometryInfo.map(e=>({...e,boundingBox:e.boundingBox?e.boundingBox.toJSON():void 0,boundingSphere:e.boundingSphere?e.boundingSphere.toJSON():void 0})),n.instanceInfo=this._instanceInfo.map(e=>({...e})),n.availableInstanceIds=this._availableInstanceIds.slice(),n.availableGeometryIds=this._availableGeometryIds.slice(),n.nextIndexStart=this._nextIndexStart,n.nextVertexStart=this._nextVertexStart,n.geometryCount=this._geometryCount,n.maxInstanceCount=this._maxInstanceCount,n.maxVertexCount=this._maxVertexCount,n.maxIndexCount=this._maxIndexCount,n.geometryInitialized=this._geometryInitialized,n.matricesTexture=this._matricesTexture.toJSON(e),n.indirectTexture=this._indirectTexture.toJSON(e),null!==this._colorsTexture&&(n.colorsTexture=this._colorsTexture.toJSON(e)),null!==this.boundingSphere&&(n.boundingSphere=this.boundingSphere.toJSON()),null!==this.boundingBox&&(n.boundingBox=this.boundingBox.toJSON())),this.isScene)this.background&&(this.background.isColor?n.background=this.background.toJSON():this.background.isTexture&&(n.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&!0!==this.environment.isRenderTargetTexture&&(n.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){n.geometry=r(e.geometries,this.geometry);const t=this.geometry.parameters;if(void 0!==t&&void 0!==t.shapes){const i=t.shapes;if(Array.isArray(i))for(let t=0,n=i.length;t<n;t++){const n=i[t];r(e.shapes,n)}else r(e.shapes,i)}}if(this.isSkinnedMesh&&(n.bindMode=this.bindMode,n.bindMatrix=this.bindMatrix.toArray(),void 0!==this.skeleton&&(r(e.skeletons,this.skeleton),n.skeleton=this.skeleton.uuid)),void 0!==this.material)if(Array.isArray(this.material)){const t=[];for(let i=0,n=this.material.length;i<n;i++)t.push(r(e.materials,this.material[i]));n.material=t}else n.material=r(e.materials,this.material);if(this.children.length>0){n.children=[];for(let t=0;t<this.children.length;t++)n.children.push(this.children[t].toJSON(e).object)}if(this.animations.length>0){n.animations=[];for(let t=0;t<this.animations.length;t++){const i=this.animations[t];n.animations.push(r(e.animations,i))}}if(t){const t=s(e.geometries),n=s(e.materials),r=s(e.textures),a=s(e.images),o=s(e.shapes),l=s(e.skeletons),c=s(e.animations),u=s(e.nodes);t.length>0&&(i.geometries=t),n.length>0&&(i.materials=n),r.length>0&&(i.textures=r),a.length>0&&(i.images=a),o.length>0&&(i.shapes=o),l.length>0&&(i.skeletons=l),c.length>0&&(i.animations=c),u.length>0&&(i.nodes=u)}return i.object=n,i;function s(e){const t=[];for(const i in e){const n=e[i];delete n.metadata,t.push(n)}return t}}clone(e){return(new this.constructor).copy(this,e)}copy(e,t=!0){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"})}}Vn.DEFAULT_UP=new Wi(0,1,0),Vn.DEFAULT_MATRIX_AUTO_UPDATE=!0,Vn.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;let Hn=class extends Vn{constructor(){super(),this.isGroup=!0,this.type="Group"}};const Wn={type:"move"};class jn{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return null===this._hand&&(this._hand=new Hn,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 Hn,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 Hn,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 n=null,r=null,s=null;const a=this._targetRay,o=this._grip,l=this._hand;if(e&&"visible-blurred"!==t.session.visibilityState){if(l&&e.hand){s=!0;for(const n of e.hand.values()){const e=t.getJointPose(n,i),r=this._getHandJoint(l,n);null!==e&&(r.matrix.fromArray(e.transform.matrix),r.matrix.decompose(r.position,r.quaternion,r.scale),r.matrixWorldNeedsUpdate=!0,r.jointRadius=e.radius),r.visible=null!==e}const n=l.joints["index-finger-tip"],r=l.joints["thumb-tip"],a=n.position.distanceTo(r.position),o=.02,c=.005;l.inputState.pinching&&a>o+c?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&a<=o-c&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else null!==o&&e.gripSpace&&(r=t.getPose(e.gripSpace,i),null!==r&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.quaternion,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1,o.eventsEnabled&&o.dispatchEvent({type:"gripUpdated",data:e,target:this})));null!==a&&(n=t.getPose(e.targetRaySpace,i),null===n&&null!==r&&(n=r),null!==n&&(a.matrix.fromArray(n.transform.matrix),a.matrix.decompose(a.position,a.quaternion,a.scale),a.matrixWorldNeedsUpdate=!0,n.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(n.linearVelocity)):a.hasLinearVelocity=!1,n.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(n.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(Wn)))}return null!==a&&(a.visible=null!==n),null!==o&&(o.visible=null!==r),null!==l&&(l.visible=null!==s),this}_getHandJoint(e,t){if(void 0===e.joints[t.jointName]){const i=new Hn;i.matrixAutoUpdate=!1,i.visible=!1,e.joints[t.jointName]=i,e.add(i)}return e.joints[t.jointName]}}const $n={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},Xn={h:0,s:0,l:0},qn={h:0,s:0,l:0};function Yn(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 Kn=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,n=Qi.workingColorSpace){return this.r=e,this.g=t,this.b=i,Qi.colorSpaceToWorking(this,n),this}setHSL(e,t,i,n=Qi.workingColorSpace){if(e=Fi(e,1),t=Ii(t,0,1),i=Ii(i,0,1),0===t)this.r=this.g=this.b=i;else{const n=i<=.5?i*(1+t):i+t-i*t,r=2*i-n;this.r=Yn(r,n,e+1/3),this.g=Yn(r,n,e),this.b=Yn(r,n,e-1/3)}return Qi.colorSpaceToWorking(this,n),this}setStyle(e,t=Xt){function i(t){void 0!==t&&parseFloat(t)<1&&Ti("Color: Alpha component of "+e+" will be ignored.")}let n;if(n=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const s=n[1],a=n[2];switch(s){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?|\.\d+)\s*)?$/.exec(a))return i(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+(?:\.\d+)?|\.\d+)\%\s*,\s*(\d+(?:\.\d+)?|\.\d+)\%\s*,\s*(\d+(?:\.\d+)?|\.\d+)\%\s*(?:,\s*(\d+(?:\.\d+)?|\.\d+)\s*)?$/.exec(a))return i(r[4]),this.setRGB(Math.min(100,parseFloat(r[1]))/100,Math.min(100,parseFloat(r[2]))/100,Math.min(100,parseFloat(r[3]))/100,t);break;case"hsl":case"hsla":if(r=/^\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))\s*,\s*(\d+(?:\.\d+)?|\.\d+)\%\s*,\s*(\d+(?:\.\d+)?|\.\d+)\%\s*(?:,\s*(\d+(?:\.\d+)?|\.\d+)\s*)?$/.exec(a))return i(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:Ti("Color: Unknown color model "+e)}}else if(n=/^\#([A-Fa-f\d]+)$/.exec(e)){const i=n[1],r=i.length;if(3===r)return this.setRGB(parseInt(i.charAt(0),16)/15,parseInt(i.charAt(1),16)/15,parseInt(i.charAt(2),16)/15,t);if(6===r)return this.setHex(parseInt(i,16),t);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=$n[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=en(e.r),this.g=en(e.g),this.b=en(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Xt){return Qi.workingToColorSpace(Zn.copy(this),e),65536*Math.round(Ii(255*Zn.r,0,255))+256*Math.round(Ii(255*Zn.g,0,255))+Math.round(Ii(255*Zn.b,0,255))}getHexString(e=Xt){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Qi.workingColorSpace){Qi.workingToColorSpace(Zn.copy(this),t);const i=Zn.r,n=Zn.g,r=Zn.b,s=Math.max(i,n,r),a=Math.min(i,n,r);let o,l;const c=(a+s)/2;if(a===s)o=0,l=0;else{const e=s-a;switch(l=c<=.5?e/(s+a):e/(2-s-a),s){case i:o=(n-r)/e+(n<r?6:0);break;case n:o=(r-i)/e+2;break;case r:o=(i-n)/e+4}o/=6}return e.h=o,e.s=l,e.l=c,e}getRGB(e,t=Qi.workingColorSpace){return Qi.workingToColorSpace(Zn.copy(this),t),e.r=Zn.r,e.g=Zn.g,e.b=Zn.b,e}getStyle(e=Xt){Qi.workingToColorSpace(Zn.copy(this),e);const t=Zn.r,i=Zn.g,n=Zn.b;return e!==Xt?`color(${e} ${t.toFixed(3)} ${i.toFixed(3)} ${n.toFixed(3)})`:`rgb(${Math.round(255*t)},${Math.round(255*i)},${Math.round(255*n)})`}offsetHSL(e,t,i){return this.getHSL(Xn),this.setHSL(Xn.h+e,Xn.s+t,Xn.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(Xn),e.getHSL(qn);const i=Ui(Xn.h,qn.h,t),n=Ui(Xn.s,qn.s,t),r=Ui(Xn.l,qn.l,t);return this.setHSL(i,n,r),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const t=this.r,i=this.g,n=this.b,r=e.elements;return this.r=r[0]*t+r[3]*i+r[6]*n,this.g=r[1]*t+r[4]*i+r[7]*n,this.b=r[2]*t+r[5]*i+r[8]*n,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}};const Zn=new Kn;Kn.NAMES=$n;class Qn extends Vn{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 En,this.environmentIntensity=1,this.environmentRotation=new En,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 Jn=new Wi,er=new Wi,tr=new Wi,ir=new Wi,nr=new Wi,rr=new Wi,sr=new Wi,ar=new Wi,or=new Wi,lr=new Wi,cr=new un,ur=new un,hr=new un;class dr{constructor(e=new Wi,t=new Wi,i=new Wi){this.a=e,this.b=t,this.c=i}static getNormal(e,t,i,n){n.subVectors(i,t),Jn.subVectors(e,t),n.cross(Jn);const r=n.lengthSq();return r>0?n.multiplyScalar(1/Math.sqrt(r)):n.set(0,0,0)}static getBarycoord(e,t,i,n,r){Jn.subVectors(n,t),er.subVectors(i,t),tr.subVectors(e,t);const s=Jn.dot(Jn),a=Jn.dot(er),o=Jn.dot(tr),l=er.dot(er),c=er.dot(tr),u=s*l-a*a;if(0===u)return r.set(0,0,0),null;const h=1/u,d=(l*o-a*c)*h,p=(s*c-a*o)*h;return r.set(1-d-p,p,d)}static containsPoint(e,t,i,n){return null!==this.getBarycoord(e,t,i,n,ir)&&(ir.x>=0&&ir.y>=0&&ir.x+ir.y<=1)}static getInterpolation(e,t,i,n,r,s,a,o){return null===this.getBarycoord(e,t,i,n,ir)?(o.x=0,o.y=0,"z"in o&&(o.z=0),"w"in o&&(o.w=0),null):(o.setScalar(0),o.addScaledVector(r,ir.x),o.addScaledVector(s,ir.y),o.addScaledVector(a,ir.z),o)}static getInterpolatedAttribute(e,t,i,n,r,s){return cr.setScalar(0),ur.setScalar(0),hr.setScalar(0),cr.fromBufferAttribute(e,t),ur.fromBufferAttribute(e,i),hr.fromBufferAttribute(e,n),s.setScalar(0),s.addScaledVector(cr,r.x),s.addScaledVector(ur,r.y),s.addScaledVector(hr,r.z),s}static isFrontFacing(e,t,i,n){return Jn.subVectors(i,t),er.subVectors(e,t),Jn.cross(er).dot(n)<0}set(e,t,i){return this.a.copy(e),this.b.copy(t),this.c.copy(i),this}setFromPointsAndIndices(e,t,i,n){return this.a.copy(e[t]),this.b.copy(e[i]),this.c.copy(e[n]),this}setFromAttributeAndIndices(e,t,i,n){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,i),this.c.fromBufferAttribute(e,n),this}clone(){return(new this.constructor).copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Jn.subVectors(this.c,this.b),er.subVectors(this.a,this.b),.5*Jn.cross(er).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return dr.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return dr.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,i,n,r){return dr.getInterpolation(e,this.a,this.b,this.c,t,i,n,r)}containsPoint(e){return dr.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return dr.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const i=this.a,n=this.b,r=this.c;let s,a;nr.subVectors(n,i),rr.subVectors(r,i),ar.subVectors(e,i);const o=nr.dot(ar),l=rr.dot(ar);if(o<=0&&l<=0)return t.copy(i);or.subVectors(e,n);const c=nr.dot(or),u=rr.dot(or);if(c>=0&&u<=c)return t.copy(n);const h=o*u-c*l;if(h<=0&&o>=0&&c<=0&&o-c>0)return s=o/(o-c),t.copy(i).addScaledVector(nr,s);lr.subVectors(e,r);const d=nr.dot(lr),p=rr.dot(lr);if(p>=0&&d<=p)return t.copy(r);const f=d*l-o*p;if(f<=0&&l>=0&&p<=0)return a=l/(l-p),t.copy(i).addScaledVector(rr,a);const m=c*p-d*u;if(m<=0&&u-c>=0&&d-p>=0)return sr.subVectors(r,n),a=(u-c)/(u-c+(d-p)),t.copy(n).addScaledVector(sr,a);const g=1/(m+f+h);return s=f*g,a=h*g,t.copy(i).addScaledVector(nr,s).addScaledVector(rr,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}class pr{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(mr.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,i=e.count;t<i;t++)this.expandByPoint(mr.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=mr.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(i),this.max.copy(e).add(i),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return(new this.constructor).copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);const i=e.geometry;if(void 0!==i){const n=i.getAttribute("position");if(!0===t&&void 0!==n&&!0!==e.isInstancedMesh&&!0!==e.isBatchedMesh)for(let t=0,i=n.count;t<i;t++)!0===e.isMesh?e.getVertexPosition(t,mr):mr.fromBufferAttribute(n,t),mr.applyMatrix4(e.matrixWorld),this.expandByPoint(mr);else void 0!==e.boundingBox?(null===e.boundingBox&&e.computeBoundingBox(),gr.copy(e.boundingBox)):(null===i.boundingBox&&i.computeBoundingBox(),gr.copy(i.boundingBox)),gr.applyMatrix4(e.matrixWorld),this.union(gr)}const n=e.children;for(let e=0,i=n.length;e<i;e++)this.expandByObject(n[e],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,mr),mr.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(Tr),Mr.subVectors(this.max,Tr),_r.subVectors(e.a,Tr),vr.subVectors(e.b,Tr),br.subVectors(e.c,Tr),yr.subVectors(vr,_r),xr.subVectors(br,vr),Sr.subVectors(_r,br);let t=[0,-yr.z,yr.y,0,-xr.z,xr.y,0,-Sr.z,Sr.y,yr.z,0,-yr.x,xr.z,0,-xr.x,Sr.z,0,-Sr.x,-yr.y,yr.x,0,-xr.y,xr.x,0,-Sr.y,Sr.x,0];return!!Ar(t,_r,vr,br,Mr)&&(t=[1,0,0,0,1,0,0,0,1],!!Ar(t,_r,vr,br,Mr)&&(Er.crossVectors(yr,xr),t=[Er.x,Er.y,Er.z],Ar(t,_r,vr,br,Mr)))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,mr).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=.5*this.getSize(mr).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()||(fr[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),fr[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),fr[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),fr[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),fr[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),fr[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),fr[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),fr[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(fr)),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 fr=[new Wi,new Wi,new Wi,new Wi,new Wi,new Wi,new Wi,new Wi],mr=new Wi,gr=new pr,_r=new Wi,vr=new Wi,br=new Wi,yr=new Wi,xr=new Wi,Sr=new Wi,Tr=new Wi,Mr=new Wi,Er=new Wi,wr=new Wi;function Ar(e,t,i,n,r){for(let s=0,a=e.length-3;s<=a;s+=3){wr.fromArray(e,s);const a=r.x*Math.abs(wr.x)+r.y*Math.abs(wr.y)+r.z*Math.abs(wr.z),o=t.dot(wr),l=i.dot(wr),c=n.dot(wr);if(Math.max(-Math.max(o,l,c),Math.min(o,l,c))>a)return!1}return!0}const Rr=Cr();function Cr(){const e=new ArrayBuffer(4),t=new Float32Array(e),i=new Uint32Array(e),n=new Uint32Array(512),r=new Uint32Array(512);for(let e=0;e<256;++e){const t=e-127;t<-27?(n[e]=0,n[256|e]=32768,r[e]=24,r[256|e]=24):t<-14?(n[e]=1024>>-t-14,n[256|e]=1024>>-t-14|32768,r[e]=-t-1,r[256|e]=-t-1):t<=15?(n[e]=t+15<<10,n[256|e]=t+15<<10|32768,r[e]=13,r[256|e]=13):t<128?(n[e]=31744,n[256|e]=64512,r[e]=24,r[256|e]=24):(n[e]=31744,n[256|e]=64512,r[e]=13,r[256|e]=13)}const s=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let e=1;e<1024;++e){let t=e<<13,i=0;for(;!(8388608&t);)t<<=1,i-=8388608;t&=-8388609,i+=947912704,s[e]=t|i}for(let e=1024;e<2048;++e)s[e]=939524096+(e-1024<<13);for(let e=1;e<31;++e)a[e]=e<<23;a[31]=1199570944,a[32]=2147483648;for(let e=33;e<63;++e)a[e]=2147483648+(e-32<<23);a[63]=3347054592;for(let e=1;e<64;++e)32!==e&&(o[e]=1024);return{floatView:t,uint32View:i,baseTable:n,shiftTable:r,mantissaTable:s,exponentTable:a,offsetTable:o}}function Nr(e){Math.abs(e)>65504&&Ti("DataUtils.toHalfFloat(): Value out of range."),e=Ii(e,-65504,65504),Rr.floatView[0]=e;const t=Rr.uint32View[0],i=t>>23&511;return Rr.baseTable[i]+((8388607&t)>>Rr.shiftTable[i])}function Pr(e){const t=e>>10;return Rr.uint32View[0]=Rr.mantissaTable[Rr.offsetTable[t]+(1023&e)]+Rr.exponentTable[t],Rr.floatView[0]}const Lr=new Wi,Dr=new Vi;let Ir=0;class Fr 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:Ir++}),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 n=0,r=this.itemSize;n<r;n++)this.array[e+n]=t.array[i+n];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(2===this.itemSize)for(let t=0,i=this.count;t<i;t++)Dr.fromBufferAttribute(this,t),Dr.applyMatrix3(e),this.setXY(t,Dr.x,Dr.y);else if(3===this.itemSize)for(let t=0,i=this.count;t<i;t++)Lr.fromBufferAttribute(this,t),Lr.applyMatrix3(e),this.setXYZ(t,Lr.x,Lr.y,Lr.z);return this}applyMatrix4(e){for(let t=0,i=this.count;t<i;t++)Lr.fromBufferAttribute(this,t),Lr.applyMatrix4(e),this.setXYZ(t,Lr.x,Lr.y,Lr.z);return this}applyNormalMatrix(e){for(let t=0,i=this.count;t<i;t++)Lr.fromBufferAttribute(this,t),Lr.applyNormalMatrix(e),this.setXYZ(t,Lr.x,Lr.y,Lr.z);return this}transformDirection(e){for(let t=0,i=this.count;t<i;t++)Lr.fromBufferAttribute(this,t),Lr.transformDirection(e),this.setXYZ(t,Lr.x,Lr.y,Lr.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,n){return e*=this.itemSize,this.normalized&&(t=this._normalize(t),i=this._normalize(i),n=this._normalize(n)),this.array[e+0]=t,this.array[e+1]=i,this.array[e+2]=n,this}setXYZW(e,t,i,n,r){return e*=this.itemSize,this.normalized&&(t=this._normalize(t),i=this._normalize(i),n=this._normalize(n),r=this._normalize(r)),this.array[e+0]=t,this.array[e+1]=i,this.array[e+2]=n,this.array[e+3]=r,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return 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 Ur extends Fr{constructor(e,t,i){super(new Uint16Array(e),t,i)}}class Or extends Fr{constructor(e,t,i){super(new Uint32Array(e),t,i)}}class Br extends Fr{constructor(e,t,i){super(new Uint16Array(e),t,i),this.isFloat16BufferAttribute=!0}getX(e){let t=Pr(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]=Nr(t),this}getY(e){let t=Pr(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]=Nr(t),this}getZ(e){let t=Pr(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]=Nr(t),this}getW(e){let t=Pr(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]=Nr(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]=Nr(t),this.array[e+1]=Nr(i),this}setXYZ(e,t,i,n){return e*=this.itemSize,this.normalized&&(t=zi(t,this.array),i=zi(i,this.array),n=zi(n,this.array)),this.array[e+0]=Nr(t),this.array[e+1]=Nr(i),this.array[e+2]=Nr(n),this}setXYZW(e,t,i,n,r){return e*=this.itemSize,this.normalized&&(t=zi(t,this.array),i=zi(i,this.array),n=zi(n,this.array),r=zi(r,this.array)),this.array[e+0]=Nr(t),this.array[e+1]=Nr(i),this.array[e+2]=Nr(n),this.array[e+3]=Nr(r),this}}class kr extends Fr{constructor(e,t,i){super(new Float32Array(e),t,i)}}const zr=new pr,Gr=new Wi,Vr=new Wi;class Hr{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):zr.setFromPoints(e).getCenter(i);let n=0;for(let t=0,r=e.length;t<r;t++)n=Math.max(n,i.distanceToSquared(e[t]));return this.radius=Math.sqrt(n),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){const t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){const i=this.center.distanceToSquared(e);return t.copy(e),i>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Gr.subVectors(e,this.center);const t=Gr.lengthSq();if(t>this.radius*this.radius){const e=Math.sqrt(t),i=.5*(e-this.radius);this.center.addScaledVector(Gr,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):(Vr.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Gr.copy(e.center).add(Vr)),this.expandByPoint(Gr.copy(e.center).sub(Vr))),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 Wr=0;const jr=new mn,$r=new Vn,Xr=new Wi,qr=new pr,Yr=new pr,Kr=new Wi;class Zr extends Ri{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:Wr++}),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)?Or:Ur)(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 n=this.attributes.tangent;return void 0!==n&&(n.transformDirection(e),n.needsUpdate=!0),null!==this.boundingBox&&this.computeBoundingBox(),null!==this.boundingSphere&&this.computeBoundingSphere(),this._transformed=!0,this}applyQuaternion(e){return jr.makeRotationFromQuaternion(e),this.applyMatrix4(jr),this}rotateX(e){return jr.makeRotationX(e),this.applyMatrix4(jr),this}rotateY(e){return jr.makeRotationY(e),this.applyMatrix4(jr),this}rotateZ(e){return jr.makeRotationZ(e),this.applyMatrix4(jr),this}translate(e,t,i){return jr.makeTranslation(e,t,i),this.applyMatrix4(jr),this}scale(e,t,i){return jr.makeScale(e,t,i),this.applyMatrix4(jr),this}lookAt(e){return $r.lookAt(e),$r.updateMatrix(),this.applyMatrix4($r.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Xr).negate(),this.translate(Xr.x,Xr.y,Xr.z),this}setFromPoints(e){const t=this.getAttribute("position");if(void 0===t){const t=[];for(let i=0,n=e.length;i<n;i++){const n=e[i];t.push(n.x,n.y,n.z||0)}this.setAttribute("position",new kr(t,3))}else{const i=Math.min(e.length,t.count);for(let n=0;n<i;n++){const i=e[n];t.setXYZ(n,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 pr);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];qr.setFromBufferAttribute(i),this.morphTargetsRelative?(Kr.addVectors(this.boundingBox.min,qr.min),this.boundingBox.expandByPoint(Kr),Kr.addVectors(this.boundingBox.max,qr.max),this.boundingBox.expandByPoint(Kr)):(this.boundingBox.expandByPoint(qr.min),this.boundingBox.expandByPoint(qr.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 Hr);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(qr.setFromBufferAttribute(e),t)for(let e=0,i=t.length;e<i;e++){const i=t[e];Yr.setFromBufferAttribute(i),this.morphTargetsRelative?(Kr.addVectors(qr.min,Yr.min),qr.expandByPoint(Kr),Kr.addVectors(qr.max,Yr.max),qr.expandByPoint(Kr)):(qr.expandByPoint(Yr.min),qr.expandByPoint(Yr.max))}qr.getCenter(i);let n=0;for(let t=0,r=e.count;t<r;t++)Kr.fromBufferAttribute(e,t),n=Math.max(n,i.distanceToSquared(Kr));if(t)for(let r=0,s=t.length;r<s;r++){const s=t[r],a=this.morphTargetsRelative;for(let t=0,r=s.count;t<r;t++)Kr.fromBufferAttribute(s,t),a&&(Xr.fromBufferAttribute(e,t),Kr.add(Xr)),n=Math.max(n,i.distanceToSquared(Kr))}this.boundingSphere.radius=Math.sqrt(n),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,n=t.normal,r=t.uv;let s=this.getAttribute("tangent");void 0!==s&&s.count===i.count||(s=new Fr(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 c=new Wi,u=new Wi,h=new Wi,d=new Vi,p=new Vi,f=new Vi,m=new Wi,g=new Wi;function _(e,t,n){l[e]=l[t]=l[n]=1,c.fromBufferAttribute(i,e),u.fromBufferAttribute(i,t),h.fromBufferAttribute(i,n),d.fromBufferAttribute(r,e),p.fromBufferAttribute(r,t),f.fromBufferAttribute(r,n),u.sub(c),h.sub(c),p.sub(d),f.sub(d);const s=1/(p.x*f.y-f.x*p.y);isFinite(s)&&(m.copy(u).multiplyScalar(f.y).addScaledVector(h,-p.y).multiplyScalar(s),g.copy(h).multiplyScalar(p.x).addScaledVector(u,-f.x).multiplyScalar(s),a[e].add(m),a[t].add(m),a[n].add(m),o[e].add(g),o[t].add(g),o[n].add(g))}let 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],n=i.start;for(let t=n,r=n+i.count;t<r;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(n,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 Fr(new Float32Array(3*t.count),3),this.setAttribute("normal",i);else for(let e=0,t=i.count;e<t;e++)i.setXYZ(e,0,0,0);const n=new Wi,r=new Wi,s=new Wi,a=new Wi,o=new Wi,l=new Wi,c=new Wi,u=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);n.fromBufferAttribute(t,d),r.fromBufferAttribute(t,p),s.fromBufferAttribute(t,f),c.subVectors(s,r),u.subVectors(n,r),c.cross(u),a.fromBufferAttribute(i,d),o.fromBufferAttribute(i,p),l.fromBufferAttribute(i,f),a.add(c),o.add(c),l.add(c),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)n.fromBufferAttribute(t,e+0),r.fromBufferAttribute(t,e+1),s.fromBufferAttribute(t,e+2),c.subVectors(s,r),u.subVectors(n,r),c.cross(u),i.setXYZ(e+0,c.x,c.y,c.z),i.setXYZ(e+1,c.x,c.y,c.z),i.setXYZ(e+2,c.x,c.y,c.z);this.normalizeNormals(),i.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,i=e.count;t<i;t++)Kr.fromBufferAttribute(e,t),Kr.normalize(),e.setXYZ(t,Kr.x,Kr.y,Kr.z)}toNonIndexed(){function e(e,t){const i=e.array,n=e.itemSize,r=e.normalized,s=new i.constructor(t.length*n);let a=0,o=0;for(let r=0,l=t.length;r<l;r++){a=e.isInterleavedBufferAttribute?t[r]*e.data.stride+e.offset:t[r]*n;for(let e=0;e<n;e++)s[o++]=i[a++]}return new Fr(s,n,r)}if(null===this.index)return Ti("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new Zr,i=this.index.array,n=this.attributes;for(const r in n){const s=e(n[r],i);t.setAttribute(r,s)}const r=this.morphAttributes;for(const n in r){const s=[],a=r[n];for(let t=0,n=a.length;t<n;t++){const n=e(a[t],i);s.push(n)}t.morphAttributes[n]=s}t.morphTargetsRelative=this.morphTargetsRelative;const s=this.groups;for(let e=0,i=s.length;e<i;e++){const i=s[e];t.addGroup(i.start,i.count,i.materialIndex)}return t}toJSON(){const e={metadata:{version:4.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 n=i[t];e.data.attributes[t]=n.toJSON(e.data)}const n={};let r=!1;for(const t in this.morphAttributes){const i=this.morphAttributes[t],s=[];for(let t=0,n=i.length;t<n;t++){const n=i[t];s.push(n.toJSON(e.data))}s.length>0&&(n[t]=s,r=!0)}r&&(e.data.morphAttributes=n,e.data.morphTargetsRelative=this.morphTargetsRelative);const s=this.groups;s.length>0&&(e.data.groups=JSON.parse(JSON.stringify(s)));const a=this.boundingSphere;return null!==a&&(e.data.boundingSphere=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 n=e.attributes;for(const e in n){const i=n[e];this.setAttribute(e,i.clone(t))}const r=e.morphAttributes;for(const e in r){const i=[],n=r[e];for(let e=0,r=n.length;e<r;e++)i.push(n[e].clone(t));this.morphAttributes[e]=i}this.morphTargetsRelative=e.morphTargetsRelative;const s=e.groups;for(let e=0,t=s.length;e<t;e++){const t=s[e];this.addGroup(t.start,t.count,t.materialIndex)}const a=e.boundingBox;null!==a&&(this.boundingBox=a.clone());const o=e.boundingSphere;return null!==o&&(this.boundingSphere=o.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this._transformed=e._transformed,this}dispose(){this.dispatchEvent({type:"dispose"})}}class Qr{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 n=0,r=this.stride;n<r;n++)this.array[e+n]=t.array[i+n];return this}set(e,t=0){return this.array.set(e,t),this}clone(e){void 0===e.arrayBuffers&&(e.arrayBuffers={});const t=Jr(this.array);void 0===e.arrayBuffers[t]&&(e.arrayBuffers[t]=this.array.slice(0).buffer);const i=new this.array.constructor(e.arrayBuffers[t]),n=new this.constructor(i,this.stride);return n.setUsage(this.usage),n}onUpload(e){return this.onUploadCallback=e,this}toJSON(e){void 0===e.arrayBuffers&&(e.arrayBuffers={});const t=Jr(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 Jr(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,n=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=e,this.itemSize=t,this.offset=i,this.normalized=n,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,n){return e=e*this.data.stride+this.offset,this.normalized&&(t=this._normalize(t),i=this._normalize(i),n=this._normalize(n)),this.data.array[e+0]=t,this.data.array[e+1]=i,this.data.array[e+2]=n,this}setXYZW(e,t,i,n,r){return e=e*this.data.stride+this.offset,this.normalized&&(t=this._normalize(t),i=this._normalize(i),n=this._normalize(n),r=this._normalize(r)),this.data.array[e+0]=t,this.data.array[e+1]=i,this.data.array[e+2]=n,this.data.array[e+3]=r,this}clone(e){if(void 0===e){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 Fr(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,ns=new Wi,rs=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,n){return this.normal.set(e,t,i),this.constant=n,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,i){const n=is.subVectors(i,t).cross(ns.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(n,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t,i=!0){const n=e.delta(is),r=this.normal.dot(n);if(0===r)return 0===this.distanceToPoint(e.start)?t.copy(e.start):null;const s=-(e.start.dot(this.normal)+this.constant)/r;return!0===i&&(s<0||s>1)?null:t.copy(e.start).addScaledVector(n,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||rs.getNormalMatrix(e),n=this.coplanarPoint(is).applyMatrix4(e),r=this.normal.applyMatrix3(i).normalize();return this.constant=-n.dot(r),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return(new this.constructor).copy(this)}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 Kn(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 n=this[t];void 0!==n?n&&n.isColor?n.set(i):n&&n.isVector2&&i&&i.isVector2||n&&n.isEuler&&i&&i.isEuler||n&&n.isVector3&&i&&i.isVector3?n.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 n(e){const t=[];for(const i in e){const n=e[i];delete n.metadata,t.push(n)}return t}if(i.uuid=this.uuid,i.type=this.type,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=n(e.textures),r=n(e.images);t.length>0&&(i.textures=t),r.length>0&&(i.images=r)}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 Kn).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 n=0;n!==e;++n)i[n]=t[n].clone()}return this.clippingPlanes=i,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.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 Kn(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 cs=new Wi,us=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,cs)),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=cs.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(cs.copy(this.origin).addScaledVector(this.direction,t),cs.distanceToSquared(e))}distanceSqToSegment(e,t,i,n){us.copy(e).add(t).multiplyScalar(.5),hs.copy(t).sub(e).normalize(),ds.copy(this.origin).sub(us);const r=.5*e.distanceTo(t),s=-this.direction.dot(hs),a=ds.dot(this.direction),o=-ds.dot(hs),l=ds.lengthSq(),c=Math.abs(1-s*s);let u,h,d,p;if(c>0)if(u=s*o-a,h=s*a-o,p=r*c,u>=0)if(h>=-p)if(h<=p){const e=1/c;u*=e,h*=e,d=u*(u+s*h+2*a)+h*(s*u+h+2*o)+l}else h=r,u=Math.max(0,-(s*h+a)),d=-u*u+h*(h+2*o)+l;else h=-r,u=Math.max(0,-(s*h+a)),d=-u*u+h*(h+2*o)+l;else h<=-p?(u=Math.max(0,-(-s*r+a)),h=u>0?-r:Math.min(Math.max(-r,-o),r),d=-u*u+h*(h+2*o)+l):h<=p?(u=0,h=Math.min(Math.max(-r,-o),r),d=h*(h+2*o)+l):(u=Math.max(0,-(s*r+a)),h=u>0?r:Math.min(Math.max(-r,-o),r),d=-u*u+h*(h+2*o)+l);else h=s>0?-r:r,u=Math.max(0,-(s*h+a)),d=-u*u+h*(h+2*o)+l;return i&&i.copy(this.origin).addScaledVector(this.direction,u),n&&n.copy(us).addScaledVector(hs,h),d}intersectSphere(e,t){if(e.radius<0)return null;cs.subVectors(e.center,this.origin);const i=cs.dot(this.direction),n=cs.dot(cs)-i*i,r=e.radius*e.radius;if(n>r)return null;const s=Math.sqrt(r-n),a=i-s,o=i+s;return o<0?null:a<0?this.at(o,t):this.at(a,t)}intersectsSphere(e){return!(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,n,r,s,a,o;const l=1/this.direction.x,c=1/this.direction.y,u=1/this.direction.z,h=this.origin;return l>=0?(i=(e.min.x-h.x)*l,n=(e.max.x-h.x)*l):(i=(e.max.x-h.x)*l,n=(e.min.x-h.x)*l),c>=0?(r=(e.min.y-h.y)*c,s=(e.max.y-h.y)*c):(r=(e.max.y-h.y)*c,s=(e.min.y-h.y)*c),i>s||r>n?null:((r>i||isNaN(i))&&(i=r),(s<n||isNaN(n))&&(n=s),u>=0?(a=(e.min.z-h.z)*u,o=(e.max.z-h.z)*u):(a=(e.max.z-h.z)*u,o=(e.min.z-h.z)*u),i>o||a>n?null:((a>i||i!=i)&&(i=a),(o<n||n!=n)&&(n=o),n<0?null:this.at(i>=0?i:n,t)))}intersectsBox(e){return null!==this.intersectBox(e,cs)}intersectTriangle(e,t,i,n,r){const s=this.origin,a=this.direction,o=a.x,l=a.y,c=a.z,u=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(c);let S,T,M,E,w,A,R,C,N,P,L,D;if(b>=y&&b>=x?(M=o,A=u,N=p,D=g,o>=0?(S=l,T=c,E=h,w=d,R=f,C=m,P=_,L=v):(S=c,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=c,T=o,E=d,w=u,R=m,C=p,P=v,L=g):(S=o,T=c,E=u,w=d,R=p,C=m,P=g,L=v)):(M=c,A=d,N=m,D=v,c>=0?(S=o,T=l,E=u,w=h,R=p,C=f,P=g,L=_):(S=l,T=o,E=h,w=u,R=f,C=p,P=_,L=g)),0===M)return null;const I=S/M,F=T/M,U=E-I*A,O=w-F*A,B=R-I*N,k=C-F*N,z=P-I*D,G=L-F*D,V=z*k-G*B,H=U*G-O*z,W=B*O-k*U;if(n){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,r)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return(new this.constructor).copy(this)}}class fs extends os{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Kn(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 En,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 mn,gs=new ps,_s=new Hr,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 Vn{constructor(e=new Zr,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,n=i.attributes.position,r=i.morphAttributes.position,s=i.morphTargetsRelative;t.fromBufferAttribute(n,e);const a=this.morphTargetInfluences;if(r&&a){Ts.set(0,0,0);for(let i=0,n=r.length;i<n;i++){const n=a[i],o=r[i];0!==n&&(Ss.fromBufferAttribute(o,e),s?Ts.addScaledVector(Ss,n):Ts.addScaledVector(Ss.sub(t),n))}t.add(Ts)}return t}intersectsFrustum(e){return e.intersectsObject(this)}raycast(e,t){const i=this.geometry,n=this.material,r=this.matrixWorld;if(void 0!==n){if(null===i.boundingSphere&&i.computeBoundingSphere(),_s.copy(i.boundingSphere),_s.applyMatrix4(r),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(r).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 n;const r=this.geometry,s=this.material,a=r.index,o=r.attributes.position,l=r.attributes.uv,c=r.attributes.uv1,u=r.attributes.normal,h=r.groups,d=r.drawRange;if(null!==a)if(Array.isArray(s))for(let r=0,o=h.length;r<o;r++){const o=h[r],p=s[o.materialIndex];for(let r=Math.max(o.start,d.start),s=Math.min(a.count,Math.min(o.start+o.count,d.start+d.count));r<s;r+=3){n=As(this,p,e,i,l,c,u,a.getX(r),a.getX(r+1),a.getX(r+2)),n&&(n.faceIndex=Math.floor(r/3),n.face.materialIndex=o.materialIndex,t.push(n))}}else{for(let r=Math.max(0,d.start),o=Math.min(a.count,d.start+d.count);r<o;r+=3){n=As(this,s,e,i,l,c,u,a.getX(r),a.getX(r+1),a.getX(r+2)),n&&(n.faceIndex=Math.floor(r/3),t.push(n))}}else if(void 0!==o)if(Array.isArray(s))for(let r=0,a=h.length;r<a;r++){const a=h[r],p=s[a.materialIndex];for(let r=Math.max(a.start,d.start),s=Math.min(o.count,Math.min(a.start+a.count,d.start+d.count));r<s;r+=3){n=As(this,p,e,i,l,c,u,r,r+1,r+2),n&&(n.faceIndex=Math.floor(r/3),n.face.materialIndex=a.materialIndex,t.push(n))}}else{for(let r=Math.max(0,d.start),a=Math.min(o.count,d.start+d.count);r<a;r+=3){n=As(this,s,e,i,l,c,u,r,r+1,r+2),n&&(n.faceIndex=Math.floor(r/3),t.push(n))}}}}function As(e,t,i,n,r,s,a,o,l,c){e.getVertexPosition(o,bs),e.getVertexPosition(l,ys),e.getVertexPosition(c,xs);const u=function(e,t,i,n,r,s,a,o){let l;if(l=1===t.side?n.intersectTriangle(a,s,r,!0,o):n.intersectTriangle(r,s,a,0===t.side,o),null===l)return null;Es.copy(o),Es.applyMatrix4(e.matrixWorld);const c=i.ray.origin.distanceTo(Es);return c<i.near||c>i.far?null:{distance:c,point:Es.clone(),object:e}}(e,t,i,n,bs,ys,xs,Ms);if(u){const e=new Wi;dr.getBarycoord(Ms,bs,ys,xs,e),r&&(u.uv=dr.getInterpolatedAttribute(r,o,l,c,e,new Vi)),s&&(u.uv1=dr.getInterpolatedAttribute(s,o,l,c,e,new Vi)),a&&(u.normal=dr.getInterpolatedAttribute(a,o,l,c,e,new Wi),u.normal.dot(n.direction)>0&&u.normal.multiplyScalar(-1));const t={a:o,b:l,c:c,normal:new Wi,materialIndex:0};dr.getNormal(bs,ys,xs,t.normal),u.face=t,u.barycoord=e}return u}class Rs extends cn{constructor(e=null,t=1,i=1,n,r,s,a,o,l=1003,c=1003,u,h){super(null,s,a,o,l,c,n,r,u,h),this.isDataTexture=!0,this.image={data:e,width:t,height:i},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class Cs extends Fr{constructor(e,t,i,n=1){super(e,t,i),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=n}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}toJSON(){const e=super.toJSON();return e.meshPerAttribute=this.meshPerAttribute,e.isInstancedBufferAttribute=!0,e}}const Ns=new mn,Ps=new mn,Ls=[],Ds=new pr,Is=new mn,Fs=new ws,Us=new Hr;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,Is)}computeBoundingBox(){const e=this.geometry,t=this.count;null===this.boundingBox&&(this.boundingBox=new pr),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 Hr),null===e.boundingSphere&&e.computeBoundingSphere(),this.boundingSphere.makeEmpty();for(let i=0;i<t;i++)this.getMatrixAt(i,Ns),Us.copy(e.boundingSphere).applyMatrix4(Ns),this.boundingSphere.union(Us)}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,n=this.morphTexture.source.data.data,r=e*(i.length+1)+1;for(let e=0;e<i.length;e++)i[e]=n[r+e]}raycast(e,t){const i=this.matrixWorld,n=this.count;if(Fs.geometry=this.geometry,Fs.material=this.material,void 0!==Fs.material&&(null===this.boundingSphere&&this.computeBoundingSphere(),Us.copy(this.boundingSphere),Us.applyMatrix4(i),!1!==e.ray.intersectsSphere(Us)))for(let r=0;r<n;r++){this.getMatrixAt(r,Ns),Ps.multiplyMatrices(i,Ns),Fs.matrixWorld=Ps,Fs.raycast(e,Ls);for(let e=0,i=Ls.length;e<i;e++){const i=Ls[e];i.instanceId=r,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,n=i.length+1;null===this.morphTexture&&(this.morphTexture=new Rs(new Float32Array(n*this.count),n,this.count,rt,$e));const r=this.morphTexture.source.data.data;let s=0;for(let e=0;e<i.length;e++)s+=i[e];const a=this.geometry.morphTargetsRelative?1:1-s,o=n*e;return r[o]=a,r.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 Hr,ks=new Vi(.5,.5),zs=new Wi;class Gs{constructor(e=new ss,t=new ss,i=new ss,n=new ss,r=new ss,s=new ss){this.planes=[e,t,i,n,r,s]}set(e,t,i,n,r,s){const a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(i),a[3].copy(n),a[4].copy(r),a[5].copy(s),this}copy(e){const t=this.planes;for(let i=0;i<6;i++)t[i].copy(e.planes[i]);return this}setFromProjectionMatrix(e,t=2e3,i=!1){const n=this.planes,r=e.elements,s=r[0],a=r[1],o=r[2],l=r[3],c=r[4],u=r[5],h=r[6],d=r[7],p=r[8],f=r[9],m=r[10],g=r[11],_=r[12],v=r[13],b=r[14],y=r[15];if(n[0].setComponents(l-s,d-c,g-p,y-_).normalize(),n[1].setComponents(l+s,d+c,g+p,y+_).normalize(),n[2].setComponents(l+a,d+u,g+f,y+v).normalize(),n[3].setComponents(l-a,d-u,g-f,y-v).normalize(),i)n[4].setComponents(o,h,m,b).normalize(),n[5].setComponents(l-o,d-h,g-m,y-b).normalize();else if(n[4].setComponents(l-o,d-h,g-m,y-b).normalize(),t===ci)n[5].setComponents(l+o,d+h,g+m,y+b).normalize();else{if(t!==ui)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);n[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,n=-e.radius;for(let e=0;e<6;e++){if(t[e].distanceToPoint(i)<n)return!1}return!0}intersectsBox(e){const t=this.planes;for(let i=0;i<6;i++){const n=t[i];if(zs.x=n.normal.x>0?e.max.x:e.min.x,zs.y=n.normal.y>0?e.max.y:e.min.y,zs.z=n.normal.z>0?e.max.z:e.min.z,n.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 mn;class Hs{constructor(){this.coordinateSystem=ci,this._frustums=[],this._count=0}setFromArrayCamera(e){const t=e.cameras,i=this._frustums;for(let e=0;e<t.length;e++){const n=t[e];Vs.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),void 0===i[e]&&(i[e]=new Gs),i[e].setFromProjectionMatrix(Vs,n.coordinateSystem,n.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 n=0;n<e._count;n++)void 0===t[n]&&(t[n]=new Gs),t[n].copy(i[n]);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 Kn(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}}const js=new Wi,$s=new Wi,Xs=new mn,qs=new ps,Ys=new Hr,Ks=new Wi,Zs=new Wi;class Qs extends Vn{constructor(e=new Zr,t=new Ws){super(),this.isLine=!0,this.type="Line",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),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}computeLineDistances(){const e=this.geometry;if(null===e.index){const t=e.attributes.position,i=[0];for(let e=1,n=t.count;e<n;e++)js.fromBufferAttribute(t,e-1),$s.fromBufferAttribute(t,e),i[e]=i[e-1],i[e]+=js.distanceTo($s);e.setAttribute("lineDistance",new kr(i,1))}else Ti("Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}intersectsFrustum(e){return e.intersectsObject(this)}raycast(e,t){const i=this.geometry,n=this.matrixWorld,r=e.params.Line.threshold,s=i.drawRange;if(null===i.boundingSphere&&i.computeBoundingSphere(),Ys.copy(i.boundingSphere),Ys.applyMatrix4(n),Ys.radius+=r,!1===e.ray.intersectsSphere(Ys))return;Xs.copy(n).invert(),qs.copy(e.ray).applyMatrix4(Xs);const a=r/((this.scale.x+this.scale.y+this.scale.z)/3),o=a*a,l=this.isLineSegments?2:1,c=i.index,u=i.attributes.position;if(null!==c){const i=Math.max(0,s.start),n=Math.min(c.count,s.start+s.count);for(let r=i,s=n-1;r<s;r+=l){const i=c.getX(r),n=c.getX(r+1),s=Js(this,e,qs,o,i,n,r);s&&t.push(s)}if(this.isLineLoop){const r=c.getX(n-1),s=c.getX(i),a=Js(this,e,qs,o,r,s,n-1);a&&t.push(a)}}else{const i=Math.max(0,s.start),n=Math.min(u.count,s.start+s.count);for(let r=i,s=n-1;r<s;r+=l){const i=Js(this,e,qs,o,r,r+1,r);i&&t.push(i)}if(this.isLineLoop){const r=Js(this,e,qs,o,n-1,i,n-1);r&&t.push(r)}}}updateMorphTargets(){const e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){const i=e[t[0]];if(void 0!==i){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=i.length;e<t;e++){const t=i[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}}function Js(e,t,i,n,r,s,a){const o=e.geometry.attributes.position;js.fromBufferAttribute(o,r),$s.fromBufferAttribute(o,s);if(i.distanceSqToSegment(js,$s,Ks,Zs)>n)return;Ks.applyMatrix4(e.matrixWorld);const l=t.ray.origin.distanceTo(Ks);return l<t.near||l>t.far?void 0:{distance:l,point:Zs.clone().applyMatrix4(e.matrixWorld),index:a,face:null,faceIndex:null,barycoord:null,object:e}}const ea=new Wi,ta=new Wi;class ia extends Qs{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const e=this.geometry;if(null===e.index){const t=e.attributes.position,i=[];for(let e=0,n=t.count;e<n;e+=2)ea.fromBufferAttribute(t,e),ta.fromBufferAttribute(t,e+1),i[e]=0===e?0:i[e-1],i[e+1]=i[e]+ea.distanceTo(ta);e.setAttribute("lineDistance",new kr(i,1))}else Ti("LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}}class na extends os{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new Kn(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 ra extends cn{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=Ie,this.minFilter=Ie,this.generateMipmaps=!1,this.needsUpdate=!0}copy(e){return super.copy(e),this.source=new sn(Object.assign({},e.image)),this}}class sa extends cn{constructor(e=[],t=301,i,n,r,s,a,o,l,c){super(e,t,i,n,r,s,a,o,l,c),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class aa extends cn{constructor(e,t,i,n,r,s,a,o,l){super(e,t,i,n,r,s,a,o,l),this.isCanvasTexture=!0,this.needsUpdate=!0}}class oa extends cn{constructor(e,t,i=1014,n,r,s,a=1003,o=1003,l,c=1026,u=1){if(c!==it&&c!==nt)throw new Error("THREE.DepthTexture: format must be either THREE.DepthFormat or THREE.DepthStencilFormat");super({width:e,height:t,depth:u},n,r,s,a,o,c,i,l),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new sn(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return t.compareFunction=this.compareFunction,t}}class la extends oa{constructor(e,t=1014,i=301,n,r,s=1003,a=1003,o,l=1026){const c={width:e,height:e,depth:1},u=[c,c,c,c,c,c];super(e,e,t,i,n,r,s,a,o,l),this.image=u,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}}class ca extends cn{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}class ua extends Zr{constructor(e=1,t=1,i=1,n=1,r=1,s=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:i,widthSegments:n,heightSegments:r,depthSegments:s};const a=this;n=Math.floor(n),r=Math.floor(r),s=Math.floor(s);const o=[],l=[],c=[],u=[];let h=0,d=0;function p(e,t,i,n,r,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*n,A[t]=a*r,A[i]=S,l.push(A.x,A.y,A.z),A[e]=0,A[t]=0,A[i]=f>0?1:-1,c.push(A.x,A.y,A.z),u.push(o/m),u.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,n=h+t+T*(e+1),r=h+(t+1)+T*(e+1),s=h+(t+1)+T*e;o.push(i,n,s),o.push(n,r,s),w+=6}a.addGroup(d,w,_),d+=w,h+=E}p("z","y","x",-1,-1,i,t,e,s,r,0),p("z","y","x",1,-1,i,t,-e,s,r,1),p("x","z","y",1,1,e,i,t,n,s,2),p("x","z","y",1,-1,e,i,-t,n,s,3),p("x","y","z",1,-1,e,t,i,n,r,4),p("x","y","z",-1,-1,e,t,-i,n,r,5),this.setIndex(o),this.setAttribute("position",new kr(l,3)),this.setAttribute("normal",new kr(c,3)),this.setAttribute("uv",new kr(u,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new ua(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}class ha extends Zr{constructor(e=1,t=1,i=1,n=32,r=1,s=!1,a=0,o=2*Math.PI){super(),this.type="CylinderGeometry",this.parameters={radiusTop:e,radiusBottom:t,height:i,radialSegments:n,heightSegments:r,openEnded:s,thetaStart:a,thetaLength:o};const l=this;n=Math.floor(n),r=Math.floor(r);const c=[],u=[],h=[],d=[];let p=0;const f=[],m=i/2;let g=0;function _(i){const r=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<=n;e++)u.push(0,m*b,0),h.push(0,b,0),d.push(.5,.5),p++;const y=p;for(let e=0;e<=n;e++){const t=e/n*o+a,i=Math.cos(t),r=Math.sin(t);f.x=v*r,f.y=m*b,f.z=v*i,u.push(f.x,f.y,f.z),h.push(0,b,0),s.x=.5*i+.5,s.y=.5*r*b+.5,d.push(s.x,s.y),p++}for(let e=0;e<n;e++){const t=r+e,n=y+e;!0===i?c.push(n,n+1,t):c.push(n+1,n,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<=r;l++){const c=[],g=l/r,v=g*(t-e)+e;for(let e=0;e<=n;e++){const t=e/n,r=t*o+a,l=Math.sin(r),f=Math.cos(r);_.x=v*l,_.y=-g*i+m,_.z=v*f,u.push(_.x,_.y,_.z),s.set(l,b,f).normalize(),h.push(s.x,s.y,s.z),d.push(t,1-g),c.push(p++)}f.push(c)}for(let i=0;i<n;i++)for(let n=0;n<r;n++){const s=f[n][i],a=f[n+1][i],o=f[n+1][i+1],l=f[n][i+1];(e>0||0!==n)&&(c.push(s,a,l),v+=3),(t>0||n!==r-1)&&(c.push(a,o,l),v+=3)}l.addGroup(g,v,0),g+=v}(),!1===s&&(e>0&&_(!0),t>0&&_(!1)),this.setIndex(c),this.setAttribute("position",new kr(u,3)),this.setAttribute("normal",new kr(h,3)),this.setAttribute("uv",new kr(d,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new ha(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class da{constructor(){this.type="Curve",this.arcLengthDivisions=200,this.needsUpdate=!1,this.cacheArcLengths=null}getPoint(){Ti("Curve: .getPoint() not implemented.")}getPointAt(e,t){const i=this.getUtoTmapping(e);return this.getPoint(i,t)}getPoints(e=5){const t=[];for(let i=0;i<=e;i++)t.push(this.getPoint(i/e));return t}getSpacedPoints(e=5){const t=[];for(let i=0;i<=e;i++)t.push(this.getPointAt(i/e));return t}getLength(){const e=this.getLengths();return e[e.length-1]}getLengths(e=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const t=[];let i,n=this.getPoint(0),r=0;t.push(0);for(let s=1;s<=e;s++)i=this.getPoint(s/e),r+=i.distanceTo(n),t.push(r),n=i;return this.cacheArcLengths=t,t}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(e,t=null){const i=this.getLengths();let n=0;const r=i.length;let s;s=t||e*i[r-1];let a,o=0,l=r-1;for(;o<=l;)if(n=Math.floor(o+(l-o)/2),a=i[n]-s,a<0)o=n+1;else{if(!(a>0)){l=n;break}l=n-1}if(n=l,i[n]===s)return n/(r-1);const c=i[n];return(n+(s-c)/(i[n+1]-c))/(r-1)}getTangent(e,t){const i=1e-4;let n=e-i,r=e+i;n<0&&(n=0),r>1&&(r=1);const s=this.getPoint(n),a=this.getPoint(r),o=t||(s.isVector2?new Vi:new Wi);return o.copy(a).sub(s).normalize(),o}getTangentAt(e,t){const i=this.getUtoTmapping(e);return this.getTangent(i,t)}computeFrenetFrames(e,t=!1){const i=new Wi,n=[],r=[],s=[],a=new Wi,o=new mn;for(let t=0;t<=e;t++){const i=t/e;n[t]=this.getTangentAt(i,new Wi)}r[0]=new Wi,s[0]=new Wi;let l=Number.MAX_VALUE;const c=Math.abs(n[0].x),u=Math.abs(n[0].y),h=Math.abs(n[0].z);c<=l&&(l=c,i.set(1,0,0)),u<=l&&(l=u,i.set(0,1,0)),h<=l&&i.set(0,0,1),a.crossVectors(n[0],i).normalize(),r[0].crossVectors(n[0],a),s[0].crossVectors(n[0],r[0]);for(let t=1;t<=e;t++){if(r[t]=r[t-1].clone(),s[t]=s[t-1].clone(),a.crossVectors(n[t-1],n[t]),a.length()>Number.EPSILON){a.normalize();const e=Math.acos(Ii(n[t-1].dot(n[t]),-1,1));r[t].applyMatrix4(o.makeRotationAxis(a,e))}s[t].crossVectors(n[t],r[t])}if(!0===t){let t=Math.acos(Ii(r[0].dot(r[e]),-1,1));t/=e,n[0].dot(a.crossVectors(r[0],r[e]))>0&&(t=-t);for(let i=1;i<=e;i++)r[i].applyMatrix4(o.makeRotationAxis(n[i],t*i)),s[i].crossVectors(n[i],r[i])}return{tangents:n,normals:r,binormals:s}}clone(){return(new this.constructor).copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this.cacheArcLengths=null,this}toJSON(){const e={metadata:{version:4.7,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this.cacheArcLengths=null,this}}class pa extends da{constructor(e=0,t=0,i=1,n=1,r=0,s=2*Math.PI,a=!1,o=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=i,this.yRadius=n,this.aStartAngle=r,this.aEndAngle=s,this.aClockwise=a,this.aRotation=o}getPoint(e,t=new Vi){const i=t,n=2*Math.PI;let r=this.aEndAngle-this.aStartAngle;const s=Math.abs(r)<Number.EPSILON;for(;r<0;)r+=n;for(;r>n;)r-=n;r<Number.EPSILON&&(r=s?0:n),!0!==this.aClockwise||s||(r===n?r=-n:r-=n);const a=this.aStartAngle+e*r;let o=this.aX+this.xRadius*Math.cos(a),l=this.aY+this.yRadius*Math.sin(a);if(0!==this.aRotation){const e=Math.cos(this.aRotation),t=Math.sin(this.aRotation),i=o-this.aX,n=l-this.aY;o=i*e-n*t+this.aX,l=i*t+n*e+this.aY}return i.set(o,l)}copy(e){return super.copy(e),this.aX=e.aX,this.aY=e.aY,this.xRadius=e.xRadius,this.yRadius=e.yRadius,this.aStartAngle=e.aStartAngle,this.aEndAngle=e.aEndAngle,this.aClockwise=e.aClockwise,this.aRotation=e.aRotation,this}toJSON(){const e=super.toJSON();return e.aX=this.aX,e.aY=this.aY,e.xRadius=this.xRadius,e.yRadius=this.yRadius,e.aStartAngle=this.aStartAngle,e.aEndAngle=this.aEndAngle,e.aClockwise=this.aClockwise,e.aRotation=this.aRotation,e}fromJSON(e){return super.fromJSON(e),this.aX=e.aX,this.aY=e.aY,this.xRadius=e.xRadius,this.yRadius=e.yRadius,this.aStartAngle=e.aStartAngle,this.aEndAngle=e.aEndAngle,this.aClockwise=e.aClockwise,this.aRotation=e.aRotation,this}}class fa extends Zr{constructor(e=1,t=1,i=1,n=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:i,heightSegments:n};const r=e/2,s=t/2,a=Math.floor(i),o=Math.floor(n),l=a+1,c=o+1,u=e/a,h=t/o,d=[],p=[],f=[],m=[];for(let e=0;e<c;e++){const t=e*h-s;for(let i=0;i<l;i++){const n=i*u-r;p.push(n,-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,n=t+l*(e+1),r=t+1+l*(e+1),s=t+1+l*e;d.push(i,n,s),d.push(n,r,s)}this.setIndex(d),this.setAttribute("position",new kr(p,3)),this.setAttribute("normal",new kr(f,3)),this.setAttribute("uv",new kr(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new fa(e.width,e.height,e.widthSegments,e.heightSegments)}}class ma extends Zr{constructor(e=1,t=32,i=16,n=0,r=2*Math.PI,s=0,a=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:e,widthSegments:t,heightSegments:i,phiStart:n,phiLength:r,thetaStart:s,thetaLength:a},t=Math.max(3,Math.floor(t)),i=Math.max(2,Math.floor(i));const o=Math.min(s+a,Math.PI);let l=0;const c=[],u=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=n+i*r;u.x=-y*Math.cos(s),u.y=b,u.z=y*Math.sin(s),p.push(u.x,u.y,u.z),h.copy(u).normalize(),f.push(h.x,h.y,h.z),m.push(i+x,1-_),g.push(l++)}c.push(g)}for(let e=0;e<i;e++)for(let n=0;n<t;n++){const t=c[e][n+1],r=c[e][n],a=c[e+1][n],l=c[e+1][n+1];(0!==e||s>0)&&d.push(t,r,l),(e!==i-1||o<Math.PI)&&d.push(r,a,l)}this.setIndex(d),this.setAttribute("position",new kr(p,3)),this.setAttribute("normal",new kr(f,3)),this.setAttribute("uv",new kr(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new ma(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}class ga extends os{constructor(e){super(),this.isShadowMaterial=!0,this.type="ShadowMaterial",this.color=new Kn(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 _a(e){const t={};for(const i in e){t[i]={};for(const n in e[i]){const r=e[i][n];if(ba(r))r.isRenderTargetTexture?(Ti("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),t[i][n]=null):t[i][n]=r.clone();else if(Array.isArray(r))if(ba(r[0])){const e=[];for(let t=0,i=r.length;t<i;t++)e[t]=r[t].clone();t[i][n]=e}else t[i][n]=r.slice();else t[i][n]=r}}return t}function va(e){const t={};for(let i=0;i<e.length;i++){const n=_a(e[i]);for(const e in n)t[e]=n[e]}return t}function ba(e){return e&&(e.isColor||e.isMatrix3||e.isMatrix4||e.isVector2||e.isVector3||e.isVector4||e.isTexture||e.isQuaternion)}function ya(e){const t=e.getRenderTarget();return null===t?e.outputColorSpace:!0===t.isXRRenderTarget?t.texture.colorSpace:Qi.workingColorSpace}const xa={clone:_a,merge:va};class Sa 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=_a(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 n=this.uniforms[i].value;n&&n.isTexture?t.uniforms[i]={type:"t",value:n.toJSON(e).uuid}:n&&n.isColor?t.uniforms[i]={type:"c",value:n.getHex()}:n&&n.isVector2?t.uniforms[i]={type:"v2",value:n.toArray()}:n&&n.isVector3?t.uniforms[i]={type:"v3",value:n.toArray()}:n&&n.isVector4?t.uniforms[i]={type:"v4",value:n.toArray()}:n&&n.isMatrix3?t.uniforms[i]={type:"m3",value:n.toArray()}:n&&n.isMatrix4?t.uniforms[i]={type:"m4",value:n.toArray()}:t.uniforms[i]={value:n}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const i={};for(const e in this.extensions)!0===this.extensions[e]&&(i[e]=!0);return Object.keys(i).length>0&&(t.extensions=i),t}fromJSON(e,t){if(super.fromJSON(e,t),void 0!==e.uniforms)for(const i in e.uniforms){const n=e.uniforms[i];switch(this.uniforms[i]={},n.type){case"t":this.uniforms[i].value=t[n.value]||null;break;case"c":this.uniforms[i].value=(new Kn).setHex(n.value);break;case"v2":this.uniforms[i].value=(new Vi).fromArray(n.value);break;case"v3":this.uniforms[i].value=(new Wi).fromArray(n.value);break;case"v4":this.uniforms[i].value=(new un).fromArray(n.value);break;case"m3":this.uniforms[i].value=(new Xi).fromArray(n.value);break;case"m4":this.uniforms[i].value=(new mn).fromArray(n.value);break;default:this.uniforms[i].value=n.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 Ta extends Sa{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class Ma extends os{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new Kn(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 Kn(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 En,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 Ea extends Ma{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 Ii(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 Kn(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 Kn(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new Kn(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 wa extends os{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new Kn(16777215),this.specular=new Kn(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Kn(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 En,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 Aa extends os{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new Kn(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Kn(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 Ra 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 Ca extends os{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new Kn(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Kn(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 En,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 Na 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 Pa 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 La extends os{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new Kn(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 Da 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 Ia={enabled:!1,files:{},add:function(e,t){!1!==this.enabled&&(Fa(e)||(this.files[e]=t))},get:function(e){if(!1!==this.enabled&&!Fa(e))return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}};function Fa(e){try{const t=e.slice(e.indexOf(":")+1);return"blob:"===new URL(t).protocol}catch(e){return!1}}class Ua{constructor(e,t,i){const n=this;let r,s=!1,a=0,o=0;const l=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=i,this._abortController=null,this.itemStart=function(e){o++,!1===s&&void 0!==n.onStart&&n.onStart(e,a,o),s=!0},this.itemEnd=function(e){a++,void 0!==n.onProgress&&n.onProgress(e,a,o),a===o&&(s=!1,void 0!==n.onLoad&&n.onLoad())},this.itemError=function(e){void 0!==n.onError&&n.onError(e)},this.resolveURL=function(e){return e=e.normalize("NFC"),r?r(e):e},this.setURLModifier=function(e){return r=e,this},this.addHandler=function(e,t){return l.push(e,t),this},this.removeHandler=function(e){const t=l.indexOf(e);return-1!==t&&l.splice(t,2),this},this.getHandler=function(e){for(let t=0,i=l.length;t<i;t+=2){const i=l[t],n=l[t+1];if(i.global&&(i.lastIndex=0),i.test(e))return n}return null},this.abort=function(){return this.abortController.abort(),this._abortController=null,this}}get abortController(){return this._abortController||(this._abortController=new AbortController),this._abortController}}const Oa=new Ua;class Ba{constructor(e){this.manager=void 0!==e?e:Oa,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(n,r){i.load(e,n,t,r)})}parse(){}setCrossOrigin(e){return this.crossOrigin=e,this}setWithCredentials(e){return this.withCredentials=e,this}setPath(e){return this.path=e,this}setResourcePath(e){return this.resourcePath=e,this}setRequestHeader(e){return this.requestHeader=e,this}setPriority(e){return this.priority=e,this}setCache(e){return this.cache=e,this}abort(){return this}}Ba.DEFAULT_MATERIAL_NAME="__DEFAULT";const ka=new WeakMap;class za extends Ba{constructor(e){super(e)}load(e,t,i,n){void 0!==this.path&&(e=this.path+e),e=this.manager.resolveURL(e);const r=this,s=Ia.get(`image:${e}`);if(void 0!==s){if(!0===s.complete)r.manager.itemStart(e),setTimeout(function(){t&&t(s),r.manager.itemEnd(e)},0);else{let e=ka.get(s);void 0===e&&(e=[],ka.set(s,e)),e.push({onLoad:t,onError:n})}return s}const a=vi("img");function o(){c(),t&&t(this);const i=ka.get(this)||[];for(let e=0;e<i.length;e++){const t=i[e];t.onLoad&&t.onLoad(this)}ka.delete(this),r.manager.itemEnd(e)}function l(t){c(),n&&n(t),Ia.remove(`image:${e}`);const i=ka.get(this)||[];for(let e=0;e<i.length;e++){const n=i[e];n.onError&&n.onError(t)}ka.delete(this),r.manager.itemError(e),r.manager.itemEnd(e)}function c(){a.removeEventListener("load",o,!1),a.removeEventListener("error",l,!1)}return a.addEventListener("load",o,!1),a.addEventListener("error",l,!1),"data:"!==e.slice(0,5)&&void 0!==this.crossOrigin&&(a.crossOrigin=this.crossOrigin),Ia.add(`image:${e}`,a),r.manager.itemStart(e),a.fetchPriority=this.priority,a.src=e,a}}class Ga extends Vn{static registerNode(e){this.prototype._lightNode=e}constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new Kn(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 Va extends Ga{constructor(e,t,i){super(e,i),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(Vn.DEFAULT_UP),this.updateMatrix(),this.groundColor=new Kn(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 Ha=new mn,Wa=new Wi,ja=new Wi;class $a{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 mn,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new Gs,this._frameExtents=new Vi(1,1),this._viewportCount=1,this._viewports=[new un(0,0,1,1)]}getViewportCount(){return this._viewportCount}getCamera(){return this.camera}getFrustum(){return this._frustum}updateMatrices(e){const t=this.camera;Wa.setFromMatrixPosition(e.matrixWorld),t.position.copy(Wa),ja.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(ja),t.updateMatrixWorld(),this._updateMatrix(t,this.matrix,this._frustum)}_updateMatrix(e,t,i,n){Ha.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),i.setFromProjectionMatrix(Ha,e.coordinateSystem,e.reversedDepth);const r=this._frameExtents,s=n?n.z/r.x:1,a=n?n.w/r.y:1,o=n?n.x/r.x:0,l=n?n.y/r.y:0;e.coordinateSystem===ui||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(Ha)}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 Xa=new Wi,qa=new Hi,Ya=new Wi;class Ka extends Vn{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new mn,this.projectionMatrix=new mn,this.projectionMatrixInverse=new mn,this.coordinateSystem=ci,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(Xa,qa,Ya),1===Ya.x&&1===Ya.y&&1===Ya.z?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(Xa,qa,Ya.set(1,1,1)).invert()}updateWorldMatrix(e,t,i=!1){super.updateWorldMatrix(e,t,i),this.matrixWorld.decompose(Xa,qa,Ya),1===Ya.x&&1===Ya.y&&1===Ya.z?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(Xa,qa,Ya.set(1,1,1)).invert()}clone(){return(new this.constructor).copy(this)}}const Za=new Wi,Qa=new Vi,Ja=new Vi;class eo extends Ka{constructor(e=50,t=1,i=.1,n=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=i,this.far=n,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=null===e.view?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=2*Li*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(.5*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){Za.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Za.x,Za.y).multiplyScalar(-e/Za.z),Za.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),i.set(Za.x,Za.y).multiplyScalar(-e/Za.z)}getViewSize(e,t){return this.getViewBounds(e,Qa,Ja),t.subVectors(Ja,Qa)}setViewOffset(e,t,i,n,r,s){this.aspect=e/t,null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=i,this.view.offsetY=n,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(.5*Pi*this.fov)/this.zoom,i=2*t,n=this.aspect*i,r=-.5*n;const s=this.view;if(null!==this.view&&this.view.enabled){const e=s.fullWidth,a=s.fullHeight;r+=s.offsetX*n/e,t-=s.offsetY*i/a,n*=s.width/e,i*=s.height/a}const a=this.filmOffset;0!==a&&(r+=e*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+n,t,t-i,e,this.far,this.coordinateSystem,this.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 to extends $a{constructor(){super(new eo(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,n=this.mapSize.width/this.mapSize.height*this.aspect,r=e.distance||t.far;i===t.fov&&n===t.aspect&&r===t.far||(t.fov=i,t.aspect=n,t.far=r,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this.aspect=e.aspect,this}toJSON(){const e=super.toJSON();return e.focus=this.focus,e.aspect=this.aspect,e}}class io extends Ga{constructor(e,t,i=0,n=Math.PI/3,r=0,s=2){super(e,t),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(Vn.DEFAULT_UP),this.updateMatrix(),this.target=new Vn,this.distance=i,this.angle=n,this.penumbra=r,this.decay=s,this.map=null,this.shadow=new to}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 no extends $a{constructor(){super(new eo(90,1,.5,500)),this.isPointLightShadow=!0}}class ro extends Ga{constructor(e,t,i=0,n=2){super(e,t),this.isPointLight=!0,this.type="PointLight",this.distance=i,this.decay=n,this.shadow=new no}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 so extends Ka{constructor(e=-1,t=1,i=1,n=-1,r=.1,s=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=i,this.bottom=n,this.near=r,this.far=s,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=null===e.view?null:Object.assign({},e.view),this}setViewOffset(e,t,i,n,r,s){null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=i,this.view.offsetY=n,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),i=(this.right+this.left)/2,n=(this.top+this.bottom)/2;let r=i-e,s=i+e,a=n+t,o=n-t;if(null!==this.view&&this.view.enabled){const e=(this.right-this.left)/this.view.fullWidth/this.zoom,t=(this.top-this.bottom)/this.view.fullHeight/this.zoom;r+=e*this.view.offsetX,s=r+e*this.view.width,a-=t*this.view.offsetY,o=a-t*this.view.height}this.projectionMatrix.makeOrthographic(r,s,a,o,this.near,this.far,this.coordinateSystem,this.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 ao extends $a{constructor(){super(new so(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class oo extends Ga{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(Vn.DEFAULT_UP),this.updateMatrix(),this.target=new Vn,this.shadow=new ao}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 lo extends Ga{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}}class co extends Ga{constructor(e,t,i=10,n=10){super(e,t),this.isRectAreaLight=!0,this.type="RectAreaLight",this.width=i,this.height=n}get power(){return this.intensity*this.width*this.height*Math.PI}set power(e){this.intensity=e/(this.width*this.height*Math.PI)}copy(e){return super.copy(e),this.width=e.width,this.height=e.height,this}toJSON(e){const t=super.toJSON(e);return t.object.width=this.width,t.object.height=this.height,t}}class uo{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let e=0;e<9;e++)this.coefficients.push(new Wi)}set(e){for(let t=0;t<9;t++)this.coefficients[t].copy(e[t]);return this}zero(){for(let e=0;e<9;e++)this.coefficients[e].set(0,0,0);return this}getAt(e,t){const i=e.x,n=e.y,r=e.z,s=this.coefficients;return t.copy(s[0]).multiplyScalar(.282095),t.addScaledVector(s[1],.488603*n),t.addScaledVector(s[2],.488603*r),t.addScaledVector(s[3],.488603*i),t.addScaledVector(s[4],i*n*1.092548),t.addScaledVector(s[5],n*r*1.092548),t.addScaledVector(s[6],.315392*(3*r*r-1)),t.addScaledVector(s[7],i*r*1.092548),t.addScaledVector(s[8],.546274*(i*i-n*n)),t}getIrradianceAt(e,t){const i=e.x,n=e.y,r=e.z,s=this.coefficients;return t.copy(s[0]).multiplyScalar(.886227),t.addScaledVector(s[1],1.023328*n),t.addScaledVector(s[2],1.023328*r),t.addScaledVector(s[3],1.023328*i),t.addScaledVector(s[4],.858086*i*n),t.addScaledVector(s[5],.858086*n*r),t.addScaledVector(s[6],.743125*r*r-.247708),t.addScaledVector(s[7],.858086*i*r),t.addScaledVector(s[8],.429043*(i*i-n*n)),t}add(e){for(let t=0;t<9;t++)this.coefficients[t].add(e.coefficients[t]);return this}addScaledSH(e,t){for(let i=0;i<9;i++)this.coefficients[i].addScaledVector(e.coefficients[i],t);return this}scale(e){for(let t=0;t<9;t++)this.coefficients[t].multiplyScalar(e);return this}lerp(e,t){for(let i=0;i<9;i++)this.coefficients[i].lerp(e.coefficients[i],t);return this}equals(e){for(let t=0;t<9;t++)if(!this.coefficients[t].equals(e.coefficients[t]))return!1;return!0}copy(e){return this.set(e.coefficients)}clone(){return(new this.constructor).copy(this)}fromArray(e,t=0){const i=this.coefficients;for(let n=0;n<9;n++)i[n].fromArray(e,t+3*n);return this}toArray(e=[],t=0){const i=this.coefficients;for(let n=0;n<9;n++)i[n].toArray(e,t+3*n);return e}static getBasisAt(e,t){const i=e.x,n=e.y,r=e.z;t[0]=.282095,t[1]=.488603*n,t[2]=.488603*r,t[3]=.488603*i,t[4]=1.092548*i*n,t[5]=1.092548*n*r,t[6]=.315392*(3*r*r-1),t[7]=1.092548*i*r,t[8]=.546274*(i*i-n*n)}}class ho extends Ga{constructor(e=new uo,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 po=-90;class fo extends Vn{constructor(e,t,i){super(),this.type="CubeCamera",this.renderTarget=i,this.coordinateSystem=null,this.activeMipmapLevel=0;const n=new eo(po,1,e,t);n.layers=this.layers,this.add(n);const r=new eo(po,1,e,t);r.layers=this.layers,this.add(r);const s=new eo(po,1,e,t);s.layers=this.layers,this.add(s);const a=new eo(po,1,e,t);a.layers=this.layers,this.add(a);const o=new eo(po,1,e,t);o.layers=this.layers,this.add(o);const l=new eo(po,1,e,t);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[i,n,r,s,a,o]=t;for(const e of t)this.remove(e);if(e===ci)i.up.set(0,1,0),i.lookAt(1,0,0),n.up.set(0,1,0),n.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),s.up.set(0,0,1),s.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),o.up.set(0,1,0),o.lookAt(0,0,-1);else{if(e!==ui)throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);i.up.set(0,-1,0),i.lookAt(-1,0,0),n.up.set(0,-1,0),n.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),s.up.set(0,0,-1),s.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),o.up.set(0,-1,0),o.lookAt(0,0,-1)}for(const e of t)this.add(e),e.updateMatrixWorld()}update(e,t){null===this.parent&&this.updateMatrixWorld();const{renderTarget:i,activeMipmapLevel:n}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[r,s,a,o,l,c]=this.children,u=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,n),m&&!1===e.autoClear&&e.clearDepth(),e.render(t,r),e.setRenderTarget(i,1,n),m&&!1===e.autoClear&&e.clearDepth(),e.render(t,s),e.setRenderTarget(i,2,n),m&&!1===e.autoClear&&e.clearDepth(),e.render(t,a),e.setRenderTarget(i,3,n),m&&!1===e.autoClear&&e.clearDepth(),e.render(t,o),e.setRenderTarget(i,4,n),m&&!1===e.autoClear&&e.clearDepth(),e.render(t,l),i.texture.mipmapsAutoUpdate=f,e.setRenderTarget(i,5,n),m&&!1===e.autoClear&&e.clearDepth(),e.render(t,c),e.setRenderTarget(u,h,d),e.xr.enabled=p,i.texture.needsPMREMUpdate=!0}}class mo extends eo{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e,this.perCameraFrustumCulled=!1}}class go{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=_o.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 _o(){!1===this._document.hidden&&this.reset()}const vo=new mn;class bo{constructor(e,t,i=0,n=1/0){this.ray=new ps(e,t),this.near=i,this.far=n,this.camera=null,this.layers=new wn,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 vo.identity().extractRotation(e.matrixWorld),this.ray.origin.setFromMatrixPosition(e.matrixWorld),this.ray.direction.set(0,0,-1).applyMatrix4(vo),this}intersectObject(e,t=!0,i=[]){return xo(e,this,i,t),i.sort(yo),i}intersectObjects(e,t=!0,i=[]){for(let n=0,r=e.length;n<r;n++)xo(e[n],this,i,t);return i.sort(yo),i}}function yo(e,t){return e.distance-t.distance}function xo(e,t,i,n){let r=!0;if(e.layers.test(t.layers)){!1===e.raycast(t,i)&&(r=!1)}if(!0===r&&!0===n){const n=e.children;for(let e=0,r=n.length;e<r;e++)xo(n[e],t,i,!0)}}class So{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=Ii(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(Ii(t/this.radius,-1,1))),this}clone(){return(new this.constructor).copy(this)}}class To{static{this.prototype.isMatrix2=!0}constructor(e,t,i,n){this.elements=[1,0,0,1],void 0!==e&&this.set(e,t,i,n)}identity(){return this.set(1,0,0,1),this}fromArray(e,t=0){for(let i=0;i<4;i++)this.elements[i]=e[i+t];return this}set(e,t,i,n){const r=this.elements;return r[0]=e,r[2]=t,r[1]=i,r[3]=n,this}}class Mo extends ia{constructor(e=10,t=10,i=4473924,n=8947848){i=new Kn(i),n=new Kn(n);const r=t/2,s=e/t,a=e/2,o=[],l=[];for(let e=0,c=0,u=-a;e<=t;e++,u+=s){o.push(-a,0,u,a,0,u),o.push(u,0,-a,u,0,a);const t=e===r?i:n;t.toArray(l,c),c+=3,t.toArray(l,c),c+=3,t.toArray(l,c),c+=3,t.toArray(l,c),c+=3}const c=new Zr;c.setAttribute("position",new kr(o,3)),c.setAttribute("color",new kr(l,3));super(c,new Ws({vertexColors:!0,toneMapped:!1})),this.type="GridHelper"}dispose(){super.dispose(),this.geometry.dispose(),this.material.dispose()}}class Eo 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 wo(e,t,i,n){const r=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}.`)}(n);switch(i){case Je:return e*t;case rt:case st:return e*t/r.components*r.byteLength;case at:case ot:return e*t*2/r.components*r.byteLength;case et:return e*t*3/r.components*r.byteLength;case tt:case ct:return e*t*4/r.components*r.byteLength;case ut: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 It:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case Ft:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case Ut:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case 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 Ao(){let e=null,t=!1,i=null,n=null;function r(t,s){n=e.requestAnimationFrame(r),i(t,s)}return{start:function(){!0!==t&&null!==i&&null!==e&&(n=e.requestAnimationFrame(r),t=!0)},stop:function(){null!==e&&e.cancelAnimationFrame(n),t=!1},setAnimationLoop:function(e){i=e},setContext:function(t){e=t}}}function Ro(e){const t=new WeakMap;return{get:function(e){return e.isInterleavedBufferAttribute&&(e=e.data),t.get(e)},remove:function(i){i.isInterleavedBufferAttribute&&(i=i.data);const n=t.get(i);n&&(e.deleteBuffer(n.buffer),t.delete(i))},update:function(i,n){if(i.isInterleavedBufferAttribute&&(i=i.data),i.isGLBufferAttribute){const e=t.get(i);return void((!e||e.version<i.version)&&t.set(i,{buffer:i.buffer,type:i.type,bytesPerElement:i.elementSize,version:i.version}))}const r=t.get(i);if(void 0===r)t.set(i,function(t,i){const n=t.array,r=t.usage,s=n.byteLength,a=e.createBuffer();let o;if(e.bindBuffer(i,a),e.bufferData(i,n,r),t.onUploadCallback(),n instanceof Float32Array)o=e.FLOAT;else if("undefined"!=typeof Float16Array&&n instanceof Float16Array)o=e.HALF_FLOAT;else if(n instanceof Uint16Array)o=t.isFloat16BufferAttribute?e.HALF_FLOAT:e.UNSIGNED_SHORT;else if(n instanceof Int16Array)o=e.SHORT;else if(n instanceof Uint32Array)o=e.UNSIGNED_INT;else if(n instanceof Int32Array)o=e.INT;else if(n instanceof Int8Array)o=e.BYTE;else if(n instanceof Uint8Array)o=e.UNSIGNED_BYTE;else{if(!(n instanceof Uint8ClampedArray))throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+n);o=e.UNSIGNED_BYTE}return{buffer:a,type:o,bytesPerElement:n.BYTES_PER_ELEMENT,version:t.version,size:s}}(i,n));else if(r.version<i.version){if(r.size!==i.array.byteLength)throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.");!function(t,i,n){const r=i.array,s=i.updateRanges;if(e.bindBuffer(n,t),0===s.length)e.bufferSubData(n,0,r);else{s.sort((e,t)=>e.start-t.start);let t=0;for(let e=1;e<s.length;e++){const i=s[t],n=s[e];n.start<=i.start+i.count+1?i.count=Math.max(i.count,n.start+n.count-i.start):(++t,s[t]=n)}s.length=t+1;for(let t=0,i=s.length;t<i;t++){const i=s[t];e.bufferSubData(n,i.start*r.BYTES_PER_ELEMENT,r,i.start,i.count)}i.clearUpdateRanges()}i.onUploadCallback()}(r.buffer,i,n),r.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 Co={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}"},No={common:{diffuse:{value:new Kn(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 Kn(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 Kn(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 Kn(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}}},Po={basic:{uniforms:va([No.common,No.specularmap,No.envmap,No.aomap,No.lightmap,No.fog]),vertexShader:Co.meshbasic_vert,fragmentShader:Co.meshbasic_frag},lambert:{uniforms:va([No.common,No.specularmap,No.envmap,No.aomap,No.lightmap,No.emissivemap,No.bumpmap,No.normalmap,No.displacementmap,No.fog,No.lights,{emissive:{value:new Kn(0)},envMapIntensity:{value:1}}]),vertexShader:Co.meshlambert_vert,fragmentShader:Co.meshlambert_frag},phong:{uniforms:va([No.common,No.specularmap,No.envmap,No.aomap,No.lightmap,No.emissivemap,No.bumpmap,No.normalmap,No.displacementmap,No.fog,No.lights,{emissive:{value:new Kn(0)},specular:{value:new Kn(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:Co.meshphong_vert,fragmentShader:Co.meshphong_frag},standard:{uniforms:va([No.common,No.envmap,No.aomap,No.lightmap,No.emissivemap,No.bumpmap,No.normalmap,No.displacementmap,No.roughnessmap,No.metalnessmap,No.fog,No.lights,{emissive:{value:new Kn(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Co.meshphysical_vert,fragmentShader:Co.meshphysical_frag},toon:{uniforms:va([No.common,No.aomap,No.lightmap,No.emissivemap,No.bumpmap,No.normalmap,No.displacementmap,No.gradientmap,No.fog,No.lights,{emissive:{value:new Kn(0)}}]),vertexShader:Co.meshtoon_vert,fragmentShader:Co.meshtoon_frag},matcap:{uniforms:va([No.common,No.bumpmap,No.normalmap,No.displacementmap,No.fog,{matcap:{value:null}}]),vertexShader:Co.meshmatcap_vert,fragmentShader:Co.meshmatcap_frag},points:{uniforms:va([No.points,No.fog]),vertexShader:Co.points_vert,fragmentShader:Co.points_frag},dashed:{uniforms:va([No.common,No.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Co.linedashed_vert,fragmentShader:Co.linedashed_frag},depth:{uniforms:va([No.common,No.displacementmap]),vertexShader:Co.depth_vert,fragmentShader:Co.depth_frag},normal:{uniforms:va([No.common,No.bumpmap,No.normalmap,No.displacementmap,{opacity:{value:1}}]),vertexShader:Co.meshnormal_vert,fragmentShader:Co.meshnormal_frag},sprite:{uniforms:va([No.sprite,No.fog]),vertexShader:Co.sprite_vert,fragmentShader:Co.sprite_frag},background:{uniforms:{uvTransform:{value:new Xi},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Co.background_vert,fragmentShader:Co.background_frag},backgroundCube:{uniforms:{envMap:{value:null},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new Xi}},vertexShader:Co.backgroundCube_vert,fragmentShader:Co.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Co.cube_vert,fragmentShader:Co.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Co.equirect_vert,fragmentShader:Co.equirect_frag},distance:{uniforms:va([No.common,No.displacementmap,{referencePosition:{value:new Wi},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Co.distance_vert,fragmentShader:Co.distance_frag},shadow:{uniforms:va([No.lights,No.fog,{color:{value:new Kn(0)},opacity:{value:1}}]),vertexShader:Co.shadow_vert,fragmentShader:Co.shadow_frag}};Po.physical={uniforms:va([Po.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 Kn(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 Kn(0)},specularColor:{value:new Kn(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:Co.meshphysical_vert,fragmentShader:Co.meshphysical_frag};const Lo={r:0,b:0,g:0},Do=new mn,Io=new Xi;function Fo(e,t,i,n,r,s){const a=new Kn(0);let o,l,c=!0===r?0:1,u=null,h=0,d=null;function p(e){let i=!0===e.isScene?e.background:null;if(i&&i.isTexture){const n=e.backgroundBlurriness>0;i=t.get(i,n)}return i}function f(t,n){t.getRGB(Lo,ya(e)),i.buffers.color.setClear(Lo.r,Lo.g,Lo.b,n,s)}return{getClearColor:function(){return a},setClearColor:function(e,t=1){a.set(e),c=t,f(a,c)},getClearAlpha:function(){return c},setClearAlpha:function(e){c=e,f(a,c)},render:function(t){let n=!1;const r=p(t);null===r?f(a,c):r&&r.isColor&&(f(r,1),n=!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||n)&&(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 r=p(i);r&&r.isCubeTexture?(void 0===l&&(l=new ws(new ua(1,1,1),new Sa({name:"BackgroundCubeMaterial",uniforms:_a(Po.backgroundCube.uniforms),vertexShader:Po.backgroundCube.vertexShader,fragmentShader:Po.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}}),n.update(l)),l.material.uniforms.envMap.value=r,l.material.uniforms.backgroundBlurriness.value=i.backgroundBlurriness,l.material.uniforms.backgroundIntensity.value=i.backgroundIntensity,l.material.uniforms.backgroundRotation.value.setFromMatrix4(Do.makeRotationFromEuler(i.backgroundRotation)).transpose(),!1===r.isRenderTargetTexture&&l.material.uniforms.backgroundRotation.value.premultiply(Io),l.material.toneMapped=Qi.getTransfer(r.colorSpace)!==Kt,u===r&&h===r.version&&d===e.toneMapping||(l.material.needsUpdate=!0,u=r,h=r.version,d=e.toneMapping),l.layers.enableAll(),t.unshift(l,l.geometry,l.material,0,0,null)):r&&r.isTexture&&(void 0===o&&(o=new ws(new fa(2,2),new Sa({name:"BackgroundMaterial",uniforms:_a(Po.background.uniforms),vertexShader:Po.background.vertexShader,fragmentShader:Po.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}}),n.update(o)),o.material.uniforms.t2D.value=r,o.material.uniforms.backgroundIntensity.value=i.backgroundIntensity,o.material.toneMapped=Qi.getTransfer(r.colorSpace)!==Kt,!0===r.matrixAutoUpdate&&r.updateMatrix(),o.material.uniforms.uvTransform.value.copy(r.matrix),u===r&&h===r.version&&d===e.toneMapping||(o.material.needsUpdate=!0,u=r,h=r.version,d=e.toneMapping),o.layers.enableAll(),t.unshift(o,o.geometry,o.material,0,0,null))},dispose:function(){void 0!==l&&(l.geometry.dispose(),l.material.dispose(),l=void 0),void 0!==o&&(o.geometry.dispose(),o.material.dispose(),o=void 0)}}}function Uo(e,t){const i=e.getParameter(e.MAX_VERTEX_ATTRIBS),n={},r=c(null);let s=r,a=!1;function o(t){return e.bindVertexArray(t)}function l(t){return e.deleteVertexArray(t)}function c(e){const t=[],n=[],r=[];for(let e=0;e<i;e++)t[e]=0,n[e]=0,r[e]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:t,enabledAttributes:n,attributeDivisors:r,object:e,attributes:{},index:null}}function u(){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 n=s.newAttributes,r=s.enabledAttributes,a=s.attributeDivisors;n[t]=1,0===r[t]&&(e.enableVertexAttribArray(t),r[t]=1),a[t]!==i&&(e.vertexAttribDivisor(t,i),a[t]=i)}function p(){const t=s.newAttributes,i=s.enabledAttributes;for(let n=0,r=i.length;n<r;n++)i[n]!==t[n]&&(e.disableVertexAttribArray(n),i[n]=0)}function f(t,i,n,r,s,a,o){!0===o?e.vertexAttribIPointer(t,i,n,s,a):e.vertexAttribPointer(t,i,n,r,s,a)}function m(){g(),a=!0,s!==r&&(s=r,o(s.object))}function g(){r.geometry=null,r.program=null,r.wireframe=!1}return{setup:function(i,r,l,m,g){let _=!1;const v=function(t,i,r,s){const a=!0===s.wireframe;let o=n[i.id];void 0===o&&(o={},n[i.id]=o);const l=!0===t.isInstancedMesh?t.id:0;let u=o[l];void 0===u&&(u={},o[l]=u);let h=u[r.id];void 0===h&&(h={},u[r.id]=h);let d=h[a];void 0===d&&(d=c(e.createVertexArray()),h[a]=d);return d}(i,m,l,r);s!==v&&(s=v,o(s.object)),_=function(e,t,i,n){const r=s.attributes,a=t.attributes;let o=0;const l=i.getAttributes();for(const t in l){if(l[t].location>=0){const i=r[t];let n=a[t];if(void 0===n&&("instanceMatrix"===t&&e.instanceMatrix&&(n=e.instanceMatrix),"instanceColor"===t&&e.instanceColor&&(n=e.instanceColor)),void 0===i)return!0;if(i.attribute!==n)return!0;if(n&&i.data!==n.data)return!0;o++}}return s.attributesNum!==o||s.index!==n}(i,m,l,g),_&&function(e,t,i,n){const r={},a=t.attributes;let o=0;const l=i.getAttributes();for(const t in l){if(l[t].location>=0){let i=a[t];void 0===i&&("instanceMatrix"===t&&e.instanceMatrix&&(i=e.instanceMatrix),"instanceColor"===t&&e.instanceColor&&(i=e.instanceColor));const n={};n.attribute=i,i&&i.data&&(n.data=i.data),r[t]=n,o++}}s.attributes=r,s.attributesNum=o,s.index=n}(i,m,l,g),null!==g&&t.update(g,e.ELEMENT_ARRAY_BUFFER),(_||a)&&(a=!1,function(i,n,r,s){u();const a=s.attributes,o=r.getAttributes(),l=n.defaultAttributeValues;for(const n in o){const r=o[n];if(r.location>=0){let o=a[n];if(void 0===o&&("instanceMatrix"===n&&i.instanceMatrix&&(o=i.instanceMatrix),"instanceColor"===n&&i.instanceColor&&(o=i.instanceColor)),void 0!==o){const n=o.normalized,a=o.itemSize,l=t.get(o);if(void 0===l)continue;const c=l.buffer,u=l.type,p=l.bytesPerElement,m=u===e.INT||u===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<r.locationSize;e++)d(r.location+e,t.meshPerAttribute);!0!==i.isInstancedMesh&&void 0===s._maxInstanceCount&&(s._maxInstanceCount=t.meshPerAttribute*t.count)}else for(let e=0;e<r.locationSize;e++)h(r.location+e);e.bindBuffer(e.ARRAY_BUFFER,c);for(let e=0;e<r.locationSize;e++)f(r.location+e,a/r.locationSize,u,n,l*p,(g+a/r.locationSize*e)*p,m)}else{if(o.isInstancedBufferAttribute){for(let e=0;e<r.locationSize;e++)d(r.location+e,o.meshPerAttribute);!0!==i.isInstancedMesh&&void 0===s._maxInstanceCount&&(s._maxInstanceCount=o.meshPerAttribute*o.count)}else for(let e=0;e<r.locationSize;e++)h(r.location+e);e.bindBuffer(e.ARRAY_BUFFER,c);for(let e=0;e<r.locationSize;e++)f(r.location+e,a/r.locationSize,u,n,a*p,a/r.locationSize*e*p,m)}}else if(void 0!==l){const t=l[n];if(void 0!==t)switch(t.length){case 2:e.vertexAttrib2fv(r.location,t);break;case 3:e.vertexAttrib3fv(r.location,t);break;case 4:e.vertexAttrib4fv(r.location,t);break;default:e.vertexAttrib1fv(r.location,t)}}}}p()}(i,r,l,m),null!==g&&e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t.get(g).buffer))},reset:m,resetDefaultState:g,dispose:function(){m();for(const e in n){const t=n[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 n[e]}},releaseStatesOfGeometry:function(e){if(void 0===n[e.id])return;const t=n[e.id];for(const e in t){const i=t[e];for(const e in i){const t=i[e];for(const e in t)l(t[e].object),delete t[e];delete i[e]}}delete n[e.id]},releaseStatesOfObject:function(e){for(const t in n){const i=n[t],r=!0===e.isInstancedMesh?e.id:0,s=i[r];if(void 0!==s){for(const e in s){const t=s[e];for(const e in t)l(t[e].object),delete t[e];delete s[e]}delete i[r],0===Object.keys(i).length&&delete n[t]}}},releaseStatesOfProgram:function(e){for(const t in n){const i=n[t];for(const t in i){const n=i[t];if(void 0===n[e.id])continue;const r=n[e.id];for(const e in r)l(r[e].object),delete r[e];delete n[e.id]}}},initAttributes:u,enableAttribute:h,disableUnusedAttributes:p}}function Oo(e,t,i){let n;this.setMode=function(e){n=e},this.render=function(t,r){e.drawArrays(n,t,r),i.update(r,n,1)},this.renderInstances=function(t,r,s){0!==s&&(e.drawArraysInstanced(n,t,r,s),i.update(r,n,s))},this.renderMultiDraw=function(e,r,s){if(0===s)return;t.get("WEBGL_multi_draw").multiDrawArraysWEBGL(n,e,0,r,0,s);let a=0;for(let e=0;e<s;e++)a+=r[e];i.update(a,n,1)}}function Bo(e,t,i,n){let r;function s(t){if("highp"===t){if(e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return"highp";t="mediump"}return"mediump"===t&&e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let a=void 0!==i.precision?i.precision:"highp";const o=s(a);o!==a&&(Ti("WebGLRenderer:",a,"not supported, using",o,"instead."),a=o);const l=!0===i.reversedDepthBuffer&&t.has("EXT_clip_control"),c=!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!==r)return r;if(!0===t.has("EXT_texture_filter_anisotropic")){const i=t.get("EXT_texture_filter_anisotropic");r=e.getParameter(i.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else r=0;return r},getMaxPrecision:s,textureFormatReadable:function(t){return t===tt||n.convert(t)===e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)},textureTypeReadable:function(i){const r=i===Xe&&(t.has("EXT_color_buffer_half_float")||t.has("EXT_color_buffer_float"));return!(i!==ze&&i!==$e&&!r&&n.convert(i)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE))},precision:a,logarithmicDepthBuffer:c,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 ko(e){const t=this;let i=null,n=0,r=!1,s=!1;const a=new ss,o=new Xi,l={value:null,needsUpdate:!1};function c(e,i,n,r){const s=null!==e?e.length:0;let c=null;if(0!==s){if(c=l.value,!0!==r||null===c){const t=n+4*s,r=i.matrixWorldInverse;o.getNormalMatrix(r),(null===c||c.length<t)&&(c=new Float32Array(t));for(let t=0,i=n;t!==s;++t,i+=4)a.copy(e[t]).applyMatrix4(r,o),a.normal.toArray(c,i),c[i+3]=a.constant}l.value=c,l.needsUpdate=!0}return t.numPlanes=s,t.numIntersection=0,c}this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(e,t){const i=0!==e.length||t||0!==n||r;return r=t,n=e.length,i},this.beginShadows=function(){s=!0,c(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(e,t){i=c(e,t,0)},this.setState=function(a,o,u){const h=a.clippingPlanes,d=a.clipIntersection,p=a.clipShadows,f=e.get(a);if(!r||null===h||0===h.length||s&&!p)s?c(null):function(){l.value!==i&&(l.value=i,l.needsUpdate=n>0);t.numPlanes=n,t.numIntersection=0}();else{const e=s?0:n,t=4*e;let r=f.clippingState||null;l.value=r,r=c(h,o,t,u);for(let e=0;e!==t;++e)r[e]=i[e];f.clippingState=r,this.numIntersection=d?this.numPlanes:0,this.numPlanes+=e}}}Io.set(-1,0,0,0,1,0,0,0,1);class zo extends dn{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const i={width:e,height:e,depth:1},n=[i,i,i,i,i,i];this.texture=new sa(n),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"},n=new ua(5,5,5),r=new Sa({name:"CubemapFromEquirect",uniforms:_a(i.uniforms),vertexShader:i.vertexShader,fragmentShader:i.fragmentShader,side:1,blending:0});r.uniforms.tEquirect.value=t;const s=new ws(n,r),a=t.minFilter;t.minFilter===ke&&(t.minFilter=Oe);return new fo(1,10,this).update(e,s),t.minFilter=a,s.geometry.dispose(),s.material.dispose(),this}clear(e,t=!0,i=!0,n=!0){const r=e.getRenderTarget();for(let r=0;r<6;r++)e.setRenderTarget(this,r),e.clear(t,i,n);e.setRenderTarget(r)}}const Go=new Wi,Vo=new Kn;let Ho=class e{constructor(e){this._renderer=e,this._cubeSize=0,this._sourceTarget=null,this._cubeCamera=new fo(1,10,null),this._boxMesh=new ws(new ua(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,n=100,r={}){const{size:s=256,position:a=Go}=r,o=this._renderer;this._setSize(s);const l=this._allocateTarget(),c=this._getSourceTarget(!0);t>0&&(c.texture.mipmapsAutoUpdate=!1);const u=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(Vo));const m=new fo(i,n,c);return m.position.copy(a),m.update(o,e),o.autoClear=u,o.autoClearColor=h,o.autoClearDepth=d,o.autoClearStencil=p,e.background=f,t>0&&(c.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=Xo(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=$o(),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=Wo(e,!1,!1),i=Math.log2(e)-3;for(let n=0;n<=i;n++)t.texture.mipmaps.push({width:e>>n,height:e>>n});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=Wo(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 n=this._boxMesh,r=this._cubeCamera;n.material=i,r.renderTarget=e,r.activeMipmapLevel=t;const s=e.width>>t;e.viewport.set(0,0,s,s),r.update(this._renderer,n),e.viewport.set(0,0,e.width,e.height)}_textureToCubemap(e){let t;e.mapping===Ae||e.mapping===Re?(null===this._cubemapMaterial&&(this._cubemapMaterial=Xo()),t=this._cubemapMaterial,t.uniforms.flipEnvMap.value=!1===e.isRenderTargetTexture?-1:1):(null===this._equirectMaterial&&(this._equirectMaterial=$o()),t=this._equirectMaterial),t.uniforms.envMap.value=e,this._renderCube(this._getSourceTarget(),0,t)}_applyPMREM(t){null===this._ggxMaterial&&(this._ggxMaterial=jo("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=jo("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,n=t.texture.mipmaps.length-1,r=this._ggxMaterial.uniforms;r.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<=n;a++){const o=e.lodToRoughness(a,n);if(a>n-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;r.roughness.value=o,r.lodBias.value=e,this._renderCube(t,a,this._ggxMaterial)}}}_blur(e,t){null===this._blurMaterial&&(this._blurMaterial=jo("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,n=i.uniforms,r=this._sourceTarget;n.sigma.value=Math.min(t,Math.PI)/Math.SQRT2,n.envMap.value=r.texture,this._renderCube(e,0,i),n.envMap.value=e.texture,this._renderCube(r,0,i)}};function Wo(e,t,i){return new zo(e,{minFilter:ke,generateMipmaps:t,type:Xe,colorSpace:qt,depthBuffer:i})}function jo(e,t,i){return new Sa({name:e,uniforms:t,vertexShader:Co.cube_vert,fragmentShader:i,side:1,blending:0,depthTest:!1,depthWrite:!1})}function $o(){return jo("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 Xo(){return jo("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 qo(e){let t=new WeakMap,i=new WeakMap,n=null;function r(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 n=t.get(i);void 0!==n&&(t.delete(i),n.dispose())}function a(e){const t=e.target;t.removeEventListener("dispose",a);const n=i.get(t);void 0!==n&&(i.delete(t),n.dispose())}return{get:function(o,l=!1){return null==o?null:l?function(t){if(t&&t.isTexture&&!0!==t.isPMREMTexture){const r=t.mapping,s=r===Ce||r===Ne,o=r===Ae||r===Re;if(s||o){let r=i.get(t);const l=void 0!==r?r.texture.pmremVersion:0;if(t.isRenderTargetTexture&&t.pmremVersion!==l)return null===n&&(n=new Ho(e)),r=s?n.fromEquirectangular(t,r):n.fromCubemap(t,r),r.texture.pmremVersion=t.pmremVersion,i.set(t,r),r.texture;if(void 0!==r)return r.texture;{const l=t.image;return s&&l&&l.height>0||o&&l&&function(e){let t=0;const i=6;for(let n=0;n<i;n++)void 0!==e[n]&&t++;return t===i}(l)?(null===n&&(n=new Ho(e)),r=s?n.fromEquirectangular(t):n.fromCubemap(t),r.texture.pmremVersion=t.pmremVersion,i.set(t,r),t.addEventListener("dispose",a),r.texture):null}}}return t}(o):function(i){if(i&&i.isTexture){const n=i.mapping;if(n===Ce||n===Ne){if(t.has(i)){return r(t.get(i).texture,i.mapping)}{const n=i.image;if(n&&n.height>0){const a=new zo(n.height);return a.fromEquirectangularTexture(e,i),t.set(i,a),i.addEventListener("dispose",s),r(a.texture,i.mapping)}return null}}}return i}(o)},dispose:function(){t=new WeakMap,i=new WeakMap,null!==n&&(n.dispose(),n=null)}}}function Yo(e){const t={};function i(i){if(void 0!==t[i])return t[i];const n=e.getExtension(i);return t[i]=n,n}return{has:function(e){return null!==i(e)},init:function(){i("EXT_color_buffer_float"),i("WEBGL_clip_cull_distance"),i("OES_texture_float_linear"),i("EXT_color_buffer_half_float"),i("WEBGL_multisampled_render_to_texture"),i("WEBGL_render_shared_exponent")},get:function(e){const t=i(e);return null===t&&Ei("WebGLRenderer: "+e+" extension not supported."),t}}}function Ko(e,t,i,n){const r={},s=new WeakMap,a=new FinalizationRegistry(e=>delete r[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 r[e.id],a.unregister(e);const l=s.get(e);l&&(t.remove(l),s.delete(e)),n.releaseStatesOfGeometry(e),!0===e.isInstancedBufferGeometry&&delete e._maxInstanceCount,i.memory.geometries--}function c(e){const i=e.index,n=e.attributes.position;let r=0;if(void 0===n)return;const a=null!==i?i.array.length:n.array.length/3-1,o=new(n.count>=65535?Or:Ur)(6*Math.ceil(a/3),1),l=o.array;if(null!==i){const e=i.array;r=i.version;for(let t=0,i=0;t<a;t+=3){const n=e[t+0],r=e[t+1],s=e[t+2];l[i++]=n,l[i++]=r,l[i++]=r,l[i++]=s,l[i++]=s,l[i++]=n}}else{r=n.version;for(let e=0,t=0;e<a;e+=3){const i=e+0,n=e+1,r=e+2;l[t++]=i,l[t++]=n,l[t++]=n,l[t++]=r,l[t++]=r,l[t++]=i}}o.version=r;const c=s.get(e);c&&t.remove(c),s.set(e,o)}return{get:function(e,t){return void 0!==r[t.id]||(t.addEventListener("dispose",o),r[t.id]=new WeakRef(t),a.register(t,t.id,t),i.memory.geometries++),t},update:function(i){const n=i.attributes;for(const i in n)t.update(n[i],e.ARRAY_BUFFER)},getWireframeAttribute:function(e){const t=s.get(e);if(t){const i=e.index;null!==i&&t.version<i.version&&c(e)}else c(e);return s.get(e)},dispose:function(){for(const e in r){const t=r[e].deref();void 0!==t&&l(t)}}}}function Zo(e,t,i){let n,r,s;this.setMode=function(e){n=e},this.setIndex=function(e){r=e.type,s=e.bytesPerElement},this.render=function(t,a){e.drawElements(n,a,r,t*s),i.update(a,n,1)},this.renderInstances=function(t,a,o){0!==o&&(e.drawElementsInstanced(n,a,r,t*s,o),i.update(a,n,o))},this.renderMultiDraw=function(e,s,a){if(0===a)return;t.get("WEBGL_multi_draw").multiDrawElementsWEBGL(n,s,0,r,e,0,a);let o=0;for(let e=0;e<a;e++)o+=s[e];i.update(o,n,1)}}function Qo(e){const t={frame:0,calls:0,triangles:0,points:0,lines:0};return{memory:{geometries:0,textures:0},render:t,programs:null,autoReset:!0,reset:function(){t.calls=0,t.triangles=0,t.points=0,t.lines=0},update:function(i,n,r){switch(t.calls++,n){case e.TRIANGLES:t.triangles+=r*(i/3);break;case e.LINES:t.lines+=r*(i/2);break;case e.LINE_STRIP:t.lines+=r*(i-1);break;case e.LINE_LOOP:t.lines+=r*i;break;case e.POINTS:t.points+=r*i;break;default:Mi("WebGLInfo: Unknown draw mode:",n)}}}}function Jo(e,t,i){const n=new WeakMap,r=new un;return{update:function(s,a,o){const l=s.morphTargetInfluences,c=a.morphAttributes.position||a.morphAttributes.normal||a.morphAttributes.color,u=void 0!==c?c.length:0;let h=n.get(a);if(void 0===h||h.count!==u){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*u),S=new pn(x,b,y,u);S.type=$e,S.needsUpdate=!0;const T=4*v;for(let E=0;E<u;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&&(r.fromBufferAttribute(w,N),x[C+P+0]=r.x,x[C+P+1]=r.y,x[C+P+2]=r.z,x[C+P+3]=0),!0===p&&(r.fromBufferAttribute(A,N),x[C+P+4]=r.x,x[C+P+5]=r.y,x[C+P+6]=r.z,x[C+P+7]=0),!0===f&&(r.fromBufferAttribute(R,N),x[C+P+8]=r.x,x[C+P+9]=r.y,x[C+P+10]=r.z,x[C+P+11]=4===R.itemSize?r.w:1)}}function M(){S.dispose(),n.delete(a),a.removeEventListener("dispose",M)}h={count:u,texture:S,size:new Vi(b,y)},n.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 I=0;I<l.length;I++)L+=l[I];const D=a.morphTargetsRelative?1:1-L;o.getUniforms().setValue(e,"morphTargetBaseInfluence",D),o.getUniforms().setValue(e,"morphTargetInfluences",l)}o.getUniforms().setValue(e,"morphTargetsTexture",h.texture,i),o.getUniforms().setValue(e,"morphTargetsTextureSize",h.size)}}}function el(e,t,i,n,r){let s=new WeakMap;function a(e){const t=e.target;t.removeEventListener("dispose",a),n.releaseStatesOfObject(t),i.remove(t.instanceMatrix),null!==t.instanceColor&&i.remove(t.instanceColor)}return{update:function(n){const o=r.render.frame,l=n.geometry,c=t.get(n,l);if(s.get(c)!==o&&(t.update(c),s.set(c,o)),n.isInstancedMesh&&(!1===n.hasEventListener("dispose",a)&&n.addEventListener("dispose",a),s.get(n)!==o&&(i.update(n.instanceMatrix,e.ARRAY_BUFFER),null!==n.instanceColor&&i.update(n.instanceColor,e.ARRAY_BUFFER),s.set(n,o))),n.isSkinnedMesh){const e=n.skeleton;s.get(e)!==o&&(e.update(),s.set(e,o))}return c},dispose:function(){s=new WeakMap}}}const tl={[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 il(e,t,i,n,r,s){const a=new dn(t,i,{type:e,depthBuffer:r,stencilBuffer:s,samples:n?4:0,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,resolveDepthBuffer:!1,resolveStencilBuffer:!1});let o=null,l=null,c=null;const u=new Zr;u.setAttribute("position",new kr([-1,3,0,-1,-1,0,3,-1,0],3)),u.setAttribute("uv",new kr([0,2,0,0,2,0],2));const h=new Ta({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(u,h),p=new so(-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 n=b[i];n.setSize&&n.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 dn(t,i,{type:Xe,depthBuffer:!1,stencilBuffer:!1}),l=new dn(t,i,{type:Xe,depthBuffer:!1,stencilBuffer:!1}));const n=!0===r&&b.some(e=>!0===e.needsDepthTexture);n!==(null!==a.depthTexture)&&(!0===n&&null===c&&(c=new oa(t,i),!0===s&&(c.format=nt,c.type=Ke)),a.dispose(),a.depthTexture=n?c:null,a.resolveDepthBuffer=n,a.storeMultisampledDepthBuffer=n);for(let e=0;e<b.length;e++){const r=b[e];r.setSize&&r.setSize(t,i),n&&!0===r.needsDepthTexture&&r.setDepthTexture&&r.setDepthTexture(c)}},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,n=o;for(let r=0;r<b.length;r++){const s=b[r];!1!==s.enabled&&(s.render(e,n,i,t),!1!==s.needsSwap&&(i=n,n=n===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=tl[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(),u.dispose(),h.dispose()}}const nl=new cn,rl=new oa(1,1),sl=new la(1),al=new pn,ol=new fn,ll=new sa,cl=[],ul=[],hl=new Float32Array(16),dl=new Float32Array(9),pl=new Float32Array(4);function fl(e,t,i){const n=e[0];if(n<=0||n>0)return e;const r=t*i;let s=cl[r];if(void 0===s&&(s=new Float32Array(r),cl[r]=s),0!==t){n.toArray(s,0);for(let n=1,r=0;n!==t;++n)r+=i,e[n].toArray(s,r)}return s}function ml(e,t){if(e.length!==t.length)return!1;for(let i=0,n=e.length;i<n;i++)if(e[i]!==t[i])return!1;return!0}function gl(e,t){for(let i=0,n=t.length;i<n;i++)e[i]=t[i]}function _l(e,t){let i=ul[t];void 0===i&&(i=new Int32Array(t),ul[t]=i);for(let n=0;n!==t;++n)i[n]=e.allocateTextureUnit();return i}function vl(e,t){const i=this.cache;i[0]!==t&&(e.uniform1f(this.addr,t),i[0]=t)}function bl(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(ml(i,t))return;e.uniform2fv(this.addr,t),gl(i,t)}}function yl(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(ml(i,t))return;e.uniform3fv(this.addr,t),gl(i,t)}}function xl(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(ml(i,t))return;e.uniform4fv(this.addr,t),gl(i,t)}}function Sl(e,t){const i=this.cache,n=t.elements;if(void 0===n){if(ml(i,t))return;e.uniformMatrix2fv(this.addr,!1,t),gl(i,t)}else{if(ml(i,n))return;pl.set(n),e.uniformMatrix2fv(this.addr,!1,pl),gl(i,n)}}function Tl(e,t){const i=this.cache,n=t.elements;if(void 0===n){if(ml(i,t))return;e.uniformMatrix3fv(this.addr,!1,t),gl(i,t)}else{if(ml(i,n))return;dl.set(n),e.uniformMatrix3fv(this.addr,!1,dl),gl(i,n)}}function Ml(e,t){const i=this.cache,n=t.elements;if(void 0===n){if(ml(i,t))return;e.uniformMatrix4fv(this.addr,!1,t),gl(i,t)}else{if(ml(i,n))return;hl.set(n),e.uniformMatrix4fv(this.addr,!1,hl),gl(i,n)}}function El(e,t){const i=this.cache;i[0]!==t&&(e.uniform1i(this.addr,t),i[0]=t)}function wl(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(ml(i,t))return;e.uniform2iv(this.addr,t),gl(i,t)}}function Al(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(ml(i,t))return;e.uniform3iv(this.addr,t),gl(i,t)}}function Rl(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(ml(i,t))return;e.uniform4iv(this.addr,t),gl(i,t)}}function Cl(e,t){const i=this.cache;i[0]!==t&&(e.uniform1ui(this.addr,t),i[0]=t)}function Nl(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(ml(i,t))return;e.uniform2uiv(this.addr,t),gl(i,t)}}function Pl(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(ml(i,t))return;e.uniform3uiv(this.addr,t),gl(i,t)}}function Ll(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(ml(i,t))return;e.uniform4uiv(this.addr,t),gl(i,t)}}function Dl(e){return 0===e.version&&(e.compareFunction=si,e.needsUpdate=!0),e}function Il(e,t,i){const n=this.cache,r=i.allocateTextureUnit();let s;n[0]!==r&&(e.uniform1i(this.addr,r),n[0]=r),s=this.type===e.SAMPLER_2D_SHADOW?Dl(rl):nl,i.setTexture2D(t||s,r)}function Fl(e,t,i){const n=this.cache,r=i.allocateTextureUnit();n[0]!==r&&(e.uniform1i(this.addr,r),n[0]=r),i.setTexture3D(t||ol,r)}function Ul(e,t,i){const n=this.cache,r=i.allocateTextureUnit();let s;n[0]!==r&&(e.uniform1i(this.addr,r),n[0]=r),s=this.type===e.SAMPLER_CUBE_SHADOW?Dl(sl):ll,i.setTextureCube(t||s,r)}function Ol(e,t,i){const n=this.cache,r=i.allocateTextureUnit();n[0]!==r&&(e.uniform1i(this.addr,r),n[0]=r),i.setTexture2DArray(t||al,r)}function Bl(e,t){e.uniform1fv(this.addr,t)}function kl(e,t){const i=fl(t,this.size,2);e.uniform2fv(this.addr,i)}function zl(e,t){const i=fl(t,this.size,3);e.uniform3fv(this.addr,i)}function Gl(e,t){const i=fl(t,this.size,4);e.uniform4fv(this.addr,i)}function Vl(e,t){const i=fl(t,this.size,4);e.uniformMatrix2fv(this.addr,!1,i)}function Hl(e,t){const i=fl(t,this.size,9);e.uniformMatrix3fv(this.addr,!1,i)}function Wl(e,t){const i=fl(t,this.size,16);e.uniformMatrix4fv(this.addr,!1,i)}function jl(e,t){e.uniform1iv(this.addr,t)}function $l(e,t){e.uniform2iv(this.addr,t)}function Xl(e,t){e.uniform3iv(this.addr,t)}function ql(e,t){e.uniform4iv(this.addr,t)}function Yl(e,t){e.uniform1uiv(this.addr,t)}function Kl(e,t){e.uniform2uiv(this.addr,t)}function Zl(e,t){e.uniform3uiv(this.addr,t)}function Ql(e,t){e.uniform4uiv(this.addr,t)}function Jl(e,t,i){const n=this.cache,r=t.length,s=_l(i,r);let a;ml(n,s)||(e.uniform1iv(this.addr,s),gl(n,s)),a=this.type===e.SAMPLER_2D_SHADOW?Dl(rl):nl;for(let e=0;e!==r;++e)i.setTexture2D(t[e]||a,s[e])}function ec(e,t,i){const n=this.cache,r=t.length,s=_l(i,r);ml(n,s)||(e.uniform1iv(this.addr,s),gl(n,s));for(let e=0;e!==r;++e)i.setTexture3D(t[e]||ol,s[e])}function tc(e,t,i){const n=this.cache,r=t.length,s=_l(i,r);let a;ml(n,s)||(e.uniform1iv(this.addr,s),gl(n,s)),a=this.type===e.SAMPLER_CUBE_SHADOW?Dl(sl):ll;for(let e=0;e!==r;++e)i.setTextureCube(t[e]||a,s[e])}function ic(e,t,i){const n=this.cache,r=t.length,s=_l(i,r);ml(n,s)||(e.uniform1iv(this.addr,s),gl(n,s));for(let e=0;e!==r;++e)i.setTexture2DArray(t[e]||al,s[e])}class nc{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 vl;case 35664:return bl;case 35665:return yl;case 35666:return xl;case 35674:return Sl;case 35675:return Tl;case 35676:return Ml;case 5124:case 35670:return El;case 35667:case 35671:return wl;case 35668:case 35672:return Al;case 35669:case 35673:return Rl;case 5125:return Cl;case 36294:return Nl;case 36295:return Pl;case 36296:return Ll;case 35678:case 36198:case 36298:case 36306:case 35682:return Il;case 35679:case 36299:case 36307:return Fl;case 35680:case 36300:case 36308:case 36293:return Ul;case 36289:case 36303:case 36311:case 36292:return Ol}}(t.type)}}class rc{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 Bl;case 35664:return kl;case 35665:return zl;case 35666:return Gl;case 35674:return Vl;case 35675:return Hl;case 35676:return Wl;case 5124:case 35670:return jl;case 35667:case 35671:return $l;case 35668:case 35672:return Xl;case 35669:case 35673:return ql;case 5125:return Yl;case 36294:return Kl;case 36295:return Zl;case 36296:return Ql;case 35678:case 36198:case 36298:case 36306:case 35682:return Jl;case 35679:case 36299:case 36307:return ec;case 35680:case 36300:case 36308:case 36293:return tc;case 36289:case 36303:case 36311:case 36292:return ic}}(t.type)}}class sc{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,i){const n=this.seq;for(let r=0,s=n.length;r!==s;++r){const s=n[r];s.setValue(e,t[s.id],i)}}}const ac=/(\w+)(\])?(\[|\.)?/g;function oc(e,t){e.seq.push(t),e.map[t.id]=t}function lc(e,t,i){const n=e.name,r=n.length;for(ac.lastIndex=0;;){const s=ac.exec(n),a=ac.lastIndex;let o=s[1];const l="]"===s[2],c=s[3];if(l&&(o|=0),void 0===c||"["===c&&a+2===r){oc(i,void 0===c?new nc(o,e,t):new rc(o,e,t));break}{let e=i.map[o];void 0===e&&(e=new sc(o),oc(i,e)),i=e}}}class cc{constructor(e,t){this.seq=[],this.map={};const i=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let n=0;n<i;++n){const i=e.getActiveUniform(t,n);lc(i,e.getUniformLocation(t,i.name),this)}const n=[],r=[];for(const t of this.seq)t.type===e.SAMPLER_2D_SHADOW||t.type===e.SAMPLER_CUBE_SHADOW||t.type===e.SAMPLER_2D_ARRAY_SHADOW?n.push(t):r.push(t);n.length>0&&(this.seq=n.concat(r))}setValue(e,t,i,n){const r=this.map[t];void 0!==r&&r.setValue(e,i,n)}setOptional(e,t,i){const n=t[i];void 0!==n&&this.setValue(e,i,n)}static upload(e,t,i,n){for(let r=0,s=t.length;r!==s;++r){const s=t[r],a=i[s.id];!1!==a.needsUpdate&&s.setValue(e,a.value,n)}}static seqWithValue(e,t){const i=[];for(let n=0,r=e.length;n!==r;++n){const r=e[n];r.id in t&&i.push(r)}return i}}function uc(e,t,i){const n=e.createShader(t);return e.shaderSource(n,i),e.compileShader(n),n}let hc=0;const dc=new Xi;function pc(e,t,i){const n=e.getShaderParameter(t,e.COMPILE_STATUS),r=(e.getShaderInfoLog(t)||"").trim();if(n&&""===r)return"";const s=/ERROR: 0:(\d+)/.exec(r);if(s){const n=parseInt(s[1]);return i.toUpperCase()+"\n\n"+r+"\n\n"+function(e,t){const i=e.split("\n"),n=[],r=Math.max(t-6,0),s=Math.min(t+6,i.length);for(let e=r;e<s;e++){const r=e+1;n.push(`${r===t?">":" "} ${r}: ${i[e]}`)}return n.join("\n")}(e.getShaderSource(t),n)}return r}function fc(e,t){const i=function(e){Qi._getMatrix(dc,Qi.workingColorSpace,e);const t=`mat3( ${dc.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 mc={[ye]:"Linear",[xe]:"Reinhard",[Se]:"Cineon",[Te]:"ACESFilmic",[Ee]:"AgX",[we]:"Neutral",[Me]:"Custom"};function gc(e,t){const i=mc[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 _c=new Wi;function vc(){Qi.getLuminanceCoefficients(_c);return["float luminance( const in vec3 rgb ) {",`\tconst vec3 weights = vec3( ${_c.x.toFixed(4)}, ${_c.y.toFixed(4)}, ${_c.z.toFixed(4)} );`,"\treturn dot( weights, rgb );","}"].join("\n")}function bc(e){return""!==e}function yc(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 xc(e,t){return e.replace(/NUM_CLIPPING_PLANES/g,t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,t.numClippingPlanes-t.numClipIntersection)}const Sc=/^[ \t]*#include +<([\w\d./]+)>/gm;function Tc(e){return e.replace(Sc,Mc)}function Mc(e,t){const i=Co[t];if(void 0===i)throw new Error("THREE.WebGLProgram: Can not resolve #include <"+t+">");return Tc(i)}const Ec=/#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 wc(e){return e.replace(Ec,Ac)}function Ac(e,t,i,n){let r="";for(let e=parseInt(t);e<parseInt(i);e++)r+=n.replace(/\[\s*i\s*\]/g,"[ "+e+" ]").replace(/UNROLLED_LOOP_INDEX/g,e);return r}function Rc(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 Cc={[B]:"SHADOWMAP_TYPE_PCF",[k]:"SHADOWMAP_TYPE_VSM"};const Nc={[Re]:"ENVMAP_MODE_REFRACTION"};const Pc={[_e]:"ENVMAP_BLENDING_MULTIPLY",[ve]:"ENVMAP_BLENDING_MIX",[be]:"ENVMAP_BLENDING_ADD"};function Lc(e,t,i,n){const r=e.getContext(),s=i.defines;let a=i.vertexShader,o=i.fragmentShader;const l=function(e){return Cc[e.shadowMapType]||"SHADOWMAP_TYPE_BASIC"}(i),c=!0===i.envMapPMREM?"ENVMAP_TYPE_PMREM":"ENVMAP_TYPE_CUBE",u=function(e){return!1===e.envMap?"ENVMAP_MODE_REFLECTION":Nc[e.envMapMode]||"ENVMAP_MODE_REFLECTION"}(i),h=function(e){return!1===e.envMap?"ENVMAP_BLENDING_NONE":Pc[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(bc).join("\n")}(i),p=function(e){const t=[];for(const i in e){const n=e[i];!1!==n&&t.push("#define "+i+" "+n)}return t.join("\n")}(s),f=r.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(bc).join("\n"),m.length>0&&(m+="\n"),g=["#define SHADER_TYPE "+i.shaderType,"#define SHADER_NAME "+i.shaderName,p].filter(bc).join("\n"),g.length>0&&(g+="\n")):(m=[Rc(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 "+u:"",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(bc).join("\n"),g=[Rc(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 "+c:"",i.envMap?"#define "+u:"",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?Co.tonemapping_pars_fragment:"",0!==i.toneMapping?gc("toneMapping",i.toneMapping):"",i.dithering?"#define DITHERING":"",i.opaque?"#define OPAQUE":"",Co.colorspace_pars_fragment,fc("linearToOutputTexel",i.outputColorSpace),vc(),i.useDepthPacking?"#define DEPTH_PACKING "+i.depthPacking:"","\n"].filter(bc).join("\n")),a=Tc(a),a=yc(a,i),a=xc(a,i),o=Tc(o),o=yc(o,i),o=xc(o,i),a=wc(a),o=wc(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=uc(r,r.VERTEX_SHADER,v),x=uc(r,r.FRAGMENT_SHADER,b);function S(t){if(e.debug.checkShaderErrors){const i=r.getProgramInfoLog(f)||"",n=r.getShaderInfoLog(y)||"",s=r.getShaderInfoLog(x)||"",a=i.trim(),o=n.trim(),l=s.trim();let c=!0,u=!0;if(!1===r.getProgramParameter(f,r.LINK_STATUS))if(c=!1,"function"==typeof e.debug.onShaderError)e.debug.onShaderError(r,f,y,x);else{const e=pc(r,y,"vertex"),i=pc(r,x,"fragment");Mi("WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(f,r.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||(u=!1);u&&(t.diagnostics={runnable:c,programLog:a,vertexShader:{log:o,prefix:m},fragmentShader:{log:l,prefix:g}})}r.deleteShader(y),r.deleteShader(x),T=new cc(r,f),M=function(e,t){const i={},n=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let r=0;r<n;r++){const n=e.getActiveAttrib(t,r),s=n.name;let a=1;n.type===e.FLOAT_MAT2&&(a=2),n.type===e.FLOAT_MAT3&&(a=3),n.type===e.FLOAT_MAT4&&(a=4),i[s]={type:n.type,location:e.getAttribLocation(t,s),locationSize:a}}return i}(r,f)}let T,M;r.attachShader(f,y),r.attachShader(f,x),void 0!==i.index0AttributeName?r.bindAttribLocation(f,0,i.index0AttributeName):!0===i.hasPositionAttribute&&r.bindAttribLocation(f,0,"position"),r.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=r.getProgramParameter(f,37297)),E},this.destroy=function(){n.releaseStatesOfProgram(this),r.deleteProgram(f),this.program=void 0},this.type=i.shaderType,this.name=i.shaderName,this.id=hc++,this.cacheKey=t,this.usedTimes=1,this.program=f,this.vertexShader=y,this.fragmentShader=x,this}let Dc=0;class Ic{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e,t,i){const n=this._getShaderCacheForMaterial(e);return!1===n.has(t)&&(n.add(t),t.usedTimes++),!1===n.has(i)&&(n.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 Fc(e),t.set(e,i)),i}}class Fc{constructor(e){this.id=Dc++,this.code=e,this.usedTimes=0}}function Uc(e){return e===at||e===Tt||e===Wt}function Oc(e,t,i,n,r,s){const a=new wn,o=new Ic,l=new Set,c=[],u=new Map,h=n.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(r,a,c,u,f,m){const g=u.fog,_=f.geometry,v=r.isMeshStandardMaterial||r.isMeshLambertMaterial||r.isMeshPhongMaterial?u.environment:null,b=r.isMeshStandardMaterial||r.isMeshLambertMaterial&&!r.envMap||r.isMeshPhongMaterial&&!r.envMap,y=t.get(r.envMap||v,b),x=d[r.type];let S=n.precision;null!==r.precision&&(S=n.getMaxPrecision(r.precision),S!==r.precision&&Ti("WebGLProgram.getParameters:",r.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=Po[x];E=e.vertexShader,w=e.fragmentShader}else{E=r.vertexShader,w=r.fragmentShader;const e=o.getVertexShaderStage(r),t=o.getFragmentShaderStage(r);o.update(r,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,I=!!r.map,F=!!r.matcap,U=!!y,O=U&&!0===y.isPMREMTexture,B=!!r.aoMap,k=!!r.lightMap,z=!!r.bumpMap&&!1===r.wireframe,G=!!r.normalMap,V=!!r.displacementMap,H=!!r.emissiveMap,W=!!r.metalnessMap,j=!!r.roughnessMap,$=r.anisotropy>0,X=r.clearcoat>0,q=r.diffuseRoughness>0,Y=r.dispersion>0,K=r.retroreflectivity>0,Z=r.iridescence>0,Q=r.sheen>0,J=r.transmission>0,ee=$&&!!r.anisotropyMap,te=X&&!!r.clearcoatMap,ie=X&&!!r.clearcoatNormalMap,ne=X&&!!r.clearcoatRoughnessMap,re=q&&!!r.diffuseRoughnessMap,se=Z&&!!r.iridescenceMap,ae=Z&&!!r.iridescenceThicknessMap,oe=Q&&!!r.sheenColorMap,le=Q&&!!r.sheenRoughnessMap,ce=!!r.specularMap,ue=!!r.specularColorMap,he=!!r.specularIntensityMap,de=J&&!!r.transmissionMap,pe=J&&!!r.thicknessMap,fe=!!r.gradientMap,me=!!r.alphaMap,ge=r.alphaTest>0,_e=!!r.alphaHash,ve=!!r.extensions;let be=0;r.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:r.type,shaderName:r.name,vertexShader:E,fragmentShader:w,defines:r.defines,customVertexShaderID:A,customFragmentShaderID:R,isRawShaderMaterial:!0===r.isRawShaderMaterial,glslVersion:r.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:!!r.alphaToCoverage,map:I,matcap:F,envMap:U,envMapMode:U&&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===r.normalMapType,normalMapTangentSpace:G&&0===r.normalMapType,packedNormalMap:G&&0===r.normalMapType&&Uc(r.normalMap.format),metalnessMap:W,roughnessMap:j,anisotropy:$,anisotropyMap:ee,clearcoat:X,clearcoatMap:te,clearcoatNormalMap:ie,clearcoatRoughnessMap:ne,diffuseRoughness:q,diffuseRoughnessMap:re,dispersion:Y,retroreflection:K,iridescence:Z,iridescenceMap:se,iridescenceThicknessMap:ae,sheen:Q,sheenColorMap:oe,sheenRoughnessMap:le,specularMap:ce,specularColorMap:ue,specularIntensityMap:he,transmission:J,transmissionMap:de,thicknessMap:pe,gradientMap:fe,opaque:!1===r.transparent&&1===r.blending&&!1===r.alphaToCoverage,alphaMap:me,alphaTest:ge,alphaHash:_e,combine:r.combine,mapUv:I&&p(r.map.channel),aoMapUv:B&&p(r.aoMap.channel),lightMapUv:k&&p(r.lightMap.channel),bumpMapUv:z&&p(r.bumpMap.channel),normalMapUv:G&&p(r.normalMap.channel),displacementMapUv:V&&p(r.displacementMap.channel),emissiveMapUv:H&&p(r.emissiveMap.channel),metalnessMapUv:W&&p(r.metalnessMap.channel),roughnessMapUv:j&&p(r.roughnessMap.channel),anisotropyMapUv:ee&&p(r.anisotropyMap.channel),clearcoatMapUv:te&&p(r.clearcoatMap.channel),clearcoatNormalMapUv:ie&&p(r.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:ne&&p(r.clearcoatRoughnessMap.channel),diffuseRoughnessMapUv:re&&p(r.diffuseRoughnessMap.channel),iridescenceMapUv:se&&p(r.iridescenceMap.channel),iridescenceThicknessMapUv:ae&&p(r.iridescenceThicknessMap.channel),sheenColorMapUv:oe&&p(r.sheenColorMap.channel),sheenRoughnessMapUv:le&&p(r.sheenRoughnessMap.channel),specularMapUv:ce&&p(r.specularMap.channel),specularColorMapUv:ue&&p(r.specularColorMap.channel),specularIntensityMapUv:he&&p(r.specularIntensityMap.channel),transmissionMapUv:de&&p(r.transmissionMap.channel),thicknessMapUv:pe&&p(r.thicknessMap.channel),alphaMapUv:me&&p(r.alphaMap.channel),vertexTangents:!!_.attributes.tangent&&(G||$),vertexNormals:!!_.attributes.normal,vertexColors:r.vertexColors,vertexAlphas:!0===r.vertexColors&&!!_.attributes.color&&4===_.attributes.color.itemSize,pointsUvs:!0===f.isPoints&&!!_.attributes.uv&&(I||me),fog:!!g,useFog:!0===r.fog,fogExp2:!!g&&g.isFogExp2,flatShading:!1===r.wireframe&&(!0===r.flatShading||void 0===_.attributes.normal&&!1===G&&(r.isMeshLambertMaterial||r.isMeshPhongMaterial||r.isMeshStandardMaterial||r.isMeshPhysicalMaterial)),sizeAttenuation:!0===r.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:r.dithering,shadowMapEnabled:e.shadowMap.enabled&&c.length>0,shadowMapType:e.shadowMap.type,toneMapping:be,decodeVideoTexture:I&&!0===r.map.isVideoTexture&&Qi.getTransfer(r.map.colorSpace)===Kt,decodeVideoTextureEmissive:H&&!0===r.emissiveMap.isVideoTexture&&Qi.getTransfer(r.emissiveMap.colorSpace)===Kt,premultipliedAlpha:r.premultipliedAlpha,doubleSided:2===r.side,flipSided:1===r.side,useDepthPacking:r.depthPacking>=0,depthPacking:r.depthPacking||0,index0AttributeName:r.index0AttributeName,extensionClipCullDistance:ve&&!0===r.extensions.clipCullDistance&&i.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(ve&&!0===r.extensions.multiDraw||D)&&i.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:i.has("KHR_parallel_shader_compile"),customProgramCacheKey:r.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=Po[t];i=xa.clone(e.uniforms)}else i=e.uniforms;return i},acquireProgram:function(t,i){let n=u.get(i);return void 0!==n?++n.usedTimes:(n=new Lc(e,i,t,r),c.push(n),u.set(i,n)),n},releaseProgram:function(e){if(0===--e.usedTimes){const t=c.indexOf(e);c[t]=c[c.length-1],c.pop(),u.delete(e.cacheKey),e.destroy()}},releaseShaderCache:function(e){o.remove(e)},programs:c,dispose:function(){o.dispose()}}}function Bc(){let e=new WeakMap;return{has:function(t){return e.has(t)},get:function(t){let i=e.get(t);return void 0===i&&(i={},e.set(t,i)),i},remove:function(t){e.delete(t)},update:function(t,i,n){e.get(t)[i]=n},dispose:function(){e=new WeakMap}}}function kc(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 zc(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 Gc(){const e=[];let t=0;const i=[],n=[],r=[];function s(e){let t=0;return e.isInstancedMesh&&(t+=2),e.isSkinnedMesh&&(t+=1),t}function a(i,n,r,a,o,l){let c=e[t];return void 0===c?(c={id:i.id,object:i,geometry:n,material:r,materialVariant:s(i),groupOrder:a,renderOrder:i.renderOrder,z:o,group:l},e[t]=c):(c.id=i.id,c.object=i,c.geometry=n,c.material=r,c.materialVariant=s(i),c.groupOrder=a,c.renderOrder=i.renderOrder,c.z=o,c.group=l),t++,c}return{opaque:i,transmissive:n,transparent:r,init:function(){t=0,i.length=0,n.length=0,r.length=0},push:function(e,t,s,o,l,c,u){!0===u.reversedDepth&&(l=-l);const h=a(e,t,s,o,l,c);s.transmission>0?n.push(h):!0===s.transparent?r.push(h):i.push(h)},unshift:function(e,t,s,o,l,c){const u=a(e,t,s,o,l,c);s.transmission>0?n.unshift(u):!0===s.transparent?r.unshift(u):i.unshift(u)},finish:function(){for(let i=t,n=e.length;i<n;i++){const t=e[i];if(null===t.id)break;t.id=null,t.object=null,t.geometry=null,t.material=null,t.group=null}},sort:function(e,t){i.length>1&&i.sort(e||kc),n.length>1&&n.sort(t||zc),r.length>1&&r.sort(t||zc)}}}function Vc(){let e=new WeakMap;return{get:function(t,i){const n=e.get(t);let r;return void 0===n?(r=new Gc,e.set(t,[r])):i>=n.length?(r=new Gc,n.push(r)):r=n[i],r},dispose:function(){e=new WeakMap}}}function Hc(){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 Kn};break;case"SpotLight":i={position:new Wi,direction:new Wi,color:new Kn,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":i={position:new Wi,color:new Kn,distance:0,decay:0};break;case"HemisphereLight":i={direction:new Wi,skyColor:new Kn,groundColor:new Kn};break;case"RectAreaLight":i={color:new Kn,position:new Wi,halfWidth:new Wi,halfHeight:new Wi}}return e[t.id]=i,i}}}let Wc=0;function jc(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+(t.map?1:0)-(e.map?1:0)}function $c(e){const t=new Hc,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}}}(),n={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++)n.probe.push(new Wi);const r=new Wi,s=new mn,a=new mn;return{setup:function(r){let s=0,a=0,o=0;for(let e=0;e<9;e++)n.probe[e].set(0,0,0);let l=0,c=0,u=0,h=0,d=0,p=0,f=0,m=0,g=0,_=0,v=0,b=0,y=0,x=0;r.sort(jc);for(let e=0,S=r.length;e<S;e++){const S=r[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++)n.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()),n.sunShadow[c]=t,n.sunShadowMap[c]=w;const r=e.getViewportCount();for(let t=0;t<r;t++)n.sunShadowMatrix[u+t]=e.getMatrix(t),n.sunShadowCascade[u+t]=e._cascadeData[t];u+=r,c++}n.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,n.directionalShadow[h]=t,n.directionalShadowMap[h]=w,n.directionalShadowMatrix[h]=S.shadow.matrix,g++}n.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,n.spot[p]=e;const r=S.shadow;if(S.map&&(n.spotLightMap[b]=S.map,b++,r.updateMatrices(S),S.castShadow&&y++),n.spotLightMatrix[p]=r.matrix,S.castShadow){const e=i.get(S);e.shadowIntensity=r.intensity,e.shadowBias=r.bias,e.shadowNormalBias=r.normalBias,e.shadowRadius=r.radius,e.shadowMapSize=r.mapSize,n.spotShadow[p]=e,n.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),n.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,n.pointShadow[d]=t,n.pointShadowMap[d]=w,n.pointShadowMatrix[d]=S.shadow.matrix,_++}n.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),n.hemi[m]=e,m++}}f>0&&(!0===e.has("OES_texture_float_linear")?(n.rectAreaLTC1=No.LTC_FLOAT_1,n.rectAreaLTC2=No.LTC_FLOAT_2):(n.rectAreaLTC1=No.LTC_HALF_1,n.rectAreaLTC2=No.LTC_HALF_2)),n.ambient[0]=s,n.ambient[1]=a,n.ambient[2]=o;const S=n.hash;S.sunLength===l&&S.directionalLength===h&&S.pointLength===d&&S.spotLength===p&&S.rectAreaLength===f&&S.hemiLength===m&&S.numSunShadows===c&&S.numDirectionalShadows===g&&S.numPointShadows===_&&S.numSpotShadows===v&&S.numSpotMaps===b&&S.numLightProbes===x||(n.sun.length=l,n.directional.length=h,n.spot.length=p,n.rectArea.length=f,n.point.length=d,n.hemi.length=m,n.sunShadow.length=c,n.sunShadowMap.length=c,n.sunShadowMatrix.length=u,n.sunShadowCascade.length=u,n.directionalShadow.length=g,n.directionalShadowMap.length=g,n.directionalShadowMatrix.length=g,n.pointShadow.length=_,n.pointShadowMap.length=_,n.pointShadowMatrix.length=_,n.spotShadow.length=v,n.spotShadowMap.length=v,n.spotLightMatrix.length=v+b-y,n.spotLightMap.length=b,n.numSpotLightShadowsWithMaps=y,n.numLightProbes=x,S.sunLength=l,S.directionalLength=h,S.pointLength=d,S.spotLength=p,S.rectAreaLength=f,S.hemiLength=m,S.numSunShadows=c,S.numDirectionalShadows=g,S.numPointShadows=_,S.numSpotShadows=v,S.numSpotMaps=b,S.numLightProbes=x,n.version=Wc++)},setupView:function(e,t){let i=0,o=0,l=0,c=0,u=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=n.sun[i];e.direction.setFromMatrixPosition(p.matrixWorld),e.direction.transformDirection(d),i++}else if(p.isDirectionalLight){const e=n.directional[o];e.direction.setFromMatrixPosition(p.matrixWorld),r.setFromMatrixPosition(p.target.matrixWorld),e.direction.sub(r),e.direction.transformDirection(d),o++}else if(p.isSpotLight){const e=n.spot[c];e.position.setFromMatrixPosition(p.matrixWorld),e.position.applyMatrix4(d),e.direction.setFromMatrixPosition(p.matrixWorld),r.setFromMatrixPosition(p.target.matrixWorld),e.direction.sub(r),e.direction.transformDirection(d),c++}else if(p.isRectAreaLight){const e=n.rectArea[u];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),u++}else if(p.isPointLight){const e=n.point[l];e.position.setFromMatrixPosition(p.matrixWorld),e.position.applyMatrix4(d),l++}else if(p.isHemisphereLight){const e=n.hemi[h];e.direction.setFromMatrixPosition(p.matrixWorld),e.direction.transformDirection(d),h++}}},state:n}}function Xc(e){const t=new $c(e),i=[],n=[],r=[];const s={lightsArray:i,shadowsArray:n,lightProbeGridArray:r,camera:null,lights:t,transmissionRenderTarget:{},textureUnits:0};return{init:function(e){s.camera=e,i.length=0,n.length=0,r.length=0},state:s,setupLights:function(){t.setup(i),r.sort((e,t)=>e.priority-t.priority||e.id-t.id)},setupLightsView:function(e){t.setupView(i,e)},pushLight:function(e){e.isLightProbeGrid?r.push(e):i.push(e)},pushShadow:function(e){n.push(e)}}}function qc(e){let t=new WeakMap;return{get:function(i,n=0){const r=t.get(i);let s;return void 0===r?(s=new Xc(e),t.set(i,[s])):n>=r.length?(s=new Xc(e),r.push(s)):s=r[n],s},dispose:function(){t=new WeakMap}}}const Yc=[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)],Kc=[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)],Zc=new mn,Qc=new Wi,Jc=new Wi;function eu(e,t,i){let n=new Gs;const r=new Vi,s=new Vi,a=new un,o=new Na,l=new Pa,c={},u=i.maxTextureSize,h={[z]:1,[G]:0,[V]:2},d=new Sa({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 Zr;f.setAttribute("position",new Fr(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,n){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 dn(r.x,r.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(n,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(n,null,s,p,m,null)}function b(t,i,n,r){let s=null;const a=!0===n.isPointLight?t.customDistanceMaterial:t.customDepthMaterial;if(void 0!==a)s=a;else if(s=!0===n.isPointLight?l:o,e.localClippingEnabled&&!0===i.clipShadows&&Array.isArray(i.clippingPlanes)&&0!==i.clippingPlanes.length||i.displacementMap&&0!==i.displacementScale||i.alphaMap&&i.alphaTest>0||i.map&&i.alphaTest>0||!0===i.alphaToCoverage){const e=s.uuid,t=i.uuid;let n=c[e];void 0===n&&(n={},c[e]=n);let r=n[t];void 0===r&&(r=s.clone(),n[t]=r,i.addEventListener("dispose",x)),s=r}if(s.visible=i.visible,s.wireframe=i.wireframe,s.side=3===r?null!==i.shadowSide?i.shadowSide:i.side:null!==i.shadowSide?i.shadowSide: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===n.isPointLight&&!0===s.isMeshDistanceMaterial){e.properties.get(s).light=n}return s}function y(i,r,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(n))){i.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,i.matrixWorld);const n=t.update(i),o=i.material;if(Array.isArray(o)){const t=n.groups;for(let c=0,u=t.length;c<u;c++){const u=t[c],h=o[u.materialIndex];if(h&&h.visible){const t=b(i,h,a,l);i.onBeforeShadow(e,i,r,s,n,t,u),e.renderBufferDirect(s,null,n,t,i,u),i.onAfterShadow(e,i,r,s,n,t,u)}}}else if(o.visible){const t=b(i,o,a,l);i.onBeforeShadow(e,i,r,s,n,t,null),e.renderBufferDirect(s,null,n,t,i,null),i.onAfterShadow(e,i,r,s,n,t,null)}}const c=i.children;for(let e=0,t=c.length;e<t;e++)y(c[e],r,s,a,o,l)}function x(e){e.target.removeEventListener("dispose",x);for(const t in c){const i=c[t],n=e.target.uuid;if(n in i){i[n].dispose(),delete i[n]}}}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(),c=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,c=t.length;l<c;l++){const c=t[l],h=c.shadow;if(void 0===h){Ti("WebGLShadowMap:",c,"has no shadow.");continue}if(!1===h.autoUpdate&&!1===h.needsUpdate)continue;r.copy(h.mapSize);const f=h.getFrameExtents();r.multiply(f),s.copy(h.mapSize),(r.x>u||r.y>u)&&(r.x>u&&(s.x=Math.floor(u/f.x),r.x=s.x*f.x,h.mapSize.x=s.x),r.y>u&&(s.y=Math.floor(u/f.y),r.y=s.y*f.y,h.mapSize.y=s.y));const m=e.state.buffers.depth.getReversed();if(h.camera._reversedDepth=m,null===h.map||!0===p){if(null!==h.map&&(null!==h.map.depthTexture&&(h.map.depthTexture.dispose(),h.map.depthTexture=null),h.map.dispose()),3===this.type){if(c.isPointLight){Ti("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}h.map=new dn(r.x,r.y,{format:at,type:Xe,minFilter:Oe,magFilter:Oe,generateMipmaps:!1}),h.map.texture.name=c.name+".shadowMap",h.map.depthTexture=new oa(r.x,r.y,$e),h.map.depthTexture.name=c.name+".shadowMapDepth",h.map.depthTexture.format=it,h.map.depthTexture.compareFunction=null,h.map.depthTexture.minFilter=Ie,h.map.depthTexture.magFilter=Ie}else c.isPointLight?(h.map=new zo(r.x),h.map.depthTexture=new la(r.x,je)):(h.map=new dn(r.x,r.y),h.map.depthTexture=new oa(r.x,r.y,je)),h.map.depthTexture.name=c.name+".shadowMap",h.map.depthTexture.format=it,1===this.type?(h.map.depthTexture.compareFunction=m?ri:ti,h.map.depthTexture.minFilter=Oe,h.map.depthTexture.magFilter=Oe):(h.map.depthTexture.compareFunction=null,h.map.depthTexture.minFilter=Ie,h.map.depthTexture.magFilter=Ie);h.camera.updateProjectionMatrix()}!0===h.map.isWebGLCubeRenderTarget||h.map.width===r.x&&h.map.height===r.y||h.map.setSize(r.x,r.y);const g=h.map.isWebGLCubeRenderTarget?6:h.getViewportCount();!0!==c.isPointLight&&h.updateMatrices(c,o);const _=4294967294&h.camera.layers.mask?h.camera.layers:o.layers;for(let t=0;t<g;t++){const r=h.getCamera(t);if(c.isPointLight){const e=h.camera,i=h.matrix,n=c.distance||e.far;n!==e.far&&(e.far=n,e.updateProjectionMatrix()),Qc.setFromMatrixPosition(c.matrixWorld),e.position.copy(Qc),Jc.copy(e.position),Jc.add(Yc[t]),e.up.copy(Kc[t]),e.lookAt(Jc),e.updateMatrixWorld(),i.makeTranslation(-Qc.x,-Qc.y,-Qc.z),Zc.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),h._frustum.setFromProjectionMatrix(Zc,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)}n=h.getFrustum(t),y(i,o,r,c,_,this.type)}!0!==h.isPointLightShadow&&3===this.type&&v(h,o),h.needsUpdate=!1}_=this.type,g.needsUpdate=!1,e.setRenderTarget(l,c,h)}}function tu(e,t){const i=new function(){let t=!1;const i=new un;let n=null;const r=new un(0,0,0,0);return{setMask:function(i){n===i||t||(e.colorMask(i,i,i,i),n=i)},setLocked:function(e){t=e},setClear:function(t,n,s,a,o){!0===o&&(t*=a,n*=a,s*=a),i.set(t,n,s,a),!1===r.equals(i)&&(e.clearColor(t,n,s,a),r.copy(i))},reset:function(){t=!1,n=null,r.set(-1,0,0,0)}}},n=new function(){let i=!1,n=!1,r=null,s=null,a=null;return{setReversed:function(e){if(n!==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),n=e;const r=a;a=null,this.setClear(r)}},getReversed:function(){return n},setTest:function(t){t?G(e.DEPTH_TEST):V(e.DEPTH_TEST)},setMask:function(t){r===t||i||(e.depthMask(t),r=t)},setFunc:function(t){if(n&&(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,n&&(t=1-t),e.clearDepth(t))},reset:function(){i=!1,r=null,s=null,a=null,n=!1}}},r=new function(){let t=!1,i=null,n=null,r=null,s=null,a=null,o=null,l=null,c=null;return{setTest:function(i){t||(i?G(e.STENCIL_TEST):V(e.STENCIL_TEST))},setMask:function(n){i===n||t||(e.stencilMask(n),i=n)},setFunc:function(t,i,a){n===t&&r===i&&s===a||(e.stencilFunc(t,i,a),n=t,r=i,s=a)},setOp:function(t,i,n){a===t&&o===i&&l===n||(e.stencilOp(t,i,n),a=t,o=i,l=n)},setLocked:function(e){t=e},setClear:function(t){c!==t&&(e.clearStencil(t),c=t)},reset:function(){t=!1,i=null,n=null,r=null,s=null,a=null,o=null,l=null,c=null}}};let s={};const a=new WeakMap;let o={},l={},c={},u=new WeakMap,h=[],d=null,p=!1,f=null,m=null,g=null,_=null,v=null,b=null,y=null,x=new Kn(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,I={};const F=e.getParameter(e.SCISSOR_BOX),U=e.getParameter(e.VIEWPORT),O=(new un).fromArray(F),B=(new un).fromArray(U);function k(t,i,n,r){const s=new Uint8Array(4),a=e.createTexture();e.bindTexture(t,a),e.texParameteri(t,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(t,e.TEXTURE_MAG_FILTER,e.NEAREST);for(let a=0;a<n;a++)t===e.TEXTURE_3D||t===e.TEXTURE_2D_ARRAY?e.texImage3D(i,0,e.RGBA,1,1,r,0,e.RGBA,e.UNSIGNED_BYTE,s):e.texImage2D(i+a,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,s);return a}const 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),n.setClear(1),r.setClear(0),G(e.DEPTH_TEST),n.setFunc(3),ue(!1),he(1),G(e.CULL_FACE),ce(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,[re]:e.SRC_ALPHA_SATURATE,[ie]:e.DST_COLOR,[ee]:e.DST_ALPHA,[Z]:e.ONE_MINUS_SRC_COLOR,[J]:e.ONE_MINUS_SRC_ALPHA,[ne]: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 ce(t,i,n,r,s,a,o,l,c,u){if(0!==t){if(!1===p&&(G(e.BLEND),p=!0),5===t)s=s||i,a=a||n,o=o||r,i===m&&s===v||(e.blendEquationSeparate($[i],$[s]),m=i,v=s),n===g&&r===_&&a===b&&o===y||(e.blendFuncSeparate(X[n],X[r],X[a],X[o]),g=n,_=r,b=a,y=o),!1!==l.equals(x)&&c===S||(e.blendColor(l.r,l.g,l.b,c),x.copy(l),S=c),f=t,T=!1;else if(t!==f||u!==T){if(m===H&&v===H||(e.blendEquation(e.FUNC_ADD),m=H,v=H),u)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=u}}else!0===p&&(V(e.BLEND),p=!1)}function ue(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,r){t?(G(e.POLYGON_OFFSET_FILL),A===i&&R===r||(A=i,R=r,n.getReversed()&&(i=-i,r=-r),e.polygonOffset(i,r))):V(e.POLYGON_OFFSET_FILL)}return{buffers:{color:i,depth:n,stencil:r},enable:G,disable:V,bindFramebuffer:function(t,i){return c[t]!==i&&(e.bindFramebuffer(t,i),c[t]=i,t===e.DRAW_FRAMEBUFFER&&(c[e.FRAMEBUFFER]=i),t===e.FRAMEBUFFER&&(c[e.DRAW_FRAMEBUFFER]=i),!0)},drawBuffers:function(t,i){let n=h,r=!1;if(t){n=u.get(i),void 0===n&&(n=[],u.set(i,n));const s=t.textures;if(n.length!==s.length||n[0]!==e.COLOR_ATTACHMENT0){for(let t=0,i=s.length;t<i;t++)n[t]=e.COLOR_ATTACHMENT0+t;n.length=s.length,r=!0}}else n[0]!==e.BACK&&(n[0]=e.BACK,r=!0);r&&e.drawBuffers(n)},useProgram:function(t){return d!==t&&(e.useProgram(t),d=t,!0)},setBlending:ce,setMaterial:function(t,s){2===t.side?V(e.CULL_FACE):G(e.CULL_FACE);let a=1===t.side;s&&(a=!a),ue(a),1===t.blending&&!1===t.transparent?ce(0):ce(t.blending,t.blendEquation,t.blendSrc,t.blendDst,t.blendEquationAlpha,t.blendSrcAlpha,t.blendDstAlpha,t.blendColor,t.blendAlpha,t.premultipliedAlpha),n.setFunc(t.depthFunc),n.setTest(t.depthTest),n.setMask(t.depthWrite),i.setMask(t.colorWrite);const o=t.stencilWrite;r.setTest(o),o&&(r.setMask(t.stencilWriteMask),r.setFunc(t.stencilFunc,t.stencilRef,t.stencilFuncMask),r.setOp(t.stencilFail,t.stencilZFail,t.stencilZPass)),de(t.polygonOffset,t.polygonOffsetFactor,t.polygonOffsetUnits),!0===t.alphaToCoverage?G(e.SAMPLE_ALPHA_TO_COVERAGE):V(e.SAMPLE_ALPHA_TO_COVERAGE)},setFlipSided:ue,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,n){void 0===n&&(n=null===D?e.TEXTURE0+C-1:D);let r=I[n];void 0===r&&(r={type:void 0,texture:void 0},I[n]=r),r.type===t&&r.texture===i||(D!==n&&(e.activeTexture(n),D=n),e.bindTexture(t,i||z[t]),r.type=t,r.texture=i)},unbindTexture:function(){const t=I[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 n=a.get(i);void 0===n&&(n=new WeakMap,a.set(i,n));let r=n.get(t);void 0===r&&(r=e.getUniformBlockIndex(i,t.name),e.uniformBlockBinding(i,r,r),n.set(t,r))},uniformBlockBinding:function(t,i,n){const r=a.get(i).get(t);s[r]!==n&&(e.bindBufferBase(e.UNIFORM_BUFFER,r,n),s[r]=n)},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),n.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,I={},c={},s={},u=new WeakMap,h=[],d=null,p=!1,f=null,m=null,g=null,_=null,v=null,b=null,y=null,x=new Kn(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(),n.reset(),r.reset()}}}function iu(e,t,i,n,r,s,a){const o=t.has("WEBGL_multisampled_render_to_texture")?t.get("WEBGL_multisampled_render_to_texture"):null,l="undefined"!=typeof navigator&&/OculusBrowser/g.test(navigator.userAgent),c=new Vi,u=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 n=1;const r=K(e);if((r.width>i||r.height>i)&&(n=i/Math.max(r.width,r.height)),n<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(n*r.width),s=Math.floor(n*r.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 ("+r.width+"x"+r.height+") to ("+i+"x"+s+")."),a}return"data"in e&&Ti("WebGLRenderer: Image in DataTexture is too big ("+r.width+"x"+r.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,n,r,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 c=n;if(n===e.RED&&(r===e.FLOAT&&(c=e.R32F),r===e.HALF_FLOAT&&(c=e.R16F),r===e.UNSIGNED_BYTE&&(c=e.R8),r===e.UNSIGNED_SHORT&&l&&(c=l.R16_EXT),r===e.SHORT&&l&&(c=l.R16_SNORM_EXT)),n===e.RED_INTEGER&&(r===e.UNSIGNED_BYTE&&(c=e.R8UI),r===e.UNSIGNED_SHORT&&(c=e.R16UI),r===e.UNSIGNED_INT&&(c=e.R32UI),r===e.BYTE&&(c=e.R8I),r===e.SHORT&&(c=e.R16I),r===e.INT&&(c=e.R32I)),n===e.RG&&(r===e.FLOAT&&(c=e.RG32F),r===e.HALF_FLOAT&&(c=e.RG16F),r===e.UNSIGNED_BYTE&&(c=e.RG8),r===e.UNSIGNED_SHORT&&l&&(c=l.RG16_EXT),r===e.SHORT&&l&&(c=l.RG16_SNORM_EXT)),n===e.RG_INTEGER&&(r===e.UNSIGNED_BYTE&&(c=e.RG8UI),r===e.UNSIGNED_SHORT&&(c=e.RG16UI),r===e.UNSIGNED_INT&&(c=e.RG32UI),r===e.BYTE&&(c=e.RG8I),r===e.SHORT&&(c=e.RG16I),r===e.INT&&(c=e.RG32I)),n===e.RGB_INTEGER&&(r===e.UNSIGNED_BYTE&&(c=e.RGB8UI),r===e.UNSIGNED_SHORT&&(c=e.RGB16UI),r===e.UNSIGNED_INT&&(c=e.RGB32UI),r===e.BYTE&&(c=e.RGB8I),r===e.SHORT&&(c=e.RGB16I),r===e.INT&&(c=e.RGB32I)),n===e.RGBA_INTEGER&&(r===e.UNSIGNED_BYTE&&(c=e.RGBA8UI),r===e.UNSIGNED_SHORT&&(c=e.RGBA16UI),r===e.UNSIGNED_INT&&(c=e.RGBA32UI),r===e.BYTE&&(c=e.RGBA8I),r===e.SHORT&&(c=e.RGBA16I),r===e.INT&&(c=e.RGBA32I)),n===e.RGB&&(r===e.UNSIGNED_SHORT&&l&&(c=l.RGB16_EXT),r===e.SHORT&&l&&(c=l.RGB16_SNORM_EXT),r===e.UNSIGNED_INT_5_9_9_9_REV&&(c=e.RGB9_E5),r===e.UNSIGNED_INT_10F_11F_11F_REV&&(c=e.R11F_G11F_B10F)),n===e.RGBA){const t=o?Yt:Qi.getTransfer(a);r===e.FLOAT&&(c=e.RGBA32F),r===e.HALF_FLOAT&&(c=e.RGBA16F),r===e.UNSIGNED_BYTE&&(c=t===Kt?e.SRGB8_ALPHA8:e.RGBA8),r===e.UNSIGNED_SHORT&&l&&(c=l.RGBA16_EXT),r===e.SHORT&&l&&(c=l.RGBA16_SNORM_EXT),r===e.UNSIGNED_SHORT_4_4_4_4&&(c=e.RGBA4),r===e.UNSIGNED_SHORT_5_5_5_1&&(c=e.RGB5_A1)}return c!==e.R16F&&c!==e.R32F&&c!==e.RG16F&&c!==e.RG32F&&c!==e.RGBA16F&&c!==e.RGBA32F||t.get("EXT_color_buffer_float"),c}function T(t,i){let n;return t?null===i||i===je||i===Ke?n=e.DEPTH24_STENCIL8:i===$e?n=e.DEPTH32F_STENCIL8:i===He&&(n=e.DEPTH24_STENCIL8,Ti("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):null===i||i===je||i===Ke?n=e.DEPTH_COMPONENT24:i===$e?n=e.DEPTH_COMPONENT32F:i===He&&(n=e.DEPTH_COMPONENT16),n}function M(e,t){return!0===b(e)||e.isFramebufferTexture&&e.minFilter!==Ie&&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);n.get(e).__ref=t,f.add(t),m.register(e,t,t)}function w(e){const t=n.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=n.get(e);if(void 0===t.__webglInit)return;const i=e.source,r=p.get(i);if(r){const n=r[t.__cacheKey];n.usedTimes--,0===n.usedTimes&&P(e),0===Object.keys(r).length&&p.delete(i)}n.remove(e)}(e),e.isVideoTexture&&u.delete(e),e.isHTMLTexture&&h.delete(e)}function N(t){t.removeEventListener("dispose",R),w(t),function(t){const i=n.get(t);i.__depthDisposeCallback&&i.__depthDisposeCallback();const r=t.depthTexture;r&&r.renderTarget===t&&C(r);if(t.isWebGLCubeRenderTarget)for(let t=0;t<6;t++){if(Array.isArray(i.__webglFramebuffer[t]))for(let n=0;n<i.__webglFramebuffer[t].length;n++)e.deleteFramebuffer(i.__webglFramebuffer[t][n]);else e.deleteFramebuffer(i.__webglFramebuffer[t]);i.__webglDepthbuffer&&e.deleteRenderbuffer(i.__webglDepthbuffer[t])}else{if(Array.isArray(i.__webglFramebuffer))for(let t=0;t<i.__webglFramebuffer.length;t++)e.deleteFramebuffer(i.__webglFramebuffer[t]);else e.deleteFramebuffer(i.__webglFramebuffer);if(i.__webglDepthbuffer&&e.deleteRenderbuffer(i.__webglDepthbuffer),i.__webglMultisampledFramebuffer&&e.deleteFramebuffer(i.__webglMultisampledFramebuffer),i.__webglColorRenderbuffer)for(let t=0;t<i.__webglColorRenderbuffer.length;t++)i.__webglColorRenderbuffer[t]&&e.deleteRenderbuffer(i.__webglColorRenderbuffer[t]);i.__webglDepthRenderbuffer&&e.deleteRenderbuffer(i.__webglDepthRenderbuffer)}const s=t.textures;for(let t=0,i=s.length;t<i;t++){const i=n.get(s[t]);i.__webglTexture&&(e.deleteTexture(i.__webglTexture),a.memory.textures--),n.remove(s[t])}n.remove(t)}(t)}function P(t){const i=n.get(t);e.deleteTexture(i.__webglTexture);const r=t.source;delete p.get(r)[i.__cacheKey],a.memory.textures--}let L=0;function D(t,r){const s=n.get(t);if(t.isVideoTexture&&function(e){const t=a.render.frame;u.get(e)!==t&&(u.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,r);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+r)}function I(t,a){const o=n.get(t);t.version>0&&o.__version!==t.version?function(t,a,o){if(6!==a.image.length)return;const l=k(t,a),c=a.source;i.bindTexture(e.TEXTURE_CUBE_MAP,t.__webglTexture,e.TEXTURE0+o);const u=n.get(c);if(c.version!==u.__version||!0===l){i.activeTexture(e.TEXTURE0+o);const t=Qi.getPrimaries(Qi.workingColorSpace),n=a.colorSpace===$t?null:Qi.getPrimaries(a.colorSpace),h=a.colorSpace===$t||t===n?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,r.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===u.__version||!0===l,A=c.dataReady;let R,C=M(a,m);if(B(e.TEXTURE_CUBE_MAP,a),a.isDepthTexture){if(x=T(a.format===nt,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 n=0;n<R.length;n++){const r=R[n];a.format!==tt?null!==g?E?A&&i.compressedTexSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,n,0,0,r.width,r.height,g,r.data):i.compressedTexImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,n,x,r.width,r.height,0,r.data):Ti("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):E?A&&i.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,n,0,0,r.width,r.height,g,_,r.data):i.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,n,x,r.width,r.height,0,g,_,r.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 n=0;n<R.length;n++){const r=R[n].image[t].image;E?A&&i.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,n+1,0,0,r.width,r.height,g,_,r.data):i.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,n+1,x,r.width,r.height,0,g,_,r.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 n=0;n<R.length;n++){const r=R[n];E?A&&i.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,n+1,0,0,g,_,r.image[t]):i.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,n+1,x,g,_,r.image[t])}}}b(a)&&!0===a.mipmapsAutoUpdate&&y(e.TEXTURE_CUBE_MAP),u.__version=c.version,a.onUpdate&&a.onUpdate(a)}t.__version=a.version}(o,t,a):i.bindTexture(e.TEXTURE_CUBE_MAP,o.__webglTexture,e.TEXTURE0+a)}const F={[Pe]:e.REPEAT,[Le]:e.CLAMP_TO_EDGE,[De]:e.MIRRORED_REPEAT},U={[Ie]:e.NEAREST,[Fe]:e.NEAREST_MIPMAP_NEAREST,[Ue]: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,[ri]:e.GEQUAL,[ii]:e.GREATER,[ni]: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!==Ue&&s.magFilter!==ke&&s.minFilter!==Oe&&s.minFilter!==Be&&s.minFilter!==Ue&&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,F[s.wrapS]),e.texParameteri(i,e.TEXTURE_WRAP_T,F[s.wrapT]),i!==e.TEXTURE_3D&&i!==e.TEXTURE_2D_ARRAY||e.texParameteri(i,e.TEXTURE_WRAP_R,F[s.wrapR]),e.texParameteri(i,e.TEXTURE_MAG_FILTER,U[s.magFilter]),e.texParameteri(i,e.TEXTURE_MIN_FILTER,U[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===Ie)return;if(s.minFilter!==Ue&&s.minFilter!==ke)return;if(s.type===$e&&!1===t.has("OES_texture_float_linear"))return;if(s.anisotropy>1||n.get(s).__currentAnisotropy){const a=t.get("EXT_texture_filter_anisotropic");e.texParameterf(i,a.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(s.anisotropy,r.getMaxAnisotropy())),n.get(s).__currentAnisotropy=s.anisotropy}}}function k(t,i){let n=!1;void 0===t.__webglInit&&(t.__webglInit=!0,i.addEventListener("dispose",A),E(i));const r=i.source;let s=p.get(r);void 0===s&&(s={},p.set(r,s));const o=function(e){const t=[];return t.push(e.wrapS),t.push(e.wrapT),t.push(e.wrapR||0),t.push(e.magFilter),t.push(e.minFilter),t.push(e.anisotropy),t.push(e.internalFormat),t.push(e.format),t.push(e.type),t.push(e.generateMipmaps),t.push(e.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++,n=!0),s[o].usedTimes++;const r=s[t.__cacheKey];void 0!==r&&(s[t.__cacheKey].usedTimes--,0===r.usedTimes&&P(i)),t.__cacheKey=o,t.__webglTexture=s[o].texture}return n}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 c=k(t,a),u=a.source;i.bindTexture(l,t.__webglTexture,e.TEXTURE0+o);const d=n.get(u);if(u.version!==d.__version||!0===c){i.activeTexture(e.TEXTURE0+o);if(!1===("undefined"!=typeof ImageBitmap&&a.image instanceof ImageBitmap)){const t=Qi.getPrimaries(Qi.workingColorSpace),n=a.colorSpace===$t?null:Qi.getPrimaries(a.colorSpace),r=a.colorSpace===$t||t===n?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,r)}i.pixelStorei(e.UNPACK_ALIGNMENT,a.unpackAlignment);let t=v(a.image,!1,r.maxTextureSize);t=Y(a,t);const n=s.convert(a.format,a.colorSpace),p=s.convert(a.type);let f,m=S(a.internalFormat,n,p,a.normalized,a.colorSpace,a.isVideoTexture);B(l,a);const g=a.mipmaps,_=!0!==a.isVideoTexture,x=void 0===d.__version||!0===c,E=u.dataReady,w=M(a,t);if(a.isDepthTexture)m=T(a.format===nt,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,n,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,r=g.length;t<r;t++)f=g[t],_?E&&i.texSubImage2D(e.TEXTURE_2D,t,0,0,f.width,f.height,n,p,f.data):i.texImage2D(e.TEXTURE_2D,t,m,f.width,f.height,0,n,p,f.data);a.generateMipmaps=!1}else _?(x&&i.texStorage2D(e.TEXTURE_2D,w,m,t.width,t.height),E&&function(t,n,r,s){const a=t.updateRanges;if(0===a.length)i.texSubImage2D(e.TEXTURE_2D,0,0,0,n.width,n.height,r,s,n.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],r=t.start+t.count,s=z(i.start,n.width,4),l=z(t.start,n.width,4);i.start<=r+1&&s===l&&z(i.start+i.count-1,n.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),c=i.getParameter(e.UNPACK_SKIP_PIXELS),u=i.getParameter(e.UNPACK_SKIP_ROWS);i.pixelStorei(e.UNPACK_ROW_LENGTH,n.width);for(let t=0,o=a.length;t<o;t++){const o=a[t],l=Math.floor(o.start/4),c=Math.ceil(o.count/4),u=l%n.width,h=Math.floor(l/n.width),d=c,p=1;i.pixelStorei(e.UNPACK_SKIP_PIXELS,u),i.pixelStorei(e.UNPACK_SKIP_ROWS,h),i.texSubImage2D(e.TEXTURE_2D,0,u,h,d,p,r,s,n.data)}t.clearUpdateRanges(),i.pixelStorei(e.UNPACK_ROW_LENGTH,l),i.pixelStorei(e.UNPACK_SKIP_PIXELS,c),i.pixelStorei(e.UNPACK_SKIP_ROWS,u)}}(a,t,n,p)):i.texImage2D(e.TEXTURE_2D,0,m,t.width,t.height,0,n,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 r=0,s=g.length;r<s;r++)if(f=g[r],a.format!==tt)if(null!==n)if(_){if(E)if(a.layerUpdates.size>0){const t=wo(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,r,0,0,s,f.width,f.height,1,n,a)}}else i.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,r,0,0,0,f.width,f.height,t.depth,n,f.data)}else i.compressedTexImage3D(e.TEXTURE_2D_ARRAY,r,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,r,0,0,0,f.width,f.height,t.depth,n,p,f.data):i.texImage3D(e.TEXTURE_2D_ARRAY,r,m,f.width,f.height,t.depth,0,n,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,r=g.length;t<r;t++)f=g[t],a.format!==tt?null!==n?_?E&&i.compressedTexSubImage2D(e.TEXTURE_2D,t,0,0,f.width,f.height,n,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,n,p,f.data):i.texImage2D(e.TEXTURE_2D,t,m,f.width,f.height,0,n,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 r=wo(t.width,t.height,a.format,a.type);for(const s of a.layerUpdates){const a=t.data.subarray(s*r/t.data.BYTES_PER_ELEMENT,(s+1)*r/t.data.BYTES_PER_ELEMENT);i.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,s,t.width,t.height,1,n,p,a)}a.clearLayerUpdates()}else i.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,t.width,t.height,t.depth,n,p,t.data)}else i.texImage3D(e.TEXTURE_2D_ARRAY,0,m,t.width,t.height,t.depth,0,n,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,n,p,t.data)):i.texImage3D(e.TEXTURE_3D,0,m,t.width,t.height,t.depth,0,n,p,t.data);else if(a.isFramebufferTexture){if(x)if(_)i.texStorage2D(e.TEXTURE_2D,w,m,t.width,t.height);else{let r=t.width,s=t.height;for(let t=0;t<w;t++)i.texImage2D(e.TEXTURE_2D,t,m,r,s,0,n,p,null),r>>=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,n=e.RGBA,r=e.RGBA,s=e.UNSIGNED_BYTE;e.texElementImage2D(e.TEXTURE_2D,i,n,r,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,r=g.length;t<r;t++)f=g[t],_?E&&i.texSubImage2D(e.TEXTURE_2D,t,0,0,n,p,f):i.texImage2D(e.TEXTURE_2D,t,m,n,p,f);a.generateMipmaps=!1}else if(_){if(x){const n=K(t);i.texStorage2D(e.TEXTURE_2D,w,m,n.width,n.height)}E&&i.texSubImage2D(e.TEXTURE_2D,0,0,0,n,p,t)}else i.texImage2D(e.TEXTURE_2D,0,m,n,p,t);b(a)&&!0===a.mipmapsAutoUpdate&&y(l),d.__version=u.version,a.onUpdate&&a.onUpdate(a)}t.__version=a.version}function V(t,r,a,l,c,u){const h=s.convert(a.format,a.colorSpace),d=s.convert(a.type),p=S(a.internalFormat,h,d,a.normalized,a.colorSpace),f=n.get(r),m=n.get(a);if(m.__renderTarget=r,!f.__hasExternalTextures){const t=Math.max(1,r.width>>u),n=Math.max(1,r.height>>u);c===e.TEXTURE_3D||c===e.TEXTURE_2D_ARRAY?i.texImage3D(c,u,p,t,n,r.depth,0,h,d,null):i.texImage2D(c,u,p,t,n,0,h,d,null)}i.bindFramebuffer(e.FRAMEBUFFER,t),q(r)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,l,c,m.__webglTexture,0,X(r)):(c===e.TEXTURE_2D||c>=e.TEXTURE_CUBE_MAP_POSITIVE_X&&c<=e.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&e.framebufferTexture2D(e.FRAMEBUFFER,l,c,m.__webglTexture,u),i.bindFramebuffer(e.FRAMEBUFFER,null)}function H(t,i,n){if(e.bindRenderbuffer(e.RENDERBUFFER,t),i.depthBuffer){const r=i.depthTexture,s=r&&r.isDepthTexture?r.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):n?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 r=0;r<t.length;r++){const a=t[r],l=s.convert(a.format,a.colorSpace),c=s.convert(a.type),u=S(a.internalFormat,l,c,a.normalized,a.colorSpace);q(i)?o.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,X(i),u,i.width,i.height):n?e.renderbufferStorageMultisample(e.RENDERBUFFER,X(i),u,i.width,i.height):e.renderbufferStorage(e.RENDERBUFFER,u,i.width,i.height)}}e.bindRenderbuffer(e.RENDERBUFFER,null)}function W(t,r,s){const a=!0===r.isWebGLCubeRenderTarget;if(i.bindFramebuffer(e.FRAMEBUFFER,t),!r.depthTexture||!r.depthTexture.isDepthTexture)throw new Error("THREE.WebGLTextures: renderTarget.depthTexture must be an instance of THREE.DepthTexture.");const l=n.get(r.depthTexture);l.__renderTarget=r;const c=a?r.depthTexture.image[0]:r.depthTexture.image;l.__webglTexture&&c.width===r.width&&c.height===r.height||(c.width=r.width,c.height=r.height,r.depthTexture.needsUpdate=!0),a?I(r.depthTexture,0):D(r.depthTexture,0);const u=l.__webglTexture,h=X(r),d=a?e.TEXTURE_CUBE_MAP_POSITIVE_X+s:e.TEXTURE_2D,p=r.depthTexture.format===nt?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;if(r.depthTexture.format===it)q(r)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,p,d,u,0,h):e.framebufferTexture2D(e.FRAMEBUFFER,p,d,u,0);else{if(r.depthTexture.format!==nt)throw new Error("THREE.WebGLTextures: Unknown depthTexture format.");q(r)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,p,d,u,0,h):e.framebufferTexture2D(e.FRAMEBUFFER,p,d,u,0)}}function j(t){const r=n.get(t),s=!0===t.isWebGLCubeRenderTarget;if(r.__boundDepthTexture!==t.depthTexture){const e=t.depthTexture;if(r.__depthDisposeCallback&&r.__depthDisposeCallback(),e){const t=()=>{delete r.__boundDepthTexture,delete r.__depthDisposeCallback,e.removeEventListener("dispose",t)};e.addEventListener("dispose",t),r.__depthDisposeCallback=t}r.__boundDepthTexture=e}if(t.depthTexture&&!r.__autoAllocateDepthBuffer)if(s)for(let e=0;e<6;e++)W(r.__webglFramebuffer[e],t,e);else{t.texture.mipmaps.length>0?W(r.__webglFramebuffer[0],t,0):W(r.__webglFramebuffer,t,0)}else if(s){r.__webglDepthbuffer=[];for(let n=0;n<6;n++)if(i.bindFramebuffer(e.FRAMEBUFFER,r.__webglFramebuffer[n]),void 0===r.__webglDepthbuffer[n])r.__webglDepthbuffer[n]=e.createRenderbuffer(),H(r.__webglDepthbuffer[n],t,!1);else{const i=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,s=r.__webglDepthbuffer[n];e.bindRenderbuffer(e.RENDERBUFFER,s),e.framebufferRenderbuffer(e.FRAMEBUFFER,i,e.RENDERBUFFER,s)}}else{if(t.texture.mipmaps.length>0?i.bindFramebuffer(e.FRAMEBUFFER,r.__webglFramebuffer[0]):i.bindFramebuffer(e.FRAMEBUFFER,r.__webglFramebuffer),void 0===r.__webglDepthbuffer)r.__webglDepthbuffer=e.createRenderbuffer(),H(r.__webglDepthbuffer,t,!1);else{const i=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,n=r.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,n),e.framebufferRenderbuffer(e.FRAMEBUFFER,i,e.RENDERBUFFER,n)}}i.bindFramebuffer(e.FRAMEBUFFER,null)}const $=[];function X(e){return Math.min(r.maxSamples,e.samples)}function q(e){const i=n.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,n=e.format,r=e.type;return!0===e.isCompressedTexture||!0===e.isVideoTexture||i!==qt&&i!==$t&&(Qi.getTransfer(i)===Kt?n===tt&&r===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?(c.width=e.naturalWidth||e.width,c.height=e.naturalHeight||e.height):"undefined"!=typeof VideoFrame&&e instanceof VideoFrame?(c.width=e.displayWidth,c.height=e.displayHeight):(c.width=e.width,c.height=e.height),c}this.allocateTextureUnit=function(){const e=L;return e>=r.maxTextures&&Ti("WebGLTextures: Trying to use "+(e+1)+" texture units while this GPU supports only "+r.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,r){const s=n.get(t);!1===t.isRenderTargetTexture&&t.version>0&&s.__version!==t.version?G(s,t,r):(t.isExternalTexture&&(s.__webglTexture=t.sourceTexture?t.sourceTexture:null),i.bindTexture(e.TEXTURE_2D_ARRAY,s.__webglTexture,e.TEXTURE0+r))},this.setTexture3D=function(t,r){const s=n.get(t);!1===t.isRenderTargetTexture&&t.version>0&&s.__version!==t.version?G(s,t,r):i.bindTexture(e.TEXTURE_3D,s.__webglTexture,e.TEXTURE0+r)},this.setTextureCube=I,this.rebindTextures=function(t,i,r){const s=n.get(t);void 0!==i&&V(s.__webglFramebuffer,t,t.texture,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,0),void 0!==r&&j(t)},this.setupRenderTarget=function(t){const r=t.texture,o=n.get(t),l=n.get(r);t.addEventListener("dispose",R),E(t);const c=t.textures,u=!0===t.isWebGLCubeRenderTarget,h=c.length>1;if(h||(void 0===l.__webglTexture&&(l.__webglTexture=e.createTexture()),l.__version=r.version,a.memory.textures++),u){o.__webglFramebuffer=[];for(let t=0;t<6;t++)if(r.mipmaps.length>0){o.__webglFramebuffer[t]=[];for(let i=0;i<r.mipmaps.length;i++)o.__webglFramebuffer[t][i]=e.createFramebuffer()}else o.__webglFramebuffer[t]=e.createFramebuffer()}else{if(r.mipmaps.length>0){o.__webglFramebuffer=[];for(let t=0;t<r.mipmaps.length;t++)o.__webglFramebuffer[t]=e.createFramebuffer()}else o.__webglFramebuffer=e.createFramebuffer();if(h)for(let t=0,i=c.length;t<i;t++){const i=n.get(c[t]);void 0===i.__webglTexture&&(i.__webglTexture=e.createTexture(),a.memory.textures++)}if(t.samples>0&&!1===q(t)){o.__webglMultisampledFramebuffer=e.createFramebuffer(),o.__webglColorRenderbuffer=[],i.bindFramebuffer(e.FRAMEBUFFER,o.__webglMultisampledFramebuffer);for(let i=0;i<c.length;i++){const n=c[i];o.__webglColorRenderbuffer[i]=e.createRenderbuffer(),e.bindRenderbuffer(e.RENDERBUFFER,o.__webglColorRenderbuffer[i]);const r=s.convert(n.format,n.colorSpace),a=s.convert(n.type),l=S(n.internalFormat,r,a,n.normalized,n.colorSpace,!0===t.isXRRenderTarget),u=X(t);e.renderbufferStorageMultisample(e.RENDERBUFFER,u,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(u){i.bindTexture(e.TEXTURE_CUBE_MAP,l.__webglTexture),B(e.TEXTURE_CUBE_MAP,r);for(let i=0;i<6;i++)if(r.mipmaps.length>0)for(let n=0;n<r.mipmaps.length;n++)V(o.__webglFramebuffer[i][n],t,r,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+i,n);else V(o.__webglFramebuffer[i],t,r,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+i,0);b(r)?y(e.TEXTURE_CUBE_MAP):r.mipmaps.length>0&&e.texParameteri(e.TEXTURE_CUBE_MAP,e.TEXTURE_MAX_LEVEL,r.mipmaps.length-1),i.unbindTexture()}else if(h){for(let r=0,s=c.length;r<s;r++){const s=c[r],a=n.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+r,l,0),b(s)&&y(l)}i.unbindTexture()}else{let n=e.TEXTURE_2D;if((t.isWebGL3DRenderTarget||t.isWebGLArrayRenderTarget)&&(n=t.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),i.bindTexture(n,l.__webglTexture),B(n,r),r.mipmaps.length>0)for(let i=0;i<r.mipmaps.length;i++)V(o.__webglFramebuffer[i],t,r,e.COLOR_ATTACHMENT0,n,i);else V(o.__webglFramebuffer,t,r,e.COLOR_ATTACHMENT0,n,0);b(r)?y(n):r.mipmaps.length>0&&e.texParameteri(n,e.TEXTURE_MAX_LEVEL,r.mipmaps.length-1),i.unbindTexture()}t.depthBuffer&&j(t)},this.updateRenderTargetMipmap=function(e){const t=e.textures;for(let r=0,s=t.length;r<s;r++){const s=t[r];if(b(s)&&!0===s.mipmapsAutoUpdate){const t=x(e),r=n.get(s).__webglTexture;i.bindTexture(t,r),y(t),i.unbindTexture()}}},this.updateMultisampleRenderTarget=function(t){if(t.samples>0)if(!1===q(t)){const r=t.textures,s=t.width,a=t.height;let o=e.COLOR_BUFFER_BIT;const c=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,u=n.get(t),h=r.length>1;if(h)for(let t=0;t<r.length;t++)i.bindFramebuffer(e.FRAMEBUFFER,u.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,null),i.bindFramebuffer(e.FRAMEBUFFER,u.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,null,0);i.bindFramebuffer(e.READ_FRAMEBUFFER,u.__webglMultisampledFramebuffer);t.texture.mipmaps.length>0?i.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__webglFramebuffer[0]):i.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__webglFramebuffer);for(let i=0;i<r.length;i++){if(t.resolveDepthBuffer&&(t.depthBuffer&&(o|=e.DEPTH_BUFFER_BIT),t.stencilBuffer&&t.resolveStencilBuffer&&(o|=e.STENCIL_BUFFER_BIT)),h){e.framebufferRenderbuffer(e.READ_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.RENDERBUFFER,u.__webglColorRenderbuffer[i]);const t=n.get(r[i]).__webglTexture;e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)}e.blitFramebuffer(0,0,s,a,0,0,s,a,o,e.NEAREST),!0===l&&($.length=0,$.push(e.COLOR_ATTACHMENT0+i),t.depthBuffer&&!1===t.storeMultisampledDepthBuffer&&$.push(c),e.invalidateFramebuffer(e.READ_FRAMEBUFFER,$))}if(i.bindFramebuffer(e.READ_FRAMEBUFFER,null),i.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),h)for(let t=0;t<r.length;t++){i.bindFramebuffer(e.FRAMEBUFFER,u.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,u.__webglColorRenderbuffer[t]);const s=n.get(r[t]).__webglTexture;i.bindFramebuffer(e.FRAMEBUFFER,u.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,s,0)}i.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__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 nu(e,t){return{convert:function(i,n=""){let r;const s=Qi.getTransfer(n);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===nt)return e.DEPTH_STENCIL;if(i===rt)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===ct)return e.RGBA_INTEGER;if(i===ut||i===ht||i===dt||i===pt)if(s===Kt){if(r=t.get("WEBGL_compressed_texture_s3tc_srgb"),null===r)return null;if(i===ut)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===ht)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===dt)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===pt)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(r=t.get("WEBGL_compressed_texture_s3tc"),null===r)return null;if(i===ut)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===ht)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===dt)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===pt)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(i===ft||i===mt||i===gt||i===_t){if(r=t.get("WEBGL_compressed_texture_pvrtc"),null===r)return null;if(i===ft)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===mt)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===gt)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===_t)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(i===vt||i===bt||i===yt||i===xt||i===St||i===Tt||i===Mt){if(r=t.get("WEBGL_compressed_texture_etc"),null===r)return null;if(i===vt||i===bt)return s===Kt?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(i===yt)return s===Kt?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC;if(i===xt)return r.COMPRESSED_R11_EAC;if(i===St)return r.COMPRESSED_SIGNED_R11_EAC;if(i===Tt)return r.COMPRESSED_RG11_EAC;if(i===Mt)return r.COMPRESSED_SIGNED_RG11_EAC}if(i===Et||i===wt||i===At||i===Rt||i===Ct||i===Nt||i===Pt||i===Lt||i===Dt||i===It||i===Ft||i===Ut||i===Ot||i===Bt){if(r=t.get("WEBGL_compressed_texture_astc"),null===r)return null;if(i===Et)return s===Kt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===wt)return s===Kt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===At)return s===Kt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===Rt)return s===Kt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===Ct)return s===Kt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===Nt)return s===Kt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===Pt)return s===Kt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===Lt)return s===Kt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===Dt)return s===Kt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===It)return s===Kt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===Ft)return s===Kt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===Ut)return s===Kt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===Ot)return s===Kt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===Bt)return s===Kt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}if(i===kt||i===zt||i===Gt){if(r=t.get("EXT_texture_compression_bptc"),null===r)return null;if(i===kt)return s===Kt?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===zt)return r.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===Gt)return r.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}if(i===Vt||i===Ht||i===Wt||i===jt){if(r=t.get("EXT_texture_compression_rgtc"),null===r)return null;if(i===Vt)return r.COMPRESSED_RED_RGTC1_EXT;if(i===Ht)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===Wt)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===jt)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}return i===Ke?e.UNSIGNED_INT_24_8:void 0!==e[i]?e[i]:null}}}class ru{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(null===this.texture){const i=new ca(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 Sa({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 fa(20,20),i)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class su extends Ri{constructor(e,t){super();const i=this;let n=null,r=1,s=null,a="local-floor",o=1,l=null,c=null,u=null,h=null,d=null,p=null;const f="undefined"!=typeof XRWebGLBinding,m=new ru,g={},_=t.getContextAttributes();let v=null,b=null;const y=[],x=[],S=new Vi;let T=null,M=null;const E=new eo;E.viewport=new un;const w=new eo;w.viewport=new un;const A=[E,w],R=new mo;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(){n.removeEventListener("select",P),n.removeEventListener("selectstart",P),n.removeEventListener("selectend",P),n.removeEventListener("squeeze",P),n.removeEventListener("squeezestart",P),n.removeEventListener("squeezeend",P),n.removeEventListener("end",L),n.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,u=null,n=null,b=null,U.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],n=x.indexOf(i);n>=0&&(x[n]=null,y[n].disconnect(i))}for(let t=0;t<e.added.length;t++){const i=e.added[t];let n=x.indexOf(i);if(-1===n){for(let e=0;e<y.length;e++){if(e>=x.length){x.push(i),n=e;break}if(null===x[e]){x[e]=i,n=e;break}}if(-1===n)break}const r=y[n];r&&r.connect(i)}}function I(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 jn,y[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=y[e];return void 0===t&&(t=new jn,y[e]=t),t.getGripSpace()},this.getHand=function(e){let t=y[e];return void 0===t&&(t=new jn,y[e]=t),t.getHandSpace()},this.setFramebufferScaleFactor=function(e){r=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===u&&f&&(u=new XRWebGLBinding(n,t)),u},this.getFrame=function(){return p},this.getSession=function(){return n},this.setSession=async function(c){if(n=c,null!==n){v=e.getRenderTarget(),n.addEventListener("select",P),n.addEventListener("selectstart",P),n.addEventListener("selectend",P),n.addEventListener("squeeze",P),n.addEventListener("squeezestart",P),n.addEventListener("squeezeend",P),n.addEventListener("end",L),n.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?nt:it,s=_.stencil?Ke:je);const o={colorFormat:t.RGBA8,depthFormat:a,scaleFactor:r};u=this.getBinding(),h=u.createProjectionLayer(o),n.updateRenderState({layers:[h]}),e.setPixelRatio(1),e.setSize(h.textureWidth,h.textureHeight,!1),b=new dn(h.textureWidth,h.textureHeight,{format:tt,type:ze,depthTexture:new oa(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:r};d=new XRWebGLLayer(n,t,i),n.updateRenderState({baseLayer:d}),e.setPixelRatio(1),e.setSize(d.framebufferWidth,d.framebufferHeight,!1),b=new dn(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 n.requestReferenceSpace(a),U.setContext(n),U.start(),i.isPresenting=!0,i.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(null!==n)return n.environmentBlendMode},this.getDepthTexture=function(){return m.getDepthTexture()},this.updateCamera=function(e){if(null===n)return;let t=e.near,i=e.far;null!==m.texture&&(m.depthNear>0&&(t=m.depthNear),m.depthFar>0&&(i=m.depthFar)),R.near=w.near=E.near=t,R.far=w.far=E.far=i,C===R.near&&N===R.far||(n.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 r=e.parent,s=R.cameras;I(R,r);for(let e=0;e<s.length;e++)I(s[e],r);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,r)},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 F=null;const U=new Ao;U.setAnimationLoop(function(t,r){if(c=r.getViewerPose(l||s),p=r,null!==c){const t=c.views;null!==d&&(e.setRenderTargetFramebuffer(b,d.framebuffer),e.setRenderTarget(b));let r=!1;t.length!==R.cameras.length&&(R.cameras.length=0,r=!0);for(let i=0;i<t.length;i++){const n=t[i];let s=null;if(null!==d)s=d.getViewport(n);else{const t=u.getViewSubImage(h,n);s=t.viewport,0===i&&(e.setRenderTargetTextures(b,t.colorTexture,t.depthStencilTexture),e.setRenderTarget(b))}let a=A[i];void 0===a&&(a=new eo,a.layers.enable(i),a.viewport=new un,A[i]=a),a.matrix.fromArray(n.transform.matrix),a.matrix.decompose(a.position,a.quaternion,a.scale),a.projectionMatrix.fromArray(n.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===r&&R.cameras.push(a)}const s=n.enabledFeatures;if(s&&s.includes("depth-sensing")&&"gpu-optimized"==n.depthUsage&&f){u=i.getBinding();const e=u.getDepthInformation(t[0]);e&&e.isValid&&e.texture&&m.init(e,n.renderState)}if(s&&s.includes("camera-access")&&f){e.state.unbindTexture(),u=i.getBinding();for(let e=0;e<t.length;e++){const i=t[e].camera;if(i){let e=g[i];e||(e=new ca,g[i]=e);const t=u.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,r,l||s)}F&&F(t,r),r.detectedPlanes&&i.dispatchEvent({type:"planesdetected",data:r}),p=null}),this.setAnimationLoop=function(e){F=e},this.dispose=function(){}}}const au=new mn,ou=new Xi;function lu(e,t){function i(e,t){!0===e.matrixAutoUpdate&&e.updateMatrix(),t.value.copy(e.matrix)}function n(e,n){e.opacity.value=n.opacity,n.color&&e.diffuse.value.copy(n.color),n.emissive&&e.emissive.value.copy(n.emissive).multiplyScalar(n.emissiveIntensity),n.map&&(e.map.value=n.map,i(n.map,e.mapTransform)),n.alphaMap&&(e.alphaMap.value=n.alphaMap,i(n.alphaMap,e.alphaMapTransform)),n.bumpMap&&(e.bumpMap.value=n.bumpMap,i(n.bumpMap,e.bumpMapTransform),e.bumpScale.value=n.bumpScale,1===n.side&&(e.bumpScale.value*=-1)),n.normalMap&&(e.normalMap.value=n.normalMap,i(n.normalMap,e.normalMapTransform),e.normalScale.value.copy(n.normalScale),1===n.side&&e.normalScale.value.negate()),n.displacementMap&&(e.displacementMap.value=n.displacementMap,i(n.displacementMap,e.displacementMapTransform),e.displacementScale.value=n.displacementScale,e.displacementBias.value=n.displacementBias),n.emissiveMap&&(e.emissiveMap.value=n.emissiveMap,i(n.emissiveMap,e.emissiveMapTransform)),n.specularMap&&(e.specularMap.value=n.specularMap,i(n.specularMap,e.specularMapTransform)),n.alphaTest>0&&(e.alphaTest.value=n.alphaTest);const r=t.get(n),s=r.envMap,a=r.envMapRotation;s&&(e.envMap.value=s,e.envMapRotation.value.setFromMatrix4(au.makeRotationFromEuler(a)).transpose(),s.isCubeTexture&&!1===s.isRenderTargetTexture&&e.envMapRotation.value.premultiply(ou),e.reflectivity.value=n.reflectivity,e.ior.value=n.ior,e.refractionRatio.value=n.refractionRatio),n.lightMap&&(e.lightMap.value=n.lightMap,e.lightMapIntensity.value=n.lightMapIntensity,i(n.lightMap,e.lightMapTransform)),n.aoMap&&(e.aoMap.value=n.aoMap,e.aoMapIntensity.value=n.aoMapIntensity,i(n.aoMap,e.aoMapTransform))}return{refreshFogUniforms:function(t,i){i.color.getRGB(t.fogColor.value,ya(e)),i.isFog?(t.fogNear.value=i.near,t.fogFar.value=i.far):i.isFogExp2&&(t.fogDensity.value=i.density)},refreshMaterialUniforms:function(e,r,s,a,o){r.isNodeMaterial?r.uniformsNeedUpdate=!1:r.isMeshBasicMaterial?n(e,r):r.isMeshLambertMaterial?(n(e,r),r.envMap&&(e.envMapIntensity.value=r.envMapIntensity)):r.isMeshToonMaterial?(n(e,r),function(e,t){t.gradientMap&&(e.gradientMap.value=t.gradientMap)}(e,r)):r.isMeshPhongMaterial?(n(e,r),function(e,t){e.specular.value.copy(t.specular),e.shininess.value=Math.max(t.shininess,1e-4)}(e,r),r.envMap&&(e.envMapIntensity.value=r.envMapIntensity)):r.isMeshStandardMaterial?(n(e,r),function(e,t){e.metalness.value=t.metalness,t.metalnessMap&&(e.metalnessMap.value=t.metalnessMap,i(t.metalnessMap,e.metalnessMapTransform));e.roughness.value=t.roughness,t.roughnessMap&&(e.roughnessMap.value=t.roughnessMap,i(t.roughnessMap,e.roughnessMapTransform));t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)}(e,r),r.isMeshPhysicalMaterial&&function(e,t,n){e.ior.value=t.ior,t.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=n.texture,e.transmissionSamplerSize.value.set(n.width,n.height),t.transmissionMap&&(e.transmissionMap.value=t.transmissionMap,i(t.transmissionMap,e.transmissionMapTransform)),e.thickness.value=t.thickness,t.thicknessMap&&(e.thicknessMap.value=t.thicknessMap,i(t.thicknessMap,e.thicknessMapTransform)),e.attenuationDistance.value=t.attenuationDistance,e.attenuationColor.value.copy(t.attenuationColor));t.anisotropy>0&&(e.anisotropyVector.value.set(t.anisotropy*Math.cos(t.anisotropyRotation),t.anisotropy*Math.sin(t.anisotropyRotation)),t.anisotropyMap&&(e.anisotropyMap.value=t.anisotropyMap,i(t.anisotropyMap,e.anisotropyMapTransform)));e.specularIntensity.value=t.specularIntensity,e.specularColor.value.copy(t.specularColor),t.specularColorMap&&(e.specularColorMap.value=t.specularColorMap,i(t.specularColorMap,e.specularColorMapTransform));t.specularIntensityMap&&(e.specularIntensityMap.value=t.specularIntensityMap,i(t.specularIntensityMap,e.specularIntensityMapTransform))}(e,r,o)):r.isMeshMatcapMaterial?(n(e,r),function(e,t){t.matcap&&(e.matcap.value=t.matcap)}(e,r)):r.isMeshDepthMaterial?n(e,r):r.isMeshDistanceMaterial?(n(e,r),function(e,i){const n=t.get(i).light;e.referencePosition.value.setFromMatrixPosition(n.matrixWorld),e.nearDistance.value=n.shadow.camera.near,e.farDistance.value=n.shadow.camera.far}(e,r)):r.isMeshNormalMaterial?n(e,r):r.isLineBasicMaterial?(function(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,t.map&&(e.map.value=t.map,i(t.map,e.mapTransform))}(e,r),r.isLineDashedMaterial&&function(e,t){e.dashSize.value=t.dashSize,e.totalSize.value=t.dashSize+t.gapSize,e.scale.value=t.scale}(e,r)):r.isPointsMaterial?function(e,t,n,r){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.size.value=t.size*n,e.scale.value=.5*r,t.map&&(e.map.value=t.map,i(t.map,e.uvTransform));t.alphaMap&&(e.alphaMap.value=t.alphaMap,i(t.alphaMap,e.alphaMapTransform));t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}(e,r,s,a):r.isSpriteMaterial?function(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.rotation.value=t.rotation,t.map&&(e.map.value=t.map,i(t.map,e.mapTransform));t.alphaMap&&(e.alphaMap.value=t.alphaMap,i(t.alphaMap,e.alphaMapTransform));t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}(e,r):r.isShadowMaterial?(e.color.value.copy(r.color),e.opacity.value=r.opacity):r.isShaderMaterial&&(r.uniformsNeedUpdate=!1)}}}function cu(e,t,i,n){let r={},s={};function a(t,i,n,r){if(!0===function(e,t,i,n){const r=e.value,s=t+"_"+i;if(Array.isArray(r)){void 0===n[s]&&(n[s]=[]);const e=n[s];let t=!1;for(let i=0;i<r.length;i++)!0===l(r[i],e,i)&&(t=!0);return t}return l(r,n,s)}(t,i,n,r)){const i=t.__offset,n=t.value;if(Array.isArray(n)){let e=0;for(let i=0;i<n.length;i++){const r=n[i],s=c(r,!0);o(r,t.__data,e),e+=s.storage/Float32Array.BYTES_PER_ELEMENT}}else o(n,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 n=t[i];if("number"==typeof e||"boolean"==typeof e){if(n!==e)return t[i]=e,!0}else{if(ArrayBuffer.isView(e))return!0;if(!1===n.equals(e))return n.copy(e),!0}}return!1}function c(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 u(t){const i=t.target;i.removeEventListener("dispose",u),e.deleteBuffer(r[i.id]),delete r[i.id],delete s[i.id]}return{bind:function(e,t){const i=t.program;n.uniformBlockBinding(e,i,r[e.id])},update:function(i,o){let l=r[i.id];void 0===l&&(!function(e){const t=e.uniforms;let i=0;const n=16;for(let e=0,r=t.length;e<r;e++){const r=Array.isArray(t[e])?t[e]:[t[e]];for(let s=0,a=r.length;s<a;s++){const a=r[s],o=Array.isArray(a.value)?a.value:[a.value],l=Array.isArray(t[e])||Array.isArray(a.value);let u=i;for(let e=0,t=o.length;e<t;e++){const t=c(o[e],l),r=i%n,s=r%t.boundary,a=r+s;i+=s,0!==a&&n-a<t.storage&&(i+=n-a),0===e&&(u=i),i+=t.storage}const h="int"===a.type?Int32Array:"uint"===a.type?Uint32Array:Float32Array;a.__data=new h((i-u)/Float32Array.BYTES_PER_ELEMENT),a.__offset=u}}const r=i%n;r>0&&(i+=n-r);e.__size=i,e.__cache={}}(i),l=function(t){const i=e.createBuffer(),n=t.__size,r=t.usage;return e.bindBuffer(e.UNIFORM_BUFFER,i),e.bufferData(e.UNIFORM_BUFFER,n,r),e.bindBuffer(e.UNIFORM_BUFFER,null),i}(i),r[i.id]=l,i.addEventListener("dispose",u));const h=o.program;n.updateUBOMapping(i,h);const d=t.render.frame;s[i.id]!==d&&(!function(t){const i=r[t.id],n=t.uniforms,s=t.__cache;e.bindBuffer(e.UNIFORM_BUFFER,i);for(let e=0,t=n.length;e<t;e++){const t=n[e];if(Array.isArray(t))for(let i=0,n=t.length;i<n;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 r)e.deleteBuffer(r[t]);r={},s={}}}}ou.set(-1,0,0,0,1,0,0,0,1);const uu=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 hu=null;const du="vertex",pu="none",fu="frame",mu="render",gu="object",_u="readOnly",vu="writeOnly",bu="readWrite",yu=["setup","analyze","generate"],xu=["fragment","vertex","compute"],Su=["x","y","z","w"],Tu=[/^StackTrace\.js$/,/^TSLCore\.js$/,/^.*Node\.js$/,/^three\.webgpu.*\.js$/];class Mu{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 n=i[1]||i[2]||"",r=i[3].split("?")[0],s=parseInt(i[4],10),a=parseInt(i[5],10);return{fn:n,file:r.split("/").pop(),line:s,column:a}}).filter(e=>e&&!Tu.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 Eu(e,t=0){let i=3735928559^t,n=1103547991^t;if(Array.isArray(e))for(let t,r=0;r<e.length;r++)t=e[r],i=Math.imul(i^t,2654435761),n=Math.imul(n^t,1597334677);else for(let t,r=0;r<e.length;r++)t=e.charCodeAt(r),i=Math.imul(i^t,2654435761),n=Math.imul(n^t,1597334677);return i=Math.imul(i^i>>>16,2246822507),i^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(i^i>>>13,3266489909),4294967296*(2097151&n)+(i>>>0)}const wu=e=>Eu(e),Au=e=>Eu(e),Ru=(...e)=>Eu(e),Cu=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]);function Nu(e){return Cu.get(e)}function Pu(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 Lu(e){if(!0===e.isDepthTexture)return"float";const t=e.format;let i,n;if(i=t===rt||t===st||t===it||t===nt||t===Je?1:t===at||t===ot?2:t===et||t===lt?3:4,n=e.type===je?"uint":e.type===We?"int":"float",1===i)return n;let r=Nu(i);return"float"!==n&&(r=n[0]+r),r}function Du(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 Kn(...t):"vec2"===i?new Vi(...t):"vec3"===i?new Wi(...t):"vec4"===i?new un(...t):"mat2"===i?new To(...t):"mat3"===i?new Xi(...t):"mat4"===i?new mn(...t):"bool"===e?t[0]||!1:"float"===e||"int"===e||"uint"===e?t[0]||0:"string"===e?t[0]||"":"ArrayBuffer"===e?(n=t[0],Uint8Array.from(atob(n),e=>e.charCodeAt(0)).buffer):null;var n}function Iu(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 Fu(e){return void 0!==e[0]&&null!==e[0]&&(e[0].isNode||Object.getPrototypeOf(e[0])!==Object.prototype)}const Uu={analyze:"setup",generate:"analyze"};let Ou=0;class Bu extends Ri{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=pu,this.updateBeforeType=pu,this.updateAfterType=pu,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=Ou++,this.stackTrace=null,!0===Bu.captureStackTrace&&(this.stackTrace=new Mu)}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 n=e.context.nodeLoop;if(void 0===t.stack&&"setup"===e.buildStage)t.stack=e.declareBeforeBlock(this);else if(!0===this.assignable&&n&&"analyze"===e.buildStage&&!1===i.isCacheable(e)&&!1===e.isDeterministic(i)){const i=e.activeStacks.indexOf(t.stack),r=e.activeStacks.indexOf(e.getDataFromNode(n).stack);-1!==i&&r>=i&&(t.forceDeclaration=!0)}}_declaresAssignable(){return!0}_declareVariable(e,t,i,n,r){const s=e.getVarFromNode(this,null,i,void 0,n,!0,r),a=e.getPropertyName(s),o=n?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 n=this.getNodeType(e),r=e.getVectorType(n);if(void 0===t.propertyName){const i=this.generate.length<2?e.format(this.generate(e)||"",n,r):this.generate(e,r)||"";t.propertyName=this._declareVariable(e,i,r,!1,"variable")}return e.format(t.propertyName,r,i)}_isFunctionScope(){return!1}_checkFlowBlock(e,t){if(void 0!==t.flowBlock){const{guard:i,parent:n}=t.flowBlock,r=void 0!==i&&this._isFunctionScope();let s=e.flowBlock;for(;null!==s&&s!==t.flowBlock&&(!r||s.guard!==i||s.parent!==n);)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,n){const r=!1===this.isGlobal(e)||e.flow.code.length!==n;!1!==i||void 0===t.propertyName&&void 0===t.snippet||!r||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,fu)}onRenderUpdate(e){return this.onUpdate(e,mu)}onObjectUpdate(e){return this.onUpdate(e,gu)}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 n=0;n<i.length;n++){const r=i[n];if(95===r.charCodeAt(0))continue;const s=this[r];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:r,index:e,childNode:i})}else if(s&&!0===s.isNode)t.push({property:r,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:r,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:n,childNode:r}of this._getChildren(t))i.push(wu(n.slice(0,-4)),r.getCacheKey(e,t));this._cacheKey=Ru(Au(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 n;return null!==t?(i.typeFromOutput=i.typeFromOutput||{},n=i.typeFromOutput[t],void 0===n&&(n=this.generateNodeType(e,t),i.typeFromOutput[t]=n)):(n=i.type,void 0===n&&(n=this.generateNodeType(e),i.type=n)),n}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 n=null;if(i&&i!==this)n=i;else if(e.context.overrideNodes){const t=e.context.overrideNodes.get(this);if(t){const i=e.getDataFromNode(this),r=i.overrides||(i.overrides=new Map);!1===r.has(t)?(r.set(t,null),n=t(e).overrideNode(this,null),r.set(t,n)):n=r.get(t)}}return n||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 n=e.getDataFromNode(this);!0===this.assignable&&this._declaresAssignable()&&this._updateAssignable(e,n),n.buildStages=n.buildStages||{setup:!1,analyze:!1,generate:!1},n.buildStages[e.buildStage]=!0;const r=Uu[e.buildStage];if(r&&!0!==n.buildStages[r]){const t=e.getBuildStage();e.setBuildStage(r),this.build(e),e.setBuildStage(t)}e.addChain(this);let s=null;const a=e.getBuildStage();if("setup"===a){e.addNode(this),this.updateReference(e);const t=e.getNodeProperties(this);if(!0!==t.initialized){t.initialized=!0,t.outputNode=this.setup(e)||t.outputNode||null;for(const 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,n);const i=void 0!==n.propertyName||void 0!==n.snippet,r=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&&n.usageCount>1,c=l?o:t;if(!0===this.assignable&&this._declaresAssignable()&&this._isVariable(e,n))s=this._buildVariable(e,n,t);else if(a&&void 0!==n.propertyName)s=e.format(n.propertyName,o,t);else{if(this.generate.length<2){const t=this.getNodeType(e);s=n.snippet,void 0===s&&(void 0===n.generated?(n.generated=!0,s=this.generate(e)||"",n.snippet=s):(Ti("Node: Recursion detected.",this),s="/* Recursion detected. */")),s=e.format(s,t,c)}else s=this.generate(e,c)||"";if(""===s&&null!==c&&"void"!==c&&"OutputType"!==c&&(Mi(`TSL: Invalid generated code, expected a "${c}".`),s=e.generateConst(c)),l){const i=this._declareVariable(e,s,o,!0!==n.assign,"cacheVariable");n.snippet=s,n.propertyName=i,s=e.format(i,o,t)}}this._setFlowBlock(e,n,i,r)}return e.removeChain(this),s}getSerializeChildren(){return this._getChildren()}serialize(e){const t=this.getSerializeChildren(),i={};for(const{property:n,index:r,childNode:s}of t)void 0!==r?(void 0===i[n]&&(i[n]=Number.isInteger(r)?[]:{}),i[n][r]=s.toJSON(e.meta).uuid):i[n]=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 n=[];for(const r of e.inputNodes[i])n.push(t[r]);this[i]=n}else if("object"==typeof e.inputNodes[i]){const n={};for(const r in e.inputNodes[i]){const s=e.inputNodes[i][r];n[r]=t[s]}this[i]=n}else{const n=e.inputNodes[i];this[i]=t[n]}}}toJSON(e){const{uuid:t,type:i}=this,n=void 0===e||"string"==typeof e;n&&(e={textures:{},images:{},nodes:{}});let r=e.nodes[t];function s(e){const t=[];for(const i in e){const n=e[i];delete n.metadata,t.push(n)}return t}if(void 0===r&&(r={uuid:t,type:i,meta:e,metadata:{version:4.7,type:"Node",generator:"Node.toJSON"}},!0!==n&&(e.nodes[r.uuid]=r),this.serialize(r),delete r.meta),n){const t=s(e.textures),i=s(e.images),n=s(e.nodes);t.length>0&&(r.textures=t),i.length>0&&(r.images=i),n.length>0&&(r.nodes=n)}return r}}Bu.captureStackTrace=!1;class ku extends Bu{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 zu extends Bu{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 n of this.convertTo.split("|"))null!==i&&e.getTypeLength(t)!==e.getTypeLength(n)||(i=n);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,n=this.getNodeType(e),r=i.build(e,n);return e.format(r,n,t)}}class Gu extends Bu{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),n=e.getTypeLength(i),r=this.nodes,s=e.getComponentType(i),a=[];let o=0;for(const t of r){if(o>=n){Mi(`TSL: Length of parameters exceeds maximum length of function '${i}()' type.`,this.stackTrace);break}let r,l=t.getNodeType(e),c=e.getTypeLength(l);o+c>n&&(Mi(`TSL: Length of '${i}()' data exceeds maximum length of output type.`,this.stackTrace),c=n-o,l=e.getTypeFromLength(c)),o+=c,r=t.build(e,l);if(e.getComponentType(l)!==s){const t=e.getTypeFromLength(c,s);r=e.format(r,l,t)}a.push(r)}const l=`${e.getType(i)}( ${a.join(", ")} )`;return e.format(l,i,t)}}const Vu=Su.join("");class Hu extends Bu{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(Su.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,n=e.getTypeLength(i.getNodeType(e));let r=null;if(n>1){let s=null;this.getVectorLength()>=n&&(s=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const a=i.build(e,s);r=this.components.length===n&&this.components===Vu.slice(0,this.components.length)?e.format(a,s,t):e.format(`${a}.${this.components}`,this.getNodeType(e),t)}else r=i.build(e,t);return r}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}class Wu extends Bu{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:n}=this,r=this.getNodeType(e),s=e.getComponentType(n.getNodeType(e)),a=e.getTypeFromLength(i.length,s),o=n.build(e,a),l=t.build(e,r),c=e.getTypeLength(r),u=[];for(let e=0;e<c;e++){const t=Su[e];t===i[0]?(u.push(o),e+=i.length-1):u.push(l+"."+t)}return`${e.getType(r)}( ${u.join(", ")} )`}}class ju extends Bu{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,n=this.getNodeType(e),r=i.build(e),s=e.getVarFromNode(this),a=e.getPropertyName(s);e.addLineFlowCode(a+" = "+r,this);const o=e.getTypeLength(n),l=[];let c=0;for(let e=0;e<o;e++){const i=Su[e];i===t[c]?(l.push("1.0 - "+a+"."+i),c++):l.push(a+"."+i)}return`${e.getType(n)}( ${l.join(", ")} )`}}class $u extends Bu{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?Pu(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=Pu(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)?Du(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 Xu=/float|u?int/;class qu extends $u{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(Xu.test(i)&&Xu.test(t)){let n=this.value;return"int"===i?n=Math.trunc(n):"uint"===i&&(n=n>=0?Math.trunc(n):0),e.generateConst(t,n)}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 Yu extends Bu{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 Ku=null;const Zu=new WeakMap,Qu=new Map;function Ju(e,t){if(Qu.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`);Qu.set(e,t),"assign"!==e&&(Bu.prototype[e]=function(...e){return this.isStackNode?this.addToStack(t(...e)):t(this,...e)},Bu.prototype[e+"Assign"]=function(...e){return this.isStackNode?this.assign(e[0],t(...e)):this.assign(t(this,...e))})}}const eh=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("");Bu.prototype.assign=function(...e){if(!0!==this.isStackNode)return null!==Ku?Ku.assign(this,...e):Mi("TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().",new Mu),this;{const t=Qu.get("assign");return this.addToStack(t(...e))}},Bu.prototype.get=function(e){return new Yu(this,e)};const th={},ih=new WeakMap;function nh(e){let t=ih.get(e);return void 0===t&&(t={},ih.set(e,t)),t}function rh(e,t,i){th[e]=th[t]=th[i]={get(){const t=nh(this);let i=t[e];return void 0===i&&(i=new Hu(this,e),t[e]=i),i},set(t){this[e].assign(Rh(t))}};const n=e.toUpperCase(),r=t.toUpperCase(),s=i.toUpperCase();Bu.prototype["set"+n]=Bu.prototype["set"+r]=Bu.prototype["set"+s]=function(t){const i=eh(e);return new Wu(this,i,Rh(t))},Bu.prototype["flip"+n]=Bu.prototype["flip"+r]=Bu.prototype["flip"+s]=function(){const t=eh(e);return new ju(this,t)}}const sh=["x","y","z","w"],ah=["r","g","b","a"],oh=["s","t","p","q"];for(let e=0;e<4;e++){let t=sh[e],i=ah[e],n=oh[e];rh(t,i,n);for(let r=0;r<4;r++){t=sh[e]+sh[r],i=ah[e]+ah[r],n=oh[e]+oh[r],rh(t,i,n);for(let s=0;s<4;s++){t=sh[e]+sh[r]+sh[s],i=ah[e]+ah[r]+ah[s],n=oh[e]+oh[r]+oh[s],rh(t,i,n);for(let a=0;a<4;a++)t=sh[e]+sh[r]+sh[s]+sh[a],i=ah[e]+ah[r]+ah[s]+ah[a],n=oh[e]+oh[r]+oh[s]+oh[a],rh(t,i,n)}}}for(let e=0;e<32;e++)th[e]={get(){const t=nh(this);let i=t[e];return void 0===i&&(i=new ku(this,new qu(e,"uint")),t[e]=i),i},set(t){this[e].assign(Rh(t))}};Object.defineProperties(Bu.prototype,th);const lh=function(e,t=null){for(const i in e)e[i]=Rh(e[i],t);return e},ch=function(e,t=null){const i=e.length;for(let n=0;n<i;n++)e[n]=Rh(e[n],t);return e},uh=function(e,t=null,i=null,n=null){function r(e){return null!==n&&(Object.assign(e,n),!0===n.assignable&&(e=e.toAssignable())),e}let s,a,o,l=t;function c(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 Mu),t.concat(new Array(a-t.length).fill(0))):void 0!==o&&t.length>o?(Mi(`TSL: "${i}" parameter length exceeds limit.`,new Mu),t.slice(0,o)):t}return null===t?s=(...t)=>r(new e(...Nh(c(t)))):null!==i?(i=Rh(i),s=(...n)=>r(new e(t,...Nh(c(n)),i))):s=(...i)=>r(new e(t,...Nh(c(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},hh=function(e,...t){return new e(...Nh(t))};class dh extends Bu{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,n=e.getNodeProperties(t),r=e.getClosestSubBuild(t.subBuilds)||"",s=r||"default";if(n[s])return n[s];const a=e.subBuildFn,o=e.fnCall;e.subBuildFn=r,e.fnCall=this;let l=null;const c=t.layout?e._getLayoutInputs(t,i):null;if(null!==c){const i=t.layout.inputs;if(Fu(c)){const t=c;for(let n=0;n<i.length;n++){const i=t[n];i&&i.isNode&&i.build(e)}}else{const t=c[0];for(const n of i){const i=t[n.name];i&&i.isNode&&i.build(e)}}const n=e.buildFunctionNode(t);e.addInclude(n);const r=function(e){let t;Ch(e),t=Fu(e)?[...e]:e[0];return t}(c);l=n.call(r)}else{let n=Zu.get(e);void 0===n&&(n=new Proxy(e,{get:(e,t,i)=>{let n;return n=Symbol.iterator===t?function*(){yield}:Reflect.get(e,t,i),n}}),Zu.set(e,n));const r=i?function(e){let t=0;return Ch(e),new Proxy(e,{get:(i,n,r)=>{let s;if("length"===n)return s=e.length,s;if(Symbol.iterator===n)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[n]?i[t++]:Reflect.get(i,n,r)}else e[0]instanceof Bu&&(s=void 0===e[n]?e[t++]:Reflect.get(e,n,r));else s=Reflect.get(i,n,r);s=Rh(s)}return s}})}(i):null,s=Array.isArray(i)?i.length>0:null!==i,a=t.jsFunc,o=s||a.length>1?a(r,n):a(n);l=Rh(o)}return e.subBuildFn=a,e.fnCall=o,t.once&&(n[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 n=null;const r=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),c=e.fnCall;if(e.fnCall=this,"setup"===r){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)}n=s[o]}else if("analyze"===r)null!==a&&!1!==this._isVariable(e,a)&&1!==e.increaseUsage(this)||l.build(e,t);else if("generate"===r)if(null!==a&&this._isVariable(e,a)){this._checkFlowBlock(e,a);const i=void 0!==a.propertyName,r=e.flow.code.length;n=this._buildVariable(e,a,t),this._setFlowBlock(e,a,i,r)}else n=l.build(e,t)||"";return e.fnCall=c,n}}class ph extends Bu{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 dh(this,e)}setup(){return this.call()}}const fh=[!1,!0],mh=[0,1,2,3],gh=[-1,-2],_h=[.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],vh=new Map;for(const e of fh)vh.set(e,new qu(e));const bh=new Map;for(const e of mh)bh.set(e,new qu(e,"uint"));const yh=new Map;for(const e of bh.keys())yh.set(e,new qu(e,"int"));for(const e of gh)yh.set(e,new qu(e,"int"));const xh=new Map;for(const e of yh.keys())xh.set(e,new qu(e));for(const e of _h)xh.set(e,new qu(e));for(const e of _h)xh.set(-e,new qu(-e));const Sh={bool:vh,uint:bh,ints:yh,float:xh},Th=new Map(vh),Mh=(e,t)=>{if(Th.has(e))return Th.get(e);if(!0===e.isNode)return e;{const i=new qu(e,t);return i.isWeak=!t&&"number"==typeof e,i}};for(const e of xh.keys())Th.set(e,Mh(e));const Eh=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 Mu),new qu(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=[Du(e,...i)]),1===i.length&&null!==t&&t.has(i[0])){const e=t.get(i[0]);return new qu(e.value,e.nodeType).toAssignable()}if(1===i.length){const t=i[0],n=Mh(t,e);return n.nodeType===e?n===t?new zu(n,e).toAssignable():Th.get(t)===n?new qu(n.value,n.nodeType).toAssignable():n.toAssignable():new zu(n,e).toAssignable()}const n=i.map(e=>Mh(e));return new Gu(n,e).toAssignable()}};function wh(e){return e&&e.isNode&&e.traverse(t=>{t.isConstNode&&(e=t.value)}),Boolean(e)}function Ah(e,t){return new ph(e,t)}const Rh=(e,t=null)=>function(e,t=null){const i=Pu(e);return"node"===i?e:null===t&&("float"===i||"boolean"===i)||i&&"shader"!==i&&"string"!==i?Mh(e,t):"shader"===i?e.isFn?e:Uh(e):e}(e,t),Ch=(e,t=null)=>new lh(e,t),Nh=(e,t=null)=>new ch(e,t),Ph=(e,t=null,i=null,n=null)=>new uh(e,t,i,n),Lh=(e,...t)=>new hh(e,...t),Dh=(e,t=null,i=null,n={})=>new uh(e,t,i,{...n,assignable:!0});let Ih=0;class Fh extends Bu{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 Mu),t=null)),this.shaderNode=new Ah(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"+Ih++,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 Uh(e,t=null){const i=new Fh(e,t);return new Proxy(()=>{},{apply:(e,t,n)=>i.call(...n),get:(e,t,n)=>Reflect.get(i,t,n),set:(e,t,n,r)=>Reflect.set(i,t,n,r)})}const Oh=e=>{Ku=e},Bh=()=>Ku,kh=(...e)=>Ku.If(...e);Ju("toStack",function(e){return Ku&&Ku.addToStack(e),e});const zh=new Eh("color"),Gh=new Eh("float",Sh.float),Vh=new Eh("int",Sh.ints),Hh=new Eh("uint",Sh.uint),Wh=new Eh("bool",Sh.bool),jh=new Eh("vec2"),$h=new Eh("ivec2"),Xh=new Eh("uvec2"),qh=new Eh("bvec2"),Yh=new Eh("vec3"),Kh=new Eh("ivec3"),Zh=new Eh("uvec3"),Qh=new Eh("bvec3"),Jh=new Eh("vec4"),ed=new Eh("ivec4"),td=new Eh("uvec4"),id=new Eh("bvec4"),nd=new Eh("mat2"),rd=new Eh("mat3"),sd=new Eh("mat4");Ju("toColor",zh),Ju("toFloat",Gh),Ju("toInt",Vh),Ju("toUint",Hh),Ju("toBool",Wh),Ju("toVec2",jh),Ju("toIVec2",$h),Ju("toUVec2",Xh),Ju("toBVec2",qh),Ju("toVec3",Yh),Ju("toIVec3",Kh),Ju("toUVec3",Zh),Ju("toBVec3",Qh),Ju("toVec4",Jh),Ju("toIVec4",ed),Ju("toUVec4",td),Ju("toBVec4",id),Ju("toMat2",nd),Ju("toMat3",rd),Ju("toMat4",sd);Ju("element",Ph(ku).setParameterLength(2)),Ju("convert",(e,t)=>new zu(Rh(e),t));class ad extends Bu{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 Su.join("").slice(0,i)!==t.components}return!1}setup(e){const{targetNode:t,sourceNode:i}=this,n=t.getScope();e.getDataFromNode(n).assign=!0;const r=e.getNodeProperties(this);r.sourceNode=i,r.targetNode=t.context({assign:!0})}generate(e,t){const{targetNode:i,sourceNode:n}=e.getNodeProperties(this),r=this.needsSplitAssign(e),s=i.build(e),a=i.getNodeType(e),o=n.build(e,a),l=n.getNodeType(e),c=e.getDataFromNode(this);let u;if(void 0!==c.propertyName)"void"!==t&&(u=s);else if(r){const n=e.getVarFromNode(this,null,a),r=e.getPropertyName(n);e.addLineFlowCode(`${r} = ${o}`,this);const l=i.node,c=l.node.context({assign:!0}).build(e);for(let t=0;t<l.components.length;t++){const i=l.components[t];e.addLineFlowCode(`${c}.${i} = ${r}[ ${t} ]`,this)}"void"!==t&&(u=s)}else u=`${s} = ${o}`,"void"!==t&&"void"!==l||(e.addLineFlowCode(u,this),"void"!==t&&(u=s));return c.propertyName=s,e.format(u,a,t)}}Ju("assign",Ph(ad).setParameterLength(2));class od extends Bu{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 ld=(...e)=>{let t;if(1===e.length){const i=e[0].map(e=>Rh(e));t=new od(null,i.length,i)}else{const i=e[0],n=e[1];t=new od(i,n)}return t};Ju("toArray",(e,t)=>ld(Array(t).fill(e)));class cd extends Bu{static get type(){return"UniformGroupNode"}constructor(e,t=!1,i=1,n=null){super("string"),this.name=e,this.shared=t,this.order=i,this.updateType=n,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 ud=(e,t=1,i=null)=>new cd(e,!1,t,i),hd=(e,t=0,i=null)=>new cd(e,!0,t,i),dd=hd("render",0,mu),pd=ud("object",1,gu);class fd extends $u{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=pd}setName(e){return this.name=e,this}label(e){return Ti('TSL: "label()" has been deprecated. Use "setName()" instead.',new Mu),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),n=this.getSharedNode(e),r=n.getInputType(e),s=e.getUniformFromNode(n,r,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 n=t.propertyName;if(void 0===n){const s=e.getVarFromNode(this,null,"bool");n=e.getPropertyName(s),t.propertyName=n,o=e.format(a,r,i),e.addLineFlowCode(`${n} = ${o}`,this)}o=n}return e.format(o,i,t)}}const md=(e,t)=>{const i=(e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null)(t||e);if(i===e&&(e=Du(i)),e&&!0===e.isNode){let t=e.value;e.traverse(e=>{!0===e.isConstNode&&(t=e.value)}),e=t}return new fd(e,i)};class gd extends Bu{static get type(){return"PropertyNode"}constructor(e,t=null,i=!1,n=null){super(e),this.name=t,this.varying=i,this.placeholderNode=Rh(n),this.isPropertyNode=!0,this.global=!0}isCacheable(){return!1}getNodeType(e){const t=super.getNodeType(e);return"output"===t?e.getOutputType():t}customCacheKey(){return wu(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 _d=(e,t,i=null)=>new gd(e,t,!1,i),vd=(e,t,i=null)=>new gd(e,t,!0,i),bd=Lh(gd,"vec4","DiffuseColor"),yd=Lh(gd,"vec3","DiffuseContribution"),xd=Lh(gd,"float","DiffuseRoughness"),Sd=Lh(gd,"vec3","EmissiveColor"),Td=Lh(gd,"float","Roughness"),Md=Lh(gd,"float","Metalness"),Ed=Lh(gd,"float","Clearcoat"),wd=Lh(gd,"float","ClearcoatRoughness"),Ad=Lh(gd,"vec3","Sheen"),Rd=Lh(gd,"float","SheenRoughness"),Cd=Lh(gd,"float","Iridescence"),Nd=Lh(gd,"float","IridescenceIOR"),Pd=Lh(gd,"float","IridescenceThickness"),Ld=Lh(gd,"float","AlphaT"),Dd=Lh(gd,"float","Anisotropy"),Id=Lh(gd,"vec3","AnisotropyT"),Fd=Lh(gd,"vec3","AnisotropyB"),Ud=Lh(gd,"color","SpecularColor"),Od=Lh(gd,"color","SpecularColorBlended"),Bd=Lh(gd,"float","SpecularF90"),kd=Lh(gd,"float","Shininess"),zd=Lh(gd,"output","Output"),Gd=Lh(gd,"float","dashSize"),Vd=Lh(gd,"float","gapSize"),Hd=Lh(gd,"float","IOR"),Wd=Lh(gd,"float","Transmission"),jd=Lh(gd,"float","Thickness"),$d=Lh(gd,"float","AttenuationDistance"),Xd=Lh(gd,"color","AttenuationColor"),qd=Lh(gd,"float","Dispersion"),Yd=Lh(gd,"float","Retroreflectivity"),Kd=Lh(gd,"float","AmbientOcclusion",!1,1);class Zd extends Bu{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,n=i.getInputs(e),r=this.parameters,s=(t,i)=>{const n=i.type;let r;return r="pointer"===n?"&"+t.build(e):t.build(e,n),r};if(Array.isArray(r)){if(r.length>n.length)Mi("TSL: The number of provided parameters exceeds the expected number of inputs in 'Fn()'."),r.length=n.length;else if(r.length<n.length)for(Mi("TSL: The number of provided parameters is less than the expected number of inputs in 'Fn()'.");r.length<n.length;)r.push(Gh(0));for(let e=0;e<r.length;e++)t.push(s(r[e],n[e]))}else for(const e of n){const i=r[e.name];void 0!==i?t.push(s(i,e)):(Mi(`TSL: Input '${e.name}' not found in 'Fn()'.`),t.push(s(Gh(0),e)))}return`${i.build(e,"property")}( ${t.join(", ")} )`}}Ju("call",(e,...t)=>(t=t.length>1||t[0]&&!0===t[0].isNode?Nh(t):Ch(t[0]),new Zd(Rh(e),t)));const Qd={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class Jd extends Bu{static get type(){return"OperatorNode"}constructor(e,t,i,...n){if(super(),n.length>0){let r=new Jd(e,t,i);for(let t=0;t<n.length-1;t++)r=new Jd(e,r,n[t]);t=r,i=n[n.length-1]}this.op=e,this.aNode=t,this.bNode=i,this.isOperatorNode=!0}getOperatorMethod(e,t){return e.getMethod(Qd[this.op],t)}generateNodeType(e,t=null){const i=this.op,n=this.aNode,r=this.bNode,s=n.getNodeType(e),a=r?r.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(n,r);return e.changeComponentType(t,i)}}generate(e,t){const i=this.op,{aNode:n,bNode:r}=this,s=this.getNodeType(e,t);let a=null,o=null;if("void"!==s)if(a=n.getNodeType(e),o=r?r.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(n,r))}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=n.build(e,a),c=r?r.build(e,o):null,u=e.getFunctionOperator(i);if("void"!==t){const n=e.renderer.coordinateSystem===ci;if("=="===i||"!="===i||"<"===i||">"===i||"<="===i||">="===i)return n&&e.isVector(a)?e.format(`${this.getOperatorMethod(e,t)}( ${l}, ${c} )`,s,t):e.format(`( ${l} ${i} ${c} )`,s,t);if("%"===i)return e.isInteger(o)?e.format(`( ${l} % ${c} )`,s,t):e.format(`${this.getOperatorMethod(e,s)}( ${l}, ${c} )`,s,t);if("!"===i)return n&&e.isVector(a)?e.format(`not( ${l} )`,t):e.format(`( ${i} ${l} )`,a,t);if("~"===i)return e.format(`( ${i} ${l} )`,a,t);if(u)return e.format(`${u}( ${l}, ${c} )`,s,t);if(e.isMatrix(a)&&e.isScalar(o))return e.format(`( ${c} ${i} ${l} )`,s,t);if(e.isScalar(a)&&e.isMatrix(o))return e.format(`${l} ${i} ${c}`,s,t);{let r=`( ${l} ${i} ${c} )`;return!n&&"bool"===s&&e.isVector(a)&&e.isVector(o)&&(r=`all${r}`),e.format(r,s,t)}}if("void"!==a)return u?e.format(`${u}( ${l}, ${c} )`,s,t):e.isMatrix(a)&&e.isScalar(o)?e.format(`${c} ${i} ${l}`,s,t):e.format(`${l} ${i} ${c}`,s,t)}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const ep=Dh(Jd,"+").setParameterLength(2,1/0).setName("add"),tp=Dh(Jd,"-").setParameterLength(2,1/0).setName("sub"),ip=Dh(Jd,"*").setParameterLength(2,1/0).setName("mul"),np=Dh(Jd,"/").setParameterLength(2,1/0).setName("div"),rp=Dh(Jd,"%").setParameterLength(2).setName("mod"),sp=Dh(Jd,"==").setParameterLength(2).setName("equal"),ap=Dh(Jd,"!=").setParameterLength(2).setName("notEqual"),op=Dh(Jd,"<").setParameterLength(2).setName("lessThan"),lp=Dh(Jd,">").setParameterLength(2).setName("greaterThan"),cp=Dh(Jd,"<=").setParameterLength(2).setName("lessThanEqual"),up=Dh(Jd,">=").setParameterLength(2).setName("greaterThanEqual"),hp=Dh(Jd,"&&").setParameterLength(2,1/0).setName("and"),dp=Dh(Jd,"||").setParameterLength(2,1/0).setName("or"),pp=Dh(Jd,"!").setParameterLength(1).setName("not"),fp=Dh(Jd,"^^").setParameterLength(2).setName("xor"),mp=Dh(Jd,"&").setParameterLength(2).setName("bitAnd"),gp=Dh(Jd,"~").setParameterLength(1).setName("bitNot"),_p=Dh(Jd,"|").setParameterLength(2).setName("bitOr"),vp=Dh(Jd,"^").setParameterLength(2).setName("bitXor"),bp=Dh(Jd,"<<").setParameterLength(2).setName("shiftLeft"),yp=Dh(Jd,">>").setParameterLength(2).setName("shiftRight"),xp=Uh(([e])=>(e.addAssign(1),e)),Sp=Uh(([e])=>(e.subAssign(1),e)),Tp=Uh(([e])=>{const t=Vh(e).toConst();return e.addAssign(1),t}),Mp=Uh(([e])=>{const t=Vh(e).toConst();return e.subAssign(1),t});Ju("add",ep),Ju("sub",tp),Ju("mul",ip),Ju("div",np),Ju("mod",rp),Ju("equal",sp),Ju("notEqual",ap),Ju("lessThan",op),Ju("greaterThan",lp),Ju("lessThanEqual",cp),Ju("greaterThanEqual",up),Ju("and",hp),Ju("or",dp),Ju("not",pp),Ju("xor",fp),Ju("bitAnd",mp),Ju("bitNot",gp),Ju("bitOr",_p),Ju("bitXor",vp),Ju("shiftLeft",bp),Ju("shiftRight",yp),Ju("incrementBefore",xp),Ju("decrementBefore",Sp),Ju("increment",Tp),Ju("decrement",Mp);class Ep extends Bu{static get type(){return"MathNode"}constructor(e,t,i=null,n=null){if(super(),(e===Ep.MAX||e===Ep.MIN)&&arguments.length>3){let r=new Ep(e,t,i);for(let t=3;t<arguments.length-1;t++)r=new Ep(e,r,arguments[t]);t=r,i=arguments[arguments.length-1],n=null}this.method=e,this.aNode=t,this.bNode=i,this.cNode=n,this.isMathNode=!0}getInputType(e){const t=this.aNode.getNodeType(e),i=this.bNode?this.bNode.getNodeType(e):null,n=this.cNode?this.cNode.getNodeType(e):null,r=e.isMatrix(t)?0:e.getTypeLength(t),s=e.isMatrix(i)?0:e.getTypeLength(i),a=e.isMatrix(n)?0:e.getTypeLength(n);let o;if(o=r>s&&r>a?t:s>a?i:a>r?n:t,e.isMatrix(o))return o;const l=wp.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===Ep.LENGTH||t===Ep.DISTANCE||t===Ep.DOT||t===Ep.DETERMINANT?"float":t===Ep.CROSS?"vec3":t===Ep.ALL||t===Ep.ANY?"bool":t===Ep.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):this.getInputType(e)}setup(e){const{aNode:t,bNode:i,method:n}=this;let r=null;if(n===Ep.ONE_MINUS)r=tp(1,t);else if(n===Ep.RECIPROCAL)r=np(Gh(1),t);else if(n===Ep.DIFFERENCE)r=tf(tp(t,i));else if(n===Ep.TRANSFORM_DIRECTION){let n,s;e.isMatrix(t.getNodeType(e))?(n=t,s=i):(n=i,s=t),r=Gp(ip(n,Jh(Yh(s),0)).xyz)}return null!==r?r:super.setup(e)}generate(e,t){if(e.getNodeProperties(this).outputNode)return super.generate(e,t);let i=this.method;const n=this.getNodeType(e),r=this.getInputType(e),s=this.aNode,a=this.bNode,o=this.cNode,l=e.renderer.coordinateSystem;if(i===Ep.NEGATE)return e.format("( - "+s.build(e,r)+" )",n,t);{const c=[];return i===Ep.CROSS?c.push(s.build(e,n),a.build(e,n)):l===ci&&i===Ep.STEP?c.push(s.build(e,1===e.getTypeLength(s.getNodeType(e))?"float":r),a.build(e,r)):l!==ci||i!==Ep.MIN&&i!==Ep.MAX?i===Ep.REFRACT?c.push(s.build(e,r),a.build(e,r),o.build(e,"float")):i===Ep.MIX?c.push(s.build(e,r),a.build(e,r),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":r)):(l===ui&&i===Ep.ATAN&&null!==a&&(i="atan2"),"fragment"===e.shaderStage||i!==Ep.DFDX&&i!==Ep.DFDY||(Mi(`TSL: '${i}' is not supported in the ${e.shaderStage} stage.`,this.stackTrace),i="/*"+i+"*/"),c.push(s.build(e,r)),null!==a&&c.push(a.build(e,r)),null!==o&&c.push(o.build(e,r))):c.push(s.build(e,r),a.build(e,1===e.getTypeLength(a.getNodeType(e))?e.getComponentType(r):r)),e.format(`${e.getMethod(i,n)}( ${c.join(", ")} )`,n,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}Ep.ALL="all",Ep.ANY="any",Ep.RADIANS="radians",Ep.DEGREES="degrees",Ep.EXP="exp",Ep.EXP2="exp2",Ep.LOG="log",Ep.LOG2="log2",Ep.SQRT="sqrt",Ep.INVERSE_SQRT="inversesqrt",Ep.FLOOR="floor",Ep.CEIL="ceil",Ep.NORMALIZE="normalize",Ep.FRACT="fract",Ep.SIN="sin",Ep.SINH="sinh",Ep.COS="cos",Ep.COSH="cosh",Ep.TAN="tan",Ep.TANH="tanh",Ep.ASIN="asin",Ep.ASINH="asinh",Ep.ACOS="acos",Ep.ACOSH="acosh",Ep.ATAN="atan",Ep.ATANH="atanh",Ep.ABS="abs",Ep.SIGN="sign",Ep.LENGTH="length",Ep.NEGATE="negate",Ep.ONE_MINUS="oneMinus",Ep.DFDX="dFdx",Ep.DFDY="dFdy",Ep.ROUND="round",Ep.RECIPROCAL="reciprocal",Ep.TRUNC="trunc",Ep.FWIDTH="fwidth",Ep.TRANSPOSE="transpose",Ep.DETERMINANT="determinant",Ep.INVERSE="inverse",Ep.EQUALS="equals",Ep.MIN="min",Ep.MAX="max",Ep.STEP="step",Ep.REFLECT="reflect",Ep.DISTANCE="distance",Ep.DIFFERENCE="difference",Ep.DOT="dot",Ep.CROSS="cross",Ep.POW="pow",Ep.TRANSFORM_DIRECTION="transformDirection",Ep.MIX="mix",Ep.CLAMP="clamp",Ep.REFRACT="refract",Ep.SMOOTHSTEP="smoothstep",Ep.FACEFORWARD="faceforward";const wp=new Set([Ep.RADIANS,Ep.DEGREES,Ep.EXP,Ep.EXP2,Ep.LOG,Ep.LOG2,Ep.SQRT,Ep.INVERSE_SQRT,Ep.FLOOR,Ep.CEIL,Ep.NORMALIZE,Ep.FRACT,Ep.SIN,Ep.SINH,Ep.COS,Ep.COSH,Ep.TAN,Ep.TANH,Ep.ASIN,Ep.ASINH,Ep.ACOS,Ep.ACOSH,Ep.ATAN,Ep.ATANH,Ep.LENGTH,Ep.DFDX,Ep.DFDY,Ep.ROUND,Ep.TRUNC,Ep.FWIDTH,Ep.RECIPROCAL,Ep.STEP,Ep.REFLECT,Ep.DISTANCE,Ep.DOT,Ep.CROSS,Ep.POW,Ep.MIX,Ep.REFRACT,Ep.SMOOTHSTEP,Ep.FACEFORWARD]),Ap=Gh(1e-6),Rp=Gh(Math.PI),Cp=Dh(Ep,Ep.ALL).setParameterLength(1),Np=Dh(Ep,Ep.ANY).setParameterLength(1),Pp=Dh(Ep,Ep.RADIANS).setParameterLength(1),Lp=Dh(Ep,Ep.DEGREES).setParameterLength(1),Dp=Dh(Ep,Ep.EXP).setParameterLength(1),Ip=Dh(Ep,Ep.EXP2).setParameterLength(1),Fp=Dh(Ep,Ep.LOG).setParameterLength(1),Up=Dh(Ep,Ep.LOG2).setParameterLength(1),Op=Dh(Ep,Ep.SQRT).setParameterLength(1),Bp=Dh(Ep,Ep.INVERSE_SQRT).setParameterLength(1),kp=Dh(Ep,Ep.FLOOR).setParameterLength(1),zp=Dh(Ep,Ep.CEIL).setParameterLength(1),Gp=Dh(Ep,Ep.NORMALIZE).setParameterLength(1),Vp=Dh(Ep,Ep.FRACT).setParameterLength(1),Hp=Dh(Ep,Ep.SIN).setParameterLength(1),Wp=Dh(Ep,Ep.SINH).setParameterLength(1),jp=Dh(Ep,Ep.COS).setParameterLength(1),$p=Dh(Ep,Ep.COSH).setParameterLength(1),Xp=Dh(Ep,Ep.TAN).setParameterLength(1),qp=Dh(Ep,Ep.TANH).setParameterLength(1),Yp=Dh(Ep,Ep.ASIN).setParameterLength(1),Kp=Dh(Ep,Ep.ASINH).setParameterLength(1),Zp=Dh(Ep,Ep.ACOS).setParameterLength(1),Qp=Dh(Ep,Ep.ACOSH).setParameterLength(1),Jp=Dh(Ep,Ep.ATAN).setParameterLength(1,2),ef=Dh(Ep,Ep.ATANH).setParameterLength(1),tf=Dh(Ep,Ep.ABS).setParameterLength(1),nf=Dh(Ep,Ep.SIGN).setParameterLength(1),rf=Dh(Ep,Ep.LENGTH).setParameterLength(1),sf=Dh(Ep,Ep.NEGATE).setParameterLength(1),af=Dh(Ep,Ep.ONE_MINUS).setParameterLength(1),of=Dh(Ep,Ep.DFDX).setParameterLength(1),lf=Dh(Ep,Ep.DFDY).setParameterLength(1),cf=Dh(Ep,Ep.ROUND).setParameterLength(1),uf=Dh(Ep,Ep.RECIPROCAL).setParameterLength(1),hf=Dh(Ep,Ep.TRUNC).setParameterLength(1),df=Dh(Ep,Ep.FWIDTH).setParameterLength(1),pf=Dh(Ep,Ep.TRANSPOSE).setParameterLength(1),ff=Dh(Ep,Ep.DETERMINANT).setParameterLength(1),mf=Dh(Ep,Ep.INVERSE).setParameterLength(1),gf=Dh(Ep,Ep.MIN).setParameterLength(2,1/0),_f=Dh(Ep,Ep.MAX).setParameterLength(2,1/0),vf=Dh(Ep,Ep.STEP).setParameterLength(2),bf=Dh(Ep,Ep.REFLECT).setParameterLength(2),yf=Dh(Ep,Ep.DISTANCE).setParameterLength(2),xf=Dh(Ep,Ep.DIFFERENCE).setParameterLength(2),Sf=Dh(Ep,Ep.DOT).setParameterLength(2),Tf=Dh(Ep,Ep.CROSS).setParameterLength(2),Mf=Dh(Ep,Ep.POW).setParameterLength(2),Ef=e=>ip(e,e),wf=e=>ip(e,e,e,e),Af=Dh(Ep,Ep.TRANSFORM_DIRECTION).setParameterLength(2),Rf=Dh(Ep,Ep.MIX).setParameterLength(3),Cf=(e,t=0,i=1)=>new Ep(Ep.CLAMP,Rh(e),Rh(t),Rh(i)),Nf=e=>Cf(e),Pf=Dh(Ep,Ep.REFRACT).setParameterLength(3),Lf=Dh(Ep,Ep.SMOOTHSTEP).setParameterLength(3),Df=Dh(Ep,Ep.FACEFORWARD).setParameterLength(3),If=Uh(([e])=>{const t=Sf(e.xy,jh(12.9898,78.233)),i=rp(t,Rp);return Vp(Hp(i).mul(43758.5453))},{uv:"vec2",return:"float"});Ju("all",Cp),Ju("any",Np),Ju("radians",Pp),Ju("degrees",Lp),Ju("exp",Dp),Ju("exp2",Ip),Ju("log",Fp),Ju("log2",Up),Ju("sqrt",Op),Ju("inverseSqrt",Bp),Ju("floor",kp),Ju("ceil",zp),Ju("normalize",Gp),Ju("fract",Vp),Ju("sin",Hp),Ju("sinh",Wp),Ju("cos",jp),Ju("cosh",$p),Ju("tan",Xp),Ju("tanh",qp),Ju("asin",Yp),Ju("asinh",Kp),Ju("acos",Zp),Ju("acosh",Qp),Ju("atan",Jp),Ju("atanh",ef),Ju("abs",tf),Ju("sign",nf),Ju("length",rf),Ju("lengthSq",e=>Sf(e,e)),Ju("negate",sf),Ju("oneMinus",af),Ju("dFdx",of),Ju("dFdy",lf),Ju("round",cf),Ju("reciprocal",uf),Ju("trunc",hf),Ju("fwidth",df),Ju("min",gf),Ju("max",_f),Ju("step",(e,t)=>vf(t,e)),Ju("reflect",bf),Ju("distance",yf),Ju("dot",Sf),Ju("cross",Tf),Ju("pow",Mf),Ju("pow2",Ef),Ju("pow3",e=>ip(e,e,e)),Ju("pow4",wf),Ju("transformDirection",Af),Ju("transformNormalByViewMatrix",(e,t)=>Gp(ip(t,Jh(Yh(e),0)).xyz)),Ju("transformNormalByInverseViewMatrix",(e,t)=>Gp(Jh(Yh(e),0).mul(t).xyz)),Ju("mix",(e,t,i)=>Rf(t,i,e)),Ju("clamp",Cf),Ju("refract",Pf),Ju("smoothstep",(e,t,i)=>Lf(t,i,e)),Ju("faceForward",Df),Ju("difference",xf),Ju("saturate",Nf),Ju("cbrt",e=>ip(nf(e),Mf(tf(e),1/3))),Ju("transpose",pf),Ju("determinant",ff),Ju("inverse",mf),Ju("rand",If);class Ff extends Error{constructor(e,t=null){super(e),this.name="NodeError",this.stackTrace=t}}class Uf extends Bu{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:n}=e.getNodeProperties(this);if(void 0===i)return e.flowBuildStage(this,"setup"),this.getNodeType(e);let r=i.getNodeType(e);if(null!==n){const t=n.getNodeType(e);e.getTypeLength(t)>e.getTypeLength(r)&&(r=t)}const s=e.getTypeLength(t.getNodeType(e));return s>1&&!e.isReference(r)&&(1===e.getTypeLength(r)||e.isVector(e.getVectorType(r)))&&(r=e.getTypeFromLength(Math.max(s,e.getTypeLength(r)),e.getComponentType(r))),r}setup(e){const{condNode:t,ifNode:i,elseNode:n}=this,r=e.getNodeProperties(this);r.condNode=t,r.ifNode=i,r.elseNode=n}generate(e,t){const i=this.getNodeType(e),n=e.getDataFromNode(this);if(void 0!==n.propertyName)return e.format(n.propertyName,i,t);const{condNode:r,ifNode:s,elseNode:a}=e.getNodeProperties(this),o=e.currentFunctionNode,l="void"!==t,c=l?_d(i).build(e):"";n.propertyName=c;const u=r.getNodeType(e);if(e.getTypeLength(u)>1){const n=e.getVectorType(i);if(e.isReference(i)||!e.isVector(n))throw new Ff(`TSL: select() with a vector condition ("${u}") 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=r.build(e,h),p=s.build(e,i),f=e.getVectorSelect(d,p,o,i);return l?(e.addFlowCode(`\n${e.tab}${c} = ${f};\n\n`),e.format(c,i,t)):""}const h=r.build(e,"bool");if(e.context.uniformFlow&&null!==a){const n=s.build(e,i),r=a.build(e,i),o=e.getTernary(h,n,r);return e.format(o,i,t)}e.addFlowCode(`\n${e.tab}if ( ${h} ) {\n\n`).addFlowTab();const d=e.getDataFromNode(r),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=c+" = "+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=c+" = "+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(c,i,t)}}const Of=Ph(Uf).setParameterLength(2,3);Ju("select",Of);class Bf extends Bu{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=Iu(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),n=this.node.build(e,t);return e.setContext(i),n}}const kf=(e=null,t={})=>{let i=e;return null!==i&&!0===i.isNode||(t=i||t,i=null),new Bf(i,t)},zf=(e,t)=>kf(e,{nodeName:t});Ju("context",kf),Ju("label",function(e,t){return Ti('TSL: "label()" has been deprecated. Use "setName()" instead.'),zf(e,t)}),Ju("uniformFlow",e=>kf(e,{uniformFlow:!0})),Ju("setName",zf),Ju("builtinShadowContext",(e,t,i)=>function(e,t,i=null){return kf(i,{getShadow:({light:i,shadowColorNode:n})=>t===i?n.mul(e):n})}(t,i,e)),Ju("builtinAOContext",(e,t)=>function(e,t=null){return kf(t,{getAO:(t,{material:i})=>!0===i.transparent?t:null!==t?t.mul(e):e})}(t,e)),Ju("builtinGIContext",(e,t,i)=>function(e,t,i=null){const n=e.max(.001);return kf(i,{getAO:(e,{material:t})=>!0===t.transparent?e:null!==e?e.mul(n):n,getGI:(e,{material:i})=>{if(!0===i.transparent)return e;const r=t.div(n);return null!==e?e.add(r):r}})}(t,i,e));class Gf extends Bu{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 n=e.getDataFromNode(this);return this._updateAssignable(e,n,this.node),this.assignable&&!0!==n.forceDeclaration&&!0!==n.assign?this.node.build(e,t):super.build(e,t)}generate(e){const{node:t,name:i,readOnly:n}=this,r=this.getNodeType(e);if("void"==r){!0!==this.isAssignable(e)&&Mi('TSL: ".toVar()" can not be used with void type.',this.stackTrace);return t.build(e)}const s=e.getVectorType(r),a=t.build(e,s),o=e.getVarFromNode(this,i,s,void 0,n,this.assignable),l=e.getPropertyName(o);let c=l;if(o.readOnly){const i=t.getArrayCount(e);c=e.isDeterministic(t)?e.generateConstStatement(o.type,l,i):e.generateLetStatement(o.type,l,i)}else o.local&&(c=e.generateVarStatement(o.type,l,o.count));return e.addLineFlowCode(`${c} = ${a}`,this),l}}const Vf=Ph(Gf);Ju("toVar",(e,t=null)=>Vf(e,t).toStack()),Ju("toConst",(e,t=null)=>Vf(e,t,!0).toStack());class Hf extends Bu{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 Wf=(e,t,i=null)=>new Hf(Rh(e),t,i);class jf extends Bu{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=Wf(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 n=this.name,r=this.getNodeType(e),s=this.interpolationType,a=this.interpolationSampling;t.varying=i=e.getVaryingFromNode(this,n,r,s,a),t.node=Wf(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(du,this.node)}analyze(e){if(e.getNodeProperties(this).outputNode)return super.analyze(e);this.setupVarying(e),e.flowNodeFromShaderStage(du,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),n=e.getNodeProperties(this),r=this.setupVarying(e),s=e.shaderStage===du?e.flowBlock:null;if(n[i]!==s){const t=this.getNodeType(e),a=e.getPropertyName(r,du);if(e.shaderStage===du){const i=n.node.build(e,t);e.addLineFlowCode(`${a} = ${i}`,this)}else e.flowNodeFromShaderStage(du,n.node,t,a);n[i]=s}return e.getPropertyName(r)}}const $f=Ph(jf).setParameterLength(1,2);Ju("toVarying",$f),Ju("toVertexStage",e=>$f(e));const Xf=Uh(([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),i=e.mul(.0773993808),n=e.lessThanEqual(.04045);return Rf(t,i,n)},{color:"vec3",return:"vec3"}),qf=Uh(([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),i=e.mul(12.92),n=e.lessThanEqual(.0031308);return Rf(t,i,n)},{color:"vec3",return:"vec3"}),Yf="WorkingColorSpace";class Kf extends Bu{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===Yf?Qi.workingColorSpace:"OutputColorSpace"===t?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){const{colorNode:t}=this,i=this.resolveColorSpace(e,this.source),n=this.resolveColorSpace(e,this.target);let r=t;return!1!==Qi.enabled&&i!==n&&i&&n?(Qi.getTransfer(i)===Kt&&(r=Jh(Xf(r.rgb),r.a)),Qi.getPrimaries(i)!==Qi.getPrimaries(n)&&(r=Jh(rd(Qi._getMatrix(new Xi,i,n)).mul(r.rgb),r.a)),Qi.getTransfer(n)===Kt&&(r=Jh(qf(r.rgb),r.a)),r):r}}const Zf=(e,t)=>new Kf(Rh(e),t,Yf);Ju("workingToColorSpace",(e,t)=>new Kf(Rh(e),Yf,t)),Ju("colorSpaceToWorking",Zf);class Qf extends ku{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),n=this.getNodeType(e);return e.format(t,i,n)}}class Jf extends Bu{static get type(){return"ReferenceBaseNode"}constructor(e,t,i=null,n=null){super(),this.property=e,this.uniformType=t,this.object=i,this.count=n,this.properties=e.split("."),this.reference=i,this.node=null,this.group=null,this.updateType=gu}isCacheable(){return!1}setGroup(e){return this.group=e,this}element(e){return new Qf(this,Rh(e))}setNodeType(e){const t=md(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 em extends Jf{static get type(){return"RendererReferenceNode"}constructor(e,t,i=null){super(e,t,i),this.renderer=i,this.setGroup(dd)}updateReference(e){return this.reference=null!==this.renderer?this.renderer:e.renderer,this.reference}}const tm=(e,t,i=null)=>new em(e,t,i);class im extends Bu{static get type(){return"ToneMappingNode"}constructor(e,t=nm,i=null){super("vec3"),this._toneMapping=e,this.exposureNode=t,this.colorNode=i}customCacheKey(){return Ru(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 n=null;const r=e.renderer.library.getToneMappingFunction(i);return null!==r?n=Jh(r(t.rgb,this.exposureNode),t.a):(Mi("ToneMappingNode: Unsupported Tone Mapping configuration.",i),n=t),n}}const nm=tm("toneMappingExposure","float");Ju("toneMapping",(e,t,i)=>((e,t,i)=>new im(e,Rh(t),Rh(i)))(t,i,e));const rm=new WeakMap;function sm(e,t){let i=rm.get(e);return void 0===i&&(i=new Qr(e,t),rm.set(e,i)),i}class am extends $u{static get type(){return"BufferAttributeNode"}constructor(e,t=null,i=0,n=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=i,this.bufferOffset=n,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),n=this.value,r=this.bufferStride||i,s=this.bufferOffset;let a;a=!0===n.isInterleavedBuffer?n:!0===n.isBufferAttribute?sm(n.array,r):sm(n,r);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 n=e.getBufferAttributeFromNode(this,t,i),r=e.getPropertyName(n);let s=null;if("vertex"===e.shaderStage||"compute"===e.shaderStage)this.name=r,s=r;else{let n;i&&(n=i+"Varying");s=$f(this,n).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 om(e,t=null,i=0,n=0,r=35044,s=!1){return"mat3"===t||null===t&&9===e.itemSize?rd(new am(e,"vec3",9,0).setUsage(r).setInstanced(s),new am(e,"vec3",9,3).setUsage(r).setInstanced(s),new am(e,"vec3",9,6).setUsage(r).setInstanced(s)):"mat4"===t||null===t&&16===e.itemSize?sd(new am(e,"vec4",16,0).setUsage(r).setInstanced(s),new am(e,"vec4",16,4).setUsage(r).setInstanced(s),new am(e,"vec4",16,8).setUsage(r).setInstanced(s),new am(e,"vec4",16,12).setUsage(r).setInstanced(s)):new am(e,t,i,n).setUsage(r)}const lm=(e,t=null,i=0,n=0)=>om(e,t,i,n),cm=(e,t=null,i=0,n=0)=>om(e,t,i,n,ai,!0),um=(e,t=null,i=0,n=0)=>om(e,t,i,n,oi,!0);Ju("toAttribute",e=>lm(e.value,e.bufferType));class hm extends Bu{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 n,r;if(i===hm.VERTEX)n=e.getVertexIndex();else if(i===hm.INSTANCE)n=e.getInstanceIndex();else if(i===hm.DRAW)n=e.getDrawIndex();else if(i===hm.INVOCATION_LOCAL)n=e.getInvocationLocalIndex();else if(i===hm.INVOCATION_SUBGROUP)n=e.getInvocationSubgroupIndex();else{if(i!==hm.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+i);n=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)r=n;else{r=$f(this).build(e,t)}return r}}hm.VERTEX="vertex",hm.INSTANCE="instance",hm.SUBGROUP="subgroup",hm.INVOCATION_LOCAL="invocationLocal",hm.INVOCATION_SUBGROUP="invocationSubgroup",hm.DRAW="draw";const dm=Lh(hm,hm.VERTEX),pm=Lh(hm,hm.INSTANCE);hm.SUBGROUP,hm.INVOCATION_SUBGROUP,hm.INVOCATION_LOCAL;const fm=Lh(hm,hm.DRAW);class mm extends Bu{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=fu}isCacheable(){return!1}setName(e){return this.name=e,this}label(e){return Ti('TSL: "label()" has been deprecated. Use "setName()" instead.',new Mu),this.setName(e)}onInit(e){return this.onInitFunction=e,this}getUpdateBeforeType(e){return e.compute!==this?this.updateBeforeType:pu}updateBefore({renderer:e}){e.compute(this)}setup(e){null!==this.count&&null===this.countNode&&(this.countNode=md(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=pm.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 gm=(e,t=[64])=>{(0===t.length||t.length>3)&&Mi("TSL: compute() workgroupSize must have 1, 2, or 3 elements",new Mu);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 Mu)}for(;t.length<3;)t.push(1);return new mm(Rh(e),t)};Ju("compute",(e,t,i)=>{const n=gm(e,i);return"number"==typeof t?n.count=t:n.dispatchSize=t,n}),Ju("computeKernel",gm);class _m extends Bu{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 n=this.node.getNodeType(e);return e.setCache(t),n}build(e,...t){this._setupInspector(e);const i=e.getCache(),n=e.getCacheFromNode(this,this.parent);e.setCache(n);const r=this.node.build(e,...t);return e.setCache(i),r}setParent(e){return this.parent=e,this}getParent(){return this.parent}}const vm=e=>new _m(Rh(e));Ju("cache",function(e,t=!0){return Ti('TSL: "cache()" has been deprecated. Use "isolate()" instead.'),vm(e).setParent(t)}),Ju("isolate",vm);class bm extends Bu{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)}}Ju("bypass",Ph(bm).setParameterLength(2));const ym=Uh(([e,t,i,n=Gh(0),r=Gh(1),s=Wh(!1)])=>{let a=e.sub(t).div(i.sub(t));return wh(s)&&(a=a.clamp()),a.mul(r.sub(n)).add(n)});Ju("remap",ym),Ju("remapClamp",function(e,t,i,n=Gh(0),r=Gh(1)){return ym(e,t,i,n,r,!0)});class xm extends Bu{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),n=this.snippet;if("void"!==i)return e.format(n,i,t);e.addLineFlowCode(n,this)}}const Sm=Ph(xm).setParameterLength(1,2);Ju("discard",e=>(e?Of(e,Sm("discard")):Sm("discard")).toStack());const Tm=Uh(([e])=>Jh(e.rgb.mul(e.a),e.a),{color:"vec4",return:"vec4"}),Mm=Uh(([e])=>e.a.equal(0).select(Jh(0),Jh(e.rgb.div(e.a),e.a)),{color:"vec4",return:"vec4"});class Em extends Bu{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=Jh(t.rgb,t.a.clamp(0,1)),!0===this.premultipliedAlpha&&(t=Mm(t));const i=(null!==this._toneMapping?this._toneMapping:e.toneMapping)||0,n=(null!==this.outputColorSpace?this.outputColorSpace:e.outputColorSpace)||$t;return 0!==i&&(t=t.toneMapping(i)),n!==$t&&n!==Qi.workingColorSpace&&(t=t.workingToColorSpace(n)),!0===this.premultipliedAlpha&&(t=Tm(t)),t}}const wm=(e,t=null,i=null)=>new Em(Rh(e),t,i);Ju("renderOutput",wm);class Am extends Bu{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 ---",n="-".repeat(t.length);let r="";r+="// #"+t+"#\n",r+=e.flow.code.replace(/^\t/gm,"")+"\n",r+="/* ... */ "+i+" /* ... */\n",r+="// #"+n+"#\n",xi(r)}return i}}Ju("debug",(e,t=null)=>new Am(Rh(e),t).toStack());class Rm 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 Cm extends Bu{static get type(){return"InspectorNode"}constructor(e,t="",i=null){super(),this.node=e,this.name=t,this.callback=i,this.updateType=fu,this.isInspectorNode=!0}getName(){return this.name||this.node.name}update(e){const{renderer:t}=e;!0!==t.backend.isWebGPUBackend&&t.inspector.constructor!==Rm&&Ei('TSL: ".toInspector()" is only available with WebGPU.'),t.inspector.inspect(this)}generateNodeType(e){return this.node.getNodeType(e)}}Ju("toInspector",function(e,t="",i=null){return(e=Rh(e))._inspectorNode=new Cm(e,t,i),e});class Nm extends Bu{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 n=e.geometry.getAttribute(t);i=e.getTypeFromAttribute(n)}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 n=e.geometry.getAttribute(t),r=e.getTypeFromAttribute(n),s=e.getAttribute(t,r);if("vertex"===e.shaderStage)return e.format(s.name,r,i);return $f(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 Pm=(e,t=null)=>new Nm(e,t);class Lm extends Bf{static get type(){return"OverrideContextNode"}constructor(e,t=null,i=null){const n={overrideNodes:e};"fragment"===i&&(n.inlineVaryings=!0),super(t,n),this.isOverrideContextNode=!0}}function Dm(e,t,i){return n=>n.shaderStage===i?t(n):e}Ju("overrideNode",(e,t,i)=>function(e,t=null,i=null){if(t&&t.isNode){const e=t;t=()=>e}return new Lm(new Map([[e,t]]),i)}(t,i,e)),Ju("overrideNodes",(e,t,i)=>function(e,t=null,i=null){const n=new Map;for(const[t,r]of e){let e=null;null!==r&&(e="function"==typeof r?r:()=>r,null!==i&&(e=Dm(t,e,i))),n.set(t,e)}return new Lm(n,t,i)}(t,e,i));class Im extends gd{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getMemberType(e,t){const i=this.getNodeType(e),n=e.getStructTypeNode(i);let r;return null!==n?r=n.getMemberType(e,t):(Mi(`TSL: Member "${t}" not found in struct "${i}".`,new Mu),r="float"),r}getHash(){return String(this.id)}generate(){return this.name}}const Fm=(e,t)=>{if(!0!==t.assignable)return!1;const i=e.getDataFromNode(t);return!0!==i.forceDeclaration&&!0!==i.assign};class Um extends Bu{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 Mu),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 Ah(t);return this._currentCond=Of(e,i),this.addToStack(this._currentCond)}ElseIf(e,t){const i=new Ah(t),n=Of(e,i);return this._currentCond.elseNode=n,this._currentCond=n,this}Else(e){return this._currentCond.elseNode=new Ah(e),this}Switch(e){return this._expressionNode=Rh(e),this}Case(...e){const t=[];if(e.length>=2)for(let i=0;i<e.length-1;i++)t.push(this._expressionNode.equal(Rh(e[i])));else Mi("TSL: Invalid parameter length. Case() requires at least two parameters.",new Mu);const i=new Ah(e[e.length-1]);let n=t[0];for(let e=1;e<t.length;e++)n=n.or(t[e]);const r=Of(n,i);return null===this._currentCond?(this._currentCond=r,this.addToStack(this._currentCond)):(this._currentCond.elseNode=r,this._currentCond=r,this)}Default(e){return this.Else(e),this}setup(e){const t=e.getNodeProperties(this);let i=0;for(const n of this.getChildren())Fm(e,n)||(t["node"+i++]=n);return t.outputNode||null}build(e,...t){this._setupInspector(e);const i=Bh(),n=e.buildStage;Oh(this),e.setActiveStack(this);for(let t=0;t<this.nodes.length;t++){const i=this.nodes[t],r=this._currentNode;if(this._currentNode=i,!Fm(e,i)){if("setup"===n)i.build(e);else if("analyze"===n)i.build(e,this);else if("generate"===n){const t=e.getDataFromNode(i,"any").stages,n=t&&t[e.shaderStage];if(i.isVarNode&&n&&1===n.length&&n[0]&&n[0].isStackNode)continue;i.build(e,"void")}this._currentNode=r}}let r;if(this.outputNode){const i=this.outputNode.build(e,...t);"generate"===e.buildStage&&"void"===this.outputNode.getNodeType(e)||(r=i)}else r=super.build(e,...t);return Oh(i),e.removeActiveStack(this),r}}const Om=Ph(Um).setParameterLength(0,1);class Bm extends Kn{constructor(e,t,i,n=1){super(e,t,i),this.a=n}set(e,t,i,n=1){return this.a=n,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 km extends Bu{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={},n=this._getInternalParams();for(let e=0,t=n.length-1;e<t;e++){const t=n[e],r=!0!==t.isNode&&t.name||this.getVarName(e),s=!0!==t.isNode&&t.type||"int";i[r]=Sm(r,s)}const r=e.addStack(),s=n[n.length-1](i);t.returnsNode=s.context({nodeLoop:this,nodeBlock:e.createBlock()}),t.stackNode=r;const a=n[0];if(!0!==a.isNode&&"function"==typeof a.update){const e=Uh(a.update)(i);t.updateNode=e.context({nodeLoop:this})}return e.removeStack(),t}_getInternalParams(){const e=this.params;return"function"==typeof e[0]?[Wh(!0),e[0]]:e}setup(e){this.getProperties(e)}generate(e){const t=this.getProperties(e),i=this._getInternalParams(),n=t.stackNode;for(let n=0,r=i.length-1;n<r;n++){const r=i[n];let s,a=!1,o=null,l=null,c=null,u=null,h=null,d=null;if(r.isNode?"bool"===r.getNodeType(e)?(a=!0,u="bool",l=r.build(e,u)):(u="int",c=this.getVarName(n),o="0",l=r.build(e,u),h="<"):(u=r.type||"int",c=r.name||this.getVarName(n),o=r.start,l=r.end,h=r.condition,d=r.update,"number"==typeof o?o=e.generateConst(u,o):o&&o.isNode&&(o=o.build(e,u)),"number"==typeof l?l=e.generateConst(u,l):l&&l.isNode&&(l=l.build(e,u)),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},n=i.start,r=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=c+" "+p()+" "+e.generateConst(u,d);break;case"string":a=c+" "+d;break;default:d.isNode?a=c+" "+p()+" "+d.build(e):(Mi("TSL: 'Loop( { update: ... } )' is not a function, string or number.",this.stackTrace),a="break /* invalid update */")}else d="int"===u||"uint"===u?h.includes("<")?"++":"--":p()+" 1.",a=c+" "+d;s=`for ( ${e.getVar(u,c)+" = "+n}; ${c+" "+h+" "+r}; ${a} )`}e.addFlowCode((0===n?"\n":"")+e.tab+s+" {\n\n").addFlowTab()}const r=e.flowBlock;e.flowBlock={parent:r};const s=n.build(e,"void");t.returnsNode.build(e,"void"),e.flowBlock=r,e.removeFlowTab().addFlowCode("\n"+e.tab+s);for(let t=0,n=i.length-1;t<n;t++)e.addFlowCode((0===t?"":e.tab)+"}\n\n").removeFlowTab();e.addFlowTab()}}const zm=(...e)=>new km(Nh(e,"int")).toStack(),Gm=new Hr;class Vm extends Bu{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=gu,this.uniformNode=new fd(null)}isCacheable(){return!1}generateNodeType(){const e=this.scope;return e===Vm.WORLD_MATRIX?"mat4":e===Vm.POSITION||e===Vm.VIEW_POSITION||e===Vm.DIRECTION||e===Vm.SCALE?"vec3":e===Vm.RADIUS?"float":void 0}update(e){const t=this.object3d,i=this.uniformNode,n=this.scope;if(n===Vm.WORLD_MATRIX)i.value=t.matrixWorld;else if(n===Vm.POSITION)i.value=i.value||new Wi,i.value.setFromMatrixPosition(t.matrixWorld);else if(n===Vm.SCALE)i.value=i.value||new Wi,i.value.setFromMatrixScale(t.matrixWorld);else if(n===Vm.DIRECTION)i.value=i.value||new Wi,t.getWorldDirection(i.value);else if(n===Vm.VIEW_POSITION){const n=e.camera;i.value=i.value||new Wi,i.value.setFromMatrixPosition(t.matrixWorld),i.value.applyMatrix4(n.matrixWorldInverse)}else if(n===Vm.RADIUS){const n=e.object.geometry;null===n.boundingSphere&&n.computeBoundingSphere(),Gm.copy(n.boundingSphere).applyMatrix4(t.matrixWorld),i.value=Gm.radius}}generate(e){const t=this.scope;return t===Vm.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===Vm.POSITION||t===Vm.VIEW_POSITION||t===Vm.DIRECTION||t===Vm.SCALE?this.uniformNode.nodeType="vec3":t===Vm.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}}Vm.WORLD_MATRIX="worldMatrix",Vm.POSITION="position",Vm.SCALE="scale",Vm.VIEW_POSITION="viewPosition",Vm.DIRECTION="direction",Vm.RADIUS="radius";class Hm extends Bu{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}isCacheable(){return!1}generate(){return this.name}}const Wm=Ph(Hm).setParameterLength(1);class jm extends fd{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 $m=(e,t,i)=>new jm(e,t,i);class Xm extends ku{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),n=this.node.getPaddedType(e);return e.format(t,n,i)}}class qm extends jm{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=null===t?Pu(e[0]):t,this.updateType=mu,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 n=4*i,r=e[i];t[n]=r.r,t[n+1]=r.g,t[n+2]=r.b||0}else if("mat2"===i)for(let i=0;i<e.length;i++){const n=4*i,r=e[i];t[n]=r.elements[0],t[n+1]=r.elements[1],t[n+2]=r.elements[2],t[n+3]=r.elements[3]}else if("mat3"===i)for(let i=0;i<e.length;i++){const n=16*i,r=e[i];t[n]=r.elements[0],t[n+1]=r.elements[1],t[n+2]=r.elements[2],t[n+4]=r.elements[3],t[n+5]=r.elements[4],t[n+6]=r.elements[5],t[n+8]=r.elements[6],t[n+9]=r.elements[7],t[n+10]=r.elements[8],t[n+15]=1}else if("mat4"===i)for(let i=0;i<e.length;i++){const n=16*i,r=e[i];for(let e=0;e<r.elements.length;e++)t[n+e]=r.elements[e]}else for(let i=0;i<e.length;i++){const n=4*i,r=e[i];t[n]=r.x,t[n+1]=r.y,t[n+2]=r.z||0,t[n+3]=r.w||0}}setup(e){const t=this.array.length,i=this.elementType;let n=Float32Array;const r=this.getPaddedType(e),s=e.getTypeLength(r);return"i"===i.charAt(0)&&(n=Int32Array),"u"===i.charAt(0)&&(n=Uint32Array),this.value=new n(t*s),this.bufferCount=t,this.bufferType=r,this.updateBuffer(),super.setup(e)}element(e){return new Xm(this,Rh(e))}}const Ym=(e,t)=>new qm(e,t);let Km,Zm;class Qm extends Bu{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this.isViewportNode=!0}isCacheable(){return!1}generateNodeType(){return this.scope===Qm.VIEWPORT?"vec4":"vec2"}update({renderer:e}){const t=e.getRenderTarget();this.scope===Qm.VIEWPORT?null!==t?Zm.copy(t.viewport):(e.getViewport(Zm),Zm.multiplyScalar(e.getPixelRatio())):null!==t?(Km.width=t.width,Km.height=t.height):e.getDrawingBufferSize(Km)}setup(){const e=this.scope;let t=null;t=e===Qm.SIZE?md(Km||(Km=new Vi)).setGroup(dd):e===Qm.VIEWPORT?md(Zm||(Zm=new un)).setGroup(dd):jh(ig.div(tg));let i=pu;return this.scope!==Qm.SIZE&&this.scope!==Qm.VIEWPORT||(i=mu),this.updateType=i,t}generate(e){if(this.scope===Qm.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const i=e.getNodeProperties(tg).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${i}.y - ${t}.y )`}return t}return super.generate(e)}}Qm.COORDINATE="coordinate",Qm.VIEWPORT="viewport",Qm.SIZE="size",Qm.UV="uv";const Jm=md(1).setGroup(dd).onRenderUpdate(({renderer:e})=>e.getPixelRatio()),eg=Lh(Qm,Qm.UV),tg=Lh(Qm,Qm.SIZE),ig=Lh(Qm,Qm.COORDINATE),ng=Lh(Qm,Qm.VIEWPORT),rg=ng.zw;ng.xy;const sg=new WeakMap;function ag(e,t,i,n){let r=sg.get(e);void 0===r&&(r=new Map,sg.set(e,r));const s=i+":"+t.cameras.length;let a=r.get(s);return void 0===a&&(a=n(t),r.set(s,a)),a}let og=null,lg=null,cg=null,ug=null,hg=null,dg=null;const pg=md(0,"uint").setName("u_cameraIndex").setGroup(hd("cameraIndex")).toVarying("v_cameraIndex"),fg=md("float").setName("cameraNear").setGroup(dd).onRenderUpdate(({camera:e})=>e.near),mg=md("float").setName("cameraFar").setGroup(dd).onRenderUpdate(({camera:e})=>e.far),gg=Uh(({camera:e,renderer:t})=>{let i;if(e.isArrayCamera&&e.cameras.length>0){const n=ag(t,e,"cameraProjectionMatrices",e=>{const t=e.cameras.map(e=>e.projectionMatrix);return Ym(t).setGroup(dd).setName("cameraProjectionMatrices").onRenderUpdate(({camera:e},t)=>{for(let i=0;i<e.cameras.length;i++)t.array[i]=e.cameras[i].projectionMatrix})});i=n.element(e.isMultiViewCamera?Wm("gl_ViewID_OVR"):pg)}else null===og&&(og=md(e.projectionMatrix).setName("cameraProjectionMatrix").setGroup(dd).onRenderUpdate(({camera:e})=>e.projectionMatrix)),i=og;return i}).once()(),_g=Uh(({camera:e,renderer:t})=>{let i;if(e.isArrayCamera&&e.cameras.length>0){const n=ag(t,e,"cameraProjectionMatricesInverse",e=>{const t=e.cameras.map(e=>e.projectionMatrixInverse);return Ym(t).setGroup(dd).setName("cameraProjectionMatricesInverse").onRenderUpdate(({camera:e},t)=>{for(let i=0;i<e.cameras.length;i++)t.array[i]=e.cameras[i].projectionMatrixInverse})});i=n.element(e.isMultiViewCamera?Wm("gl_ViewID_OVR"):pg)}else null===lg&&(lg=md(e.projectionMatrixInverse).setName("cameraProjectionMatrixInverse").setGroup(dd).onRenderUpdate(({camera:e})=>e.projectionMatrixInverse)),i=lg;return i}).once()(),vg=Uh(({camera:e,renderer:t})=>{let i;if(e.isArrayCamera&&e.cameras.length>0){const n=ag(t,e,"cameraViewMatrices",e=>{const t=e.cameras.map(e=>e.matrixWorldInverse);return Ym(t).setGroup(dd).setName("cameraViewMatrices").onRenderUpdate(({camera:e},t)=>{for(let i=0;i<e.cameras.length;i++)t.array[i]=e.cameras[i].matrixWorldInverse})});i=n.element(e.isMultiViewCamera?Wm("gl_ViewID_OVR"):pg)}else null===cg&&(cg=md(e.matrixWorldInverse).setName("cameraViewMatrix").setGroup(dd).onRenderUpdate(({camera:e})=>e.matrixWorldInverse)),i=cg;return i}).once()(),bg=Uh(({camera:e,renderer:t})=>{let i;if(e.isArrayCamera&&e.cameras.length>0){const n=ag(t,e,"cameraWorldMatrices",e=>{const t=e.cameras.map(e=>e.matrixWorld);return Ym(t).setGroup(dd).setName("cameraWorldMatrices").onRenderUpdate(({camera:e},t)=>{for(let i=0;i<e.cameras.length;i++)t.array[i]=e.cameras[i].matrixWorld})});i=n.element(e.isMultiViewCamera?Wm("gl_ViewID_OVR"):pg)}else null===ug&&(ug=md(e.matrixWorld).setName("cameraWorldMatrix").setGroup(dd).onRenderUpdate(({camera:e})=>e.matrixWorld)),i=ug;return i}).once()(),yg=Uh(({camera:e,renderer:t})=>{let i;if(e.isArrayCamera&&e.cameras.length>0){const n=ag(t,e,"cameraPositions",e=>{const t=[];for(let i=0,n=e.cameras.length;i<n;i++)t.push(new Wi);return Ym(t).setGroup(dd).setName("cameraPositions").onRenderUpdate(({camera:e},t)=>{const i=e.cameras,n=t.array;for(let e=0,t=i.length;e<t;e++)n[e].setFromMatrixPosition(i[e].matrixWorld)})});i=n.element(e.isMultiViewCamera?Wm("gl_ViewID_OVR"):pg)}else null===hg&&(hg=md(new Wi).setName("cameraPosition").setGroup(dd).onRenderUpdate(({camera:e},t)=>t.value.setFromMatrixPosition(e.matrixWorld))),i=hg;return i}).once()(),xg=Uh(({camera:e,renderer:t})=>{let i;if(e.isArrayCamera&&e.cameras.length>0){const n=ag(t,e,"cameraViewports",e=>{const t=e.cameras.map(e=>e.viewport);return Ym(t,"vec4").setGroup(dd).setName("cameraViewports").onRenderUpdate(({camera:e},t)=>{for(let i=0;i<e.cameras.length;i++)t.array[i]=e.cameras[i].viewport})});i=n.element(pg)}else null===dg&&(dg=Jh(0,0,tg.x,tg.y).toConst("cameraViewport")),i=dg;return i}).once()(),Sg=new mn;class Tg extends Vm{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const Mg=Lh(Tg,Tg.WORLD_MATRIX),Eg=md(new Xi).onObjectUpdate(({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld)),wg=Uh(e=>e.context.modelViewMatrix||Ag).once()().toVar("modelViewMatrix"),Ag=vg.mul(Mg),Rg=Uh(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 mn);const n=Ym(e).onObjectUpdate(({object:e,camera:t},i)=>{const n=t.cameras,r=i.array;for(let t=0,i=n.length;t<i;t++)r[t].multiplyMatrices(n[t].matrixWorldInverse,e.matrixWorld)});i=n.element(t.isMultiViewCamera?Wm("gl_ViewID_OVR"):pg)}else i=md("mat4").onObjectUpdate(({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld));return i}).once()().toVar("highpModelViewMatrix"),Cg=Uh(e=>{const t=e.context.isHighPrecisionModelViewMatrix,i=e.camera;let n;if(i.isArrayCamera&&i.cameras.length>0){const e=[];for(let t=0;t<i.cameras.length;t++)e.push(new Xi);const t=Ym(e).onObjectUpdate(({object:e,camera:t},i)=>{const n=t.cameras,r=i.array;for(let t=0,i=n.length;t<i;t++)Sg.multiplyMatrices(n[t].matrixWorldInverse,e.matrixWorld),r[t].getNormalMatrix(Sg)});n=t.element(i.isMultiViewCamera?Wm("gl_ViewID_OVR"):pg)}else n=md("mat3").onObjectUpdate(({object:e,camera:i})=>(!0!==t&&e.modelViewMatrix.multiplyMatrices(i.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix)));return n}).once()().toVar("highpModelNormalViewMatrix"),Ng=Uh(e=>"fragment"!==e.shaderStage?(Ei("TSL: `clipSpace` is only available in fragment stage."),Jh()):e.context.clipSpace.toVarying("v_clipSpace")).once()(),Pg=Pm("position","vec3"),Lg=Pg.toVarying("positionLocal"),Dg=Pg.toVarying("positionPrevious"),Ig=Uh(e=>Mg.mul(Lg).xyz.toVarying(e.getSubBuildProperty("v_positionWorld")),"vec3").once(["POSITION"])(),Fg=Uh(()=>Lg.transformDirection(Mg).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection"),"vec3").once(["POSITION"])(),Ug=Uh(e=>{if("fragment"===e.shaderStage&&e.material.vertexNode){const e=_g.mul(Ng);return e.xyz.div(e.w).toVar("positionView")}return e.context.setupPositionView().toVarying("v_positionView")},"vec3").once(["POSITION","VERTEX"])(),Og=Uh(e=>{let t;return t=e.camera.isOrthographicCamera?Yh(0,0,1):Ug.negate().toVarying("v_positionViewDirection").normalize(),t.toVar("positionViewDirection")},"vec3").once(["POSITION"])(),Bg=(e=0)=>Pm("uv"+(e>0?e:""),"vec2"),kg=Uh(([e=Fg])=>{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 jh(t,i)}),zg=Uh(([e=Bg()])=>{const t=e.x.sub(.5).mul(2*Math.PI),i=e.y.sub(.5).mul(Math.PI),n=i.cos(),r=n.mul(t.cos()),s=i.sin(),a=n.mul(t.sin());return Yh(r,s,a)});class Gg extends Bu{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 Vg=Gh(Lh(Gg)).mul(2).sub(1),Hg=Uh(([e],{material:t})=>{const i=t.side;return 1===i?e=e.mul(-1):2===i&&(e=e.mul(Vg)),e}),Wg=Pm("normal","vec3"),jg=Uh(e=>!1===e.geometry.hasAttribute("normal")?(Ti('TSL: Vertex attribute "normal" not found on geometry.'),Yh(0,1,0)):Wg,"vec3").once()().toVar("normalLocal"),$g=Ug.dFdx().cross(Ug.dFdy()).normalize().toVar("normalFlat"),Xg=Uh(e=>{let t;return t=e.isFlatShading()?$g:Jg(jg).toVarying("v_normalViewGeometry").normalize(),t},"vec3").once()().toVar("normalViewGeometry"),qg=Uh(e=>{let t=Xg.transformNormalByInverseViewMatrix(vg);return!0!==e.isFlatShading()&&(t=t.toVarying("v_normalWorldGeometry")),t.normalize().toVar("normalWorldGeometry")},"vec3").once()(),Yg=Uh(e=>{let t;return"NORMAL"===e.subBuildFn||"VERTEX"===e.subBuildFn?(t=Xg,!0!==e.isFlatShading()&&(t=Hg(t))):t=e.context.setupNormal().context({getUV:null,getTextureLevel:null}),t},"vec3").once(["NORMAL","VERTEX"])().toVar("normalView"),Kg=Yg.transformNormalByInverseViewMatrix(vg).toVar("normalWorld"),Zg=Uh(({subBuildFn:e,context:t})=>{let i;return i="NORMAL"===e||"VERTEX"===e?Yg:t.setupClearcoatNormal().context({getUV:null,getTextureLevel:null}),i},"vec3").once(["NORMAL","VERTEX"])().toVar("clearcoatNormalView"),Qg=Uh(([e,t=Mg])=>rd(t).inverse().transpose().mul(e).normalize());Ju("transformNormal",Qg);const Jg=Uh(([e],t)=>{const i=t.context.modelNormalViewMatrix;if(i)return e.transformNormalByViewMatrix(i);return Eg.mul(e).transformNormalByViewMatrix(vg)}),e_=Uh(()=>{const e=Yh(Og.z,0,Og.x.negate()).normalize(),t=Og.cross(e);return jh(e.dot(Yg),t.dot(Yg)).mul(.495).add(.5)}).once(["NORMAL","VERTEX"])().toVar("matcapUV");class t_ extends fd{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=fu}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 i_=Ph(t_).setParameterLength(1),n_=e=>Yh(e,Op(Nf(Gh(1).sub(Sf(e,e)))));class r_ extends Bu{static get type(){return"RotateNode"}constructor(e,t,i="XYZ"){super(),this.positionNode=e,this.rotationNode=t,this._order=i}customCacheKey(){return wu(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(),n=t.sin();return nd(e,n,n.negate(),e).mul(i)}{const e=t,n=this._order,r={X:sd(Jh(1,0,0,0),Jh(0,jp(e.x),Hp(e.x),0),Jh(0,Hp(e.x).negate(),jp(e.x),0),Jh(0,0,0,1)),Y:sd(Jh(jp(e.y),0,Hp(e.y).negate(),0),Jh(0,1,0,0),Jh(Hp(e.y),0,jp(e.y),0),Jh(0,0,0,1)),Z:sd(Jh(jp(e.z),Hp(e.z),0,0),Jh(Hp(e.z).negate(),jp(e.z),0,0),Jh(0,0,1,0),Jh(0,0,0,1))};return r[n.charAt(0)].mul(r[n.charAt(1)]).mul(r[n.charAt(2)]).mul(Jh(i,1)).xyz}}serialize(e){super.serialize(e),e.order=this._order}deserialize(e){super.deserialize(e),this._order=e.order}}const s_=Ph(r_).setParameterLength(2,3);class a_ extends Bu{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"),n=e.generateTextureSize(this.textureNode.value,t,i);return e.format(n,this.getNodeType(e))}}const o_=Ph(a_).setParameterLength(1,2),l_=new cn;class c_ extends fd{static get type(){return"TextureNode"}constructor(e=l_,t=null,i=null,n=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=i,this.biasNode=n,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 Ru(this.id,e,t,i)}generateNodeType(){return null!==this.gatherNode?"vec4":Lu(this.value)}getInputType(){return"texture"}getDefaultUV(){return Bg(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return this._getMatrixUniform().mul(Yh(e,1)).xy}_getTransformedGradient(e){return this._getMatrixUniform().mul(Yh(e,0)).xy}_getMatrixUniform(){const e=this.getBase();return null===e._matrixUniform&&(e._matrixUniform=md(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=md(!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(Vh(o_(this,this.levelNode).y).sub(Vh(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 Ff("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().",this.stackTrace);const n=Uh(()=>{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 r=this.levelNode;null===r&&e.context.getTextureLevel&&(r=e.context.getTextureLevel(this));let s=null,a=null;if(null!==this.compareNode)if(e.renderer.hasCompatibility(pi))s=this.compareNode;else{const e=i.compareFunction;null===e||e===Jt||e===ti||e===ii||e===ri?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===r&&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=n,t.levelNode=r,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,n,r,s,a,o,l,c,u){const h=this.value;let d;return d=r?e.generateTextureBias(h,t,i,r,s,c):o?e.generateTextureGrad(h,t,i,o,s,c):l?a?e.generateTextureGatherCompare(h,t,i,a,s,c,u):e.generateTextureGather(h,t,i,l,s,c,u):a?e.generateTextureCompare(h,t,i,a,s,c):!1===this.sampler?e.generateTextureLoad(h,t,i,n,s,c):n?e.generateTextureLevel(h,t,i,n,s,c):e.generateTexture(h,t,i,s,c),d}generate(e,t){const i=this.value,n=e.getNodeProperties(this),r=super.generate(e,"property");if("samplerComparison"!==t&&null===n.compareNode||(this.getSharedNode(e)._samplerComparison=!0),/^sampler/.test(t))return r+"_sampler";if(e.isReference(t))return r;{const s=e.getDataFromNode(this),a=this.getNodeType(e);let o=s.propertyName;if(void 0===o){const{uvNode:t,levelNode:l,biasNode:c,compareNode:u,compareStepNode:h,depthNode:d,gradNode:p,gatherNode:f,offsetNode:m}=n,g=this.generateUV(e,t),_=l?l.build(e,"float"):null,v=c?c.build(e,"float"):null,b=d?d.build(e,"int"):null,y=u?u.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,r,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===ri?vf(Sm(N,a),Sm(x,"float")).build(e,a):vf(Sm(x,"float"),Sm(N,a)).build(e,a)}e.addLineFlowCode(`${o} = ${N}`,this),s.snippet=N,s.propertyName=o}let l=o;return e.needsToWorkingColorSpace(i)&&(l=Zf(Sm(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=Rh(e),t.referenceNode=this.getBase(),t}load(e){return this.sample(e).setSampler(!1)}blur(e){const t=this.clone();t.biasNode=Rh(e).mul(i_(t)),t.referenceNode=this.getBase();const i=t.value;return!1===t.generateMipmaps&&(i&&!1===i.generateMipmaps||i.minFilter===Ie||i.magFilter===Ie)&&(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=Rh(e),t.referenceNode=this.getBase(),t}size(e){return o_(this,e)}bias(e){const t=this.clone();return t.biasNode=Rh(e),t.referenceNode=this.getBase(),t}getBase(){return this.referenceNode?this.referenceNode.getBase():this}compare(e){const t=this.clone();return t.compareNode=Rh(e),t.referenceNode=this.getBase(),t}grad(e,t){const i=this.clone();return i.gradNode=[Rh(e),Rh(t)],i.referenceNode=this.getBase(),i}gather(e=0){const t=this.clone();return t.gatherNode=Rh(e),t.referenceNode=this.getBase(),t}isSampleCompare(){return null!==this.compareNode||!0===this._samplerComparison}depth(e){const t=this.clone();return t.depthNode=Rh(e),t.referenceNode=this.getBase(),t}offset(e){const t=this.clone();return t.offsetNode=Rh(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 u_=Ph(c_).setParameterLength(1,4).setName("texture"),h_=(e=l_,t=null,i=null,n=null)=>{let r;return e&&!0===e.isTextureNode?(r=e.clone(),r.referenceNode=e.getBase(),null!==t&&(r.uvNode=Rh(t)),null!==i&&(r.levelNode=Rh(i)),null!==n&&(r.biasNode=Rh(n))):r=u_(e,t,i,n),r},d_=(...e)=>h_(...e).setSampler(!1),p_=new Vi;class f_ extends c_{static get type(){return"ViewportTextureNode"}constructor(e=eg,t=null,i=null){let n=null;null===i?(n=new ra,n.minFilter=ke,i=n):n=i,super(i,e,t),this.generateMipmaps=!1,this.defaultFramebuffer=n,this.isOutputTextureNode=!0,this.updateBeforeType=mu,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 n=t.clone();i.set(e,n)}return i.get(e)}updateReference(e){const t=e.renderer,i=t.getRenderTarget(),n=t.getCanvasTarget(),r=i||n;return this.value=this.getTextureForReference(r),this.value}updateBefore(e){const t=e.renderer,i=t.getRenderTarget(),n=t.getCanvasTarget(),r=i||n;null===r?t.getDrawingBufferSize(p_):r.getDrawingBufferSize?r.getDrawingBufferSize(p_):p_.set(r.width,r.height);const s=this.getTextureForReference(r);s.image.width===p_.width&&s.image.height===p_.height||(s.image.width=p_.width,s.image.height=p_.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 m_=Ph(f_,null,null,{generateMipmaps:!0}).setParameterLength(0,3),g_=m_(),__=(e=eg,t=null)=>g_.sample(e,t);let v_=null;class b_ extends f_{static get type(){return"ViewportDepthTextureNode"}constructor(e=eg,t=null,i=null){null===i&&(null===v_&&(v_=new oa),i=v_),super(e,t,i)}}const y_=Ph(b_).setParameterLength(0,3);class x_ extends Bu{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===x_.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,i=this.valueNode;let n=null;if(t===x_.DEPTH_BASE)null!==i&&(n=A_().assign(i));else if(t===x_.DEPTH)n=!0!==e.isOrthographicCamera?M_(Ug.z,fg,mg):S_(Ug.z,fg,mg);else if(t===x_.LINEAR_DEPTH)if(null!==i)if(!0!==e.isOrthographicCamera){const e=E_(i,fg,mg);n=S_(e,fg,mg)}else n=i;else n=S_(Ug.z,fg,mg);return n}}x_.DEPTH_BASE="depthBase",x_.DEPTH="depth",x_.LINEAR_DEPTH="linearDepth";const S_=(e,t,i)=>e.add(t).div(t.sub(i)),T_=Uh(([e,t,i],n)=>!0===n.renderer.reversedDepthBuffer?i.sub(t).mul(e).sub(i):t.sub(i).mul(e).sub(t)),M_=(e,t,i)=>t.add(e).mul(i).div(i.sub(t).mul(e)),E_=Uh(([e,t,i],n)=>!0===n.renderer.reversedDepthBuffer?t.mul(i).div(t.sub(i).mul(e).sub(t)):t.mul(i).div(i.sub(t).mul(e).sub(i))),w_=(e,t,i)=>{t=t.max(Ap).toVar();const n=Up(e.negate().div(t)),r=Up(i.div(t));return n.div(r)},A_=Ph(x_,x_.DEPTH_BASE),R_=Lh(x_,x_.DEPTH);y_(),R_.assign=e=>A_(e),new mn;const C_=new hn;eg.flipX(),C_.depthTexture=new oa(1,1);const N_=new mn,P_=md(0).onReference(({material:e})=>e).onObjectUpdate(({material:e})=>e.refractionRatio),L_=md(1).onReference(({material:e})=>e).onObjectUpdate(function({material:e,scene:t}){return e.envMap?e.envMapIntensity:t.environmentIntensity}),D_=md(new mn).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?N_.makeRotationFromEuler(i).transpose():N_.identity(),N_}),I_=Og.negate().reflect(Yg),F_=Og.negate().refract(Yg,P_),U_=I_.transformDirection(bg).toVar("reflectVector"),O_=F_.transformDirection(bg).toVar("refractVector"),B_=new sa;class k_ extends c_{static get type(){return"CubeTextureNode"}constructor(e,t=null,i=null,n=null){super(e,t,i,n),this.isCubeTextureNode=!0}getInputType(){return!0===this.value.isDepthTexture?"cubeDepthTexture":"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===Ae?U_:e.mapping===Re?O_:(Mi('CubeTextureNode: Mapping "%s" not supported.',e.mapping),Yh(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const i=this.value;return e.renderer.coordinateSystem!==ui&&(i.isRenderTargetTexture||i.isDepthTexture)||(t=Yh(t.x.negate(),t.yz)),t}generateUV(e,t){return t.build(e,!0===this.sampler?"vec3":"ivec3")}}const z_=Ph(k_).setParameterLength(1,4).setName("cubeTexture"),G_=(e=B_,t=null,i=null,n=null)=>{let r;return e&&!0===e.isCubeTextureNode?(r=e.clone(),r.referenceNode=e,null!==t&&(r.uvNode=Rh(t)),null!==i&&(r.levelNode=Rh(i)),null!==n&&(r.biasNode=Rh(n))):r=z_(e,t,i,n),r};class V_ extends Bu{static get type(){return"ReferenceNode"}constructor(e,t,i=null,n=null){super(),this.property=e,this.uniformType=t,this.object=i,this.count=n,this.properties=e.split("."),this.reference=i,this.node=null,this.group=null,this.name=null,this.updateType=gu}isCacheable(){return!1}element(e){return new Qf(this,Rh(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=$m(null,e,this.count):Array.isArray(this.getValueFromReference())?(t=Ym(null,e),t.updateType=gu):t="texture"===e?h_(null):"cubeTexture"===e?G_(null):md(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 H_=(e,t,i)=>new V_(e,t,i),W_=(e,t,i,n)=>new V_(e,t,n,i);class j_ extends V_{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 $_=(e,t,i=null)=>new j_(e,t,i),X_=Bg(),q_=Ug.dFdx(),Y_=Ug.dFdy(),K_=X_.dFdx(),Z_=X_.dFdy(),Q_=Yg,J_=Y_.cross(Q_),ev=Q_.cross(q_),tv=J_.mul(K_.x).add(ev.mul(Z_.x)),iv=J_.mul(K_.y).add(ev.mul(Z_.y)),nv=tv.dot(tv).max(iv.dot(iv)),rv=nv.equal(0).select(0,nv.inverseSqrt()),sv=tv.mul(rv).toVar("tangentViewFrame"),av=iv.mul(rv).toVar("bitangentViewFrame"),ov=Pm("tangent","vec4"),lv=ov.xyz.toVar("tangentLocal"),cv=Uh(e=>{let t;return t="VERTEX"===e.subBuildFn||e.geometry.hasAttribute("tangent")?wg.mul(Jh(lv,0)).xyz.toVarying("v_tangentView").normalize():sv,!0!==e.isFlatShading()&&(t=Hg(t)),t},"vec3").once(["NORMAL","VERTEX"])().toVar("tangentView"),uv=Uh(([e,t],i)=>{let n=e.mul(ov.w).xyz;return"NORMAL"===i.subBuildFn&&!0!==i.isFlatShading()&&(n=n.toVarying(t)),n}).once(["NORMAL"]),hv=rd(cv,Uh(e=>{let t;return t="VERTEX"===e.subBuildFn||e.geometry.hasAttribute("tangent")?uv(Yg.cross(cv),"v_bitangentView").normalize():av,!0!==e.isFlatShading()&&(t=Hg(t)),t},"vec3").once(["NORMAL","VERTEX"])().toVar("bitangentView"),Yg).toVar("TBNViewMatrix"),dv=Uh(()=>{let e=Fd.cross(Og);return e=e.cross(Fd).normalize(),e=Rf(e,Yg,Dd.mul(Td.oneMinus()).oneMinus().pow2().pow2()).normalize(),e}).once()();class pv extends Bu{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:n}=this;let r=this.node.mul(2).sub(1);if(0===t?"rg"===n?r=n_(r.xy):"ga"===n?r=n_(r.yw):""!==n&&Mi(`THREE.NodeMaterial: Unexpected unpack normal mode: ${n}`):""!==n&&Mi(`THREE.NodeMaterial: Normal map type '${t}' is not compatible with unpack normal mode '${n}'`),null!==i){let t=i;!0===e.isFlatShading()&&(t=Hg(t)),r=Yh(r.xy.mul(t),r.z)}let s=null;return 1===t?s=Jg(r):0===t?s=hv.mul(r).normalize():(Mi(`NodeMaterial: Unsupported normal map type: ${t}`),s=Yg),s}}const fv=Ph(pv).setParameterLength(1,2),mv=Uh(({textureNode:e,bumpScale:t})=>{const i=t=>e.isolate().context({getUV:e=>t(e.uvNode||Bg()),forceUVContext:!0}),n=Gh(i(e=>e));return jh(Gh(i(e=>e.add(e.dFdx()))).sub(n),Gh(i(e=>e.add(e.dFdy()))).sub(n)).mul(t)}),gv=Uh(e=>{const{surf_pos:t,surf_norm:i,dHdxy:n}=e,r=t.dFdx().normalize(),s=i,a=t.dFdy().normalize().cross(s),o=s.cross(r),l=r.dot(a).mul(Vg),c=l.sign().mul(n.x.mul(a).add(n.y.mul(o)));return l.abs().mul(i).sub(c).normalize()});class _v extends Bu{static get type(){return"BumpMapNode"}constructor(e,t=null,i=Yg){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=mv({textureNode:this.textureNode,bumpScale:t});return gv({surf_pos:Ug,surf_norm:this.normalNode,dHdxy:i})}}const vv=Ph(_v).setParameterLength(1,3),bv=new Map;class yv extends Bu{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}isCacheable(){return!1}getCache(e,t){let i=bv.get(e);return void 0===i&&(i=$_(e,t),bv.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 n=null;if(i===yv.COLOR){const e=void 0!==t.color?this.getColor(i):Yh();n=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(i===yv.OPACITY){const e=this.getFloat(i);n=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(i===yv.SPECULAR_STRENGTH)n=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:Gh(1);else if(i===yv.SPECULAR_INTENSITY){const e=this.getFloat(i);n=t.specularIntensityMap&&!0===t.specularIntensityMap.isTexture?e.mul(this.getTexture(i).a):e}else if(i===yv.SPECULAR_COLOR){const e=this.getColor(i);n=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(i).rgb):e}else if(i===yv.ROUGHNESS){const e=this.getFloat(i);n=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(i).g):e}else if(i===yv.DIFFUSE_ROUGHNESS){const e=this.getFloat(i);n=t.diffuseRoughnessMap&&!0===t.diffuseRoughnessMap.isTexture?e.mul(this.getTexture(i).r):e}else if(i===yv.METALNESS){const e=this.getFloat(i);n=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(i).b):e}else if(i===yv.EMISSIVE){const e=this.getFloat("emissiveIntensity"),r=this.getColor(i).mul(e);n=t.emissiveMap&&!0===t.emissiveMap.isTexture?r.mul(this.getTexture(i)):r}else if(i===yv.NORMAL)t.normalMap?(n=fv(this.getTexture("normal"),this.getCache("normalScale","vec2")),n.normalMapType=t.normalMapType,t.normalMap.format!=at&&t.normalMap.format!=Wt&&t.normalMap.format!=Tt||(n.unpackNormalMode="rg")):n=t.bumpMap?vv(this.getTexture("bump").r,this.getFloat("bumpScale")):Yg;else if(i===yv.CLEARCOAT){const e=this.getFloat(i);n=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(i).r):e}else if(i===yv.CLEARCOAT_ROUGHNESS){const e=this.getFloat(i);n=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(i).g):e}else if(i===yv.CLEARCOAT_NORMAL)n=t.clearcoatNormalMap?fv(this.getTexture(i),this.getCache(i+"Scale","vec2")):Yg;else if(i===yv.SHEEN){const e=this.getColor("sheenColor").mul(this.getFloat("sheen"));n=t.sheenColorMap&&!0===t.sheenColorMap.isTexture?e.mul(this.getTexture("sheenColor").rgb):e}else if(i===yv.SHEEN_ROUGHNESS){const e=this.getFloat(i);n=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(i).a):e,n=n.clamp(1e-4,1)}else if(i===yv.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(i);n=nd(ab.x,ab.y,ab.y.negate(),ab.x).mul(e.rg.mul(2).sub(jh(1)).normalize().mul(e.b))}else n=ab;else if(i===yv.IRIDESCENCE_THICKNESS){const e=this.getFloat("iridescenceThicknessMaximum");if(t.iridescenceThicknessMap){const t=this.getFloat("iridescenceThicknessMinimum");n=e.sub(t).mul(this.getTexture(i).g).add(t)}else n=e}else if(i===yv.TRANSMISSION){const e=this.getFloat(i);n=t.transmissionMap?e.mul(this.getTexture(i).r):e}else if(i===yv.THICKNESS){const e=this.getFloat(i);n=t.thicknessMap?e.mul(this.getTexture(i).g):e}else if(i===yv.IOR)n=this.getFloat(i);else if(i===yv.LIGHT_MAP)n=t.lightMap?this.getTexture(i).rgb.mul(this.getFloat("lightMapIntensity")):Yh(0);else if(i===yv.AO)n=t.aoMap?this.getTexture(i).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1):Gh(1);else if(i===yv.LINE_DASH_OFFSET)n=t.dashOffset?this.getFloat(i):Gh(0);else{const t=this.getNodeType(e);n=this.getCache(i,t)}return n}}yv.ALPHA_TEST="alphaTest",yv.COLOR="color",yv.OPACITY="opacity",yv.SHININESS="shininess",yv.SPECULAR="specular",yv.SPECULAR_STRENGTH="specularStrength",yv.SPECULAR_INTENSITY="specularIntensity",yv.SPECULAR_COLOR="specularColor",yv.REFLECTIVITY="reflectivity",yv.ROUGHNESS="roughness",yv.DIFFUSE_ROUGHNESS="diffuseRoughness",yv.METALNESS="metalness",yv.NORMAL="normal",yv.CLEARCOAT="clearcoat",yv.CLEARCOAT_ROUGHNESS="clearcoatRoughness",yv.CLEARCOAT_NORMAL="clearcoatNormal",yv.EMISSIVE="emissive",yv.ROTATION="rotation",yv.SHEEN="sheen",yv.SHEEN_ROUGHNESS="sheenRoughness",yv.ANISOTROPY="anisotropy",yv.IRIDESCENCE="iridescence",yv.IRIDESCENCE_IOR="iridescenceIOR",yv.IRIDESCENCE_THICKNESS="iridescenceThickness",yv.IOR="ior",yv.TRANSMISSION="transmission",yv.THICKNESS="thickness",yv.ATTENUATION_DISTANCE="attenuationDistance",yv.ATTENUATION_COLOR="attenuationColor",yv.LINE_SCALE="scale",yv.LINE_DASH_SIZE="dashSize",yv.LINE_GAP_SIZE="gapSize",yv.LINE_WIDTH="linewidth",yv.LINE_DASH_OFFSET="dashOffset",yv.POINT_SIZE="size",yv.DISPERSION="dispersion",yv.RETROREFLECTIVITY="retroreflectivity",yv.LIGHT_MAP="light",yv.AO="ao";const xv=Lh(yv,yv.ALPHA_TEST),Sv=Lh(yv,yv.COLOR),Tv=Lh(yv,yv.SHININESS),Mv=Lh(yv,yv.EMISSIVE),Ev=Lh(yv,yv.OPACITY),wv=Lh(yv,yv.SPECULAR),Av=Lh(yv,yv.SPECULAR_INTENSITY),Rv=Lh(yv,yv.SPECULAR_COLOR),Cv=Lh(yv,yv.SPECULAR_STRENGTH),Nv=Lh(yv,yv.REFLECTIVITY),Pv=Lh(yv,yv.ROUGHNESS),Lv=Lh(yv,yv.DIFFUSE_ROUGHNESS),Dv=Lh(yv,yv.METALNESS),Iv=Lh(yv,yv.NORMAL),Fv=Lh(yv,yv.CLEARCOAT),Uv=Lh(yv,yv.CLEARCOAT_ROUGHNESS),Ov=Lh(yv,yv.CLEARCOAT_NORMAL),Bv=Lh(yv,yv.ROTATION),kv=Lh(yv,yv.SHEEN),zv=Lh(yv,yv.SHEEN_ROUGHNESS),Gv=Lh(yv,yv.ANISOTROPY),Vv=Lh(yv,yv.IRIDESCENCE),Hv=Lh(yv,yv.IRIDESCENCE_IOR),Wv=Lh(yv,yv.IRIDESCENCE_THICKNESS),jv=Lh(yv,yv.TRANSMISSION),$v=Lh(yv,yv.THICKNESS),Xv=Lh(yv,yv.IOR),qv=Lh(yv,yv.ATTENUATION_DISTANCE),Yv=Lh(yv,yv.ATTENUATION_COLOR),Kv=Lh(yv,yv.LINE_SCALE),Zv=Lh(yv,yv.LINE_DASH_SIZE),Qv=Lh(yv,yv.LINE_GAP_SIZE),Jv=Lh(yv,yv.LINE_WIDTH),eb=Lh(yv,yv.LINE_DASH_OFFSET),tb=Lh(yv,yv.POINT_SIZE),ib=Lh(yv,yv.DISPERSION),nb=Lh(yv,yv.RETROREFLECTIVITY),rb=Lh(yv,yv.LIGHT_MAP),sb=Lh(yv,yv.AO),ab=md(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))}),ob=Uh(e=>e.context.setupModelViewProjection(),"vec4").once()().toVarying("v_modelViewProjection");class lb extends Bu{static get type(){return"EventNode"}constructor(e,t){super("void"),this.eventType=e,this.callback=t,e===lb.OBJECT?this.updateType=gu:e===lb.MATERIAL?this.updateType=mu:e===lb.FRAME?this.updateType=fu:e===lb.AFTER_OBJECT?this.updateAfterType=gu:e===lb.BEFORE_OBJECT?this.updateBeforeType=gu:e===lb.BEFORE_MATERIAL?this.updateBeforeType=mu:e===lb.BEFORE_FRAME&&(this.updateBeforeType=fu)}isCacheable(){return!1}setup(e){const{eventType:t,callback:i}=this;if(t===lb.BEFORE_RENDER_PIPELINE){const t=e.context.onBeforePipelineCallbacks;t&&t.push(i)}else if(t===lb.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)}}lb.OBJECT="object",lb.MATERIAL="material",lb.FRAME="frame",lb.AFTER_OBJECT="afterObject",lb.BEFORE_OBJECT="beforeObject",lb.BEFORE_MATERIAL="beforeMaterial",lb.BEFORE_FRAME="beforeFrame",lb.BEFORE_RENDER_PIPELINE="beforeRenderPipeline",lb.AFTER_RENDER_PIPELINE="afterRenderPipeline";const cb=(e,t)=>new lb(e,t).toStack(),ub=e=>cb(lb.OBJECT,e),hb=e=>cb(lb.AFTER_OBJECT,e);class db extends ku{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 n=e.isContextAssign();if(i=!1===e.isAvailable("storageBuffer")?!0!==this.node.isPBO||!0===n||!this.node.value.isInstancedBufferAttribute&&"compute"===e.shaderStage?this.node.build(e):e.generatePBO(this):super.generate(e),!0!==n){const n=this.getNodeType(e);i=e.format(i,n,t)}return i}}const pb=Ph(db).setParameterLength(2);class fb extends jm{static get type(){return"StorageBufferNode"}constructor(e,t=null,i=0){let n,r=null;t&&t.isStructTypeNode?(n="struct",r=t,(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(i=e.count)):null===t&&(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)?(n=Nu(e.itemSize),i=e.count):n=t,super(e,n,i),this.isStorageBufferNode=!0,this.structTypeNode=r,this.access=bu,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 pb(this,e)}setPBO(e){return this.isPBO=e,this}getPBO(){return this.isPBO}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(_u)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return null===this._attribute&&(this._attribute=lm(this.value),this._varying=$f(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(),n=i.build(e);return e.registerTransform(n,t),e.format(n,t.getNodeType(e),this.getNodeType(e))}}const mb=(e,t=null,i=0)=>new fb(e,t,i),gb=new WeakMap;function _b(e,t,i){let n=gb.get(e);return void 0===n&&(n=[],gb.set(e,n)),n[i]||(n[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 Mu)}(t),i))}class vb extends am{static get type(){return"ReferenceBufferAttributeNode"}constructor(e,t,i=0,n=0){super(null,t,i,n),this.referenceNode=e,this.isReferenceBufferAttributeNode=!0}getHash(){return String(this.id)}getObjectAttribute(e){const t=this.referenceNode.getAttribute(e);return t&&0!==this.bufferStride?_b(t,this.bufferType,this.bufferOffset):t}setup(e){this.attribute=this.getObjectAttribute(e.object)}}class bb extends Bu{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?pm:dm;return mb(t,i,Math.max(t.count,1)).onObjectUpdate(({object:e})=>this.getAttribute(e)).element(e)}return"mat4"===i?sd(...[0,4,8,12].map(e=>new vb(this,"vec4",16,e))):"mat3"===i?rd(...[0,3,6].map(e=>new vb(this,"vec3",9,e))):new vb(this,i)}}const yb=(e,t=null,i=null)=>new bb(e,t,i),xb=new WeakMap,Sb=new WeakMap;function Tb(e,t){let i;const n=Math.max(t.count,1);if(!0===t.isStorageInstancedBufferAttribute)i=mb(t,"mat4",n).element(pm);else{if(16*n*4<=e.getUniformBufferLimit())i=$m(t.array,"mat4",n).element(pm);else{const e=t.usage===oi?um:cm,n=[0,4,8,12].map(i=>e(new ts(t,4,i)));i=sd(...n)}}return i}function Mb({target:e}){xb.get(e).previousInstanceMatrix.dispose()}function Eb(e){const t=e.instanceMatrix;let i=Sb.get(e);return void 0!==i&&i.count===t.count||(void 0===i?e.addEventListener("dispose",wb):i.dispose(),i=t.clone(),Sb.set(e,i)),i}function wb({target:e}){e.removeEventListener("dispose",wb),Sb.get(e).dispose(),Sb.delete(e)}class Ab extends bb{static get type(){return"PreviousInstanceMatrixNode"}constructor(){super("previousInstanceMatrix","mat4")}getValueFromReference(e){return Eb(e)}}function Rb(e,t,i){const n=t.mul(Lg).xyz;if(Lg.assign(n),null!==i&&Dg.assign(i.mul(Dg).xyz),e.hasGeometryAttribute("normal")){const e=Qg(jg,t);jg.assign(e)}}const Cb=vd("vec3","vInstanceColor"),Nb=Uh(([e,t=null],i)=>{const n=t&&!0===t.isStorageInstancedBufferAttribute,r=Tb(i,e);let s=null;if(t)if(n)s=mb(t,"vec3",Math.max(t.count,1)).element(pm);else{const e=t.usage===oi?um:cm;s=Yh(e(t))}let a=null;if(i.needsPreviousData()){const t=i.object;hb(({object:t})=>{const{previousInstanceMatrix:i}=xb.get(t);i.array.set(e.array),i.version=e.version}),a=function(e,t,i){let n=xb.get(e);if(void 0===n){const r=t.clone();n={previousInstanceMatrix:r,node:Tb(i,r)},xb.set(e,n),e.addEventListener("dispose",Mb)}return n.node}(t,e,i)}Rb(i,r,a),null!==s&&Cb.assign(s)},"void"),Pb=Uh(([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()&&(hb(({object:e})=>{const t=Eb(e);t.array.set(e.instanceMatrix.array),t.version=e.instanceMatrix.version}),i=new Ab),Rb(t,yb("instanceMatrix","mat4"),i),null!==e.instanceColor&&Cb.assign(yb("instanceColor","vec3"))}else t.objectSpecific=!0,Nb(e.instanceMatrix,e.instanceColor)},"void"),Lb=Uh(([e,t])=>{const i=Vh(o_(d_(e),0).x).toConst(),n=Vh(t),r=n.mod(i).toConst(),s=n.div(i).toConst();return d_(e,$h(r,s))}),Db=Uh(([e,t])=>{const i=Vh(o_(d_(e),0).x).toConst(),n=Vh(t).mod(i).toConst(),r=Vh(t).div(i).toConst();return d_(e,$h(n,r)).x});function Ib(e,t){const i=Vh(o_(d_(e),0).x).toConst(),n=Gh(t).mul(4).toInt().toConst(),r=n.mod(i).toConst(),s=n.div(i).toConst();return sd(d_(e,$h(r,s)),d_(e,$h(r.add(1),s)),d_(e,$h(r.add(2),s)),d_(e,$h(r.add(3),s)))}function Fb(e){let t=e._previousMatricesTexture;if(null===t){const{image:i,format:n,type:r,version:s}=e._matricesTexture;t=new Rs(i.data.slice(),i.width,i.height,n,r),t.version=s,e._previousMatricesTexture=t}return t}const Ub=vd("vec4","vBatchColor"),Ob=vd("uint","vBatchIndirectId"),Bb=Uh(([e],t)=>{const i=null===t.getDrawIndex()?pm:fm,n=Db(e._indirectTexture,Vh(i));Ob.assign(n);const r=Ib(e._matricesTexture,n),s=e._colorsTexture;if(null!==s){const e=Lb(s,n);Ub.assign(e)}const a=rd(r);if(Lg.assign(r.mul(Lg)),t.needsPreviousData()){hb(({object:e})=>{const t=Fb(e),i=e._matricesTexture;t.version!==i.version&&(t.image.data.set(i.image.data),t.version=i.version)});const t=Ib(Fb(e),n);Dg.assign(t.mul(Dg).xyz)}const o=jg.div(Yh(a[0].dot(a[0]),a[1].dot(a[1]),a[2].dot(a[2]))),l=a.mul(o).xyz;jg.assign(l),t.hasGeometryAttribute("tangent")&&lv.mulAssign(a);const c=!0===t.renderer.backend.isWebGPUBackend?"merged":"multiDraw";ub(({object:e,camera:t,material:i})=>{e._updateDrawParameters(t,e.geometry,i,c)})},"void"),kb=new WeakMap;function zb(e){return{element:t=>{const i=Vh(o_(e).x).toConst(),n=Vh(t).mul(4).toConst(),r=n.div(i).toConst(),s=n.sub(r.mul(i)).toConst();return sd(e.load($h(s,r)),e.load($h(s.add(1),r)),e.load($h(s.add(2),r)),e.load($h(s.add(3),r)))}}}function Gb(e,t,i,n,r,s){const a=e.element(r.x),o=e.element(r.y),l=e.element(r.z),c=e.element(r.w),u=i.mul(t),h=ep(a.mul(s.x).mul(u),o.mul(s.y).mul(u),l.mul(s.z).mul(u),c.mul(s.w).mul(u));return n.mul(h).xyz}function Vb(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 Hb=Uh(([e],t)=>{const i=Pm("skinIndex","uvec4"),n=Pm("skinWeight","vec4"),r=H_("bindMatrix","mat4"),s=H_("bindMatrixInverse","mat4"),a=function(e,t){let i;if(16*t.bones.length*4<=e.getUniformBufferLimit())i=W_("skeleton.boneMatrices","mat4",t.bones.length);else{null===t.boneTexture&&t.computeBoneTexture();const e=h_(t.boneTexture);ub(({object:t})=>{const i=t.skeleton;null===i.boneTexture&&i.computeBoneTexture(),e.value=i.boneTexture}),i=zb(e)}return i}(t,e.skeleton),o=t.needsPreviousData();if(ub(({object:e,frameId:t})=>{const i=e.skeleton;o&&Vb(i),kb.get(i)!==t&&(kb.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(Vb(t),16*t.bones.length*4<=e.getUniformBufferLimit())i=W_("skeleton.previousBoneMatrices","mat4",t.bones.length);else{const e=h_(t.previousBoneTexture);ub(({object:t})=>{e.value=t.skeleton.previousBoneTexture}),i=zb(e)}return i}(t,e.skeleton),o=Gb(a,Dg,r,s,i,n);Dg.assign(o)}const l=Gb(a,Lg,r,s,i,n);if(Lg.assign(l),t.hasGeometryAttribute("normal")){const{skinNormal:e,skinTangent:o}=function(e,t,i,n,r,s,a){const o=e.element(s.x),l=e.element(s.y),c=e.element(s.z),u=e.element(s.w);let h=ep(a.x.mul(o),a.y.mul(l),a.z.mul(c),a.w.mul(u));h=r.mul(h).mul(n);const d=rd(h);return{skinNormal:d.mul(t),skinTangent:d.mul(i)}}(a,jg,lv,r,s,i,n);jg.assign(e),t.hasGeometryAttribute("tangent")&&lv.assign(o)}},"void"),Wb=new WeakMap,jb=new un,$b=new WeakMap,Xb=Uh(({bufferMap:e,influence:t,stride:i,width:n,depth:r,offset:s})=>{const a=Vh(dm).mul(i).add(s),o=a.div(n),l=a.sub(o.mul(n));return d_(e,$h(l,o)).depth(r).mul(t)}),qb=md(1).onObjectUpdate(({object:e})=>e.geometry.morphTargetsRelative?1:1-e.morphTargetInfluences.reduce((e,t)=>e+t,0)),Yb=_d("vec4","morphColorSum"),Kb=Uh(([e],{geometry:t})=>4===t.morphAttributes.color[0].itemSize?$f(e.mul(qb).add(Yb)):$f(Jh(e.rgb.mul(qb).add(Yb.rgb),e.a)));const Zb=Uh(([e],t)=>{const{geometry:i}=e,n=void 0!==i.morphAttributes.position,r=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 c=$b.get(e);void 0!==c&&c.count===l||(c={influences:e.morphTargetInfluences?Ym(e.morphTargetInfluences,"float"):null,count:l},$b.set(e,c));const{influences:u}=c,{texture:h,stride:d,size:p}=function(e){const t=void 0!==e.morphAttributes.position,i=void 0!==e.morphAttributes.normal,n=void 0!==e.morphAttributes.color,r=e.morphAttributes.position||e.morphAttributes.normal||e.morphAttributes.color,s=void 0!==r?r.length:0;let a=Wb.get(e);if(void 0===a||a.count!==s){void 0!==a&&a.texture.dispose();const o=e.morphAttributes.position||[],l=e.morphAttributes.normal||[],c=e.morphAttributes.color||[];let u=0;!0===t&&(u=1),!0===i&&(u=2),!0===n&&(u=3);let h=e.attributes.position.count*u,d=1;const p=4096;h>p&&(d=Math.ceil(h/p),h=p);const f=new Float32Array(h*d*4*s),m=new pn(f,h,d,s);m.type=$e,m.needsUpdate=!0;const g=4*u;for(let v=0;v<s;v++){const b=o[v],y=l[v],x=c[v],S=h*d*4*v;for(let T=0;T<b.count;T++){const M=T*g;!0===t&&(jb.fromBufferAttribute(b,T),f[S+M+0]=jb.x,f[S+M+1]=jb.y,f[S+M+2]=jb.z,f[S+M+3]=0),!0===i&&(jb.fromBufferAttribute(y,T),f[S+M+4]=jb.x,f[S+M+5]=jb.y,f[S+M+6]=jb.z,f[S+M+7]=0),!0===n&&(jb.fromBufferAttribute(x,T),f[S+M+8]=jb.x,f[S+M+9]=jb.y,f[S+M+10]=jb.z,f[S+M+11]=4===x.itemSize?jb.w:1)}}function _(){m.dispose(),Wb.delete(e),e.removeEventListener("dispose",_)}a={count:s,texture:m,stride:u,size:new Vi(h,d)},Wb.set(e,a),e.addEventListener("dispose",_)}return a}(i);!0===n&&Lg.mulAssign(qb),!0===r&&jg.mulAssign(qb),!0===s&&Yb.assign(0);const f=Vh(p.width);zm(l,({i:t})=>{const i=Gh(0).toVar();e.count>1&&null!==e.morphTexture&&void 0!==e.morphTexture?i.assign(d_(e.morphTexture,$h(Vh(t).add(1),Vh(pm))).r):i.assign(u.element(t).toVar()),kh(i.notEqual(0),()=>{if(!0===n&&Lg.addAssign(Xb({bufferMap:h,influence:i,stride:d,width:f,depth:t,offset:Vh(0)}).xyz),!0===r&&jg.addAssign(Xb({bufferMap:h,influence:i,stride:d,width:f,depth:t,offset:Vh(1)}).xyz),!0===s){const e=Xb({bufferMap:h,influence:i,stride:d,width:f,depth:t,offset:Vh(2)});!0===a?Yb.addAssign(e):Yb.rgb.addAssign(e.rgb)}})}),ub(({object:e})=>{const{influences:t}=c;t&&(t.array=e.morphTargetInfluences,t.update())})},"void");class Qb extends Bu{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}isCacheable(){return!1}}class Jb extends Qb{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class ey extends Bf{static get type(){return"LightingContextNode"}constructor(e,t=null,i=[],n=null,r=null){super(e),this.lightingModel=t,this.materialLightings=i,this.backdropNode=n,this.backdropAlphaNode=r,this._value=null}getContext(){const{materialLightings:e,backdropNode:t,backdropAlphaNode:i}=this,n={directDiffuse:Yh().toVar("directDiffuse"),directSpecular:Yh().toVar("directSpecular"),indirectDiffuse:Yh().toVar("indirectDiffuse"),indirectSpecular:Yh().toVar("indirectSpecular")};return{radiance:Yh().toVar("radiance"),irradiance:Yh().toVar("irradiance"),iblIrradiance:Yh().toVar("iblIrradiance"),ambientOcclusion:Gh(1).toVar("ambientOcclusion"),reflectedLight:n,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 ty=Ph(ey);class iy extends Qb{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}class ny extends Bu{static get type(){return"ClippingNode"}constructor(e=ny.DEFAULT){super(),this.scope=e}isCacheable(){return!1}setup(e){super.setup(e);const t=e.clippingContext,{intersectionPlanes:i,unionPlanes:n}=t;return this.hardwareClipping=e.hardwareClipping,this.position=!0===e.camera.isArrayCamera?bg.mul(Jh(Ug,1)).xyz:Ug,this.scope===ny.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(i,n):this.scope===ny.HARDWARE?this.setupHardwareClipping(n,e):this.setupDefault(i,n)}setupAlphaToCoverage(e,t){return Uh(()=>{const i=Gh().toVar("distanceToPlane"),n=Gh().toVar("distanceToGradient"),r=Gh(1).toVar("clipOpacity"),s=t.length;if(!1===this.hardwareClipping&&s>0){const e=Ym(t).setGroup(dd);zm(s,({i:t})=>{const s=e.element(t);i.assign(this.position.dot(s.xyz).negate().add(s.w)),n.assign(i.fwidth().div(2)),r.mulAssign(Lf(n.negate(),n,i))})}const a=e.length;if(a>0){const t=Ym(e).setGroup(dd),s=Gh(1).toVar("intersectionClipOpacity");zm(a,({i:e})=>{const r=t.element(e);i.assign(this.position.dot(r.xyz).negate().add(r.w)),n.assign(i.fwidth().div(2)),s.mulAssign(Lf(n.negate(),n,i).oneMinus())}),r.mulAssign(s.oneMinus())}bd.a.mulAssign(r),bd.a.equal(0).discard()})()}setupDefault(e,t){return Uh(()=>{const i=t.length;if(!1===this.hardwareClipping&&i>0){const e=Ym(t).setGroup(dd);zm(i,({i:t})=>{const i=e.element(t);this.position.dot(i.xyz).greaterThan(i.w).discard()})}const n=e.length;if(n>0){const t=Ym(e).setGroup(dd),i=Wh(!0).toVar("clipped");zm(n,({i:e})=>{const n=t.element(e);i.assign(this.position.dot(n.xyz).greaterThan(n.w).and(i))}),i.discard()}})()}setupHardwareClipping(e,t){const i=e.length;return t.enableHardwareClipping(i),Uh(()=>{const n=Ym(e).setGroup(dd),r=Wm(t.getClipDistance());zm(i,({i:e})=>{const t=n.element(e),i=this.position.dot(t.xyz).sub(t.w).negate();r.element(e).assign(i)})})()}}ny.ALPHA_TO_COVERAGE="alphaToCoverage",ny.DEFAULT="default",ny.HARDWARE="hardware";const ry=["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"],sy=new WeakMap,ay=new WeakMap,oy=new WeakMap,ly=new WeakMap,cy=new WeakMap;class uy{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=!0===e.object.isSkinnedMesh,this.refreshUniforms=ry,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:n}=e;t={geometryId:i.id,geometryVersion:this.getGeometryData(i)._version,materialVersion:this.getMaterialData(e.material)._version,attributesDisposeVersion:e._geometries.attributes.disposeVersion,worldMatrix:n.matrixWorld.clone()},n.center&&(t.center=n.center.clone()),n.morphTargetInfluences&&(t.morphTargetInfluences=n.morphTargetInfluences.slice()),!0===n.isInstancedMesh&&(t.instanceMatrix=n.instanceMatrix,t.instanceMatrixVersion=n.instanceMatrix.version,t.instanceColor=n.instanceColor,t.instanceColorVersion=null!==n.instanceColor?n.instanceColor.version:null,t.morphTextureVersion=null!==n.morphTexture?n.morphTexture.version:null),!0===n.isBatchedMesh&&(t.matricesTextureVersion=n._matricesTexture.version,t.colorsTextureVersion=null!==n._colorsTexture?n._colorsTexture.version:null,t.indirectTextureVersion=n._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:r,environmentIntensity:s,environmentRotation:a}=e.scene;t.environmentIntensity=s,t.environmentRotation=a.clone(),t.environmentVersion=null!==r?this.getTextureData(r)._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:n}=t;let r=cy.get(e);return void 0===r?(r={_version:0,width:i,height:n},cy.set(e,r)):r.width===i&&r.height===n||(r.width=i,r.height=n,r._version++),r}getAttributesData(e){const t={};for(const i in e){const n=e[i];t[i]={id:n.isInterleavedBufferAttribute?n.data.uuid:n.id,version:n.isInterleavedBufferAttribute?n.data.version:n.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=oy.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++}),oy.set(e,t)),t}getTextureData(e){let t=ly.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),ly.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=ay.get(e);if(void 0===t){t={_renderId:-1,_version:0};for(const i of this.refreshUniforms){const n=e[i];void 0!==n&&(null===n?t[i]=null:"object"==typeof n&&void 0!==n.clone?!0===n.isTexture?t[i]={id:n.id,version:0,cacheVersion:this.getTextureData(n)._version,transform:this.getTextureTransformData(n)}:t[i]=n.clone():t[i]=n)}ay.set(e,t)}return t}equals(e,t,i){const{object:n,material:r,geometry:s}=e,a=this.getRenderObjectData(e);if(!0!==a.worldMatrix.equals(n.matrixWorld))return a.worldMatrix.copy(n.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],n=r[t];if("_renderId"!==t&&"_version"!==t)if(null===i||null==n)i!==(void 0===n?null:n)&&(null==n?o[t]=null:!0===n.isTexture?o[t]={id:n.id,version:n.version,cacheVersion:this.getTextureData(n)._version,transform:this.getTextureTransformData(n)}:"object"==typeof n&&void 0!==n.clone?o[t]=n.clone():o[t]=n,e=!0);else if(void 0!==i.equals)!1===i.equals(n)&&(i.copy(n),e=!0);else if(!0===n.isTexture){const t=this.getTextureData(n);i.id===n.id&&i.version===n.version&&i.cacheVersion===t._version&&!1!==this.equalsTextureTransform(i.transform,n)||(i.id=n.id,i.version=n.version,i.cacheVersion=t._version,i.transform.offset.copy(n.offset),i.transform.repeat.copy(n.repeat),i.transform.center.copy(n.center),i.transform.rotation=n.rotation,i.transform.matrix.copy(n.matrix),e=!0)}else i!==n&&(o[t]=n,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 c=this.getGeometryData(e.geometry);if(c._renderId!==i){c._renderId=i;let e=!1;const t=s.attributes,n=c.attributes;let r=0,a=0;for(const e in t)r++;for(const i in n){a++;const r=n[i],s=t[i];if(void 0===s){delete n[i],e=!0;continue}const o=s.isInterleavedBufferAttribute?s.data.uuid:s.id,l=s.isInterleavedBufferAttribute?s.data.version:s.version;r.id===o&&r.version===l||(r.id=o,r.version=l,e=!0)}a!==r&&(c.attributes=this.getAttributesData(t),e=!0);const o=s.index,l=o?o.id:null,u=o?o.version:null;c.indexId===l&&c.indexVersion===u||(c.indexId=l,c.indexVersion=u,e=!0),c.drawRange.start===s.drawRange.start&&c.drawRange.count===s.drawRange.count||(c.drawRange.start=s.drawRange.start,c.drawRange.count=s.drawRange.count,e=!0),!0===e&&c._version++}if(a.geometryVersion!==c._version)return a.geometryVersion=c._version,!1;if(a.morphTargetInfluences){let e=!1;for(let t=0;t<a.morphTargetInfluences.length;t++)a.morphTargetInfluences[t]!==n.morphTargetInfluences[t]&&(a.morphTargetInfluences[t]=n.morphTargetInfluences[t],e=!0);if(e)return!1}if(!0===n.isInstancedMesh){const e=null!==n.instanceColor?n.instanceColor.version:null,t=null!==n.morphTexture?n.morphTexture.version:null;if(a.instanceMatrix!==n.instanceMatrix||a.instanceMatrixVersion!==n.instanceMatrix.version||a.instanceColor!==n.instanceColor||a.instanceColorVersion!==e||a.morphTextureVersion!==t)return a.instanceMatrix=n.instanceMatrix,a.instanceMatrixVersion=n.instanceMatrix.version,a.instanceColor=n.instanceColor,a.instanceColorVersion=e,a.morphTextureVersion=t,!1}if(!0===n.isBatchedMesh){const e=null!==n._colorsTexture?n._colorsTexture.version:null;if(a.matricesTextureVersion!==n._matricesTexture.version||a.colorsTextureVersion!==e||a.indirectTextureVersion!==n._indirectTexture.version)return a.matricesTextureVersion=n._matricesTexture.version,a.colorsTextureVersion=e,a.indirectTextureVersion=n._indirectTexture.version,!1}if(a.lights)for(let e=0;e<t.length;e++){const i=a.lights[e],n=t[e];if(i.map!==n.map||i.cacheVersion!==n.cacheVersion||i.shadowMapWidth!==n.shadowMapWidth||i.shadowMapHeight!==n.shadowMapHeight)return i.map=n.map,i.cacheVersion=n.cacheVersion,i.shadowMapWidth=n.shadowMapWidth,i.shadowMapHeight=n.shadowMapHeight,!1}const u=e.scene;if(null!==u.environment&&null===r.envMap){const e=this.getTextureData(u.environment)._version;if(a.environmentIntensity!==u.environmentIntensity||!1===a.environmentRotation.equals(u.environmentRotation)||a.environmentVersion!==e)return a.environmentIntensity=u.environmentIntensity,a.environmentRotation.copy(u.environmentRotation),a.environmentVersion=e,!1}return a.center&&!1===a.center.equals(n.center)?(a.center.copy(n.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=sy.get(e);return void 0===i&&(i={renderId:-1,lightsData:[]},sy.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 n=e.getIndex();return null!==n&&!1===i.has(n)||(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 n=fi;this.renderId!==i&&(this.renderId=i,n=mi);const r=this.getRenderObjectData(e),s=this.getOutputTarget(t.renderer);r.outputTarget!==s&&(r.outputTarget=s,n=gi);const a=e._geometries.attributes;r.attributesDisposeVersion!==a.disposeVersion&&this.hasDisposedAttributes(e,r)&&(n=gi);const o=!0===e.object.static,l=null!==e.bundle&&!0===e.bundle.static&&r.version===e.bundle.version;if(o||l)return n;const c=this.getLights(e.lightsNode,i);return!1===this.equals(e,c,i)&&(n=gi),n}}const hy=Uh(([e])=>Vp(ip(1e4,Hp(ip(17,e.x).add(ip(.1,e.y)))).mul(ep(.1,tf(Hp(ip(13,e.y).add(e.x)))))),{value:"vec2",return:"float"}),dy=Uh(([e])=>hy(jh(hy(e.xy),e.z)),{value:"vec3",return:"float"}),py=Uh(([e])=>{const t=_f(rf(of(e.xyz)),rf(lf(e.xyz))),i=Gh(1).div(Gh(.05).mul(t)).toVar("pixScale"),n=jh(Ip(kp(Up(i))),Ip(zp(Up(i)))),r=jh(dy(kp(n.x.mul(e.xyz))),dy(kp(n.y.mul(e.xyz)))),s=Vp(Up(i)),a=ep(ip(s.oneMinus(),r.x),ip(s,r.y)),o=gf(s,s.oneMinus()),l=Yh(a.mul(a).div(ip(2,o).mul(tp(1,o))),a.sub(ip(.5,o)).div(tp(1,o)),tp(1,tp(1,a).mul(tp(1,a)).div(ip(2,o).mul(tp(1,o))))),c=a.lessThan(o.oneMinus()).select(a.lessThan(o).select(l.x,l.y),l.z);return Cf(c,1e-6,1)},{position:"vec3",return:"float"});class fy extends Nm{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 un(1,1,1,1)),i}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}class my 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(wu(t.slice(0,-4)),i.getCacheKey(!0));return this.type+Au(e)}build(e){this.setup(e)}setupObserver(e){return new uy(e)}setup(e){e.context.setupNormal=()=>Wf(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 n=this.setupVertex(e),r=Wf(this.vertexNode||n,"VERTEX");let s;e.context.clipSpace=r,e.stack.outputNode=r,this.setupHardwareClipping(e),null!==this.geometryNode&&(e.stack.outputNode=e.stack.outputNode.bypass(this.geometryNode)),e.addFlow("vertex",e.removeStack()),e.addStack();const a=this.setupClipping(e);if(!0!==this.depthWrite&&!0!==this.depthTest||(null!==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 n=this.setupLighting(e);null!==a&&e.stack.addToStack(a);const r=Jh(n,bd.a).max(0);s=this.setupOutput(e,r),zd.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&&zd.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 n=null;if(t.length>0||i.length>0){const t=e.renderer.currentSamples;this.alphaToCoverage&&t>1?n=new ny(ny.ALPHA_TO_COVERAGE):e.stack.addToStack(new ny)}return n}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 ny(ny.HARDWARE)),e.hardwareClipping=!0)}setupDepth(e){const{renderer:t,camera:i}=e;let n=this.depthNode;if(null===n){const e=t.getMRT();e&&e.has("depth")?n=e.get("depth"):!0===t.logarithmicDepthBuffer&&(n=!0!==i.isOrthographicCamera?w_(Ug.z,fg,mg):S_(Ug.z,fg,mg))}null!==n&&R_.assign(n).toStack()}setupPositionView(){return wg.mul(Lg).xyz}setupModelViewProjection(){return gg.mul(Ug)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.position=e.removeStack(),ob}setupPosition(e){const{object:t,geometry:i}=e;if((i.morphAttributes.position||i.morphAttributes.normal||i.morphAttributes.color)&&Zb(t),!0===t.isSkinnedMesh&&Hb(t),this.displacementMap){const e=$_("displacementMap","texture"),t=$_("displacementScale","float"),i=$_("displacementBias","float");Lg.addAssign(jg.normalize().mul(e.x.mul(t).add(i)))}return t.isBatchedMesh&&Bb(t),t.isInstancedMesh&&t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&Pb(t),null!==this.positionNode&&Lg.assign(Wf(this.positionNode,"POSITION","vec3")),Lg}setupDiffuseColor(e){const{object:t,geometry:i}=e;null!==this.maskNode&&Wh(this.maskNode).not().discard();let n=this.colorNode?Jh(this.colorNode):Sv,r=null;!0===this.vertexColors&&i.hasAttribute("color")&&(r=((e=0)=>new fy(e))()),t.instanceColor&&(r=null!==r?r.mul(Cb):Cb),t.isBatchedMesh&&t._colorsTexture&&(r=null!==r?r.mul(Ub):Ub),!0===this.vertexColors&&void 0!==i.morphAttributes.color&&(r=Kb(Jh(null!==r?r:1))),null!==r&&(n=n.mul(r)),bd.assign(n);const s=this.opacityNode?Gh(this.opacityNode):Ev;bd.a.assign(bd.a.mul(s));let a=null;(null!==this.alphaTestNode||this.alphaTest>0)&&(a=null!==this.alphaTestNode?Gh(this.alphaTestNode):xv,!0===this.alphaToCoverage?(bd.a=Lf(a,a.add(df(bd.a)),bd.a),bd.a.lessThanEqual(0).discard()):bd.a.lessThanEqual(a).discard()),!0===this.alphaHash&&bd.a.lessThan(py(Lg)).discard(),e.isOpaque()&&bd.a.assign(1)}setupVariants(){}setupOutgoingLight(){return!0===this.lights?Yh(0):bd.rgb}setupNormal(){return this.normalNode?Yh(this.normalNode):Iv}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?$_("envMap","cubeTexture"):$_("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new iy(rb)),t}setupMaterialLightings(e){const t=[],i=this.setupEnvironment(e);i&&i.isLightingNode&&t.push(i);const n=this.setupLightMap(e);if(n&&n.isLightingNode&&t.push(n),e.context.ambientOcclusion&&t.push(new Jb(e.context.ambientOcclusion)),e.context.getGI){const i=e.context.getGI(null,e);null!==i&&t.push(new iy(i))}return t}setupAmbientOcclusion(e){let t=this.aoNode;null===t&&e.material.aoMap&&(t=sb),e.context.getAO&&(t=e.context.getAO(t,e)),null!==t&&(Kd.assign(t),e.context.ambientOcclusion=Kd)}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:i,backdropAlphaNode:n,emissiveNode:r}=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 c=this.setupOutgoingLight(e);if(l&&(o.length>0||l.getScope().hasLights)){const t=this.setupLightingModel(e)||null;c=ty(l,t,o,i,n)}else null!==i&&(c=Yh(null!==n?Rf(c,i,n):i));return(r&&!0===r.isNode||t.emissive&&!0===t.emissive.isColor)&&(Sd.assign(Yh(r||Mv)),c=c.add(Sd)),c}setupFog(e,t){const i=e.fogNode;return i&&(zd.assign(t),t=Jh(i.toVar())),t}setupPremultipliedAlpha(e,t){return Tm(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:n}of this._getNodeChildren())i.inputNodes[t]=n.toJSON(e).uuid;function n(e){const t=[];for(const i in e){const n=e[i];delete n.metadata,t.push(n)}return t}if(t){const t=n(e.textures),r=n(e.images),s=n(e.nodes);t.length>0&&(i.textures=t),r.length>0&&(i.images=r),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 gy=new so(-1,1,1,-1,0,1);class _y extends Zr{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new kr([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new kr(t,2))}}const vy=new _y,by=Jh(ld([-1,-1,3]).element(dm),ld([3,-1,-1]).element(dm),0,1);class yy extends ws{constructor(e){super(vy,e),this.camera=gy,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,gy)}render(e){const t=this.material.vertexNode;this.material.vertexNode=by,e.render(this,gy),this.material.vertexNode=t}}function xy(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 Kn),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 Sy=Uh(([e])=>Vp(Gh(52.9829189).mul(Vp(Sf(e,jh(.06711056,.00583715))))),{position:"vec2",return:"float"}),Ty=Uh(([e,t,i])=>{const n=Gh(2.399963229728653),r=Op(Gh(e).add(.5).div(Gh(t))),s=Gh(e).mul(n).add(i);return jh(jp(s),Hp(s)).mul(r)},{sampleIndex:"int",samplesCount:"int",phi:"float",return:"vec2"}),My=1/6,Ey=e=>{const t=(e=>ip(My,ip(e,ip(e,e.negate().add(3)).sub(3)).add(1)))(e),i=(e=>ip(My,ip(e,ip(e,ip(3,e).sub(6))).add(4)))(e),n=(e=>ip(My,ip(e,ip(e,ip(-3,e).add(3)).add(3)).add(1)))(e),r=(e=>ip(My,Mf(e,3)))(e),s=t.add(i),a=n.add(r);return{g0:s,g1:a,h0:ep(-1,i.div(s)),h1:ep(1,r.div(a))}},wy=(e,t,i,n,r,s)=>{const a=jh(i.x,t.y),o=jh(t.x,i.y),l=n.y.mul(ep(n.x.mul(e.sample(t).level(s)),r.x.mul(e.sample(a).level(s)))),c=r.y.mul(ep(n.x.mul(e.sample(o).level(s)),r.x.mul(e.sample(i).level(s))));return l.add(c)},Ay=Uh(([e,t])=>{const i=jh(e.size(Vh(t))),n=jh(e.size(Vh(t.add(1)))),r=Jh(i,n),s=np(1,r),a=e.uvNode.xyxy.mul(r).add(.5),o=kp(a),l=Vp(a),{g0:c,g1:u,h0:h,h1:d}=Ey(l),p=o.add(h).sub(.5).mul(s),f=o.add(d).sub(.5).mul(s),m=wy(e,p.xy,f.xy,c.xy,u.xy,kp(t)),g=wy(e,p.zw,f.zw,c.zw,u.zw,zp(t));return Vp(t).mix(m,g)}),Ry=new mn,Cy=md(0).setGroup(dd).onRenderUpdate(({scene:e})=>e.backgroundBlurriness),Ny=md(1).setGroup(dd).onRenderUpdate(({scene:e})=>e.backgroundIntensity),Py=md(new mn).setGroup(dd).onRenderUpdate(({scene:e})=>{const t=e.background;return null!==t&&t.isTexture&&300!==t.mapping||e.backgroundNode&&e.backgroundNode.isNode?Ry.makeRotationFromEuler(e.backgroundRotation).transpose():Ry.identity(),Ry}),Ly=Uh(([e,t])=>e.mul(t).clamp(),{color:"vec3",exposure:"float",return:"vec3"}),Dy=Uh(([e,t])=>(e=e.mul(t)).div(e.add(1)).clamp(),{color:"vec3",exposure:"float",return:"vec3"}),Iy=Uh(([e,t])=>{const i=(e=(e=e.mul(t)).sub(.004).max(0)).mul(e.mul(6.2).add(.5)),n=e.mul(e.mul(6.2).add(1.7)).add(.06);return i.div(n).pow(2.2)},{color:"vec3",exposure:"float",return:"vec3"}),Fy=Uh(([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"}),Uy=Uh(([e,t])=>{const i=rd(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),n=rd(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=i.mul(e),e=Fy(e),(e=n.mul(e)).clamp()},{color:"vec3",exposure:"float",return:"vec3"}),Oy=rd(Yh(1.6605,-.1246,-.0182),Yh(-.5876,1.1329,-.1006),Yh(-.0728,-.0083,1.1187)),By=rd(Yh(.6274,.0691,.0164),Yh(.3293,.9195,.088),Yh(.0433,.0113,.8956)),ky=Uh(([e])=>{const t=Yh(e).toVar(),i=Yh(t.mul(t)).toVar(),n=Yh(i.mul(i)).toVar();return Gh(15.5).mul(n.mul(i)).sub(ip(40.14,n.mul(t))).add(ip(31.96,n).sub(ip(6.868,i.mul(t))).add(ip(.4298,i).add(ip(.1191,t).sub(.00232))))},{x:"vec3",return:"vec3"}),zy=Uh(([e,t])=>{const i=Yh(e).toVar(),n=rd(Yh(.856627153315983,.137318972929847,.11189821299995),Yh(.0951212405381588,.761241990602591,.0767994186031903),Yh(.0482516061458583,.101439036467562,.811302368396859)),r=rd(Yh(1.1271005818144368,-.1413297634984383,-.14132976349843826),Yh(-.11060664309660323,1.157823702216272,-.11060664309660294),Yh(-.016493938717834573,-.016493938717834257,1.2519364065950405)),s=Gh(-12.47393),a=Gh(4.026069);return i.mulAssign(t),i.assign(By.mul(i)),i.assign(n.mul(i)),i.assign(_f(i,1e-10)),i.assign(Up(i)),i.assign(i.sub(s).div(a.sub(s))),i.assign(Cf(i,0,1)),i.assign(ky(i)),i.assign(r.mul(i)),i.assign(Mf(_f(Yh(0),i),Yh(2.2))),i.assign(Oy.mul(i)),i.assign(Cf(i,0,1)),i},{color:"vec3",exposure:"float",return:"vec3"}),Gy=Uh(([e,t])=>{const i=Gh(.76),n=Gh(.15);e=e.mul(t);const r=gf(e.r,gf(e.g,e.b)),s=Of(r.lessThan(.08),r.sub(ip(6.25,r.mul(r))),.04);e.subAssign(s);const a=_f(e.r,_f(e.g,e.b));kh(a.lessThan(i),()=>e);const o=tp(1,i),l=tp(1,o.mul(o).div(a.add(o.sub(i))));e.mulAssign(l.div(a));const c=tp(1,np(1,n.mul(a.sub(l)).add(1)));return Rf(e,Yh(l),c)},{color:"vec3",exposure:"float",return:"vec3"});class Vy extends Bu{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 Hy extends Vy{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),n=e.getDataFromNode(this),r=i.type;let s=n.functionPropertyName;if(void 0===s){super.generate(e);const t=i.name,a=e.getCodeFromNode(this,r);""!==t&&(a.name=t,e.registerDeclaration(a)),s=e.getPropertyName(a),a.code=i.getCode(s)+"\n",n.functionPropertyName=s}return"property"===t?s:e.format(`${s}()`,r,t)}}function Wy(e){let t;const i=e.context.getViewZ;return void 0!==i&&(t=i(this)),(t||Ug.z).negate()}const jy=Uh(([e,t],i)=>{const n=Wy(i);return Lf(e,t,n)}),$y=Uh(([e],t)=>{const i=Wy(t);return e.mul(e,i,i).negate().exp().oneMinus()}),Xy=Uh(([e,t])=>Jh(t.toFloat().mix(zd.rgb,e.toVec3()),zd.a));let qy;function Yy(e){qy=qy||new WeakMap;let t=qy.get(e);return void 0===t&&qy.set(e,t={}),t}function Ky(e){const t=Yy(e);return t.shadowMatrix||(t.shadowMatrix=md("mat4").setGroup(dd).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 Zy(e){const t=Yy(e);return t.position||(t.position=md(new Wi).setGroup(dd).onRenderUpdate((t,i)=>i.value.setFromMatrixPosition(e.matrixWorld)))}function Qy(e){const t=Yy(e);return t.viewPosition||(t.viewPosition=Uh(({camera:i})=>i.isArrayCamera&&i.cameras.length>0?vg.mul(Jh(Zy(e),1)).xyz:t.viewPositionUniform||(t.viewPositionUniform=md(new Wi).setGroup(dd).onRenderUpdate(({camera:t},i)=>{i.value=i.value||new Wi,i.value.setFromMatrixPosition(e.matrixWorld),i.value.applyMatrix4(t.matrixWorldInverse)}))).once()())}const Jy=e=>vg.transformDirection(Zy(e).sub(function(e){const t=Yy(e);return t.targetPosition||(t.targetPosition=md(new Wi).setGroup(dd).onRenderUpdate((t,i)=>i.value.setFromMatrixPosition(e.target.matrixWorld)))}(e))),ex=_d("vec3","totalDiffuse"),tx=_d("vec3","totalSpecular"),ix=_d("vec3","outgoingLight"),nx=(e,t)=>{for(const i of t)if(i.isAnalyticLightNode&&i.light.id===e)return i;return null},rx=new WeakMap,sx=[];class ax extends Bu{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=ex,this.totalSpecularNode=tx,this.outgoingLightNode=ix,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(sx.push(i.id),sx.push(i.castShadow?1:0),!0===i.castShadow){const e=rx.get(i),t=e?e.version:0;sx.push(t)}if(!0===i.isSpotLight){const e=null!==i.map?i.map.id:-1,t=i.colorNode?i.colorNode.getCacheKey():-1;sx.push(e,t)}}const t=Au(sx);return sx.length=0,t}getHash(e){const t=e.getDataFromNode(this);if(void 0===t.lightNodesHash){const i=this.setupLightsNode(e);t.lightNodes=i;const n=[];for(const e of i)n.push(e.getHash());t.lightNodesHash="lights-"+n.join(",")}return t.lightNodesHash}setupLightsNode(e){const t=[],i=e.getDataFromNode(this).lightNodes||null,n=(e=>e.sort((e,t)=>e.id-t.id))([...e.context.materialLightings,...this.getBuiltinLights()]);for(const e of n)if(e.isNode)t.push(e);else{let n=null;if(null!==i&&(n=nx(e.id,i)),null===n){const t=e._lightNode;if(void 0===t){Ti(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}!1===rx.has(e)&&rx.set(e,new t(e)),n=rx.get(e)}t.push(n)}return t}setupDirectLight(e,t,i){const{lightingModel:n,reflectedLight:r}=e.context;n.direct({...i,lightNode:t,reflectedLight:r},e)}setupDirectRectAreaLight(e,t,i){const{lightingModel:n,reflectedLight:r}=e.context;n.directRectArea({...i,lightNode:t,reflectedLight:r},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 n=e.context,r=n.lightingModel;if(r){const{totalDiffuseNode:t,totalSpecularNode:s}=this;n.outgoingLight=i,e.addStack(),r.start(e);const{backdrop:a,backdropAlpha:o}=n,{directDiffuse:l,directSpecular:c,indirectDiffuse:u,indirectSpecular:h}=n.reflectedLight;let d=l.add(u);null!==a&&(d=Yh(null!==o?o.mix(d,a):a)),t.assign(d),s.assign(c.add(h)),i.assign(t.add(s)),r.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 ox{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 n=e[t];!1===i.has(n)&&i.set(n,new WeakMap),i=i.get(n)}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 lx=new WeakMap,cx=new ox,ux=[];class hx extends Bu{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=mu,this.isShadowBaseNode=!0}isCacheable(){return!1}getShadowMaterial(){return(e=>{let t=lx.get(e);return void 0===t&&(t=new my,t.colorNode=Jh(0,0,0,1),t.isShadowPassMaterial=!0,t.name="ShadowMaterial",t.blending=0,t.fog=!1,lx.set(e,t)),t})(this.light)}disposeShadowMaterial(){(e=>{const t=lx.get(e);void 0!==t&&(t.dispose(),lx.delete(e))})(this.light)}getShadowRenderObjectFunction(e,t=this.light.shadow){return((e,t,i)=>{ux[0]=e,ux[1]=t;let n=cx.get(ux);return void 0!==n&&n.shadowType===i||(n=(n,r,s,a,o,l,c,u,h)=>{(!0===n.castShadow||n.receiveShadow&&3===i)&&(n.onBeforeShadow(e,n,s,t.camera,a,r.overrideMaterial,l),e.renderObject(n,r,s,a,o,l,c,u,h),n.onAfterShadow(e,n,s,t.camera,a,r.overrideMaterial,l))},n.shadowType=i,cx.set(ux,n)),ux[0]=null,ux[1]=null,n})(e,t,e.shadowMap.type)}setupShadowPosition({context:e,material:t}){dx.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||Ig)}}const dx=_d("vec3","shadowPositionWorld"),px=new WeakMap;const fx=Uh(({depthTexture:e,shadowCoord:t,depthLayer:i})=>{let n=h_(e,t.xy).setName("t_basic");return e.isArrayTexture&&(n=n.depth(i)),n.compare(t.z)}),mx=Uh(({depthTexture:e,shadowCoord:t,shadow:i,depthLayer:n})=>{const r=(t,i)=>{let r=h_(e,t);return e.isArrayTexture&&(r=r.depth(n)),r.compare(i)},{mapSize:s,radius:a}=function(e){let t=px.get(e);return void 0===t&&(t={mapSize:H_("mapSize","vec2",e).setGroup(dd),radius:H_("radius","float",e).setGroup(dd)},px.set(e,t)),t}(i),o=jh(1).div(s),l=a.mul(o),c=Sy(ig.xy).mul(6.28318530718);return ep(r(t.xy.add(Ty(0,5,c).mul(l)),t.z),r(t.xy.add(Ty(1,5,c).mul(l)),t.z),r(t.xy.add(Ty(2,5,c).mul(l)),t.z),r(t.xy.add(Ty(3,5,c).mul(l)),t.z),r(t.xy.add(Ty(4,5,c).mul(l)),t.z)).mul(.2)}),gx=Uh(({depthTexture:e,shadowCoord:t,depthLayer:i},n)=>{let r=h_(e).sample(t.xy);e.isArrayTexture&&(r=r.depth(i)),r=r.rg;const s=r.x,a=_f(1e-7,r.y.mul(r.y)),o=n.renderer.reversedDepthBuffer?vf(s,t.z):vf(t.z,s),l=Gh(1).toVar();return kh(o.notEqual(1),()=>{const e=t.z.sub(s);let i=a.div(a.add(e.mul(e)));i=Cf(tp(i,.3).div(.65)),l.assign(_f(o,i))}),l}),_x=Uh(({samples:e,radius:t,size:i,shadowPass:n,depthLayer:r})=>{const s=Gh(0).toVar("meanVertical"),a=Gh(0).toVar("squareMeanVertical"),o=e.lessThanEqual(Gh(1)).select(Gh(0),Gh(2).div(e.sub(1))),l=e.lessThanEqual(Gh(1)).select(Gh(0),Gh(-1));zm({start:Vh(0),end:Vh(e),type:"int",condition:"<"},({i:e})=>{const c=l.add(Gh(e).mul(o));let u=n.sample(ep(ig.xy,jh(0,c).mul(t)).div(i));n.value.isArrayTexture&&(u=u.depth(r)),u=u.x,s.addAssign(u),a.addAssign(u.mul(u))}),s.divAssign(e),a.divAssign(e);const c=Op(a.sub(s.mul(s)).max(0));return jh(s,c)}),vx=Uh(({samples:e,radius:t,size:i,shadowPass:n,depthLayer:r})=>{const s=Gh(0).toVar("meanHorizontal"),a=Gh(0).toVar("squareMeanHorizontal"),o=e.lessThanEqual(Gh(1)).select(Gh(0),Gh(2).div(e.sub(1))),l=e.lessThanEqual(Gh(1)).select(Gh(0),Gh(-1));zm({start:Vh(0),end:Vh(e),type:"int",condition:"<"},({i:e})=>{const c=l.add(Gh(e).mul(o));let u=n.sample(ep(ig.xy,jh(c,0).mul(t)).div(i));n.value.isArrayTexture&&(u=u.depth(r)),s.addAssign(u.x),a.addAssign(ep(u.y.mul(u.y),u.x.mul(u.x)))}),s.divAssign(e),a.divAssign(e);const c=Op(a.sub(s.mul(s)).max(0));return jh(s,c)}),bx=[fx,mx,null,gx];let yx;const xx=new yy;class Sx extends hx{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:n,shadow:r,depthLayer:s}){const a=n.x.greaterThanEqual(0).and(n.x.lessThanEqual(1)).and(n.y.greaterThanEqual(0)).and(n.y.lessThanEqual(1)).and(n.z.lessThanEqual(1)),o=t({depthTexture:i,shadowCoord:n,shadow:r,depthLayer:s});return a.select(o,Gh(1))}setupShadowCoord(e,t){const{shadow:i}=this,{renderer:n}=e,r=i.biasNode||H_("bias","float",i).setGroup(dd);let s,a=t;if(i.camera.isOrthographicCamera||!0!==n.logarithmicDepthBuffer)a=a.xyz.div(a.w),s=a.z;else{const e=a.w;a=a.xy.div(e);const t=H_("near","float",i.camera).setGroup(dd),n=H_("far","float",i.camera).setGroup(dd);s=w_(e.negate(),t,n)}return a=Yh(a.x,a.y.oneMinus(),n.reversedDepthBuffer?s.sub(r):s.add(r)),a}getShadowFilterFn(e){return bx[e]}setupRenderTarget(e,t){const i=new oa(e.mapSize.width,e.mapSize.height);i.name="ShadowDepthTexture",i.compareFunction=t.renderer.reversedDepthBuffer?ri:ti;const n=t.createRenderTarget(e.mapSize.width,e.mapSize.height);return n.texture.name="ShadowMap",n.texture.type=e.mapType,n.depthTexture=i,{shadowMap:n,depthTexture:i}}setupShadow(e){const{renderer:t,camera:i}=e,{light:n,shadow:r}=this,{depthTexture:s,shadowMap:a}=this.setupRenderTarget(r,e),o=t.shadowMap.type,l=t.hasCompatibility(pi);if(1===o&&l?(s.minFilter=Oe,s.magFilter=Oe):(s.minFilter=Ie,s.magFilter=Ie),r.camera.coordinateSystem=i.coordinateSystem,r.camera._reversedDepth=t.reversedDepthBuffer,r.camera.updateProjectionMatrix(),3===o&&!0!==r.isPointLightShadow){s.compareFunction=null,a.depth>1?(a._vsmShadowMapVertical||(a._vsmShadowMapVertical=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:at,type:Xe,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapVertical.texture.name="VSMVertical"),this.vsmShadowMapVertical=a._vsmShadowMapVertical,a._vsmShadowMapHorizontal||(a._vsmShadowMapHorizontal=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:at,type:Xe,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapHorizontal.texture.name="VSMHorizontal"),this.vsmShadowMapHorizontal=a._vsmShadowMapHorizontal):(this.vsmShadowMapVertical=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:at,type:Xe,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:at,type:Xe,depthBuffer:!1}));let t=h_(s);s.isArrayTexture&&(t=t.depth(this.depthLayer));let i=h_(this.vsmShadowMapVertical.texture);s.isArrayTexture&&(i=i.depth(this.depthLayer));const n=H_("blurSamples","float",r).setGroup(dd),o=H_("radius","float",r).setGroup(dd),l=H_("mapSize","vec2",r).setGroup(dd),c=kf(e.getSharedContext());let u=this.vsmMaterialVertical||(this.vsmMaterialVertical=new my);u.contextNode=c,u.fragmentNode=_x({samples:n,radius:o,size:l,shadowPass:t,depthLayer:this.depthLayer}),u.name="VSMVertical",u=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new my),u.contextNode=c,u.fragmentNode=vx({samples:n,radius:o,size:l,shadowPass:i,depthLayer:this.depthLayer}),u.name="VSMHorizontal"}const c=H_("intensity","float",r).setGroup(dd),u=H_("normalBias","float",r).setGroup(dd),h=Ky(n),d=Kg.mul(u);let p;if(!t.highPrecision||e.material.receivedShadowPositionNode||e.context.shadowPositionWorld)p=h.mul(dx.add(d));else{p=md("mat4").onObjectUpdate(({object:e},t)=>t.value.multiplyMatrices(h.value,e.matrixWorld)).mul(Lg).add(h.mul(Jh(d,0)))}const f=this.setupShadowCoord(e,p),m=r.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!==r.isPointLightShadow?this.vsmShadowMapHorizontal.texture:s,_=this.setupShadowFilter(e,{filterFn:m,shadowTexture:a.texture,depthTexture:g,shadowCoord:f,shadow:r,depthLayer:this.depthLayer});let v,b;!0===t.shadowMap.transmitted&&(a.texture.isCubeTexture?v=G_(a.texture,f.xyz):(v=h_(a.texture,f),s.isArrayTexture&&(v=v.depth(this.depthLayer)))),b=v?Rf(1,_.rgb.mix(v,1),c.mul(v.a)).toVar():Rf(1,_,c).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?G_(this.shadowMap.texture,zg()):h_(this.shadowMap.texture)),b.toInspector(`${y} / Depth`,()=>{const e=H_("near","float",this.shadow.camera),t=H_("far","float",this.shadow.camera);let i,n;return i=this.shadowMap.texture.isCubeTexture?G_(this.shadowMap.depthTexture,zg()).r:h_(this.shadowMap.depthTexture).r,n=this.shadow.camera.isPerspectiveCamera?E_(i,e,t):T_(i,e,t),n=S_(n,e,t),n.oneMinus()})}setup(e){if(!1!==e.renderer.shadowMap.enabled)return Uh(()=>{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:n}=this,{renderer:r,scene:s}=e;t.updateMatrices(n),i.setSize(t.mapSize.width,t.mapSize.height,i.depth);const a=s.name;s.name=`Shadow Map [ ${n.name||"ID: "+n.id} ]`,r.render(s,t.camera),s.name=a}updateShadow(e){const{shadowMap:t,shadow:i}=this,{renderer:n,scene:r,camera:s}=e,a=n.shadowMap.type,o=i.camera.layers.mask;4294967294&i.camera.layers.mask||(i.camera.layers.mask=s.layers.mask);const l=n.getRenderObjectFunction();yx=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=xy(e,i)),i}(n,r,yx),r.overrideMaterial=this.getShadowMaterial(),n.setRenderObjectFunction(this.getShadowRenderObjectFunction(n,this.shadow||this.light.shadow)),n.setClearColor(0,0),n.setRenderTarget(t);const c=r.matrixWorldAutoUpdate;r.matrixWorldAutoUpdate=!1,this.renderShadow(e),r.matrixWorldAutoUpdate=c,n.setRenderObjectFunction(l),3===a&&!0!==i.isPointLightShadow&&this.vsmPass(n),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)}(n,r,yx)}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),xx.material=this.vsmMaterialVertical,xx.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),xx.material=this.vsmMaterialHorizontal,xx.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 Tx=new Kn,Mx=new mn,Ex=new Wi,wx=new Wi,Ax=[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)],Rx=[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)],Cx=[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)],Nx=[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=(e,t,i,n,r)=>{const{reversedDepthBuffer:s,logarithmicDepthBuffer:a}=r;if(!0===a)return r=>w_(r.mul(e).negate(),t,i).add(n);const o=i.sub(t),l=t.mul(i).div(o.mul(e));let c,u;return!0===s?(c=t.div(o).add(n).negate().toConst(),u=l.toConst()):(c=i.div(o).add(n).toConst(),u=l.negate().toConst()),e=>c.add(u.div(e))},Lx=Uh(({depthTexture:e,bd3D:t,dp:i})=>G_(e,t).compare(i)),Dx=Uh(({depthTexture:e,bd3D:t,distance:i,shadow:n},r)=>{const s=H_("radius","float",n).setGroup(dd),a=H_("mapSize","vec2",n).setGroup(dd),o=H_("near","float",n.camera).setGroup(dd),l=H_("far","float",n.camera).setGroup(dd),c=H_("bias","float",n).setGroup(dd),u=s.div(a.x).toConst(),h=tf(t),d=Gp(Tf(t,h.x.greaterThan(h.z).select(Yh(0,1,0),Yh(1,0,0)))).toConst(),p=Tf(t,d).toConst(),f=Sy(ig.xy).mul(6.28318530718).toConst(),m=Px(i,o,l,c,r.renderer),g=Gh(0).toVar();return zm(5,({i:i})=>{const n=Ty(i,5,f),r=t.add(d.mul(n.x).add(p.mul(n.y)).mul(u)).toConst(),s=tf(r).toConst(),a=_f(s.x,s.y,s.z).toConst();g.addAssign(G_(e,r).compare(m(a)))}),g.mul(.2)}),Ix=Uh(({filterFn:e,depthTexture:t,shadowCoord:i,shadow:n},r)=>{const s=i.xyz.toConst(),a=s.abs().toConst(),o=a.x.max(a.y).max(a.z),l=md("float").setGroup(dd).onRenderUpdate(()=>n.camera.near),c=md("float").setGroup(dd).onRenderUpdate(()=>n.camera.far),u=H_("bias","float",n).setGroup(dd),h=Gh(1).toVar();return kh(o.sub(c).lessThanEqual(0).and(o.sub(l).greaterThanEqual(0)),()=>{const i=s.normalize(),a=s.length(),d=Px(a,l,c,u,r.renderer)(o.div(a));h.assign(e({depthTexture:t,bd3D:i,dp:d,distance:a,shadow:n}))}),h});class Fx extends Sx{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return 0===e?Lx:Dx}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,depthTexture:i,shadowCoord:n,shadow:r}){return Ix({filterFn:t,depthTexture:i,shadowCoord:n,shadow:r})}setupRenderTarget(e,t){const i=new la(e.mapSize.width);i.name="PointShadowDepthTexture",i.compareFunction=t.renderer.reversedDepthBuffer?ri:ti;const n=t.createCubeRenderTarget(e.mapSize.width);return n.texture.name="PointShadowMap",n.depthTexture=i,{shadowMap:n,depthTexture:i}}renderShadow(e){const{shadow:t,shadowMap:i,light:n}=this,{renderer:r,scene:s}=e,a=t.camera,o=t.matrix,l=r.coordinateSystem===ui,c=l?Ax:Cx,u=l?Rx:Nx;i.setSize(t.mapSize.width,t.mapSize.width);const h=r.autoClear,d=r.getClearColor(Tx),p=r.getClearAlpha();r.autoClear=!1,r.setClearColor(t.clearColor,t.clearAlpha);for(let e=0;e<6;e++){r.setRenderTarget(i,e),r.clear();const l=n.distance||a.far;l!==a.far&&(a.far=l,a.updateProjectionMatrix()),Ex.setFromMatrixPosition(n.matrixWorld),a.position.copy(Ex),wx.copy(a.position),wx.add(c[e]),a.up.copy(u[e]),a.lookAt(wx),a.updateMatrixWorld(),o.makeTranslation(-Ex.x,-Ex.y,-Ex.z),Mx.multiplyMatrices(a.projectionMatrix,a.matrixWorldInverse),t._frustum.setFromProjectionMatrix(Mx,a.coordinateSystem,a.reversedDepth);const h=s.name;s.name=`Point Light Shadow [ ${n.name||"ID: "+n.id} ] - Face ${e+1}`,r.render(s,a),s.name=h}r.autoClear=h,r.setClearColor(d,p)}}class Ux extends Qb{static get type(){return"AnalyticLightNode"}constructor(e=null){super(),this.light=e,this.color=new Kn,this.colorNode=e&&e.colorNode||md(this.color).setGroup(dd),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=fu,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 Qy(this.light).sub(e.context.positionView||Ug)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return((e,t)=>new Sx(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?Rh(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 Ox=Uh(({lightDistance:e,cutoffDistance:t,decayExponent:i})=>{const n=e.pow(i).max(.01).reciprocal();return t.greaterThan(0).select(n.mul(e.div(t).pow4().oneMinus().clamp().pow2()),n)},{lightDistance:"float",cutoffDistance:"float",decayExponent:"float",return:"float"});class Bx extends Ux{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=md(0).setGroup(dd),this.decayExponentNode=md(2).setGroup(dd)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return((e,t)=>new Fx(e,t))(this.light)}setupDirect(e){return(({color:e,lightVector:t,cutoffDistance:i,decayExponent:n})=>{const r=t.normalize(),s=t.length(),a=Ox({lightDistance:s,cutoffDistance:i,decayExponent:n});return{lightDirection:r,lightColor:e.mul(a)}})({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}const kx=Uh(({SAMPLES:e,sigma:t,direction:i,envMap:n})=>{const r=Yh(i).toVar(),s=Of(tf(r.z).lessThan(.999),Yh(0,0,1),Yh(1,0,0)),a=Gp(Tf(s,r)).toVar(),o=Tf(r,a).toVar(),l=gf(t.mul(3),Math.PI),c=Dp(l.mul(l).mul(-.5).div(t.mul(t))).oneMinus().toVar(),u=Yh(0).toVar(),h=Gh(0).toVar();return zm({start:Vh(0),end:e},({i:i})=>{const s=Gh(i).add(.5).div(Gh(e)),l=t.mul(Op(Fp(s.mul(c).oneMinus()).mul(-2))).toVar(),d=Gh(i).mul(2.399963229728653).toVar(),p=a.mul(jp(d)).add(o.mul(Hp(d))),f=r.mul(jp(l)).add(p.mul(Hp(l))),m=Hp(l).div(l).toVar();u.addAssign(n.sample(f).level(0).rgb.mul(m)),h.addAssign(m)}),Jh(u.div(h),1)}),zx=Uh(([e])=>{const t=Hh(e).toVar();return t.assign(t.shiftLeft(Hh(16)).bitOr(t.shiftRight(Hh(16)))),t.assign(t.bitAnd(Hh(1431655765)).shiftLeft(Hh(1)).bitOr(t.bitAnd(Hh(2863311530)).shiftRight(Hh(1)))),t.assign(t.bitAnd(Hh(858993459)).shiftLeft(Hh(2)).bitOr(t.bitAnd(Hh(3435973836)).shiftRight(Hh(2)))),t.assign(t.bitAnd(Hh(252645135)).shiftLeft(Hh(4)).bitOr(t.bitAnd(Hh(4042322160)).shiftRight(Hh(4)))),t.assign(t.bitAnd(Hh(16711935)).shiftLeft(Hh(8)).bitOr(t.bitAnd(Hh(4278255360)).shiftRight(Hh(8)))),Gh(t).mul(2.3283064365386963e-10)}),Gx=Uh(([e,t])=>jh(Gh(e).div(Gh(t)),zx(e))),Vx=Uh(({roughness:e,lodBias:t,envMap:i,direction:n,GGX_SAMPLES:r})=>{const s=Yh(n).toVar(),a=Yh(0).toVar();return kh(e.lessThan(.001),()=>{a.assign(i.sample(s).level(0).rgb)}).Else(()=>{const n=e.mul(e).toConst(),o=n.mul(n).toConst(),l=Of(tf(s.z).lessThan(.999),Yh(0,0,1),Yh(1,0,0)),c=Gp(Tf(l,s)).toVar(),u=Tf(s,c).toVar(),h=Gh(0).toVar();zm({start:Hh(0),end:r},({i:e})=>{const l=Gx(e,r),d=Gh(1).div(l.x.oneMinus().add(o.mul(l.x))).toConst(),p=l.x.oneMinus().sub(o.mul(l.x)).mul(d).toConst();kh(p.greaterThan(0),()=>{const e=l.y.mul(2*Math.PI).toConst(),r=n.mul(2).mul(Op(l.x.mul(l.x.oneMinus()))).mul(d).toConst(),f=s.mul(p).add(c.mul(jp(e)).add(u.mul(Hp(e))).mul(r)).toConst(),m=o.mul(d),g=_f(Up(m).add(t),0);a.addAssign(i.sample(f).level(g).rgb.mul(p)),h.addAssign(p)})}),a.divAssign(h)}),Jh(a,1)}),Hx=Uh(({roughness:e,sourceLod:t,sourceSize:i,envMap:n,direction:r})=>{const s=Yh(r).toVar(),a=e.mul(e).toConst(),o=a.mul(a).toConst(),l=Gh(2).div(Gh(i)).toConst(),c=Yh(0).toVar(),u=Gh(0).toVar();return zm({start:Vh(0),end:Vh(3),name:"face"},({face:e})=>{zm({start:Vh(0),end:i,name:"y"},({y:r})=>{zm({start:Vh(0),end:i,name:"x"},({x:i})=>{const a=jh(i,r).add(.5).mul(l).sub(1).toConst(),h=Of(e.equal(0),Yh(1,a),Of(e.equal(1),Yh(a.x,1,a.y),Yh(a,1))).toVar(),d=Bp(Sf(a,a).add(1)).toConst(),p=Sf(s,h).toVar();h.mulAssign(Of(p.lessThan(0),-1,1)),p.assign(tf(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();c.addAssign(n.sample(h).level(t).rgb.mul(m)),u.addAssign(m)})})}),Jh(c.div(u),1)});class Wx extends hn{constructor(e=1,t={}){super(e,e,t),this.isCubeRenderTarget=!0;const i={width:e,height:e,depth:1},n=[i,i,i,i,i,i];this.texture=new sa(n),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){const i=t.minFilter,n=t.generateMipmaps;t.generateMipmaps=!0,this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const r=new ua(5,5,5),s=kg(Fg),a=new my;a.colorNode=h_(t,s,0),a.side=1,a.blending=0;const o=new ws(r,a),l=new Qn;l.add(o),t.minFilter===ke&&(t.minFilter=Oe);const c=new fo(1,10,this),u=e.getMRT();return e.setMRT(null),c.update(e,l),e.setMRT(u),t.minFilter=i,t.generateMipmaps=n,o.geometry.dispose(),o.material.dispose(),this}clear(e,t=!0,i=!0,n=!0){const r=e.getRenderTarget();for(let r=0;r<6;r++)e.setRenderTarget(this,r),e.clear(t,i,n);e.setRenderTarget(r)}}const jx=new Wi,$x=new Kn,Xx=new WeakMap;class qx{constructor(e){this._renderer=e,this._cubeSize=0,this._sourceTarget=null,this._cubeCamera=new fo(1,10,null),this._boxMesh=new ws(new ua(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,n=100,r={}){const{size:s=256,position:a=jx,renderTarget:o=null}=r,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 c=o||this._allocateTarget(),u=this._getSourceTarget(!0);t>0&&(u.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($x));const g=new fo(i,n,u);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&&(u.texture.mipmapsAutoUpdate=!0,this._blur(c,t)),this._applyPMREM(c),c}async fromSceneAsync(e,t=0,i=.1,n=100,r={}){return Ei('PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this.fromScene(e,t,i,n,r)}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=Zx(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=Qx(),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=Yx(e,!1,!1),i=Math.log2(e)-3;for(let n=0;n<=i;n++)t.texture.mipmaps.push({width:e>>n,height:e>>n});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=Yx(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 n=this._boxMesh,r=this._cubeCamera;n.material=i,r.renderTarget=e,r.activeMipmapLevel=t,r.update(this._renderer,n)}_textureToCubemap(e){let t;e.mapping===Ae||e.mapping===Re?(null===this._cubemapMaterial&&(this._cubemapMaterial=Zx()),t=this._cubemapMaterial):(null===this._equirectMaterial&&(this._equirectMaterial=Qx()),t=this._equirectMaterial),Xx.get(t).envMap.value=e,this._renderCube(this._getSourceTarget(),0,t)}_applyPMREM(e){null===this._ggxMaterial&&(this._ggxMaterial=function(){const e={envMap:G_(),roughness:md(0),lodBias:md(0)};return Kx("ggx",e,Vx({...e,direction:Fg,GGX_SAMPLES:Hh(256)}))}(),this._integrationMaterial=function(){const e={envMap:G_(),roughness:md(0),sourceLod:md(0),sourceSize:md(16,"int")};return Kx("integration",e,Hx({...e,direction:Fg}))}());const t=this._cubeSize,i=e.texture.mipmaps.length-1,n=Xx.get(this._ggxMaterial);n.envMap.value=this._sourceTarget.texture;const r=Xx.get(this._integrationMaterial);r.envMap.value=this._sourceTarget.texture,r.sourceLod.value=Math.log2(t/16);for(let s=0;s<=i;s++){const a=qx.lodToRoughness(s,i);if(s>i-3)r.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;n.roughness.value=a,n.lodBias.value=i,this._renderCube(e,s,this._ggxMaterial)}}}_blur(e,t){null===this._blurMaterial&&(this._blurMaterial=function(){const e={envMap:G_(),sigma:md(0)};return Kx("blur",e,kx({...e,direction:Fg,SAMPLES:Vh(20)}))}());const i=this._blurMaterial,n=Xx.get(i),r=this._sourceTarget;n.sigma.value=Math.min(t,Math.PI)/Math.SQRT2,n.envMap.value=r.texture,this._renderCube(e,0,i),n.envMap.value=e.texture,this._renderCube(r,0,i)}}function Yx(e,t,i){return new Wx(e,{minFilter:ke,generateMipmaps:t,type:Xe,colorSpace:qt,depthBuffer:i})}function Kx(e,t,i){const n=new my;return n.name=`PMREM_${e}`,n.fragmentNode=i,n.side=1,n.blending=0,n.depthTest=!1,n.depthWrite=!1,Xx.set(n,t),n}function Zx(){const e={envMap:G_()};return Kx("cubemap",e,e.envMap.sample(Fg))}function Qx(){const e={envMap:h_()},t=Uh(()=>{const t=Fg,i=t.dFdx().mul(.25).toConst(),n=t.dFdy().mul(.25).toConst(),r=e.envMap.sample(kg(t.sub(i).sub(n).normalize())).level(0).rgb.add(e.envMap.sample(kg(t.add(i).sub(n).normalize())).level(0).rgb).add(e.envMap.sample(kg(t.sub(i).add(n).normalize())).level(0).rgb).add(e.envMap.sample(kg(t.add(i).add(n).normalize())).level(0).rgb);return Jh(r.mul(.25),1)})();return Kx("equirect",e,t)}const Jx=new WeakMap;function eS(e,t,i){const n=function(e){let t=Jx.get(e);void 0===t&&(t=new WeakMap,Jx.set(e,t));return t}(t);let r=n.get(e);if((void 0!==r?r.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 n=0;n<i;n++)void 0!==e[n]&&t++;return t===i}(t))return null;r=i.fromCubemap(e,r)}else{if(!function(e){return null!=e&&e.height>0}(t))return null;r=i.fromEquirectangular(e,r)}if(r.texture.pmremVersion=e.pmremVersion,!1===n.has(e)){const t=()=>{e.removeEventListener("dispose",t);const i=n.get(e);void 0!==i&&(i.texture.pmremVersion=-1,i.dispose(),n.delete(e))};e.addEventListener("dispose",t)}n.set(e,r)}return r.texture}class tS extends Bu{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 n=new sa;n.isRenderTargetTexture=!0,this._texture=G_(n),this._maxLod=md(0),this._size=md(0),this.updateBeforeType=mu}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,n=this._value;i!==n.pmremVersion&&(!0===n.isPMREMTexture?t=n:(null===this._generator&&(this._generator=new qx(e.renderer)),t=eS(n,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(D_.mul(t)).level(((e,t)=>(e=Gh(e).clamp(),Gh(t).mul(e).mul(Gh(2).sub(e))))(i,this._maxLod)).rgb}dispose(){super.dispose(),null!==this._generator&&this._generator.dispose()}}const iS=Ph(tS).setParameterLength(1,3),nS=1e-7,rS=.5-2/(3*Math.PI),sS=2/3-28/(15*Math.PI),aS=Uh(({mu:e,roughness:t,A:i})=>{const n=e.oneMinus(),r=n.mul(n.mul(n.mul(n.mul(.0714429953).sub(.332181442)).add(.491881867)).add(.0571085289));return i.mul(t.mul(r).add(1))},{mu:"float",roughness:"float",A:"float",return:"float"}),oS=Uh(({lightDirection:e,diffuseColor:t,roughness:i,normalView:n=Yg,viewDirection:r=Og})=>{const s=t.clamp(),a=n.dot(e).clamp(),o=n.dot(r).clamp(),l=e.dot(r).sub(a.mul(o)),c=l.greaterThan(0).select(l.div(a.max(o).max(nS)),l),u=i.mul(rS).add(1).reciprocal(),h=s.mul(1/Math.PI,u,i.mul(c).add(1)),d=u.mul(i.mul(sS).add(1)),p=aS({mu:o,roughness:i,A:u}),f=aS({mu:a,roughness:i,A:u}),m=s.mul(s,d).div(s.mul(d.oneMinus()).oneMinus().max(nS)).mul(1/Math.PI,p.oneMinus().max(nS),f.oneMinus().max(nS)).div(d.oneMinus().max(nS)),g=h.add(m);return i.lessThanEqual(nS).select(s.mul(1/Math.PI),g)}),lS=Uh(({diffuseColor:e,roughness:t,dotNV:i})=>{const n=e.clamp(),r=t.mul(rS).add(1).reciprocal(),s=aS({mu:i.clamp(),roughness:t,A:r}),a=r.mul(t.mul(sS).add(1)),o=n.mul(n,a).div(n.mul(a.oneMinus()).oneMinus().max(nS)),l=n.mul(s).add(o.mul(s.oneMinus()));return t.lessThanEqual(nS).select(n,l)},{diffuseColor:"vec3",roughness:"float",dotNV:"float",return:"vec3"}),cS=Uh(({f0:e,f90:t,dotVH:i})=>{const n=i.mul(-5.55473).sub(6.98316).mul(i).exp2();return e.mul(n.oneMinus()).add(t.mul(n))}),uS=Uh(({alpha:e,dotNL:t,dotNV:i})=>{const n=e.pow2(),r=t.mul(n.add(n.oneMinus().mul(i.pow2())).sqrt()),s=i.mul(n.add(n.oneMinus().mul(t.pow2())).sqrt());return np(.5,r.add(s).max(Ap))},{alpha:"float",dotNL:"float",dotNV:"float",return:"float"}),hS=Uh(({alphaT:e,alphaB:t,dotTV:i,dotBV:n,dotTL:r,dotBL:s,dotNV:a,dotNL:o})=>{const l=o.mul(Yh(e.mul(i),t.mul(n),a).length()),c=a.mul(Yh(e.mul(r),t.mul(s),o).length());return np(.5,l.add(c).max(Ap))},{alphaT:"float",alphaB:"float",dotTV:"float",dotBV:"float",dotTL:"float",dotBL:"float",dotNV:"float",dotNL:"float",return:"float"}),dS=Uh(({alpha:e,dotNH:t})=>{const i=e.pow2(),n=t.pow2().mul(i.oneMinus()).oneMinus();return i.div(n.pow2()).mul(1/Math.PI)},{alpha:"float",dotNH:"float",return:"float"}),pS=Gh(1/Math.PI),fS=Uh(({alphaT:e,alphaB:t,dotNH:i,dotTH:n,dotBH:r})=>{const s=e.mul(t),a=Yh(t.mul(n),e.mul(r),s.mul(i)),o=a.dot(a),l=s.div(o);return pS.mul(s.mul(l.pow2()))},{alphaT:"float",alphaB:"float",dotNH:"float",dotTH:"float",dotBH:"float",return:"float"}),mS=Uh(({lightDirection:e,f0:t,f90:i,roughness:n,f:r,normalView:s=Yg,viewDirection:a=Og,USE_IRIDESCENCE:o,USE_ANISOTROPY:l})=>{const c=n.max(.045).pow2(),u=e.add(a).normalize(),h=s.dot(e).clamp(),d=s.dot(a).clamp(),p=s.dot(u).clamp(),f=a.dot(u).clamp();let m,g,_=cS({f0:t,f90:i,dotVH:f});if(wh(o)&&(_=Cd.mix(_,r)),wh(l)){const t=Id.dot(e),i=Id.dot(a),n=Id.dot(u),r=Fd.dot(e),s=Fd.dot(a),o=Fd.dot(u),l=Ld.max(c);m=hS({alphaT:l,alphaB:c,dotTV:i,dotBV:s,dotTL:t,dotBL:r,dotNV:d,dotNL:h}),g=fS({alphaT:l,alphaB:c,dotNH:p,dotTH:n,dotBH:o})}else m=uS({alpha:c,dotNL:h,dotNV:d}),g=dS({alpha:c,dotNH:p});return _.mul(m).mul(g)}),gS=Uh(e=>e.diffuseColor.mul(1/Math.PI)),_S=Uh(({roughness:e,dotNH:t})=>{const i=e.pow2(),n=Gh(1).div(i),r=t.pow2().oneMinus().max(.0078125);return Gh(2).add(n).mul(r.pow(n.mul(.5))).div(2*Math.PI)},{roughness:"float",dotNH:"float",return:"float"}),vS=Uh(({dotNV:e,dotNL:t})=>Gh(1).div(Gh(4).mul(t.add(e).sub(t.mul(e)))).clamp(),{dotNV:"float",dotNL:"float",return:"float"}),bS=Uh(({lightDirection:e})=>{const t=e.add(Og).normalize(),i=Yg.dot(e).clamp(),n=Yg.dot(Og).clamp(),r=Yg.dot(t).clamp(),s=_S({roughness:Rd,dotNH:r}),a=vS({dotNV:n,dotNL:i});return Ad.mul(s).mul(a)}),yS=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 xS=null;const SS=Uh(({roughness:e,dotNV:t})=>{null===xS&&(xS=new Rs(yS,16,16,at,Xe),xS.name="DFG_LUT",xS.minFilter=Oe,xS.magFilter=Oe,xS.wrapS=Le,xS.wrapT=Le,xS.generateMipmaps=!1,xS.needsUpdate=!0);const i=jh(e,t);return h_(xS,i).rg}),TS=Uh(e=>{const{dotNV:t,specularColor:i,specularF90:n,roughness:r}=e,s=SS({dotNV:t,roughness:r});return i.mul(s.x).add(n.mul(s.y))}),MS=Uh(({f:e,f90:t,dotVH:i})=>{const n=i.oneMinus().saturate(),r=n.mul(n),s=n.mul(r,r).clamp(0,.9999);return e.sub(Yh(t).mul(s)).div(s.oneMinus())},{f:"vec3",f90:"float",dotVH:"float",return:"vec3"}),ES=Uh(({N:e,V:t,roughness:i})=>{const n=e.dot(t).saturate(),r=jh(i,n.oneMinus().sqrt());return r.assign(r.mul(.984375).add(.0078125)),r},{N:"vec3",V:"vec3",roughness:"float",return:"vec2"}),wS=Uh(({f:e})=>{const t=e.length();return _f(t.mul(t).add(e.z).div(t.add(1)),0)},{f:"vec3",return:"float"}),AS=Uh(({v1:e,v2:t})=>{const i=e.dot(t),n=i.abs().toVar(),r=n.mul(.0145206).add(.4965155).mul(n).add(.8543985).toVar(),s=n.add(4.1616724).mul(n).add(3.417594).toVar(),a=r.div(s),o=i.greaterThan(0).select(a,_f(i.mul(i).oneMinus(),1e-7).inverseSqrt().mul(.5).sub(a));return e.cross(t).mul(o)},{v1:"vec3",v2:"vec3",return:"vec3"}),RS=Uh(({N:e,V:t,P:i,mInv:n,p0:r,p1:s,p2:a,p3:o})=>{const l=s.sub(r).toVar(),c=o.sub(r).toVar(),u=l.cross(c),h=Yh().toVar();return kh(u.dot(i.sub(r)).greaterThanEqual(0),()=>{const l=t.sub(e.mul(t.dot(e))).normalize(),c=e.cross(l).negate(),u=n.mul(rd(l,c,e).transpose()).toVar(),d=u.mul(r.sub(i)).normalize().toVar(),p=u.mul(s.sub(i)).normalize().toVar(),f=u.mul(a.sub(i)).normalize().toVar(),m=u.mul(o.sub(i)).normalize().toVar(),g=Yh(0).toVar();g.addAssign(AS({v1:d,v2:p})),g.addAssign(AS({v1:p,v2:f})),g.addAssign(AS({v1:f,v2:m})),g.addAssign(AS({v1:m,v2:d})),h.assign(Yh(wS({f:g})))}),h},{N:"vec3",V:"vec3",P:"vec3",mInv:"mat3",p0:"vec3",p1:"vec3",p2:"vec3",p3:"vec3",return:"vec3"}),CS=Uh(e=>{if(!1===e.geometry.hasAttribute("normal"))return Gh(0);const t=Xg.dFdx().abs().max(Xg.dFdy().abs());return t.x.max(t.y).max(t.z)}),NS=Uh(e=>{const{roughness:t}=e,i=CS();let n=t.max(.045);return n=n.add(i),n=n.min(1),n}),PS=Uh(([e,t])=>{const i=e.x,n=e.y,r=e.z;let s=t.element(0).mul(.886227);return s=s.add(t.element(1).mul(1.023328).mul(n)),s=s.add(t.element(2).mul(1.023328).mul(r)),s=s.add(t.element(3).mul(1.023328).mul(i)),s=s.add(t.element(4).mul(.858086).mul(i).mul(n)),s=s.add(t.element(5).mul(.858086).mul(n).mul(r)),s=s.add(t.element(6).mul(r.mul(r).mul(.743125).sub(.247708))),s=s.add(t.element(7).mul(.858086).mul(i).mul(r)),s=s.add(t.element(8).mul(.429043).mul(ip(i,i).sub(ip(n,n)))),s}),LS=new Ws;class DS extends my{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(LS),this.setValues(e)}}const IS=new Da;class FS extends my{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(IS),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?Gh(this.offsetNode):eb,t=this.dashScaleNode?Gh(this.dashScaleNode):Kv,i=this.dashSizeNode?Gh(this.dashSizeNode):Zv,n=this.gapSizeNode?Gh(this.gapSizeNode):Qv;Gd.assign(i),Vd.assign(n);const r=$f(Pm("lineDistance").mul(t));(e?r.add(e):r).mod(Gd.add(Vd)).greaterThan(Gd).discard()}}const US=vd("vec3","worldStart"),OS=vd("vec3","worldEnd"),BS=vd("float","lineDistance"),kS=vd("vec4","worldPos"),zS=Uh(({start:e,end:t})=>{const i=gg.element(2).element(2),n=gg.element(3).element(2);return i.greaterThan(0).select(n.negate().div(i.add(1)),n.mul(-.5).div(i)).sub(e.z).div(t.z.sub(e.z))},{start:"vec4",end:"vec4",return:"float"}),GS=Uh(({p1:e,p2:t,p3:i,p4:n})=>{const r=e.sub(i),s=n.sub(i),a=t.sub(e),o=r.dot(s),l=s.dot(a),c=r.dot(a),u=s.dot(s),h=a.dot(a).mul(u).sub(l.mul(l)),d=o.mul(l).sub(c.mul(u)).div(h).clamp(),p=o.add(l.mul(d)).div(u).clamp();return jh(d,p)},{p1:"vec3",p2:"vec3",p3:"vec3",p4:"vec3",return:"vec2"});Uh(({material:e})=>{const t=e._useDash,i=e._useWorldUnits,n=Pm("instanceStart"),r=Pm("instanceEnd"),s=Jh(wg.mul(Jh(n,1))).toVar("start"),a=Jh(wg.mul(Jh(r,1))).toVar("end");let o,l;t&&(o=Gh(Pm("instanceDistanceStart")).toVar("distanceStart"),l=Gh(Pm("instanceDistanceEnd")).toVar("distanceEnd")),i&&(US.assign(s.xyz),OS.assign(a.xyz));const c=ng.z.div(ng.w),u=gg.element(2).element(3).equal(-1);if(kh(u,()=>{kh(s.z.lessThan(0).and(a.z.greaterThan(0)),()=>{const e=zS({start:s,end:a});a.assign(Jh(Rf(s.xyz,a.xyz,e),a.w)),t&&l.assign(Rf(o,l,e))}).ElseIf(a.z.lessThan(0).and(s.z.greaterThanEqual(0)),()=>{const e=zS({start:a,end:s});s.assign(Jh(Rf(a.xyz,s.xyz,e),s.w)),t&&o.assign(Rf(l,o,e))})}),t){const t=e.dashScaleNode?Gh(e.dashScaleNode):Kv,i=e.offsetNode?Gh(e.offsetNode):eb;let n=Pg.y.lessThan(.5).select(t.mul(o),t.mul(l));n=n.add(i),BS.assign(n)}const h=gg.mul(s),d=gg.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(c)),m.assign(m.normalize());const g=Jh().toVar();if(i){const e=a.xyz.sub(s.xyz).normalize(),i=u.select(Rf(s.xyz,a.xyz,.5).normalize(),Yh(0,0,-1)),n=e.cross(i).normalize(),r=e.cross(n);kS.assign(Pg.y.lessThan(.5).select(s,a));const o=Jv.mul(.5);kS.addAssign(Jh(Pg.x.lessThan(0).select(n.mul(o),n.mul(o).negate()),0)),t||(kS.addAssign(Jh(Pg.y.lessThan(.5).select(e.mul(o).negate(),e.mul(o)),0)),kS.addAssign(Jh(r.mul(o),0)),kh(Pg.y.greaterThan(1).or(Pg.y.lessThan(0)),()=>{kS.subAssign(Jh(r.mul(2).mul(o),0))})),g.assign(gg.mul(kS));const l=Yh().toVar();l.assign(Pg.y.lessThan(.5).select(p,f)),kh(g.w.greaterThan(0),()=>{g.z.assign(l.z.mul(g.w))})}else{const e=jh(m.y,m.x.negate()).toVar("offset");m.x.assign(m.x.div(c)),e.x.assign(e.x.div(c)),e.assign(Pg.x.lessThan(0).select(e.negate(),e)),kh(Pg.y.lessThan(0),()=>{e.assign(e.sub(m))}).ElseIf(Pg.y.greaterThan(1),()=>{e.assign(e.add(m))}),e.assign(e.mul(Jv)),e.assign(e.div(ng.w.div(Jm))),g.assign(Pg.y.lessThan(.5).select(h,d)),e.assign(e.mul(g.w)),g.assign(g.add(Jh(e,0,0)))}return g})(),Uh(({material:e,renderer:t})=>{const i=e._useAlphaToCoverage,n=e._useDash,r=e._useWorldUnits,s=Bg();if(n){const t=e.dashSizeNode?Gh(e.dashSizeNode):Zv,i=e.gapSizeNode?Gh(e.gapSizeNode):Qv;Gd.assign(t),Vd.assign(i),s.y.lessThan(-1).or(s.y.greaterThan(1)).discard(),BS.mod(Gd.add(Vd)).greaterThan(Gd).discard()}const a=Gh(1).toVar("alpha");if(r){const e=Gh().toVar(),r=gg.element(2).element(3).notEqual(-1).toConst();kh(r,()=>{const t=OS.xy.sub(US.xy),i=kS.xy.sub(US.xy).dot(t).div(t.dot(t)).clamp();e.assign(US.xy.add(t.mul(i)).sub(kS.xy).length())}).Else(()=>{const t=kS.xyz.normalize().mul(1e5),i=OS.sub(US),n=GS({p1:US,p2:OS,p3:Yh(0,0,0),p4:t}),r=US.add(i.mul(n.x)),s=t.mul(n.y),a=r.sub(s);e.assign(a.length())});const s=e.div(Jv);if(!n)if(i&&t.currentSamples>0){const e=s.fwidth();a.assign(Lf(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)),n=Gh(i.fwidth()).toVar("dlen");kh(s.y.abs().greaterThan(1),()=>{a.assign(Lf(n.oneMinus(),n.add(1),i).oneMinus())})}else kh(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 VS=new Ra;class HS extends my{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(VS),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?Gh(this.opacityNode):Ev;bd.assign(Zf(Jh(Rh(Yg).mul(.5).add(.5),e),Xt))}}const WS=new WeakMap;class jS extends Bu{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=G_(null);const t=new sa;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=mu}updateBefore(e){const{renderer:t,material:i}=e,n=this.envNode;if(n.isTextureNode||n.isMaterialReferenceNode){const e=n.isTextureNode?n.value:i[n.property];if(e&&e.isTexture){const i=e.mapping;if(i===Ce||i===Ne){if(WS.has(e)){const t=WS.get(e);XS(t,e.mapping),this._cubeTexture=t}else{const i=e.image;if(function(e){return null!=e&&e.height>0}(i)){const n=new Wx(i.height);n.fromEquirectangularTexture(t,e),XS(n.texture,e.mapping),this._cubeTexture=n.texture,WS.set(e,n.texture),e.addEventListener("dispose",$S)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function $S(e){const t=e.target;t.removeEventListener("dispose",$S);const i=WS.get(t);void 0!==i&&(WS.delete(t),i.dispose())}function XS(e,t){t===Ce?e.mapping=Ae:t===Ne&&(e.mapping=Re)}const qS=Ph(jS).setParameterLength(1);class YS extends Qb{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=qS(this.envNode).context({getUV:e=>D_.mul(e.uvNode||e.getDefaultUV()),forceUVContext:!0})}}class KS extends Qb{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=Gh(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class ZS{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class QS extends ZS{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,i=e.reflectedLight,n=e.irradianceLightMap;i.indirectDiffuse.assign(Jh(0)),n?i.indirectDiffuse.addAssign(n):i.indirectDiffuse.addAssign(Jh(1,1,1,0)),i.indirectDiffuse.mulAssign(t),i.indirectDiffuse.mulAssign(bd.rgb)}finish(e){const{material:t,context:i}=e,n=i.outgoingLight,r=e.context.environment;if(r)switch(t.combine){case 0:n.rgb.assign(Rf(n.rgb,n.rgb.mul(r.rgb),Cv.mul(Nv)));break;case 1:n.rgb.assign(Rf(n.rgb,r.rgb,Cv.mul(Nv)));break;case 2:n.rgb.addAssign(r.rgb.mul(Cv.mul(Nv)));break;default:Ti("BasicLightingModel: Unsupported .combine value:",t.combine)}}}const JS=new fs;class eT extends my{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(JS),this.setValues(e)}setupNormal(){return Hg(Xg)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new YS(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new KS(rb)),t}setupOutgoingLight(){return bd.rgb}setupLightingModel(){return new QS}}const tT=Uh(({dotNH:e})=>kd.mul(Gh(.5)).add(1).mul(Gh(1/Math.PI)).mul(e.pow(kd))),iT=Uh(({lightDirection:e})=>{const t=e.add(Og).normalize(),i=Yg.dot(t).clamp(),n=Og.dot(t).clamp(),r=cS({f0:Ud,f90:1,dotVH:n}),s=Gh(.25),a=tT({dotNH:i});return r.mul(s).mul(a)});class nT extends QS{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:i}){const n=Yg.dot(e).clamp().mul(t);i.directDiffuse.addAssign(n.mul(gS({diffuseColor:bd.rgb}))),!0===this.specular&&i.directSpecular.addAssign(n.mul(iT({lightDirection:e})).mul(Cv))}indirect(e){const{ambientOcclusion:t,irradiance:i,reflectedLight:n}=e.context;n.indirectDiffuse.addAssign(i.mul(gS({diffuseColor:bd}))),n.indirectDiffuse.mulAssign(t)}}const rT=new Ca;class sT extends my{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.emissiveNode=null,this.setDefaultValues(rT),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new YS(t):null}setupLightingModel(){return new nT(!1)}}const aT=new wa;class oT extends my{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(aT),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new YS(t):null}setupLightingModel(){return new nT}setupVariants(){const e=(this.shininessNode?Gh(this.shininessNode):Tv).max(1e-4);kd.assign(e);const t=this.specularNode||wv;Ud.assign(t)}}const lT=Uh(([e,t,i,n,r])=>{const s=Yh(Pf(t.negate(),Gp(e),np(1,n))),a=Yh(rf(r[0].xyz),rf(r[1].xyz),rf(r[2].xyz));return Gp(s).mul(i.mul(a))},{n:"vec3",v:"vec3",thickness:"float",ior:"float",modelMatrix:"mat4",return:"vec3"}),cT=Uh(([e,t])=>e.mul(Cf(t.mul(2).sub(2),0,1)),{roughness:"float",ior:"float",return:"float"}),uT=m_(),hT=__(),dT=Uh(([e,t,i],{material:n})=>{const r=(1===n.side?uT:hT).sample(e.mul(xg.zw).add(xg.xy).div(tg)),s=Up(xg.z).mul(cT(t,i));return Ay(r,s)}),pT=Uh(([e,t,i])=>(kh(i.notEqual(0),()=>{const n=Fp(t).negate().div(i);return Dp(n.negate().mul(e))}),Yh(1)),{transmissionDistance:"float",attenuationColor:"vec3",attenuationDistance:"float",return:"vec3"}),fT=Uh(([e,t,i,n,r,s,a,o,l,c,u,h,d,p,f])=>{let m,g;if(f){m=Jh().toVar(),g=Yh().toVar();const r=u.sub(1).mul(f.mul(.025)),s=Yh(u.sub(r),u,u.add(r));zm({start:0,end:3},({i:r})=>{const u=s.element(r),f=lT(e,t,h,u,o),_=a.add(f),v=c.mul(l.mul(Jh(_,1))),b=jh(v.xy.div(v.w)).toVar();b.addAssign(1),b.divAssign(2),b.assign(jh(b.x,b.y.oneMinus()));const y=dT(b,i,u);m.element(r).assign(y.element(r)),m.a.addAssign(y.a),g.element(r).assign(n.element(r).mul(pT(rf(f),d,p).element(r)))}),m.a.divAssign(3)}else{const r=lT(e,t,h,u,o),s=a.add(r),f=c.mul(l.mul(Jh(s,1))),_=jh(f.xy.div(f.w)).toVar();_.addAssign(1),_.divAssign(2),_.assign(jh(_.x,_.y.oneMinus())),m=dT(_,i,u),g=n.mul(pT(rf(r),d,p))}const _=g.rgb.mul(m.rgb),v=e.dot(t).clamp(),b=Yh(TS({dotNV:v,specularColor:r,specularF90:s,roughness:i})),y=g.r.add(g.g,g.b).div(3);return Jh(b.oneMinus().mul(_),m.a.oneMinus().mul(y).oneMinus())}),mT=rd(3.2404542,-1.5371385,-.4985314,-.969266,1.8760108,.041556,.0556434,-.2040259,1.0572252),gT=(e,t)=>e.sub(t).div(e.add(t)).pow2(),_T=Uh(({outsideIOR:e,eta2:t,cosTheta1:i,thinFilmThickness:n,baseF0:r})=>{const s=Rf(e,t,Lf(0,.03,n)),a=e.div(s).pow2().mul(i.pow2().oneMinus()).oneMinus();kh(a.lessThan(0),()=>Yh(1));const o=a.sqrt(),l=gT(s,e),c=cS({f0:l,f90:1,dotVH:i}),u=c.oneMinus(),h=s.lessThan(e).select(Math.PI,0),d=Gh(Math.PI).sub(h),p=(e=>{const t=e.sqrt();return Yh(1).add(t).div(Yh(1).sub(t))})(r.clamp(0,.9999)),f=gT(p,s.toVec3()),m=cS({f0:f,f90:1,dotVH:o}),g=Yh(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(n,o,2),v=Yh(d).add(g),b=c.mul(m).clamp(1e-5,.9999),y=b.sqrt(),x=u.pow2().mul(m).div(Yh(1).sub(b)),S=c.add(x).toVar(),T=x.sub(u).toVar();return zm({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),n=Yh(54856e-17,44201e-17,52481e-17),r=Yh(1681e3,1795300,2208400),s=Yh(43278e5,93046e5,66121e5),a=Gh(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(i.mul(2239900).add(t.x).cos()).mul(i.pow2().mul(-45282e5).exp());let o=n.mul(s.mul(2*Math.PI).sqrt()).mul(r.mul(i).add(t).cos()).mul(i.pow2().negate().mul(s).exp());return o=Yh(o.x.add(a),o.y,o.z).div(1.0685e-7),mT.mul(o)})(Gh(e).mul(_),Gh(e).mul(v)).mul(2);S.addAssign(T.mul(t))}),S.max(Yh(0))},{outsideIOR:"float",eta2:"float",cosTheta1:"float",thinFilmThickness:"float",baseF0:"vec3",return:"vec3"}),vT=Uh(({normal:e,viewDir:t,roughness:i})=>{const n=e.dot(t).saturate(),r=i.mul(i),s=i.add(.1).reciprocal(),a=Gh(-1.9362).add(i.mul(1.0678)).add(r.mul(.4573)).sub(s.mul(.8469)),o=Gh(-.6014).add(i.mul(.5538)).sub(r.mul(.467)).sub(s.mul(.1255));return a.mul(n).add(o).exp().saturate()},{normal:"vec3",viewDir:"vec3",roughness:"float",return:"float"}),bT=Yh(.04),yT=Gh(1);class xT extends ZS{constructor(e=!1,t=!1,i=!1,n=!1,r=!1,s=!1,a=!1,o=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=i,this.anisotropy=n,this.transmission=r,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=Yh().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=Yh().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=Yh().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=Yh().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=Yh().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=Yg.dot(Og).clamp(),t=_T({outsideIOR:Gh(1),eta2:Nd,cosTheta1:e,thinFilmThickness:Pd,baseF0:Ud}),i=_T({outsideIOR:Gh(1),eta2:Nd,cosTheta1:e,thinFilmThickness:Pd,baseF0:bd.rgb});this.iridescenceFresnel=Rf(t,i,Md),this.iridescenceF0Dielectric=MS({f:t,f90:1,dotVH:e}),this.iridescenceF0Metallic=MS({f:i,f90:1,dotVH:e})}if(!0===this.transmission){const t=Ig,i=yg.sub(Ig).normalize(),n=Kg,r=e.context;r.backdrop=fT(n,i,Td,yd,Od,Bd,t,Mg,vg,gg,Hd,jd,Xd,$d,this.dispersion?qd:null),r.backdropAlpha=Wd,bd.a.mulAssign(Rf(1,r.backdrop.a,Wd))}const t=Yg.dot(Og).clamp();this.dfg=SS({roughness:Td,dotNV:t}).toConst("dfg");const i=this.dfg.x.add(this.dfg.y);this.multiScatteringCompensation=Od.mul(i.reciprocal().sub(1)).add(1).toConst("multiScatteringCompensation"),this.singleScatteringDielectric=Yh().toVar("singleScatteringDielectric"),this.multiScatteringDielectric=Yh().toVar("multiScatteringDielectric"),this.computeMultiscattering(this.singleScatteringDielectric,this.multiScatteringDielectric,Bd,Ud,this.iridescenceF0Dielectric),!0===this.diffuseRoughness&&(this.eonDirectionalAlbedo=lS({diffuseColor:bd.rgb,roughness:xd,dotNV:t})),super.start(e)}computeMultiscattering(e,t,i,n,r=null){const s=this.dfg,a=r?Cd.mix(n,r):n,o=a.mul(s.x).add(i.mul(s.y)),l=s.x.add(s.y).oneMinus(),c=a.add(a.oneMinus().mul(.047619)),u=o.mul(c).div(l.mul(c).oneMinus());e.addAssign(o),t.addAssign(u.mul(l))}direct({lightDirection:e,lightColor:t,reflectedLight:i}){const n=Yg.dot(e).clamp().mul(t).toVar();if(!0===this.sheen){this.sheenSpecularDirect.addAssign(n.mul(bS({lightDirection:e})));const t=vT({normal:Yg,viewDir:Og,roughness:Rd}),i=vT({normal:Yg,viewDir:e,roughness:Rd}),r=Ad.r.max(Ad.g).max(Ad.b).mul(t.max(i)).oneMinus();n.mulAssign(r)}if(!0===this.clearcoat){const i=Zg.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(i.mul(mS({lightDirection:e,f0:bT,f90:yT,roughness:wd,normalView:Zg})))}const r=e.add(Og).normalize(),s=Og.dot(r).clamp();let a=cS({f0:Ud,f90:Bd,dotVH:s}),o=mS({lightDirection:e,f0:Od,f90:Bd,roughness:Td,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy});if(!0===this.retroreflection){const t=Og.negate().reflect(Yg),i=e.add(t).normalize(),n=t.dot(i).clamp(),r=cS({f0:Ud,f90:Bd,dotVH:n}),s=mS({lightDirection:e,viewDirection:t,f0:Od,f90:Bd,roughness:Td,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy});a=Rf(a,r,Yd.clamp()),o=Rf(o,s,Yd.clamp())}const l=this.diffuseRoughness?oS({lightDirection:e,diffuseColor:bd.rgb,roughness:xd}).mul(Md.oneMinus()):gS({diffuseColor:yd});i.directDiffuse.addAssign(n.mul(l).mul(a.oneMinus())),i.directSpecular.addAssign(n.mul(o).mul(this.multiScatteringCompensation))}directRectArea({lightColor:e,lightPosition:t,halfWidth:i,halfHeight:n,reflectedLight:r,ltc_1:s,ltc_2:a}){const o=t.add(i).sub(n),l=t.sub(i).sub(n),c=t.sub(i).add(n),u=t.add(i).add(n),h=Yg,d=Og,p=Ug.toVar(),f=ES({N:h,V:d,roughness:Td}),m=s.sample(f).toVar(),g=a.sample(f).toVar(),_=rd(Yh(m.x,0,m.y),Yh(0,1,0),Yh(m.z,0,m.w)).toVar(),v=Od.mul(g.x).add(Bd.sub(Od).mul(g.y)).toVar();if(r.directSpecular.addAssign(e.mul(v).mul(RS({N:h,V:d,P:p,mInv:_,p0:o,p1:l,p2:c,p3:u}))),r.directDiffuse.addAssign(e.mul(yd).mul(RS({N:h,V:d,P:p,mInv:rd(1,0,0,0,1,0,0,0,1),p0:o,p1:l,p2:c,p3:u}))),!0===this.clearcoat){const t=Zg,i=ES({N:t,V:d,roughness:wd}),n=s.sample(i),r=a.sample(i),h=rd(Yh(n.x,0,n.y),Yh(0,1,0),Yh(n.z,0,n.w)),f=bT.mul(r.x).add(yT.sub(bT).mul(r.y));this.clearcoatSpecularDirect.addAssign(e.mul(f).mul(RS({N:t,V:d,P:p,mInv:h,p0:o,p1:l,p2:c,p3:u})))}}indirect(e){this.indirectDiffuse(e),this.indirectSpecular(e),this.ambientOcclusion(e)}indirectDiffuse(e){const{irradiance:t,reflectedLight:i}=e.context,n=this.singleScatteringDielectric,r=this.multiScatteringDielectric,s=this.diffuseRoughness?this.eonDirectionalAlbedo.mul(Md.oneMinus(),1/Math.PI):gS({diffuseColor:yd}),a=t.mul(s).mul(n.add(r).oneMinus()).toVar();if(!0===this.sheen){const e=vT({normal:Yg,viewDir:Og,roughness:Rd});this.sheenSpecularIndirect.addAssign(t.mul(Ad,e,1/Math.PI));const i=Ad.r.max(Ad.g).max(Ad.b).mul(e).oneMinus();a.mulAssign(i)}i.indirectDiffuse.addAssign(a)}indirectSpecular(e){const{radiance:t,iblIrradiance:i,reflectedLight:n}=e.context;if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(i.mul(Ad,vT({normal:Yg,viewDir:Og,roughness:Rd}),1/Math.PI)),!0===this.clearcoat){const e=Zg.dot(Og).clamp(),t=TS({dotNV:e,specularColor:bT,specularF90:yT,roughness:wd});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const r=this.singleScatteringDielectric,s=this.multiScatteringDielectric,a=Yh().toVar("singleScatteringMetallic"),o=Yh().toVar("multiScatteringMetallic");this.computeMultiscattering(a,o,Bd,bd.rgb,this.iridescenceF0Metallic);const l=Rf(r,a,Md),c=Rf(s,o,Md),u=r.add(s),h=(this.diffuseRoughness?this.eonDirectionalAlbedo.mul(Md.oneMinus()):yd).mul(u.oneMinus()),d=i.mul(1/Math.PI),p=t.mul(l).add(c.mul(d)).toVar(),f=h.mul(d).toVar();if(!0===this.sheen){const e=vT({normal:Yg,viewDir:Og,roughness:Rd}),t=Ad.r.max(Ad.g).max(Ad.b).mul(e).oneMinus();p.mulAssign(t),f.mulAssign(t)}n.indirectSpecular.addAssign(p),n.indirectDiffuse.addAssign(f)}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:i}=e.context,n=Yg.dot(Og).clamp().add(t),r=Td.mul(-16).oneMinus().negate().exp2(),s=t.sub(n.pow(r).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=Zg.dot(Og).clamp(),i=cS({dotVH:e,f0:bT,f90:yT}),n=t.mul(Ed.mul(i).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(Ed));t.assign(n)}if(!0===this.sheen){const e=t.add(this.sheenSpecularDirect,this.sheenSpecularIndirect);t.assign(e)}}}const ST=new WeakMap;class TT extends Qb{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 n=t.get(i);void 0===n&&(n=iS(this._getEnvTexture(e)),t.set(i,n)),this._pmremNode=n,this.updateBeforeType=i.isMaterialReferenceNode?gu:mu,i=n}const n=!0===t.useAnisotropy||t.anisotropy>0?dv:Yg;let r=vm(i.context(MT(Td,n)).mul(L_));if(!0===t.useRetroreflection||t.retroreflectivity>0){const e=vm(i.context(ET(Td,n)).mul(L_));r=Yd.clamp().mix(r,e)}const s=i.context(wT(Kg)).mul(Math.PI).mul(L_),a=vm(s);e.context.radiance.addAssign(r),e.context.iblIrradiance.addAssign(a);const o=e.context.lightingModel.clearcoatRadiance;if(o){const e=i.context(MT(wd,Zg)).mul(L_),t=vm(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=ST.get(e);return void 0===t&&(t=new WeakMap,ST.set(e,t)),t}}const MT=(e,t)=>{let i=null;return{getUV:()=>(null===i&&(i=Og.negate().reflect(t),i=wf(e).mix(i,t).normalize(),i=i.transformDirection(bg)),i),getTextureLevel:()=>e}},ET=(e,t)=>{let i=null;return{getUV:()=>(null===i&&(i=wf(e).mix(Og,t).normalize(),i=i.transformDirection(bg)),i),getTextureLevel:()=>e}},wT=e=>({getUV:()=>e,getTextureLevel:()=>Gh(1)}),AT=new Ma;class RT extends my{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(AT),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new TT(t):null}setupLightingModel(){return new xT}setupSpecular(){const e=Rf(Yh(.04),bd.rgb,Md);Ud.assign(Yh(.04)),Od.assign(e),Bd.assign(1)}setupVariants(){const e=this.metalnessNode?Gh(this.metalnessNode):Dv;Md.assign(e);let t=this.roughnessNode?Gh(this.roughnessNode):Pv;t=NS({roughness:t}),Td.assign(t),this.setupSpecular(),yd.assign(bd.rgb.mul(e.oneMinus()))}}const CT=new Ea;class NT extends RT{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(CT),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?Gh(this.iorNode):Xv,t=this.specularColorNode?Yh(this.specularColorNode):Rv,i=this.specularIntensityNode?Gh(this.specularIntensityNode):Av;Hd.assign(e),Ud.assign(gf(Ef(Hd.sub(1).div(Hd.add(1))).mul(t),Yh(1)).mul(i)),Od.assign(Rf(Ud,bd.rgb,Md)),Bd.assign(Rf(i,1,Md))}setupLightingModel(){return new xT(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?Gh(this.diffuseRoughnessNode):Lv;xd.assign(e.clamp())}if(this.useClearcoat){const e=this.clearcoatNode?Gh(this.clearcoatNode):Fv,t=this.clearcoatRoughnessNode?Gh(this.clearcoatRoughnessNode):Uv;Ed.assign(e),wd.assign(NS({roughness:t}))}if(this.useSheen){const e=this.sheenNode?Yh(this.sheenNode):kv,t=this.sheenRoughnessNode?Gh(this.sheenRoughnessNode):zv;Ad.assign(e),Rd.assign(t)}if(this.useRetroreflection){const e=this.retroreflectivityNode?Gh(this.retroreflectivityNode):nb;Yd.assign(e)}if(this.useIridescence){const e=this.iridescenceNode?Gh(this.iridescenceNode):Vv,t=this.iridescenceIORNode?Gh(this.iridescenceIORNode):Hv,i=this.iridescenceThicknessNode?Gh(this.iridescenceThicknessNode):Wv;Cd.assign(e),Nd.assign(t),Pd.assign(i)}if(this.useAnisotropy){const e=(this.anisotropyNode?jh(this.anisotropyNode):Gv).toVar();Dd.assign(e.length()),kh(Dd.equal(0),()=>{e.assign(jh(1,0))}).Else(()=>{e.divAssign(jh(Dd)),Dd.assign(Dd.saturate())}),Ld.assign(Dd.pow2().mix(Td.pow2(),1)),Id.assign(hv[0].mul(e.x).add(hv[1].mul(e.y))),Fd.assign(hv[1].mul(e.x).sub(hv[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?Gh(this.transmissionNode):jv,t=this.thicknessNode?Gh(this.thicknessNode):$v,i=this.attenuationDistanceNode?Gh(this.attenuationDistanceNode):qv,n=this.attenuationColorNode?Yh(this.attenuationColorNode):Yv;if(Wd.assign(e),jd.assign(t),$d.assign(i),Xd.assign(n),this.useDispersion){const e=this.dispersionNode?Gh(this.dispersionNode):ib;qd.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?Yh(this.clearcoatNormalNode):Ov}setup(e){e.context.setupClearcoatNormal=()=>Wf(this.setupClearcoatNormal(e),"NORMAL","vec3"),super.setup(e)}}const PT=Uh(({normal:e,lightDirection:t,builder:i})=>{const n=e.dot(t),r=jh(n.mul(.5).add(.5),0);if(i.material.gradientMap){const e=$_("gradientMap","texture").context({getUV:()=>r});return Yh(e.r)}{const e=r.fwidth().mul(.5);return Rf(Yh(.7),Yh(1),Lf(Gh(.7).sub(e.x),Gh(.7).add(e.x),r.x))}});class LT extends ZS{direct({lightDirection:e,lightColor:t,reflectedLight:i},n){const r=PT({normal:Yg,lightDirection:e,builder:n}).mul(t);i.directDiffuse.addAssign(r.mul(gS({diffuseColor:bd.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:i,reflectedLight:n}=e.context;n.indirectDiffuse.addAssign(i.mul(gS({diffuseColor:bd}))),n.indirectDiffuse.mulAssign(t)}}const DT=new Aa;class IT extends my{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.emissiveNode=null,this.setDefaultValues(DT),this.setValues(e)}setupLightingModel(){return new LT}}const FT=new La;class UT extends my{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(FT),this.setValues(e)}setupVariants(e){const t=e_;let i;i=e.material.matcap?$_("matcap","texture").context({getUV:()=>t}):Yh(Rf(.2,.8,t.y)),bd.rgb.mulAssign(i.rgb)}}const OT=new ls;class BT extends my{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(OT),this.setValues(e)}setupPositionView(e){const{object:t,camera:i}=e,{positionNode:n,rotationNode:r,scaleNode:s,sizeAttenuation:a}=this,o=wg.mul(Yh(n||0));let l=jh(Mg[0].xyz.length(),Mg[1].xyz.length());null!==s&&(l=l.mul(jh(s))),!0!==i.isOrthographicCamera&&!1===a&&(l=l.mul(o.z.negate()));let c=Pg.xy;if(t.center&&!0===t.center.isVector2){const e=((e,t,i)=>new Jf(e,t,i))("center","vec2");c=c.sub(e.sub(.5))}c=c.mul(l);const u=Gh(r||Bv),h=s_(c,u);return Jh(o.xy.add(h),o.zw)}get sizeAttenuation(){return this._useSizeAttenuation}set sizeAttenuation(e){this._useSizeAttenuation!==e&&(this._useSizeAttenuation=e,this.needsUpdate=!0)}}const kT=new na,zT=new Vi;class GT extends BT{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(kT),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return wg.mul(Yh(e||Lg)).xyz}setupVertexSprite(e){const{material:t,camera:i}=e,{rotationNode:n,scaleNode:r,sizeNode:s,sizeAttenuation:a}=this;let o=super.setupVertex(e);if(!0!==t.isNodeMaterial)return o;let l=null!==s?jh(s):tb;l=l.mul(Jm),!0!==i.isOrthographicCamera&&!0===a&&(l=l.mul(VT.div(Ug.z.negate()))),r&&r.isNode&&(l=l.mul(jh(r)));let c=Pg.xy;if(n&&n.isNode){const e=Gh(n);c=s_(c,e)}return c=c.mul(l),c=c.div(rg.div(2)),c=c.mul(o.w),o=o.add(Jh(c,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 VT=md(1).setGroup(dd).onRenderUpdate(function({renderer:e}){const t=e.getSize(zT);this.value=.5*t.y});class HT extends ZS{constructor(){super(),this.shadowNode=Gh(1).toVar("shadowMask")}direct({lightNode:e}){null!==e.shadowNode&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){bd.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(bd.rgb)}}const WT=new ga;class jT extends my{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(WT),this.setValues(e)}setupLightingModel(){return new HT}}_d("vec3"),_d("float"),_d("vec3");class $T{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 XT=0;const qT=new WeakMap,YT=[0,0,0,0,0],KT=["side","blending","combine","normalMapType"];function ZT(e){return null==e?"-":!0===e.isStorageInstancedBufferAttribute?"s":"a"}class QT{constructor(e,t,i,n,r,s,a,o,l,c){this.id=XT++,this._nodes=e,this._geometries=t,this.renderer=i,this.object=n,this.material=r,this.scene=s,this.camera=a,this.lightsNode=o,this.context=l,this.geometry=n.geometry,this.geometryVersion=0,this.version=r.version,this.drawRange=null,this.attributes=null,this.attributesId=null,this.pipeline=null,this.group=null,this.vertexBuffers=null,this.drawParams=null,this.bundle=null,this.clippingContext=c,this.clippingContextCacheKey=null!==c?c.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=[],n=new Set,r={};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?r[s.name]=e.data.uuid:r[s.name]=e.id)),void 0===e)continue;i.push(e);const a=e.isInterleavedBufferAttribute?e.data:e;n.add(a)}return this.attributes=i,this.attributesId=r,this.vertexBuffers=Array.from(n.values()),i}getVertexBuffers(){return null===this.vertexBuffers&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){const{object:e,material:t,geometry:i,group:n,drawRange:r}=this,s=this.drawParams||(this.drawParams={vertexCount:0,firstVertex:0,instanceCount:0,firstInstance:0}),a=this.getIndex(),o=null!==a;let l=1;if(!0===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 c=1;!0!==t.wireframe||e.isPoints||e.isLineSegments||e.isLine||e.isLineLoop||(c=2);let u=r.start*c,h=(r.start+r.count)*c;null!==n&&(u=Math.max(u,n.start*c),h=Math.min(h,(n.start+n.count)*c));const d=i.attributes.position;let p=1/0;o?p=a.count:null!=d&&(p=d.count),u=Math.max(u,0),h=Math.min(h,p);const f=h-u;return f<0||f===1/0?null:(s.vertexCount=f,s.firstVertex=u,s)}getGeometryCacheKey(){const{geometry:e}=this;let t="";for(const i of Object.keys(e.attributes).sort()){const n=e.attributes[i];t+=i+",",n.itemSize&&(t+=n.itemSize+","),n.normalized&&(t+="n,")}for(const i of Object.keys(e.morphAttributes).sort()){const n=e.morphAttributes[i];t+="morph-"+i+",";for(let e=0,i=n.length;e<i;e++){t+=n[e].id+","}}return t}getMaterialCacheKey(){const{object:e,material:t,renderer:i,scene:n}=this;let r=this._nodes.getCustomProgramCacheKey(t,n);for(const e of function(e){const t=Object.keys(e);let i=qT.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 n=e[t];n&&"function"==typeof n.get&&i.push(t)}t=Object.getPrototypeOf(t)}qT.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 n=t[e];let s;if(null!==n){const t=typeof n;"number"===t?s=KT.includes(e)?String(n):0!==n?"1":"0":"object"===t?(s="{",n.isTexture&&(s+=n.mapping,s+=n.channel,!0===i.backend.isWebGPUBackend&&(s+=n.magFilter,s+=n.minFilter,s+=n.wrapS,s+=n.wrapT,s+=n.wrapR)),s+="}"):s=String(n)}else s=String(n);r+=s+","}if(r+=this.clippingContextCacheKey+",",e.geometry&&(r+=this.getGeometryCacheKey()),e.skeleton&&(r+=e.skeleton.bones.length+","),e.isBatchedMesh&&(r+=e._matricesTexture.uuid+",",null!==e._colorsTexture&&(r+=e._colorsTexture.uuid+",")),e.isInstancedMesh){const{instanceMatrix:t,instanceColor:i,morphTexture:n}=e;r+=ZT(t)+ZT(i)+(null!==n?"m":"")+","}else e.count>1&&(r+=e.uuid+",");return r+=this.context.stateKey+",",r+=e.receiveShadow+",",wu(r)}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 n=i.isInterleavedBufferAttribute?i.data.uuid:i.id;if(e[t]!==n)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)),YT[0]=e,YT[1]=this.camera.isArrayCamera?this.camera.cameras.length:0,YT[2]=this.object.receiveShadow?1:0,YT[3]=this.renderer.contextNode.id,YT[4]=this.renderer.contextNode.version,Au(YT)}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 JT=[null,null,null,null],eM=[null,null,null,null,null];class tM{constructor(e,t,i,n,r,s){this.renderer=e,this.nodes=t,this.geometries=i,this.pipelines=n,this.bindings=r,this.info=s,this._chainMaps={},this._renderObjects=new Set}get(e,t,i,n,r,s,a,o){const l=this.getChainMap(o),c=this.renderer._currentSourceMaterial,u=null!==c?c.version:0,h=null!==c?eM:JT;h[0]=e,h[1]=t,h[2]=s,h[3]=r,null!==c&&(h[4]=c);let d=l.get(h);if(void 0===d)d=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,i,n,r,s,a,o),l.set(h,d);else{let l=!1;d.camera=n,d.updateClipping(a),d.needsGeometryUpdate&&(d.setGeometry(e.geometry),d.initialGeometryCacheKey!==d.getGeometryCacheKey()&&(l=!0)),(d.version!==t.version||d.sourceMaterialVersion!==u||d.needsUpdate||l)&&(d.initialCacheKey!==d.getCacheKey()?(d.dispose(),d=this.get(e,t,i,n,r,s,a,o)):(d.version=t.version,d.sourceMaterialVersion=u))}return h[0]=null,h[1]=null,h[2]=null,h[3]=null,null!==c&&(h[4]=null),d}getChainMap(e="default"){return this._chainMaps[e]||(this._chainMaps[e]=new ox)}dispose(){for(const e of this._renderObjects)e.dispose();this._renderObjects.clear(),this._chainMaps={}}createRenderObject(e,t,i,n,r,s,a,o,l,c,u){const h=this.getChainMap(u),d=new QT(e,t,i,n,r,s,a,o,l,c);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 iM{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 nM=1,rM=2,sM=3,aM=4,oM=16;let lM=0;class cM extends iM{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===nM?(this.backend.createAttribute(e),this.info.createAttribute(e)):t===rM?(this.backend.createIndexAttribute(e),this.info.createIndexAttribute(e)):t===sM?(this.backend.createStorageAttribute(e),this.info.createStorageAttribute(e)):t===aM&&(this.backend.createIndirectStorageAttribute(e),this.info.createIndirectStorageAttribute(e)),i.version=e.version,i.generation=lM++,!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 uM(e){return null!==e.index?e.index.version:e.attributes.position.version}function hM(e){return null!==e.index?e.index.id:e.attributes.position.id}function dM(e){const t=e.index,i=e.attributes.position,n=null!==t?t.array.length:i.array.length/3-1,r=new(i.count>=65535?Or:Ur)(6*Math.ceil(n/3),1),s=r.array;if(null!==t){const e=t.array;for(let t=0,i=0;t<n;t+=3){const n=e[t+0],r=e[t+1],a=e[t+2];s[i++]=n,s[i++]=r,s[i++]=r,s[i++]=a,s[i++]=a,s[i++]=n}}else for(let e=0,t=0;e<n;e+=3){const i=e+0,n=e+1,r=e+2;s[t++]=i,s[t++]=n,s[t++]=n,s[t++]=r,s[t++]=r,s[t++]=i}return r.version=uM(e),r.__id=hM(e),r}class pM extends iM{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 n=this.wireframes.get(e);void 0!==n&&this.attributes.delete(n),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,sM):this.updateAttribute(e,nM);const i=this.getIndex(e);null!==i&&this.updateAttribute(i,rM);const n=e.geometry.indirect;null!==n&&this.updateAttribute(n,aM)}updateAttribute(e,t){const i=this.info.render.calls,n=this.backend.getBufferAttribute(e);this.attributeCall.get(n)!==i&&(this.attributes.update(n,t),this.attributeCall.set(n,i))}getIndirect(e){return e.geometry.indirect}getIndirectOffset(e){return e.geometry.indirectOffset}getIndex(e){const{geometry:t,material:i}=e;let n=t.index;if(!0===i.wireframe){const e=this.wireframes;let i=e.get(t);void 0===i?(i=dM(t),e.set(t,i)):i.version===uM(t)&&i.__id===hM(t)||(this.attributes.delete(i),i=dM(t),e.set(t,i)),n=i}return n}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 fM{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===rt||e.format===st||e.format===it||e.format===nt?i=1:e.format===at||e.format===ot?i=2:e.format!==et&&e.format!==lt||(i=3);let n=t*i;e.type===qe||e.type===Ye?n=2:e.type!==Ke&&e.type!==Ze&&e.type!==Qe||(n=4);const r=e.width||1,s=e.height||1,a=e.isCubeTexture?6:e.depth||1;let o=r*s*a*n;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,r>>t))*(i.height||Math.max(1,s>>t))*a*n}}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 mM{constructor(e){this.cacheKey=e,this.usedTimes=0}}class gM extends mM{constructor(e,t,i){super(e),this.vertexProgram=t,this.fragmentProgram=i}}class _M extends mM{constructor(e,t,i=null,n=null){super(e),this.computeProgram=t,this.transforms=i,this.attributes=n,this.isComputePipeline=!0}}let vM=0;class bM{constructor(e,t,i){this.id=vM++,this.code=e,this.stage=t,this.name=i,this.usedTimes=0}}class yM extends iM{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:n}=this,r=this.get(e);if(this._needsComputeUpdate(e)){const s=r.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 bM(a.computeShader,"compute",e.name),this.programs.compute.set(a.computeShader,o),n.createProgram(o),this.info.createProgram(o));const l=this._getComputeCacheKey(e,o);let c=this.caches.get(l);void 0===c&&(c=this._getComputePipeline(e,o,l,t,i)),c.usedTimes++,o.usedTimes++,s&&(0===s.usedTimes&&this._releasePipeline(s),0===s.computeProgram.usedTimes&&this._releaseProgram(s.computeProgram)),r.version=e.version,r.pipeline=c}return r.pipeline}getForRender(e,t=null){const{backend:i}=this,n=this.get(e);if(this._needsRenderUpdate(e)){const r=n.pipeline;r&&(r.usedTimes--,r.vertexProgram.usedTimes--,r.fragmentProgram.usedTimes--);const s=e.getNodeBuilderState(),a=e.material?e.material.name:"";let o=this.programs.vertex.get(s.vertexShader);void 0===o&&(o=new bM(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 bM(s.fragmentShader,"fragment",a),this.programs.fragment.set(s.fragmentShader,l),i.createProgram(l),this.info.createProgram(l));const c=this._getRenderCacheKey(e,o,l);let u=this.caches.get(c);void 0===u?u=this._getRenderPipeline(e,o,l,c,t):e.pipeline=u,u.usedTimes++,o.usedTimes++,l.usedTimes++,r&&(0===r.usedTimes&&this._releasePipeline(r),0===r.vertexProgram.usedTimes&&this._releaseProgram(r.vertexProgram),0===r.fragmentProgram.usedTimes&&this._releaseProgram(r.fragmentProgram)),n.pipeline=u}return n.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,n,r){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 _M(i,t,a,o),this.caches.set(i,s),this.backend.createComputePipeline(s,n,r)}return s}_getRenderPipeline(e,t,i,n,r){n=n||this._getRenderCacheKey(e,t,i);let s=this.caches.get(n);return void 0===s&&(s=new gM(n,t,i),this.caches.set(n,s),e.pipeline=s,this.backend.createRenderPipeline(e,r)),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 xM=[];class SM extends iM{constructor(e,t,i,n,r,s){super(),this.backend=e,this.textures=i,this.pipelines=r,this.attributes=n,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 n=wu(i);let r=this._sharedBindGroups.get(t);void 0===r&&(r=new Map,this._sharedBindGroups.set(t,r));let s=r.get(n);if(void 0===s){s=this.has(e)?e.clone():e,r.set(n,s);const i=this.get(s);i.renderContext=t,i.cacheKey=n}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?aM:sM;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 n=!1,r=!0,s=0,a=0;for(const t of e.bindings){if(!1!==this.nodes.updateGroup(t)){if(t.isStorageBuffer){const e=t.attribute,r=e.isIndirectStorageBufferAttribute?aM:sM,o=i.get(t);this.attributes.update(e,r);const l=this.attributes.get(e).generation;o.attribute===e&&o.generation===l||(o.attribute=e,o.generation=l,n=!0),xM[s++]=e.id,a+=l}if(t.isUniformBuffer){t.update()&&i.updateBinding(t)}else if(t.isSampledTexture){const o=t.update(),l=t.texture,c=this.textures.get(l);if(o){const i=this.textures.updateTexture(l);t.generation!==i&&(t.generation=i,n=!0),c.bindGroups.add(e)}if(void 0!==i.get(l).externalTexture||c.isDefaultTexture?r=!1:(xM[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,n=!0)}}t.isBuffer&&t.updateRanges.length>0&&t.clearUpdateRanges()}}if(!0===n){xM.length=s;const i=r?xM.join(","):"";this.backend.updateBindings(e,t,i,a)}}}const TM=Object.freeze([]);function MM(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 EM(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 wM(e){return(e.transmission>0||e.transmissionNode&&e.transmissionNode.isNode)&&2===e.side&&!1===e.forceSinglePass}class AM{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,n,r,s,a){let o=this.renderItems[this.renderItemsIndex];return void 0===o?(o={id:e.id,object:e,geometry:t,material:i,groupOrder:n,renderOrder:e.renderOrder,z:r,group:s,clippingContext:a},this.renderItems[this.renderItemsIndex]=o):(o.id=e.id,o.object=e,o.geometry=t,o.material=i,o.groupOrder=n,o.renderOrder=e.renderOrder,o.z=r,o.group=s,o.clippingContext=a),this.renderItemsIndex++,o}push(e,t,i,n,r,s,a){!0===this.camera.reversedDepth&&(r=-r);const o=this.getNextRenderItem(e,t,i,n,r,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?(wM(i)&&this.transparentDoublePass.push(o),this.transparent.push(o)):this.opaque.push(o)}unshift(e,t,i,n,r,s,a){const o=this.getNextRenderItem(e,t,i,n,r,s,a);!0===i.transparent||i.transmission>0||i.transmissionNode&&i.transmissionNode.isNode||i.backdropNode&&i.backdropNode.isNode?(wM(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||MM),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||EM),this.transparent.length>1&&this.transparent.sort(t||EM)}finish(){this.lightsNode.setLights(this.lighting.enabled?this.lightsArray:TM);for(let e=this.renderItemsIndex,t=this.renderItems.length;e<t;e++){const t=this.renderItems[e];if(null===t.id)break;RM(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;RM(t)}this.opaque.length=0,this.transparentDoublePass.length=0,this.transparent.length=0,this.bundles.length=0}}function RM(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 CM=[];class NM{constructor(){this.lists=new ox,this._activeLists=new Set,this._frameId=-1}get(e,t,i){const n=this.lists;CM[0]=e,CM[1]=t,CM[2]=i;let r=n.get(CM);return void 0===r&&(r=new AM(i,e,t),n.set(CM,r)),CM[0]=null,CM[1]=null,CM[2]=null,r.frameId=this._frameId,this._activeLists.add(r),r}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 ox,this._activeLists.clear(),this._frameId=-1}}let PM=0;class LM{constructor(){this.id=PM++,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 un,this.scissor=!1,this.scissorValue=new un,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 DM(this)}}function DM(e){const{textures:t,activeCubeFace:i,activeMipmapLevel:n}=e,r=[i,n];for(const e of t)r.push(e.id);return Au(r)}class IM{constructor(e){this.renderer=e,this._renderContexts={}}get(e=null,t=null,i=0,n=null){let r;if(null===e)r="default";else{const t=e.texture?.format,i=e.texture?.type;r=`${e.textures.length}:${t}:${i}:${e.samples}:${e.depthBuffer}:${e.stencilBuffer}`}const s=r+"-"+(null!==t?t.id:"default")+"-"+(!0===n?.isOrthographicCamera?"orthographic":"perspective"),a=s+"-"+i;let o=this._renderContexts[a];return void 0===o&&(o=new LM,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 FM=new Wi;function UM(e){return!0===e.isCompressedCubeTexture?e.image[0].mipmaps:e.mipmaps}class OM extends iM{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),n=0===e.samples?1:e.samples,r=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 c=e.depthTexture||r[t];const u=!0===e.depthBuffer||!0===e.stencilBuffer;let h=!1;const d=void 0!==c&&void 0!==c.image&&c.image.depth>1,p=a.depth>1&&(e.useArrayDepthTexture||e.multiview||d);void 0===c&&u&&(c=new oa,c.format=e.stencilBuffer?nt:it,c.type=!0===this.renderer.reversedDepthBuffer?$e:e.stencilBuffer?Ke:je,c.image.width=o,c.image.height=l,c.image.depth=a.depth,c.renderTarget=e,r[t]=c),c&&(c.isArrayTexture=p),i.width===a.width&&a.height===i.height||(h=!0,c&&c.renderTarget===e&&(c.needsUpdate=!0,c.image.width=o,c.image.height=l,c.image.depth=p?a.depth:1)),i.width=a.width,i.height=a.height,i.textures=s,i.depthTexture=c||null,i.depth=e.depthBuffer,i.stencil=e.stencilBuffer,i.renderTarget=e,i.sampleCount!==n&&(h=!0,c&&c.renderTarget===e&&(c.needsUpdate=!0),i.sampleCount=n),!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:n};if(!0!==e.isXRRenderTarget){for(let e=0;e<s.length;e++){const t=s[e];h&&(t.needsUpdate=!0),this.updateTexture(t,f)}c&&this.updateTexture(c,f)}}updateTexture(e,t={}){const i=this.get(e);if(!0===i.initialized&&i.version===e.version)return i.generation;const n=e.isRenderTargetTexture||e.isDepthTexture?e.renderTarget:null;if(null!==n&&!0!==this.get(n).initialized)return this.updateRenderTarget(n),i.generation;const r=e.isRenderTargetTexture||e.isDepthTexture||e.isFramebufferTexture,s=this.backend;if(r&&!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&&!r&&t.levels++,r||!0===e.isStorageTexture||!0===e.isExternalTexture)s.createTexture(e,t),i.generation=e.version;else if(e.version>0){const n=e.image;if(void 0===n)Ti("Renderer: Texture marked for update but image is undefined.");else if(!1===n.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=n;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===UM(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=FM){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 n;const r=UM(e);return n=r.length>0?r.length:!0===e.isCompressedTexture?1:Math.floor(Math.log2(Math.max(t,i)))+1,n}needsMipmaps(e){return!0===e.generateMipmaps||UM(e).length>0}_destroyRenderTarget(e){if(!0===this.has(e)){const t=this.get(e),i=t.textures,n=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]);n&&n.renderTarget===e&&this._destroyTexture(n),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 BM=new Bm;class kM extends iM{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,i){const n=this.renderer,r=this.nodes.getBackgroundNode(e)||e.background;let s=!1;if(null===r)n._clearColor.getRGB(BM),BM.a=n._clearColor.a;else if(!0===r.isColor)r.getRGB(BM),BM.a=1,s=!0;else if(!0===r.isNode){const o=this.get(e),l=r;BM.copy(n._clearColor);let c=o.backgroundMesh;if(void 0===c){const h=Jh(l).mul(Ny).context({getUV:()=>Py.mul(qg),getTextureLevel:()=>Cy}),d=gg.element(3).element(3).equal(1),p=np(1,gg.element(1).element(1)).mul(3),f=d.select(Lg.mul(p),Lg),m=wg.mul(Jh(f,0));let g=gg.mul(Jh(m.xyz,1));g=g.setZ(g.w);const _=new my;function v(){r.removeEventListener("dispose",v),c.material.dispose(),c.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=c=new ws(new ma(1,32,32),_),c.frustumCulled=!1,c.name="Background.mesh",r.addEventListener("dispose",v)}const u=l.getCacheKey();o.backgroundCacheKey!==u&&(o.backgroundMeshNode.node=Jh(l).mul(Ny),o.backgroundMeshNode.needsUpdate=!0,c.material.needsUpdate=!0,o.backgroundCacheKey=u),t.unshift(c,c.geometry,c.material,0,0,null,null)}else Mi("Renderer: Unsupported background configuration.",r);const a=n.xr.getEnvironmentBlendMode();if("additive"===a?BM.set(0,0,0,1):"alpha-blend"===a&&BM.set(0,0,0,0),!0===n.autoClear||!0===s){const b=i.clearColorValue;b.r=BM.r,b.g=BM.g,b.b=BM.b,b.a=BM.a,!0!==n.backend.isWebGLBackend&&!0!==n.alpha||(b.r*=b.a,b.g*=b.a,b.b*=b.a),i.depthClearValue=n.getClearDepth(),i.stencilClearValue=n.getClearStencil(),i.clearColor=!0===n.autoClearColor,i.clearDepth=!0===n.autoClearDepth,i.clearStencil=!0===n.autoClearStencil}else i.clearColor=!1,i.clearDepth=!1,i.clearStencil=!1}}let zM=0;class GM{constructor(e="",t=[]){this.name=e,this.bindings=t,this.id=zM++}clone(){return new GM(this.name,this.bindings.map(e=>e.clone()))}}class VM{constructor(e,t,i,n,r,s,a,o,l,c,u=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=i,this.transforms=u,this.nodeAttributes=n,this.bindings=r,this.updateNodes=s,this.updateBeforeNodes=a,this.updateAfterNodes=o,this.observer=l,this.hardwareClipping=c,this.usedTimes=0}createBindings(e,t){const i=[];for(const n of this.bindings){if(!0!==n.bindings[0].groupNode.shared){const e=new GM(n.name,[]);i.push(e);for(const t of n.bindings)e.bindings.push(t.clone())}else i.push(e.getSharedBindGroup(n,t))}return i}}class HM{constructor(e,t,i=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=i}}class WM{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 jM{constructor(e,t,i=!1,n=null,r=!1){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=i,this.local=r,this.count=n}}class $M extends jM{constructor(e,t,i=null,n=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=i,this.interpolationSampling=n}}class XM{constructor(e,t,i=""){this.name=e,this.type=t,this.code=i,Object.defineProperty(this,"isNodeCode",{value:!0})}}let qM=0;class YM{constructor(e=null){this.id=qM++,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 KM{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class ZM{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 QM extends ZM{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class JM extends ZM{constructor(e,t=new Vi){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class eE extends ZM{constructor(e,t=new Wi){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class tE extends ZM{constructor(e,t=new un){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class iE extends ZM{constructor(e,t=new Kn){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class nE extends ZM{constructor(e,t=new To){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class rE extends ZM{constructor(e,t=new Xi){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class sE extends ZM{constructor(e,t=new mn){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class aE extends QM{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class oE extends JM{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class lE extends eE{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class cE extends tE{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class uE extends iE{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class hE extends nE{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class dE extends rE{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class pE extends sE{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}let fE=0;const mE=new WeakMap,gE=new WeakMap,_E=(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,n)=>{i[e.name]=t[n]}),i},vE=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),bE=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0"),yE={bool:0,uint:1,int:2,float:3};class xE{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 SE=new Map,TE=new Map,ME=new Map,EE=new Map,wE=new Map,AE=e=>{if(e.writeUsageCount>0)return!0;if(void 0!==e.subBuildsCache)for(const t in e.subBuildsCache)if(AE(e.subBuildsCache[t]))return!0;return!1},RE=(e,t)=>{for(const i in e)if("nodeBlock"!==i&&"nodeLoop"!==i&&e[i]!==t[i])return!0;return!1};class CE{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=Om(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new YM,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:fE++})}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 hn(e,t,i)}createCubeRenderTarget(e,t){return new Wx(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]?Lu(t.textures[e]):"vec4"}getOutputStructName(){}_getBindGroup(e,t){const i=t[0].groupNode;let n=i.shared;if(n)for(let e=1;e<t.length;e++)i!==t[e].groupNode&&(n=!1);let r=new GM(e,t);return n&&void 0!==this.renderer._bindings&&(r=this.renderer._bindings.getSharedBindGroup(r)),r}getBindGroupArray(e,t){const i=this.bindings[t];let n=i[e];return void 0===n&&(void 0===this.bindingsIndexes[e]&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),i[e]=n=[]),n}getBindings(){let e=this.bindGroups;if(null===e){const t={},i=this.bindings;for(const e of xu)for(const n in i[e]){const r=i[e][n],s=t[n]||(t[n]=[]);for(const e of r)!1===s.includes(e)&&s.push(e)}e=[];for(const i in t){const n=t[i],r=this._getBindGroup(i,n);e.push(r)}this.bindGroups=e}return e}sortBindingGroups(){const e=this.getBindings();e.sort((e,t)=>e.bindings[0].groupNode.order-t.bindings[0].groupNode.order);for(let t=0;t<e.length;t++){const 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===pu&&i===pu||this.sequentialNodes.add(e)}buildUpdateNodes(){for(const e of this.nodes){e.updateType!==pu&&this.updateNodes.push(e)}for(const e of this.sequentialNodes){const t=e.updateBeforeType,i=e.updateAfterType;t!==pu&&this.updateBeforeNodes.push(e),i!==pu&&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===Ue||e.magFilter===ke||e.minFilter===Oe||e.minFilter===Be||e.minFilter===Ue||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(Iu(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 YM(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(AE(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 n=this.generateArrayDeclaration(e,t)+"( ";for(let r=0;r<t;r++){const s=i?i[r]:null;n+=null!==s?s.build(this,e):this.generateConst(e),r<t-1&&(n+=", ")}return n+=" )",n}generateStruct(e,t,i=null){const n=[];for(const e of t){const{name:t,type:r}=e;i&&i[t]&&i[t].isNode?n.push(i[t].build(this,r)):n.push(this.generateConst(r))}return e+"( "+n.join(", ")+" )"}generateConst(e,t=null){if(null===t&&("float"===e||"int"===e||"uint"===e?t=0:"bool"===e?t=!1:"color"===e?t=new Kn:"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 un)),"float"===e)return bE(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")}( ${bE(t.r)}, ${bE(t.g)}, ${bE(t.b)} )`;const i=this.getTypeLength(e),n=this.getComponentType(e),r=e=>this.generateConst(n,e);if(2===i)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)} )`;if(3===i)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)} )`;if(4===i&&"mat2"!==e)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)}, ${r(t.w)} )`;if(i>=4&&t&&(t.isMatrix2||t.isMatrix3||t.isMatrix4))return`${this.getType(e)}( ${t.elements.map(r).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 n=new HM(e,t);return this.registerDeclaration(n),i.push(n),n}getPropertyName(e){return e.name}isScalar(e){return"float"===e||"bool"===e||"int"===e||"uint"===e}isReservedKeyword(){return!1}isVector(e){let t=ME.get(e);return void 0===t&&ME.set(e,t=/vec\d/.test(e)),t}isMatrix(e){let t=EE.get(e);return void 0===t&&EE.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=SE.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",SE.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=Nu(e);const n="float"===t?"":t[0];return!0===/mat2/.test(t)&&(i=i.replace("vec","mat")),n+i}getTypeFromArray(e){return vE.get(e.constructor)}isInteger(e){let t=wE.get(e);return void 0===t&&wE.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,n=e.itemSize,r=e.normalized;let s;return e instanceof Br||!0===r||(s=this.getTypeFromArray(i)),this.getTypeFromLength(n,s)}getTypeLength(e){const t=this.getVectorType(e);let i=TE.get(t);return void 0===i&&(i=this._getTypeLength(t),TE.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,n=!0,r=!0;for(const s of e)if(null!==s)if(!0===s.isWeak){const e=Math.trunc(s.value);i=!0,n=n&&e>=0&&e<=4294967295,r=r&&e>=-2147483648&&e<=2147483647}else{const e=this.getComponentType(s.getNodeType(this));(null===t||yE[e]>yE[t])&&(t=e)}return null===t||"bool"===t&&i?"float":"uint"===t&&!1===n?r?"int":"float":"int"===t&&!1===r?"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)&&!RE(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=Om(this.stack);const e=Bh();return this.stacks.push(e),Oh(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,Oh(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,i=null){let n=(i=null===i?e.isGlobal(this)?this.globalCache:this.cache:i).getData(e);void 0===n&&(n={},i.setData(e,n)),void 0===n[t]&&(n[t]=new xE);let r=n[t];if(0===this.subBuildLayers.length)return r;const s=n.any?n.any.subBuilds:null,a=this.getClosestSubBuild(s);return a&&(void 0===r.subBuildsCache&&(r.subBuildsCache={}),r=r.subBuildsCache[a]||(r.subBuildsCache[a]=new xE),r.subBuilds=s),r}getNodeProperties(e,t="any"){const i=this.getDataFromNode(e,t);return i.properties||(i.properties={outputNode:null})}getBufferAttributeFromNode(e,t,i=null){const n=this.getDataFromNode(e,"vertex");let r=n.bufferAttribute;if(void 0===r){const s=this.uniforms.index++;null===i&&(i="nodeAttribute"+s),r=new HM(i,t,e),this.bufferAttributes.push(r),n.bufferAttribute=r}return r}getStructTypeNode(e,t=this.shaderStage){return this.types[t][e]||null}getStructTypeFromNode(e,t,i=null,n=this.shaderStage){const r=this.getDataFromNode(e,n,this.globalCache);let s=r.structType;if(void 0===s){const a=this.structs.index++;null===i&&(i="StructType"+a),s=new KM(i,t),this.structs[n].push(s),this.types[n][i]=e,r.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,n=null){const r=this.getDataFromNode(e,i,this.globalCache);let s=r.uniform;if(void 0===s){const a=this.uniforms.index++;s=new WM(n||"nodeUniform"+a,t,e),this.uniforms[i].push(s),this.registerDeclaration(s),r.uniform=s}return s}getVarFromNode(e,t=null,i=e.getNodeType(this),n=this.shaderStage,r=!1,s=!1,a="variable"){const o=this.getDataFromNode(e,n),l=this.getSubBuildProperty(a,o.subBuilds);let c=o[l];if(void 0===c){const u=r?"_const":"_var",h=this.vars[n]||(this.vars[n]=[]),d=this.vars[u]||(this.vars[u]=0);null===t&&(t=(r?"nodeConst":"nodeVar")+d,this.vars[u]++),l!==a&&(t=this.getSubBuildProperty(t,o.subBuilds));const p=e.getArrayCount(this);c=new jM(t,i,r,p,s),r||s||h.push(c),this.registerDeclaration(c),o[l]=c}return c}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),n=null,r=null){const s=this.getDataFromNode(e,"any"),a=this.getSubBuildProperty("varying",s.subBuilds);let o=s[a];if(void 0===o){const e=this.varyings,l=e.length;null===t&&(t="nodeVarying"+l),"varying"!==a&&(t=this.getSubBuildProperty(t,s.subBuilds)),o=new $M(t,i,n,r),e.push(o),this.registerDeclaration(o),s[a]=o}return o}registerDeclaration(e){const t=this.shaderStage,i=this.declarations[t]||(this.declarations[t]={}),n=this.renderer.debug.diagnostics.keywords,r=e.name;let s=r,a=this.getDeclarationName(e),o=1;for(;n&&this.isReservedKeyword(s)||void 0!==i[a];)s=r+"_"+o++,e.name=s,a=this.getDeclarationName(e);s!==r&&Ti(`TSL: Declaration name '${r}' 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 n=this.getDataFromNode(e);let r=n.code;if(void 0===r){const e=this.codes[i]||(this.codes[i]=[]),s=e.length;r=new XM("nodeCode"+s,t),e.push(r),n.code=r}return r}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=mE.get(t);void 0===i&&(i=new WeakMap,mE.set(t,i));let n=i.get(e);if(void 0===n){n=new Hy;const t=this.currentFunctionNode;this.currentFunctionNode=n,n.code=this.buildFunctionCode(e),this.currentFunctionNode=t,i.set(e,n)}return n}flowShaderNode(e){const t=e.layout,i=_E(t,t.inputs.map(e=>new Im(e.type,e.name)));e.layout=null;const n=e.call(i),r=this.flowStagesNode(n,t.type);return e.layout=t,r}_getLayoutInputs(e,t){const i=e.layout.inputs,n=null!==t&&t.length>0?t[0]:null,r=null!=n&&!1===Fu(t)?n:null,s=i.map((e,i)=>null!==r?void 0!==r[e.name]:null!==t&&void 0!==t[i]);if(s.every(Boolean))return null!==t?t:[];if(e.once)return null;let a=gE.get(e);void 0===a&&(a=new Map,gE.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!==r){const e={...r};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,n=i.inputs.map(e=>new Im(e.type,e.name)),r=this._getLayoutCallGraph(e,_E(i,n)),s=this._getLayoutCallGraph(e,_E(i,n.map((e,i)=>t[i]?e:void 0))),a=new Map;n.forEach((e,i)=>{!1===t[i]&&a.set(e,i)});const o=[],l=new Map,c=(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 n=[...e.getChildren()],r=[...t.getChildren()];if(n.length!==r.length)return!1;for(let e=0;e<n.length;e++)if(!1===c(n[e],r[e]))return!1;return!0},u=s.nodes.length-r.nodes.length;if(u<0)return null;if(l.set(r,s),!1===c(r.outputNode,s.outputNode))return null;for(let e=0;e<r.nodes.length;e++)if(!1===c(r.nodes[e],s.nodes[u+e]))return null;const h=new Set(n);for(const e of a.values()){const t=o[e];if(void 0===t)return null;const i=[t],n=new Set;for(;i.length>0;){const e=i.pop();if(h.has(e))return null;if(!n.has(e)){n.add(e);for(const t of e.getChildren())i.push(t)}}}return o}_getLayoutCallGraph(e,t){const i=e.layout;let n;e.layout=null,this.addStack();try{this.stack.outputNode=e.call(t).call(this)}finally{n=this.removeStack(),e.layout=i}return n}flowBuildStage(e,t,i=null){const n=this.getBuildStage();this.setBuildStage(t);const r=e.build(this,i);return this.setBuildStage(n),r}flowStagesNode(e,t=null){const i=this.flow,n=this.vars,r=this.declarations,s=this.cache,a=this.buildStage,o=this.stack,l=this.flowBlock,c={code:""};this.flow=c,this.vars={},this.declarations={},this.cache=new YM,this.stack=Om(),this.flowBlock=null;for(const i of yu)this.setBuildStage(i),c.result=e.build(this,t);return c.vars=this.getVars(this.shaderStage),this.flow=i,this.vars=n,this.declarations=r,this.cache=s,this.stack=o,this.flowBlock=l,this.setBuildStage(a),c}getFunctionOperator(){return null}buildFunctionCode(){Ti("Abstract function.")}flowChildNode(e,t=null){const i=this.flow,n={code:""};return this.flow=n,n.result=e.build(this,t),this.flow=i,n}flowNodeFromShaderStage(e,t,i=null,n=null){const r=this.tab,s=this.cache,a=this.shaderStage,o=this.context,l=this.flowBlock;this.setShaderStage(e);const c={...this.context};delete c.nodeBlock,this.flowBlock=null,this.cache=this.globalCache,this.tab="\t",this.context=c;let u=null;if("generate"===this.buildStage){const r=this.flowChildNode(t,i);null!==n&&(r.code+=`${this.tab+n} = ${r.result};\n`),this.flowCode[e]=this.flowCode[e]+r.code,u=r}else u=t.build(this);return this.setShaderStage(a),this.cache=s,this.tab=r,this.context=o,this.flowBlock=l,u}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=[],n=this.vars[e];if(void 0!==n)for(const e of n)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 n=t[e];if(i.includes(n))return n}return null}getSubBuildOutput(e){return this.getSubBuildProperty("outputNode",e)}getSubBuildProperty(e="",t=null){let i,n;return i=null!==t?this.getClosestSubBuild(t):this.subBuildFn,n=i?e?i+"_"+e:i:e,n}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 my),i.build(this)}else this.addFlow("compute",this.compute)}build(){this.prebuild();for(const e of yu){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(const t of xu){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 yu){this.setBuildStage(t),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(const i of xu){this.setShaderStage(i);const n=this.flowNodes[i];for(const e of n)"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 aE(e);if("vec2"===t||"ivec2"===t||"uvec2"===t)return new oE(e);if("vec3"===t||"ivec3"===t||"uvec3"===t)return new lE(e);if("vec4"===t||"ivec4"===t||"uvec4"===t)return new cE(e);if("color"===t)return new uE(e);if("mat2"===t)return new hE(e);if("mat3"===t)return new dE(e);if("mat4"===t)return new pE(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 n=this.getTypeLength(t),r=this.getTypeLength(i);if(16===n&&9===r)return`${this.getType(i)}( ${e}[ 0 ].xyz, ${e}[ 1 ].xyz, ${e}[ 2 ].xyz )`;if(9===n&&4===r)return`${this.getType(i)}( ${e}[ 0 ].xy, ${e}[ 1 ].xy )`;if(n>4)return e;if(r>4||0===r)return e;if(n===r)return`${this.getType(i)}( ${e} )`;if(n>r)return e="bool"===i?`all( ${e} )`:`${e}.${"xyz".slice(0,r)}`,this.format(e,this.getTypeFromLength(r,this.getComponentType(t)),i);if(4===r&&n>1){const n=this.getComponentType(i),r=this.getTypeFromLength(3,n);return`${this.getType(i)}( ${this.format(e,t,r)}, ${this.generateConst(n,"bool"===n||1)} )`}if(2===n){const n=this.getComponentType(i),r=this.getTypeFromLength(2,n);return`${this.getType(i)}( ${this.format(e,t,r)}, ${this.generateConst(n,"bool"!==n&&0)} )`}return 1===n&&r>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 NE{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===fu){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===mu){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===gu&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(this),i=e.updateReference(this);if(t===fu){const t=this._getMaps(this.updateAfterMap,i);t.frameId!==this.frameId&&!1!==e.updateAfter(this)&&(t.frameId=this.frameId)}else if(t===mu){const t=this._getMaps(this.updateAfterMap,i);t.renderId!==this.renderId&&!1!==e.updateAfter(this)&&(t.renderId=this.renderId)}else t===gu&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(this),i=e.updateReference(this);if(t===fu){const t=this._getMaps(this.updateMap,i);t.frameId!==this.frameId&&!1!==e.update(this)&&(t.frameId=this.frameId)}else if(t===mu){const t=this._getMaps(this.updateMap,i);t.renderId!==this.renderId&&!1!==e.update(this)&&(t.renderId=this.renderId)}else t===gu&&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 PE{constructor(e,t,i=null,n="",r=!1){this.type=e,this.name=t,this.count=i,this.qualifier=n,this.isConst=r}}PE.isNodeFunctionInput=!0;class LE extends Ux{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class DE extends Ux{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:Jy(this.light),lightColor:e}}}class IE extends Ux{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=Zy(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=md(new Kn).setGroup(dd)}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:n}=this,r=Kg.dot(n).mul(.5).add(.5),s=Rf(i,t,r);e.context.irradiance.addAssign(s)}}class FE extends Ux{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=md(0).setGroup(dd),this.penumbraCosNode=md(0).setGroup(dd),this.cutoffDistanceNode=md(0).setGroup(dd),this.decayExponentNode=md(0).setGroup(dd),this.colorNode=md(this.color).setGroup(dd)}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:n}=this;return Lf(i,n,t)}getLightCoord(e){const t=e.getNodeProperties(this);let i=t.projectionUV;return void 0===i&&(i=function(e,t=Ig){const i=Ky(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:n,light:r}=this,s=this.getLightVector(e),a=s.normalize(),o=a.dot(Jy(r)),l=this.getSpotAttenuation(e,o),c=s.length(),u=Ox({lightDistance:c,cutoffDistance:i,decayExponent:n});let h,d,p=t.mul(l).mul(u);if(r.colorNode?(d=this.getLightCoord(e),h=r.colorNode(d)):r.map&&(d=this.getLightCoord(e),h=h_(r.map,d.xy).onRenderUpdate(()=>r.map)),h){p=d.mul(2).sub(1).abs().lessThan(1).all().select(p.mul(h),p)}return{lightColor:p,lightDirection:a}}}class UE extends FE{static get type(){return"IESSpotLightNode"}constructor(e=null){super(e),this._iesTextureNode=null}getSpotAttenuation(e,t){const i=this.light.iesMap;let n=null;if(i&&!0===i.isTexture){const r=this.getLightCoord(e).sub(.5);this._iesTextureNode=h_(i);const s=Gh(.5).div(jh(o_(this._iesTextureNode))),a=ym(Jp(r.y,r.x),-Math.PI,Math.PI).add(s.y),o=ym(t.acos(),0,Math.PI,s.x,Gh(1).sub(s.x));n=this._iesTextureNode.sample(jh(o,a)).level(0).r}else n=super.getSpotAttenuation(e,t);return n}update(e){super.update(e),null!==this._iesTextureNode&&this.light.iesMap&&(this._iesTextureNode.value=this.light.iesMap)}}class OE extends Ux{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=Ym(t).setGroup(dd)}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=PS(Kg,this.lightProbe);e.context.irradiance.addAssign(t)}}const BE=Uh(([e,t])=>{const i=e.abs().sub(t);return rf(_f(i,0)).add(gf(_f(i.x,i.y),0))},{p:"vec2",b:"vec2",return:"float"});class kE extends FE{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=Gh(0),i=this.penumbraCosNode,n=Ky(this.light).mul(e.context.positionWorld||Ig);return kh(n.w.greaterThan(0),()=>{const e=n.xyz.div(n.w),r=BE(e.xy.sub(jh(.5)),jh(.5)),s=np(-1,tp(1,Zp(i)).sub(1));t.assign(Nf(r.mul(-2).mul(s)))}),t}}const zE=new mn;let GE=null;class VE extends Ux{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=md(new Wi).setGroup(dd),this.halfWidth=md(new Wi).setGroup(dd),this.updateType=mu}update(e){super.update(e);const{light:t}=this;zE.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(zE),this.halfHeight.value.applyMatrix4(zE)}setupDirectRectArea(e){let t,i;e.isAvailable("float32Filterable")?(t=h_(GE.LTC_FLOAT_1),i=h_(GE.LTC_FLOAT_2)):(t=h_(GE.LTC_HALF_1),i=h_(GE.LTC_HALF_2));const{colorNode:n,light:r}=this;return{lightColor:n,lightPosition:Qy(r),halfWidth:vg.mul(Jh(this.halfWidth,0)).xyz,halfHeight:vg.mul(Jh(this.halfHeight,0)).xyz,ltc_1:t,ltc_2:i}}static setLTC(e){GE=e}}class HE{parseFunction(){Ti("Abstract function.")}}class WE{constructor(e,t,i="",n=""){this.type=e,this.inputs=t,this.name=i,this.precision=n}getCode(){Ti("Abstract function.")}}WE.isNodeFunction=!0;const jE=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,$E=/[a-z_0-9]+/gi,XE="#pragma main";class qE extends WE{constructor(e){const{type:t,inputs:i,name:n,precision:r,inputsCode:s,blockCode:a,headerCode:o}=(e=>{const t=(e=e.trim()).indexOf(XE),i=(-1!==t?e.slice(t+12):e).replace(/^(?:\s*\/\/[^\r\n]*|\s*\/\*[\s\S]*?\*\/|\s*)+/,""),n=i.match(jE);if(null!==n&&5===n.length){const r=n[4],s=[];let a=null;for(;null!==(a=$E.exec(r));)s.push(a);const o=[];let l=0;for(;l<s.length;){const e="const"===s[l][0];!0===e&&l++;let t=s[l][0];"in"===t||"out"===t||"inout"===t?l++:t="";const i=s[l++][0];let n=Number.parseInt(s[l][0]);!1===Number.isNaN(n)?l++:n=null;const r=s[l++][0];o.push(new PE(i,r,n,t,e))}const c=i.substring(n[0].length),u=void 0!==n[3]?n[3]:"";return{type:n[2],inputs:o,name:u,precision:void 0!==n[1]?n[1]:"",inputsCode:r,blockCode:c,headerCode:-1!==t?e.slice(0,t):""}}throw new Error("THREE.FunctionNode: Function is not a GLSL code.")})(e);super(t,i,n,r),this.inputsCode=s,this.blockCode=a,this.headerCode=o}getCode(e=this.name){let t;const i=this.blockCode;if(""!==i){const{type:n,inputsCode:r,headerCode:s,precision:a}=this;let o=`${n} ${e} ( ${r.trim()} )`;""!==a&&(o=`${a} ${o}`),t=s+o+i}else t="";return t}}class YE extends HE{parseFunction(e){return new qE(e)}}const KE=[],ZE=[],QE=md(0,"int").setGroup(dd);class JE extends iM{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new NE,this.nodeBuilderCache=new Map,this.callHashCache=new ox,this.groupsData=new ox,this._buildQueue=[],this._buildInProgress=!1,this.cacheLib={}}updateGroup(e){const t=e.groupNode;if(t.updateType===gu)return!0;KE[0]=t,KE[1]=e;let i=this.groupsData.get(KE);return void 0===i&&this.groupsData.set(KE,i={}),KE[0]=null,KE[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),n=this.renderer.debug.onNodeBuilderCreated;return null!==n&&n(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 Mu(e.stack)),Mi("TSL: "+e,t)}getForRender(e,t=null){const i=this.get(e);let n=i.nodeBuilderState;if(void 0===n){const{nodeBuilderCache:r}=this,s=this.getForRenderCacheKey(e);if(n=r.get(s),void 0===n){const a=async()=>{let i=this._createNodeBuilder(e,e.material);try{null!==t?await i.buildAsync(t):i.build()}catch(n){i=this._createNodeBuilder(e,new my),null!==t?await i.buildAsync(t):i.build(),this._reportBuildError(n)}return i};if(null!==t)return a().then(e=>(n=this._createNodeBuilderState(e),!1===e.objectSpecific&&r.set(s,n),n.usedTimes++,i.nodeBuilderState=n,n));{let t=this._createNodeBuilder(e,e.material);try{t.build()}catch(i){t=this._createNodeBuilder(e,new my),t.build(),this._reportBuildError(i)}n=this._createNodeBuilderState(t),!1===t.objectSpecific&&r.set(s,n)}}n.usedTimes++,i.nodeBuilderState=n}return n}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),n=this.nodeBuilderCache.get(i);return void 0!==n?(n.usedTimes++,t.nodeBuilderState=n,n):(!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 n=this.get(e);let r=n.nodeBuilderState;if(void 0===r||n.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(()=>(r=this._createNodeBuilderState(s),n.nodeBuilderState=r,n.version=e.version,r));s.build(),r=this._createNodeBuilderState(s),n.nodeBuilderState=r,n.version=e.version}return r}getForComputeAsync(e,t=wi){const i=this.getForCompute(e,!0,t);return i.then?i:Promise.resolve(i)}_createNodeBuilderState(e){return new VM(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){KE[0]=e,KE[1]=t;const i=this.renderer.info.calls,n=this.callHashCache.get(KE)||{};if(n.callId!==i){if(ZE.push(this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview?1:0),ZE.push(this.renderer.lighting.enabled?1:0),this.renderer.lighting.enabled){ZE.push(t.getCacheKey(!0)),ZE.push(this.renderer.shadowMap.enabled?1:0),ZE.push(this.renderer.shadowMap.type);const i=this.getEnvironmentNode(e);i&&ZE.push(i.getCacheKey())}const r=this.getFogNode(e);r&&ZE.push(r.getCacheKey()),n.callId=i,n.cacheKey=Au(ZE),this.callHashCache.set(KE,n),ZE.length=0}return KE[0]=null,KE[1]=null,n.cacheKey}get isToneMappingState(){return!this.renderer.getRenderTarget()}updateBackground(e){const t=this.get(e),i=e.background;if(i){const n=0===e.backgroundBlurriness&&t.backgroundBlurriness>0||e.backgroundBlurriness>0&&0===t.backgroundBlurriness;if(t.background!==i||n){const r=this.getCacheNode("background",i,()=>{if(!0===i.isCubeTexture||i.mapping===Ce||i.mapping===Ne){if(e.backgroundBlurriness>0||!0===i.isPMREMTexture)return iS(i);{let e;return e=!0===i.isCubeTexture?G_(i):h_(i),qS(e)}}if(!0===i.isTexture)return h_(i,eg.flipY()).setUpdateMatrix(!0);!0!==i.isColor&&Mi("WebGPUNodes: Unsupported background configuration.",i)},n);t.backgroundNode=r,t.background=i,t.backgroundBlurriness=e.backgroundBlurriness}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}getCacheNode(e,t,i,n=!1){const r=this.cacheLib[e]||(this.cacheLib[e]=new WeakMap);let s=r.get(t);if(void 0===s||n){if(void 0===s&&!0===t.isTexture){const e=()=>{t.removeEventListener("dispose",e);const i=r.get(t);void 0!==i&&(r.delete(t),i.dispose())};t.addEventListener("dispose",e)}s=i(),r.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=H_("color","color",i).setGroup(dd),t=H_("density","float",i).setGroup(dd);return Xy(e,$y(t))}if(i.isFog){const e=H_("color","color",i).setGroup(dd),t=H_("near","float",i).setGroup(dd),n=H_("far","float",i).setGroup(dd);return Xy(e,jy(t,n))}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?G_(i):!0===i.isTexture?h_(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,n=null,r=null,s=null){const a=this.nodeFrame;return a.renderer=e,a.scene=t,a.object=i,a.camera=n,a.material=r,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?h_(e,eg).depth(Wm("gl_ViewID_OVR")).renderOutput(t.toneMapping,t.currentColorSpace):h_(e,eg).depth(QE).renderOutput(t.toneMapping,t.currentColorSpace):h_(e,eg).renderOutput(t.toneMapping,t.currentColorSpace),i}setOutputLayerIndex(e){QE.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 NE,this.nodeBuilderCache=new Map,this.cacheLib={}}}const ew=new ss;let tw=0;class iw{constructor(e=null){this.id=tw++,this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewMatrix=new mn,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 n=e.length;for(let r=0;r<n;r++){ew.copy(e[r]).applyMatrix4(this.viewMatrix,this.viewNormalMatrix);const n=t[i+r],s=ew.normal;n.x=-s.x,n.y=-s.y,n.z=-s.z,n.w=ew.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 n=t.clippingPlanes,r=n.length;let s,a;if(this.clipIntersection?(s=this.intersectionPlanes,a=e.intersectionPlanes.length):(s=this.unionPlanes,a=e.unionPlanes.length),s.length!==a+r){s.length=a+r;for(let e=0;e<r;e++)s[a+e]=new un;i=!0}this.projectPlanes(n,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 iw(this),this.clippingGroupContexts.set(e,t)),t.update(this,e),t}get unionClippingCount(){return this.unionPlanes.length}}class nw{constructor(e,t,i){this.bundleGroup=e,this.camera=t,this.renderContext=i}}const rw=[];class sw{constructor(){this.bundles=new ox}get(e,t,i){const n=this.bundles;rw[0]=e,rw[1]=t,rw[2]=i;let r=n.get(rw);return void 0===r&&(r=new nw(e,t,i),n.set(rw,r)),rw[0]=null,rw[1]=null,rw[2]=null,r}dispose(){this.bundles=new ox}}class aw{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 ow=new ax;class lw{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 ax).setLights(e)}getNode(e){if(!0!==e.isScene&&!0!==e.isGroup)return ow;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 cw extends hn{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 uw=new WeakMap;class hw extends Ri{constructor(e,t=!1){super(),this.enabled=!1,this.isPresenting=!1,this.cameraAutoUpdate=!0,this._renderer=e,this._cameraL=new eo,this._cameraL.viewport=new un,this._cameraL.matrixWorldAutoUpdate=!1,this._cameraR=new eo,this._cameraR.viewport=new un,this._cameraR.matrixWorldAutoUpdate=!1,this._cameras=[this._cameraL,this._cameraR],this._cameraXR=new mo,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=gw.bind(this),this._gl=null,this._currentAnimationContext=null,this._currentAnimationLoop=null,this._currentPixelRatio=null,this._currentSize=new Vi,this._currentCameraSettings=null,this._onSessionEvent=pw.bind(this),this._onSessionEnd=fw.bind(this),this._onInputSourcesChange=mw.bind(this),this._onAnimationFrame=_w.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 n=this.getBinding();if(null===n||"function"!=typeof n.foveateBoundTexture)return;this._renderer._textures.updateRenderTarget(e);const{textureGPU:r,glTextureType:s}=t.get(e.texture);if(void 0!==r&&void 0!==s&&e._xrFoveationTextureGPU!==r){e._xrFoveationTextureGPU=r,t.state.bindTexture(s,r);try{n.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 hn(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 n=0;n<e.length;n++){const r=t.getViewSubImage(this._glProjLayer,e[n]);null===i.colorTexture&&(i.colorTexture=r.colorTexture),i.viewports.push(r.viewport),r.getViewDescriptor&&i.viewDescriptors.push(r.getViewDescriptor())}return i}getFrame(){return this._xrFrame}useMultiview(){return this._useMultiview}createQuadLayer(e,t,i,n,r,s,a,o={}){const l=new fa(e,t),c=new cw(r,s,{format:tt,type:ze,depthTexture:new oa(r,s,o.stencil?Ke:je,void 0,void 0,void 0,void 0,void 0,void 0,o.stencil?nt:it),stencilBuffer:o.stencil,samples:o.samples??this._renderer.samples,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledColorBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1}),u=new fs({color:16777215,side:0});u.map=c.texture,u.map.offset.y=1,u.map.repeat.y=-1;const h=new ws(l,u);h.position.copy(i),h.quaternion.copy(n);const d={type:"quad",width:e,height:t,translation:i,quaternion:n,pixelwidth:r,pixelheight:s,samples:c.samples,plane:h,material:u,rendercall:a,renderTarget:c};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 c.isXRRenderTarget=!1;return h}createCylinderLayer(e,t,i,n,r,s,a,o,l={}){const c=new ha(e,e,e*t/i,64,64,!0,Math.PI-t/2,t),u=new cw(s,a,{format:tt,type:ze,depthTexture:new oa(s,a,l.stencil?Ke:je,void 0,void 0,void 0,void 0,void 0,void 0,l.stencil?nt: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=u.texture,h.map.offset.y=1,h.map.repeat.y=-1;const d=new ws(c,h);d.position.copy(n),d.quaternion.copy(r);const p={type:"cylinder",radius:e,centralAngle:t,aspectratio:i,translation:n,quaternion:r,pixelwidth:s,pixelheight:a,samples:u.samples,plane:d,material:h,rendercall:o,renderTarget:u};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 u.isXRRenderTarget=!1;return d}renderLayers(){const e=new Wi,t=new Hi,i=this._renderer,n=this.isPresenting;this.isPresenting=!1;const r=new Vi;i.getSize(r);const s=i.getRenderTarget();for(const n of this._layers){n.renderTarget.isXRRenderTarget=null!==this._session,n.renderTarget._hasExternalTextures=n.renderTarget.isXRRenderTarget;const r=i.contextNode;let s;if(n.renderTarget.isXRRenderTarget&&this._sessionUsesLayers){n.xrlayer.transform=new XRRigidTransform(n.plane.getWorldPosition(e),n.plane.getWorldQuaternion(t));const a=this._glBinding.getSubImage(n.xrlayer,this._xrFrame);i.backend.setXRRenderTargetTextures(n.renderTarget,a.colorTexture,void 0),i._setXRLayerSize(n.renderTarget.width,n.renderTarget.height),s=uw.get(r),void 0===s&&(s=kf({getOutput:(e,t)=>{const n=wm(e,i.toneMapping,i.outputColorSpace);return n.premultipliedAlpha=t.material.premultipliedAlpha,n},...r.getFlowContextData()}),uw.set(r,s))}else s=r;i.contextNode=s,i.setRenderTarget(n.renderTarget),n.rendercall(),i.contextNode=r}i.setRenderTarget(s),i._setXRLayerSize(r.x,r.y),this.isPresenting=n}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 n=null,r=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,n=t.stencil?nt:it,r=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),c=[l];this._glProjLayer=l,t.setPixelRatio(1),t._setXRLayerSize(l.textureWidth,l.textureHeight);const u=this._useMultiview?2:1,h=new oa(l.textureWidth,l.textureHeight,r,void 0,void 0,void 0,void 0,void 0,void 0,n,u);if(this._xrRenderTarget=new cw(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),c.unshift(e.xrlayer);e.updateRenderState({layers:c})}else{await t.backend.makeXRCompatible(),this.setFoveation(this.getFoveation());const n={antialias:t.currentSamples>0,alpha:!0,depth:t.depth,stencil:t.stencil,framebufferScaleFactor:this.getFramebufferScaleFactor()},r=new XRWebGLLayer(e,i,n);this._glBaseLayer=r,e.updateRenderState({baseLayer:r}),t.setPixelRatio(1),t._setXRLayerSize(r.framebufferWidth,r.framebufferHeight),this._xrRenderTarget=new cw(r.framebufferWidth,r.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,n=e.far,r=this._cameraXR,s=this._cameraL,a=this._cameraR;r.near=a.near=s.near=i,r.far=a.far=s.far=n,r.isMultiViewCamera=this._useMultiview,this._currentDepthNear===r.near&&this._currentDepthFar===r.far||(t.updateRenderState({depthNear:r.near,depthFar:r.far}),this._currentDepthNear=r.near,this._currentDepthFar=r.far),r.layers.mask=6|e.layers.mask,s.layers.mask=-5&r.layers.mask,a.layers.mask=-3&r.layers.mask;const o=e.parent,l=r.cameras;dw(r,o);for(let e=0;e<l.length;e++)dw(l[e],o);r.projectionMatrix.copy(s.projectionMatrix),r.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,r,o)}_getController(e){let t=this._controllers[e];return void 0===t&&(t=new jn,this._controllers[e]=t),t}}function dw(e,t){null===t?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}function pw(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 fw(){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 cw(e.pixelwidth,e.pixelheight,{format:tt,type:ze,depthTexture:new oa(e.pixelwidth,e.pixelheight,e.stencilBuffer?Ke:je,void 0,void 0,void 0,void 0,void 0,void 0,e.stencilBuffer?nt: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 mw(e){const t=this._controllers,i=this._controllerInputSources;for(let n=0;n<e.removed.length;n++){const r=e.removed[n],s=i.indexOf(r);s>=0&&(i[s]=null,t[s].disconnect(r))}for(let n=0;n<e.added.length;n++){const r=e.added[n];let s=i.indexOf(r);if(-1===s){for(let e=0;e<t.length;e++){if(e>=i.length){i.push(r),s=e;break}if(null===i[e]){i[e]=r,s=e;break}}if(-1===s)break}const a=t[s];a&&a.connect(r)}}function gw(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 _w(e,t){if(void 0===t)return;const i=this._cameraXR,n=this._renderer,r=n.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&&r.setXRTarget(s.framebuffer);let a=!1;e.length!==i.cameras.length&&(i.cameras.length=0,a=!0);for(let n=0;n<e.length;n++){const o=e[n];let l;if(null!==t)l=t.viewports[n];else if(!0===this._supportsLayers){const e=this._glBinding.getViewSubImage(this._glProjLayer,o);l=e.viewport,0===n&&r.setXRRenderTargetTextures(this._xrRenderTarget,e.colorTexture,this._glProjLayer.ignoreDepthValues&&!this._useMultiview?void 0:e.depthStencilTexture)}else l=s.getViewport(o);let c=this._cameras[n];void 0===c&&(c=new eo,c.layers.enable(n),c.viewport=new un,c.matrixWorldAutoUpdate=!1,this._cameras[n]=c),c.matrix.fromArray(o.transform.matrix),c.matrix.decompose(c.position,c.quaternion,c.scale),c.projectionMatrix.fromArray(o.projectionMatrix),c.projectionMatrixInverse.copy(c.projectionMatrix).invert(),c.viewport.set(l.x,l.y,l.width,l.height),0===n&&(i.matrix.copy(c.matrix),i.matrix.decompose(i.position,i.quaternion,i.scale)),!0===a&&i.cameras.push(c)}null!==t&&null!==t.colorTexture&&r.setXRRenderTargetTextures(this._xrRenderTarget,t.colorTexture,t.viewDescriptors),n.setOutputRenderTarget(this._xrRenderTarget);const l=n._getFrameBufferTarget();null!==t&&(this._xrRenderTarget.samples=null===l?n.samples:0,this._xrRenderTarget.depthBuffer=null===l),n.xr.foveateBoundTexture(l)}for(let e=0;e<this._controllers.length;e++){const i=this._controllerInputSources[e],n=this._controllers[e];null!==i&&void 0!==n&&n.update(i,t,a)}this._currentAnimationLoop&&this._currentAnimationLoop(e,t),t.detectedPlanes&&this.dispatchEvent({type:"planesdetected",data:t}),this._xrFrame=null}class vw extends Ri{constructor(e){super(),this.domElement=e,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new un(0,0,this._width,this._height),this._scissor=new un(0,0,this._width,this._height),this._scissorTest=!1,this.colorTexture=new ra,this.depthTexture=new oa}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,n){const r=this._scissor;e.isVector4?r.copy(e):r.set(e,t,i,n)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,i,n,r=0,s=1){const a=this._viewport;e.isVector4?a.copy(e):a.set(e,t,i,n),a.minDepth=r,a.maxDepth=s}_dispatchResize(){this.dispatchEvent({type:"resize"})}dispose(){this.dispatchEvent({type:"dispose"})}}const bw=new un;class yw{constructor(){this.renderer=null,this._frustum=new Gs,this._frustumArray=null,this._projScreenMatrix=new mn,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,n,r,s,a,o){e.push(t,i,n,r,s,a,o)}project(e,t,i,n,r){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&&(r=r.getGroupContext(e));else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)n.pushLight(e);else if(e.isSprite){if(!1===this.isCulled(e,t)){!0===s.sortObjects&&bw.setFromMatrixPosition(e.matrixWorld).applyMatrix4(this._projScreenMatrix);const{geometry:t,material:a}=e;a.visible&&this.pushRenderItem(n,e,t,a,i,bw.z,null,r)}}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(),bw.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],c=a[l.materialIndex];c&&c.visible&&this.pushRenderItem(n,e,t,c,i,bw.z,l,r)}}else a.visible&&this.pushRenderItem(n,e,t,a,i,bw.z,null,r)}if(!0===e.isBundleGroup&&void 0!==s.backend.beginBundle){const a=n;n=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(n),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,n,r);this._bundleDepth--,this.finishRenderList(n)}return void a.pushBundle({bundleGroup:e,camera:t,renderList:n})}const a=e.children;for(let e=0,s=a.length;e<s;e++)this.project(a[e],t,i,n,r)}}const xw=new Qn,Sw=new Vi,Tw=new un,Mw=new un,Ew={[z]:1,[G]:0,[V]:2};class ww{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 Aw{constructor(e,t={}){this.isRenderer=!0;const{logarithmicDepthBuffer:i=!1,reversedDepthBuffer:n=!1,alpha:r=!0,depth:s=!0,stencil:a=!1,antialias:o=!1,samples:l=0,getFallback:c=null,outputBufferType:u=Xe,multiview:h=!1}=t;this.backend=e,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.alpha=r,this.logarithmicDepthBuffer=i,this.reversedDepthBuffer=n,this.outputColorSpace=Xt,this.toneMapping=0,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=s,this.stencil=a,this.info=new fM,this.contextNode=kf(),this.library=new aw,this.lighting=new lw,this._drawingPipeline=null,this.drawingPipeline=new yw,this._samples=l||(!0===o?4:0),this._onCanvasTargetResize=this._onCanvasTargetResize.bind(this),this._onCanvasTargetDispose=this._onCanvasTargetDispose.bind(this),this._canvasTarget=new vw(e.getDomElement()),this._canvasTarget.addEventListener("resize",this._onCanvasTargetResize),this._canvasTarget.addEventListener("dispose",this._onCanvasTargetDispose),this._canvasTarget.isDefaultCanvasTarget=!0,this._inspector=new Rm,this._inspector.setRenderer(this),this._getFallback=c,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 Bm(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=u,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 hw(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 n=this.needsFrameBufferTarget&&null===this._renderTarget?this._getFrameBufferTarget():this._renderTarget||this._outputRenderTarget,r=this._renderLists.get(e,t,this.lighting),s=this._renderContexts.get(n,this._mrt,0,t),a=e.overrideMaterial||i.material,o=this._objects.get(i,a,e,t,r.lightsNode,s,s.clippingContext),{fragmentShader:l,vertexShader:c}=o.getNodeBuilderState();return{fragmentShader:l,vertexShader:c}}}}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 JE(this,i),this._animation=new $T(this,this._nodes,this.info),this._attributes=new cM(i,this.info),this._background=new kM(this,this._nodes),this._geometries=new pM(i,this._attributes,this.info),this._textures=new OM(this,i,this.info),this._pipelines=new yM(i,this._nodes,this.info),this._bindings=new SM(i,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new tM(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new NM,this._bundles=new sw,this._renderContexts=new IM(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,n=null){if(!0===this._isDeviceLost)return;!1===this._initialized&&await this.init();const r=this.drawingPipeline.prepareAsync(e,t);void 0!==r&&await r,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,c=this._handleObjectFunction,u=this._compilationPromises;null===i&&(i=e);const h=!0===e.isScene?e:!0===i.isScene?i:xw,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 iw),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=c,this._compilationPromises=u,this._finishPreCompile();const w=y.length;let A=0;const R=new ww,C=new Set,N=()=>{A++,null!==n&&n(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 n=this._objects.get(e.object,e.material,e.scene,e.camera,e.lightsNode,e.renderContext,e.clippingContext,e.passId);if(n.drawRange=e.object.geometry.drawRange,n.group=e.group,await this._nodes.getForRenderAsync(n,P),this._nodes.updateBefore(n),this._geometries.updateForRender(n),this._nodes.updateForRender(n),this._bindings.updateForRender(n),this._pipelines.getForRender(n,t),this._nodes.updateAfter(n),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:n,renderContext:r,item:s}=e;!0===t&&this.setRenderTarget(i),this.setMRT(n),null!==s&&(e.materialSide=s.material.side,s.material.side=s.side),this._callDepth++,e.previousRenderContext=this._currentRenderContext,void 0!==r&&(this._currentRenderContext=r),this._precompilationState=e}_finishPreCompile(){const{useFrameBufferTarget:e,outputRenderTarget:t,activeCubeFace:i,activeMipmapLevel:n,outputMRT:r,previousRenderContext:s,item:a,materialSide:o}=this._precompilationState;!0===e&&this.setRenderTarget(t,i,n),this.setMRT(r),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 n=i.length;let r=0;const s=new ww,a=new Set,o=()=>{r++,null!==t&&t(new ProgressEvent("progress",{lengthComputable:!0,loaded:r,total:n}))},l=async()=>{s.needsYield()&&await s.yield()},c=this._pipelines,u=this._bindings,h=this._nodes;for(const e of i){if(!1===c.has(e)){const t=()=>{e.removeEventListener("dispose",t),c.delete(e),u.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),u.updateForCompute(e);const t=u.getForCompute(e),i=[];if(c.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=Rg,t.modelNormalViewMatrix=Cg):this.highPrecision&&(delete t.modelViewMatrix,delete t.modelNormalViewMatrix)}get highPrecision(){const e=this.contextNode.value;return e.modelViewMatrix===Rg&&e.modelNormalViewMatrix===Cg}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 n=e.getIndex();let r=null!==n&&!1===i.has(n);for(const t of e.getVertexBuffers())!1===i.has(t)&&(r=!0);if(r)return t.version=null,!0}}return!1}_renderBundle(e,t,i){const{bundleGroup:n,camera:r,renderList:s}=e,a=this._currentRenderContext,o=this._bundles.get(n,r,a),l=this.backend.get(o);if(this._bundleNeedsUpdate(n,l)){this.backend.beginBundle(a);const e=this._currentRenderBundle;this._currentRenderBundle=o,l.version=n.version,l.drawingPipeline=this.drawingPipeline;const{transparentDoublePass:c,transparent:u,opaque:h}=s;!0===this.opaque&&h.length>0&&this._renderObjects(h,r,t,i),!0===this.transparent&&u.length>0&&this._renderTransparents(u,c,r,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],n=this._nodes.needsRefresh(i);n===gi?(this._nodes.updateBefore(i),this._geometries.updateForRender(i),this._nodes.updateForRender(i),this._bindings.updateForRender(i),this._nodes.updateAfter(i)):n===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(Sw),{depth:i,stencil:n}=this,r=this._outputRenderTarget||this._canvasTarget;let s=this._frameBufferTargets.get(r);if(void 0===s){s=new hn(e,t,{depthBuffer:i,stencilBuffer:n,type:this._outputBufferType,format:tt,colorSpace:Qi.workingColorSpace,generateMipmaps:!1,minFilter:Oe,magFilter:Oe,samples:this.samples}),s.isPostProcessingRenderTarget=!0;const a=()=>{r.removeEventListener("dispose",a),s.dispose(),this._frameBufferTargets.delete(r);const e=this._quadCache.get(s);void 0!==e&&(e.quad.material.dispose(),this._quadCache.delete(s))};r.addEventListener("dispose",a),this._frameBufferTargets.set(r,s)}const a=this.getOutputRenderTarget();s.depthBuffer=i,s.stencilBuffer=n,null!==a?s.setSize(a.width,a.height,a.depth):s.setSize(e,t,1);const o=this._outputRenderTarget?this._outputRenderTarget.viewport:r._viewport,l=this._outputRenderTarget?this._outputRenderTarget.scissor:r._scissor,c=this._outputRenderTarget?1:r._pixelRatio,u=this._outputRenderTarget?this._outputRenderTarget.scissorTest:r._scissorTest;return s.viewport.copy(o),s.scissor.copy(l),s.viewport.multiplyScalar(c),s.scissor.multiplyScalar(c),s.scissorTest=u,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 n=i?this._getFrameBufferTarget():null,r=this._nodes.nodeFrame,s=r.renderId,a=this._currentRenderContext,o=this._currentRenderObjectFunction,l=this._handleObjectFunction,c=this._currentRenderBundle;this._currentRenderBundle=null,this.lighting.beginRender(e),this._callDepth++;const u=!0===e.isScene?e:xw,h=this._renderTarget||this._outputRenderTarget,d=!0===this.xr.isPresenting&&this.isOutputTarget,p=this._activeCubeFace,f=this._activeMipmapLevel;let m;if(null!==n?(m=n,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++,r.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 iw),g.clippingContext.updateGlobal(u,t),u.onBeforeRender(this,e,t,m),this.drawingPipeline.begin(t,g),this._renderLists.update(r.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(Sw),g.textures=null,g.depthTexture=null,g.width=Sw.width,g.height=Sw.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(Mw.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)),Tw.set(0,0,g.width,g.height),g.viewport=!1===g.viewportValue.equals(Tw),g.scissor=y&&!1===g.scissorValue.equals(Tw),this._background.update(u,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,u,w),!0===this.opaque&&C.length>0&&this._renderObjects(C,t,u,w),!0===this.transparent&&R.length>0&&this._renderTransparents(R,A,t,u,w),this.backend.finishRender(g),r.renderId=s,this._currentRenderContext=a,this._currentRenderObjectFunction=o,this._handleObjectFunction=l,this._currentRenderBundle=c,this.lighting.finishRender(e),this._callDepth--,null!==n&&(this.setRenderTarget(h,p,f),this._renderOutput(m)),u.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,n=this._quadCache.get(e);void 0===n?(i=new yy(new my),i.name="Output Color Transform",i.material.name="outputColorTransform",i.material.fragmentNode=this._nodes.getOutputNode(e.texture),n={quad:i,cacheKey:t},this._quadCache.set(e,n)):(i=n.quad,n.cacheKey!==t&&(i.material.fragmentNode=this._nodes.getOutputNode(e.texture),i.material.needsUpdate=!0,n.cacheKey=t));const r=this.autoClear,s=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderOutputLayers(i,e),this.autoClear=r,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,n=-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||n>0&&n%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,n)}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,n){this._canvasTarget.setScissor(e,t,i,n)}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,n,r=0,s=1){this._canvasTarget.setViewport(e,t,i,n,r,s)}getClearColor(e){return e.copy(this._clearColor)}setClearColor(e,t=1){this._clearColor.set(e),this._clearColor.a=t}getClearAlpha(){return this._clearColor.a}setClearAlpha(e){this._clearColor.a=e}getClearDepth(){return!0===this.reversedDepthBuffer?1-this._clearDepth:this._clearDepth}setClearDepth(e){this._clearDepth=e}getClearStencil(){return this._clearStencil}setClearStencil(e){this._clearStencil=e}isOccluded(e){const t=this._currentRenderContext;return t&&this.backend.isOccluded(t,e)}clear(e=!0,t=!0,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 n=this._renderTarget||this._getFrameBufferTarget();let r=null;if(null!==n){this._textures.updateRenderTarget(n);const e=this._textures.get(n);r=this._renderContexts.get(n,null,-1),r.textures=e.textures,r.depthTexture=e.depthTexture,r.width=e.width,r.height=e.height,r.renderTarget=n,r.depth=n.depthBuffer,r.stencil=n.stencilBuffer;const t=this.backend.getClearColor();r.clearColorValue.r=t.r,r.clearColorValue.g=t.g,r.clearColorValue.b=t.b,r.clearColorValue.a=t.a,r.clearDepthValue=this.getClearDepth(),r.clearStencilValue=this.getClearStencil(),r.activeCubeFace=this.getActiveCubeFace(),r.activeMipmapLevel=this.getActiveMipmapLevel(),!0===n.depthBuffer&&(e.depthInitialized=!0)}this.backend.clear(e,t,i,r),null!==n&&null===this._renderTarget&&this._renderOutput(n)}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 n=this._nodes.nodeFrame,r=n.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,n.renderId=this.info.calls,this.backend.updateTimeStampUID(e),this.inspector.beginCompute(this.backend.getTimestampUID(e),e);const s=this.backend,a=this._pipelines,o=this._bindings,l=this._nodes;s.beginCompute(e);for(const n of i){if(!1===a.has(n)){const e=()=>{n.removeEventListener("dispose",e),a.delete(n),o.deleteForCompute(n),l.delete(n)};n.addEventListener("dispose",e);const t=n.onInitFunction;null!==t&&t.call(n,{renderer:this})}l.updateBeforeForCompute(n),l.updateForCompute(n),o.updateForCompute(n);const i=o.getForCompute(n),r=a.getForCompute(n,i);this._updateDispatchSize(n,t),s.compute(e,n,i,r,t),l.updateAfterForCompute(n)}s.finishCompute(e),n.renderId=r,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=Mw.set(t.x,t.y,e.image.width,e.image.height).floor();else{if(!t.isVector4)return void Mi("Renderer.copyFramebufferToTexture: Invalid rectangle.");t=Mw.copy(t).floor()}else t=Mw.set(0,0,e.image.width,e.image.height);let i,n=this._currentRenderContext;null!==n?i=n.renderTarget:(i=this._renderTarget||this._getFrameBufferTarget(),null!==i&&(this._textures.updateRenderTarget(i),n=this._textures.get(i))),this._textures.updateTexture(e,{renderTarget:i}),this.backend.copyFramebufferToTexture(e,n,t),this._inspector.copyFramebufferToTexture(e)}copyTextureToTexture(e,t,i=null,n=null,r=0,s=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,i,n,r,s),this._inspector.copyTextureToTexture(e,t)}async readRenderTargetPixelsAsync(e,t,i,n,r,s=0,a=0){return this.backend.copyTextureToBuffer(e.textures[s],t,i,n,r,a)}_renderBundles(e,t,i){for(const n of e)this._renderBundle(n,t,i)}_renderTransparents(e,t,i,n,r){if(t.length>0){for(const{material:e}of t)e.side=1;this._renderObjects(t,i,n,r,"backSide");for(const{material:e}of t)e.side=0;this._renderObjects(e,i,n,r);for(const{material:e}of t)e.side=2}else this._renderObjects(e,i,n,r)}_renderObjects(e,t,i,n,r=null){for(let s=0,a=e.length;s<a;s++){const{object:a,geometry:o,material:l,group:c,clippingContext:u}=e[s];this._currentRenderObjectFunction(a,i,t,o,l,c,n,u,r)}}_getShadowNodes(e){const t=e.version;let i=this._cacheShadowNodes.get(e);if(void 0===i||i.version!==t){const n=e.map&&e.map.isTexture,r=e.colorNode&&e.colorNode.isNode,s=e.castShadowNode&&e.castShadowNode.isNode,a=e.maskShadowNode&&e.maskShadowNode.isNode||e.maskNode&&e.maskNode.isNode;let o=null,l=null,c=null;if(n||r||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=Yh(0),i=Gh(1)),n&&(i=i.mul(H_("map","texture",e).a)),r&&(i=i.mul(e.colorNode.a)),l=Jh(t,i),a){const t=e.maskShadowNode||e.maskNode;l=Uh(([e])=>(t.not().discard(),e))(l)}}e.depthNode&&e.depthNode.isNode&&(c=e.depthNode),e.castShadowPositionNode&&e.castShadowPositionNode.isNode?o=e.castShadowPositionNode:e.positionNode&&e.positionNode.isNode&&(o=e.positionNode),i={version:t,colorNode:l,depthNode:c,positionNode:o},this._cacheShadowNodes.set(e,i)}return i}_updateCamera(e,t){const i=this.xr,n=!0===i.enabled&&!0===i.isPresenting&&!0===t;if(!1===n){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===n&&(!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,aM)}renderObject(e,t,i,n,r,s,a,o=null,l=null){let c,u,h,d,p,f,m,g=!1;const _=this._currentSourceMaterial;if(e.onBeforeRender(this,t,i,n,r,s),!0===r.allowOverride&&null!==t.overrideMaterial){this._currentSourceMaterial=r;const e=t.overrideMaterial;if(g=!0,c=e.isNodeMaterial?e.colorNode:null,u=e.isNodeMaterial?e.depthNode:null,h=e.isNodeMaterial?e.positionNode:null,d=t.overrideMaterial.side,p=e.displacementMap,f=e.displacementScale,m=e.displacementBias,r.positionNode&&r.positionNode.isNode&&(e.positionNode=r.positionNode),e._alphaTest=r.alphaTest,e.alphaMap=r.alphaMap,e.displacementMap=r.displacementMap,e.displacementScale=r.displacementScale,e.displacementBias=r.displacementBias,e.transparent=r.transparent||r.transmission>0||r.transmissionNode&&r.transmissionNode.isNode||r.backdropNode&&r.backdropNode.isNode,e.isShadowPassMaterial){const{colorNode:t,depthNode:i,positionNode:n}=this._getShadowNodes(r);3===this.shadowMap.type?e.side=null!==r.shadowSide?r.shadowSide:r.side:e.side=null!==r.shadowSide?r.shadowSide:Ew[r.side],null!==t&&(e.colorNode=t),null!==i&&(e.depthNode=i),null!==n&&(e.positionNode=n)}r=e}!0===r.transparent&&2===r.side&&!1===r.forceSinglePass?(r.side=1,this._handleObjectFunction(e,r,t,i,a,s,o,"backSide"),r.side=0,this._handleObjectFunction(e,r,t,i,a,s,o,l),r.side=2):this._handleObjectFunction(e,r,t,i,a,s,o,l),g&&(t.overrideMaterial.colorNode=c,t.overrideMaterial.depthNode=u,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,n,r,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,n,r,s,a,o){const l=this._objects.get(e,t,i,n,r,this._currentRenderContext,a,o);if(l.drawRange=e.geometry.drawRange,l.group=s,null!==this._currentRenderBundle){this.backend.get(this._currentRenderBundle).renderObjects.push(l),l.bundle=this._currentRenderBundle.bundleGroup}const c=this._nodes.needsRefresh(l);c===gi?(this._nodes.updateBefore(l),this._geometries.updateForRender(l),this._nodes.updateForRender(l),this._bindings.updateForRender(l)):c===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),c!==fi&&this._nodes.updateAfter(l)):null!==this._currentRenderBundle&&(this.backend.get(this._currentRenderBundle).version=-1)}_createObjectPipeline(e,t,i,n,r,s,a,o){if(null!==this._compilationPromises)return void this._compilationPromises.push({object:e,material:t,side:t.side,scene:i,camera:n,lightsNode:r,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,n,r,this._currentRenderContext,a,o);l.drawRange=e.geometry.drawRange,l.group=s,this._nodes.updateBefore(l),this._geometries.updateForRender(l),this._nodes.updateForRender(l),this._bindings.updateForRender(l),this._pipelines.getForRender(l,this._compilationPromises),this._nodes.updateAfter(l)}_onCanvasTargetResize(){this._initialized&&this.backend.updateSize()}_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 Rw{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}clone(){return Object.assign(new this.constructor,this)}}class Cw extends Rw{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)+(oM-e%oM)%oM;var e}get buffer(){return this._buffer}update(){return!0}release(){this._buffer=null}}class Nw extends Cw{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let Pw=0;class Lw extends Nw{constructor(e,t){super("UniformBuffer_"+(e&&e.name?e.name:Pw++)),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 Dw extends Nw{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,n=this.uniforms.length;i<n;i++){const n=this.uniforms[i],r=n.boundary,s=n.itemSize*e,a=t%oM,o=a%r,l=a+o;t+=o,0!==l&&oM-l<s&&(t+=oM-l),n.offset=t/e,n.index=i,t+=s}return Math.ceil(t/oM)*oM}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,n=e.getValue(),r=e.offset,s=e.getType();if(i[r]!==n){this._getBufferForType(s)[r]=i[r]=n,t=!0,this.addUniformUpdateRange(e)}return t}updateVector2(e){let t=!1;const i=this.values,n=e.getValue(),r=e.offset,s=e.getType();if(i[r+0]!==n.x||i[r+1]!==n.y){const a=this._getBufferForType(s);a[r+0]=i[r+0]=n.x,a[r+1]=i[r+1]=n.y,t=!0,this.addUniformUpdateRange(e)}return t}updateVector3(e){let t=!1;const i=this.values,n=e.getValue(),r=e.offset,s=e.getType();if(i[r+0]!==n.x||i[r+1]!==n.y||i[r+2]!==n.z){const a=this._getBufferForType(s);a[r+0]=i[r+0]=n.x,a[r+1]=i[r+1]=n.y,a[r+2]=i[r+2]=n.z,t=!0,this.addUniformUpdateRange(e)}return t}updateVector4(e){let t=!1;const i=this.values,n=e.getValue(),r=e.offset,s=e.getType();if(i[r+0]!==n.x||i[r+1]!==n.y||i[r+2]!==n.z||i[r+3]!==n.w){const a=this._getBufferForType(s);a[r+0]=i[r+0]=n.x,a[r+1]=i[r+1]=n.y,a[r+2]=i[r+2]=n.z,a[r+3]=i[r+3]=n.w,t=!0,this.addUniformUpdateRange(e)}return t}updateColor(e){let t=!1;const i=this.values,n=e.getValue(),r=e.offset;if(i[r+0]!==n.r||i[r+1]!==n.g||i[r+2]!==n.b){const s=this.buffer;s[r+0]=i[r+0]=n.r,s[r+1]=i[r+1]=n.g,s[r+2]=i[r+2]=n.b,t=!0,this.addUniformUpdateRange(e)}return t}updateMatrix3(e){let t=!1;const i=this.values,n=e.getValue().elements,r=e.offset;if(i[r+0]!==n[0]||i[r+1]!==n[1]||i[r+2]!==n[2]||i[r+4]!==n[3]||i[r+5]!==n[4]||i[r+6]!==n[5]||i[r+8]!==n[6]||i[r+9]!==n[7]||i[r+10]!==n[8]){const s=this.buffer;s[r+0]=i[r+0]=n[0],s[r+1]=i[r+1]=n[1],s[r+2]=i[r+2]=n[2],s[r+4]=i[r+4]=n[3],s[r+5]=i[r+5]=n[4],s[r+6]=i[r+6]=n[5],s[r+8]=i[r+8]=n[6],s[r+9]=i[r+9]=n[7],s[r+10]=i[r+10]=n[8],t=!0,this.addUniformUpdateRange(e)}return t}updateMatrix4(e){let t=!1;const i=this.values,n=e.getValue().elements,r=e.offset;if(!1===function(e,t,i){for(let n=0,r=t.length;n<r;n++)if(e[i+n]!==t[n])return!1;return!0}(i,n,r)){this.buffer.set(n,r),function(e,t,i){for(let n=0,r=t.length;n<r;n++)e[i+n]=t[n]}(i,n,r),t=!0,this.addUniformUpdateRange(e)}return t}_getBufferForType(e){return"int"===e||"ivec2"===e||"ivec3"===e||"ivec4"===e?new Int32Array(this.buffer.buffer):"uint"===e||"uvec2"===e||"uvec3"===e||"uvec4"===e?new Uint32Array(this.buffer.buffer):this.buffer}}let Iw=0;class Fw extends Dw{constructor(e,t){super(e),this.id=Iw++,this.groupNode=t,this.isNodeUniformsGroup=!0}}class Uw extends Rw{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 Ow=0;class Bw extends Uw{constructor(e,t){super(e,t),this.id=Ow++,this.store=!1,this.mipLevel=0,this.isSampledTexture=!0}}class kw extends Bw{constructor(e,t,i,n=null){super(e,t?t.value:null),this.textureNode=t,this.groupNode=i,this.access=n}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 zw extends kw{constructor(e,t,i,n=null){super(e,t,i,n),this.isSampledCubeTexture=!0}}class Gw extends kw{constructor(e,t,i,n=null){super(e,t,i,n),this.isSampledTexture3D=!0}}const Vw={textureGather:new Vy("\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 Vy("\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 Vy("\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 Vy("\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 Vy("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 Vy("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 Vy("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 Vy("vec4 tsl_unpackUnorm4x8( uint x ) { return vec4( uvec4( x, x >> 8, x >> 16, x >> 24 ) & 0xffu ) / 255.0; }")},Hw={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"},Ww={low:"lowp",medium:"mediump",high:"highp"},jw={swizzleAssign:!0,storageBuffer:!1},$w={perspective:"smooth",linear:"noperspective"},Xw={centroid:"centroid"},qw="\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",Yw=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 Kw extends CE{constructor(e,t){super(e,t,new YE),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==$t}_include(e){const t=Vw[e];return t.build(this),this.addInclude(t),t}getMethod(e){return void 0!==Vw[e]&&this._include(e),Hw[e]||e}getBitcastMethod(e,t){const i=this.getComponentType(t),n=this.getComponentType(e);return"float"!==i&&"float"!==n&&this.getTypeLength(t)===this.getTypeLength(e)?this.getType(e):this.getMethod(`bitcast_${i}_${n}`)}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,n){const r=this.getComponentType(n);if("float"===r)return`mix( ${i}, ${t}, ${e} )`;const s=this.getType(n);if("bool"===r){const r=this.getType(this.getTypeFromLength(this.getTypeLength(n),"int")),a=`${r}( ${i} )`;return`${s}( ${a} + ${`${r}( ${e} )`} * ( ${`${r}( ${t} )`} - ${a} ) )`}return`${i} + ${`${s}( ${e} )`} * ( ${t} - ${i} )`}getOutputStructName(){return""}buildFunctionCode(e){const t=e.layout,i=this.flowShaderNode(e),n=[];for(const e of t.inputs)n.push(this.getType(e.type)+" "+e.name);return`${this.getType(t.type)} ${t.name}( ${n.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:n}=t,r=t.array.constructor.name.toLowerCase().includes("int");let s=r?st:rt;2===n?s=r?ot:at:3===n?s=r?lt:et:4===n&&(s=r?ct: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/n))));let l=Math.ceil(i/n/o);o*l*n<i&&l++;const c=o*l*n,u=new e.constructor(c);u.set(e,0),t.array=u;const h=new Rs(t.array,o,l,s,a[t.array.constructor.name]||$e);h.needsUpdate=!0,h.isPBOTexture=!0;const d=new c_(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 Yw.has(e)}generatePBO(e){const{node:t,indexNode:i}=e,n=t.value;if(this.renderer.backend.has(n)){this.renderer.backend.get(n).pbo=n.pbo}const r=this.getUniformFromNode(n.pboNode,"texture",this.shaderStage,this.context.nodeName),s=this.getPropertyName(r);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 r=this.getDataFromNode(t);let c=r.propertySizeName;void 0===c&&(c=l+"Size",this.getVarFromNode(t,c,"uint"),this.addLineFlowCode(`${c} = uint( textureSize( ${s}, 0 ).x )`,e),r.propertySizeName=c);const{itemSize:u}=n,h="."+Su.join("").slice(0,u),d=`ivec2(${a} % ${c}, ${a} / ${c})`,p=this.generateTextureLoad(null,s,d,"0",null,null);let f="vec4";n.pbo.type===je?f="uvec4":n.pbo.type===We&&(f="ivec4");const m=this.getTypeFromLength(u,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,n,r,s){let a;return null===n&&(n="0"),a=r?s?`texelFetchOffset( ${t}, ivec3( ${i}, ${r} ), int( ${n} ), ${s} )`:`texelFetch( ${t}, ivec3( ${i}, ${r} ), int( ${n} ) )`:s?`texelFetchOffset( ${t}, ${i}, int( ${n} ), ${s} )`:`texelFetch( ${t}, ${i}, int( ${n} ) )`,null!==e&&e.isDepthTexture&&(a+=".x"),a}generateTexture(e,t,i,n,r){return n&&(i=`vec3( ${i}, ${n} )`),e.isDepthTexture?r?`textureOffset( ${t}, ${i}, ${r} ).x`:`texture( ${t}, ${i} ).x`:r?`textureOffset( ${t}, ${i}, ${r} )`:`texture( ${t}, ${i} )`}generateTextureSize(e,t,i){return`textureSize( ${t}, ${i} )`}generateTextureLevel(e,t,i,n,r,s){return r&&(i=`vec3( ${i}, ${r} )`),e.isDepthTexture?s?`textureLodOffset( ${t}, ${i}, ${n}, ${s} ).x`:`textureLod( ${t}, ${i}, ${n} ).x`:s?`textureLodOffset( ${t}, ${i}, ${n}, ${s} )`:`textureLod( ${t}, ${i}, ${n} )`}generateTextureBias(e,t,i,n,r,s){return r&&(i=`vec3( ${i}, ${r} )`),s?`textureOffset( ${t}, ${i}, ${s}, ${n} )`:`texture( ${t}, ${i}, ${n} )`}generateTextureGrad(e,t,i,n,r,s){return r&&(i=`vec3( ${i}, ${r} )`),s?`textureGradOffset( ${t}, ${i}, ${n[0]}, ${n[1]}, ${s} )`:`textureGrad( ${t}, ${i}, ${n[0]}, ${n[1]} )`}generateTextureCompare(e,t,i,n,r,s,a=this.shaderStage){if("fragment"===a)return e.isCubeTexture?`texture( ${t}, vec4( ${i}, ${n} ) )`:r?s?`textureOffset( ${t}, vec4( ${i}, ${r}, ${n} ), ${s} )`:`texture( ${t}, vec4( ${i}, ${r}, ${n} ) )`:s?`textureOffset( ${t}, vec3( ${i}, ${n} ), ${s} )`:`texture( ${t}, vec3( ${i}, ${n} ) )`;Mi(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${a} shader.`)}generateTextureGather(e,t,i,n,r,s,a){return e.isDepthTexture&&(n="0"),null===s&&(s="ivec2( 0 )"),null===a&&(a="false"),r?(this._include("textureGatherArray"),`tsl_textureGather_array( ${n}, ${t}, vec3( ${i}, ${r} ), ${s}, ${a} )`):(this._include("textureGather"),`tsl_textureGather( ${n}, ${t}, ${i}, ${s}, ${a} )`)}generateTextureGatherCompare(e,t,i,n,r,s,a){return null===s&&(s="ivec2( 0 )"),null===a&&(a="false"),r?(this._include("textureGatherCompareArray"),`tsl_textureGatherCompare_array( ${t}, vec3( ${i}, ${r} ), ${s}, ${n}, ${a} )`):(this._include("textureGatherCompare"),`tsl_textureGatherCompare( ${t}, ${i}, ${s}, ${n}, ${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=[],n={};for(const r of t){let t=null,s=!1;if("texture"===r.type||"texture3D"===r.type){const e=r.node,i=e.value,n=this.getComponentTypeFromTexture(i),s="float"===n?"":n.charAt(0);t="texture3D"===r.type&&!1===i.isArrayTexture?`${s}sampler3D ${r.name};`:i.compareFunction&&e.isSampleCompare()?!0===i.isArrayTexture?`sampler2DArrayShadow ${r.name};`:`sampler2DShadow ${r.name};`:!0===i.isArrayTexture||!0===i.isDataArrayTexture||!0===i.isCompressedArrayTexture?`${s}sampler2DArray ${r.name};`:`${s}sampler2D ${r.name};`}else if("cubeTexture"===r.type)t=`samplerCube ${r.name};`;else if("cubeDepthTexture"===r.type){t=r.node.value.compareFunction?`samplerCubeShadow ${r.name};`:`samplerCube ${r.name};`}else if("buffer"===r.type){const i=r.node,n=this.getType(i.bufferType),s=i.bufferCount,a=s>0?s:"";t=`${this.getUniformBufferName(r,e)} {\n\t${n} ${r.name}[${a}];\n};\n`}else{const e=r.groupNode.name;if(void 0===n[e]){const t=this.uniformGroups[e];if(void 0!==t){const i=[];for(const e of t.uniforms){const t=e.getType(),n=this.getVectorType(t),r=e.nodeUniform.node.precision;let s=`${n} ${e.name};`;null!==r&&(s=Ww[r]+" "+s),i.push("\t"+s)}n[e]=i}}s=!0}if(!s){const e=r.node.precision;null!==e&&(t=Ww[e]+" "+t),t="uniform "+t,i.push(t)}}let r="";for(const e in n){const t=n[e];r+=this._getGLSLUniformStruct(e,t.join("\n"))+"\n"}return r+=i.join("\n"),r}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==We){let i=e;e.isInterleavedBufferAttribute&&(i=e.data);const n=i.array;!1==(n instanceof Uint32Array||n 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 n of e)t+=`layout( location = ${i++} ) in ${n.type} ${n.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],n=[];for(const e of i)if(e.output)for(const t of e.members)n.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===n.length&&n.push(`layout( location = 0 ) out ${this.getOutputType()} fragColor;`),"\n"+n.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 n of i){"compute"===e&&(n.needsInterpolation=!0);const i=this.getType(n.type);if(n.needsInterpolation)if(n.interpolationType){t+=`${$w[n.interpolationType]||n.interpolationType} ${Xw[n.interpolationSampling]||""} out ${i} ${n.name};\n`}else{t+=`${i.includes("int")||i.includes("uv")||i.includes("iv")?"flat ":""}out ${i} ${n.name};\n`}else t+=`${i} ${n.name};\n`}else if("fragment"===e)for(const e of i)if(e.needsInterpolation){const i=this.getType(e.type);if(e.interpolationType){t+=`${$w[e.interpolationType]||e.interpolationType} ${Xw[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 n=this.extensions[i]||(this.extensions[i]=new Map);!1===n.has(e)&&n.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:n}of i.values())t.push(`#extension ${e} : ${n}`);return t.join("\n")}getClipDistance(){return"gl_ClipDistance"}isAvailable(e){let t=jw[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)}jw[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 n=e[i],r=this.getPropertyName(n.attributeNode);r&&(t+=`${n.varyingName} = ${r};\n\t`)}return t}_getGLSLUniformStruct(e,t){return`\nlayout( std140 ) uniform ${e} {\n${t}\n};`}_getGLSLVertexCode(e){return`#version 300 es\n\n${this.getSignature()}\n\n// extensions\n${e.extensions}\n\n// precision\n${qw}\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${qw}\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 n=this.flowNodes[t],r=n[n.length-1];for(const e of n){const n=this.getFlowData(e),s=e.name;s&&(i.length>0&&(i+="\n"),i+=`\t// flow -> ${s}\n\t`),i+=`${n.code}\n\t`,e===r&&"compute"!==t&&(i+="// result\n\t","vertex"===t?(i+="gl_Position = ",i+=`${this.format(n.result,r.getNodeType(this),"vec4")};`):"fragment"===t&&(e.outputNode.isOutputStructNode||(i+="fragColor = ",i+=`${this.format(n.result,r.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,n=null){const r=super.getUniformFromNode(e,t,i,"buffer"===t?null:n),s=this.getDataFromNode(e,i,this.globalCache);let a=s.uniformGPU;if(void 0===a){const n=e.groupNode,o=n.name,l=this.getBindGroupArray(o,i);if("texture"===t)a=new kw(r.name,r.node,n),l.push(a);else if("cubeTexture"===t||"cubeDepthTexture"===t)a=new zw(r.name,r.node,n),l.push(a);else if("texture3D"===t)a=new Gw(r.name,r.node,n),l.push(a);else if("buffer"===t){const t=new Lw(e,n);l.push(t),a=t}else{let e=this.uniformGroups[o];void 0===e?(e=new Fw(o,n),this.uniformGroups[o]=e,l.push(e)):-1===l.indexOf(e)&&l.push(e),a=this.getNodeUniform(r,t);const i=a.name,s=e.uniforms.some(e=>e.name===i);s||e.addUniform(a)}s.uniformGPU=a}return r}}let Zw=null,Qw=null;class Jw{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 n,r=e.id;Array.isArray(e)?(r=e.map(e=>e.id).join(","),n="c:"+this.renderer.info.compute.frameCalls):n=!0===e.isComputeNode?"c:"+this.renderer.info.compute.frameCalls:"r:"+this.renderer.info.render.frameCalls,t.timestampUID=n+":"+r+":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 Zw=Zw||new Vi,this.renderer.getDrawingBufferSize(Zw)}setScissorTest(){}resetState(){}getClearColor(){const e=this.renderer;return Qw=Qw||new Bm,e.getClearColor(Qw),Qw.getRGB(Qw),Qw}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 eA,tA,iA=0;class nA{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 rA{constructor(e){this.backend=e}createAttribute(e,t){const i=this.backend,{gl:n}=i,r=i.getBufferAttribute(e);if(void 0!==i.get(r).bufferGPU)return;const s=e.array,a=e.usage||n.STATIC_DRAW,o=this._createBuffer(n,t,s,a);let l;if(s instanceof Float32Array)l=n.FLOAT;else if("undefined"!=typeof Float16Array&&s instanceof Float16Array)l=n.HALF_FLOAT;else if(s instanceof Uint16Array)l=e.isFloat16BufferAttribute?n.HALF_FLOAT:n.UNSIGNED_SHORT;else if(s instanceof Int16Array)l=n.SHORT;else if(s instanceof Uint32Array)l=n.UNSIGNED_INT;else if(s instanceof Int32Array)l=n.INT;else if(s instanceof Int8Array)l=n.BYTE;else if(s instanceof Uint8Array)l=n.UNSIGNED_BYTE;else{if(!(s instanceof Uint8ClampedArray))throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+s);l=n.UNSIGNED_BYTE}let c={bufferGPU:o,bufferType:t,type:l,byteLength:s.byteLength,bytesPerElement:s.BYTES_PER_ELEMENT,version:r.version,pbo:e.pbo,isInteger:l===n.INT||l===n.UNSIGNED_INT||e.gpuType===We,id:iA++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(n,t,s,a);c=new nA(c,e)}i.set(r,c)}updateAttribute(e){const t=this.backend,{gl:i}=t,n=e.array,r=t.getBufferAttribute(e),s=t.get(r),a=r.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,n);else{for(let e=0,t=a.length;e<t;e++){const t=a[e];i.bufferSubData(o,t.start*n.BYTES_PER_ELEMENT,n,t.start,t.count)}r.clearUpdateRanges()}i.bindBuffer(o,null),s.version=r.version}destroyAttribute(e){const t=this.backend,{gl:i}=t,n=t.getBufferAttribute(e),r=t.get(n);if(void 0!==r.buffers)for(const e of r.buffers)i.deleteBuffer(e);else i.deleteBuffer(r.bufferGPU);t.delete(n)}async getArrayBufferAsync(e,t=null,i=0,n=-1){const r=this.backend,{gl:s}=r,a=r.getBufferAttribute(e),o=r.get(a),{bufferGPU:l}=o,c=-1===n?o.byteLength-i:n;let u;if(null===t)u=new Uint8Array(new ArrayBuffer(c));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),u=new Uint8Array(new ArrayBuffer(c)),t.buffer=u.buffer}else u=new Uint8Array(t);return s.bindBuffer(s.COPY_READ_BUFFER,l),s.getBufferSubData(s.COPY_READ_BUFFER,i,u),s.bindBuffer(s.COPY_READ_BUFFER,null),s.bindBuffer(s.COPY_WRITE_BUFFER,null),t&&t.isReadbackBuffer?t:u.buffer}_createBuffer(e,t,i,n){const r=e.createBuffer(),s=this.backend.state;return t===e.ELEMENT_ARRAY_BUFFER&&null!==s.currentVAO&&s.resetVertexState(),e.bindBuffer(t,r),e.bufferData(t,i,n),e.bindBuffer(t,null),r}}class sA{constructor(e){this.backend=e,this.cache=new Map}getVAO(e,t,i=null){const n=this.backend,r=n.get(e),s=null!==i?n.get(i):null,a=null!==s?s.bufferGPU:null;if(!1===this._needsUpdate(r,t,a))return r.vaoGPU;let o="",l="";const c=[],u=[];for(let e=0;e<t.length;e++){const i=t[e],r=n.get(n.getBufferAttribute(i));o+=":"+r.id,i.isInterleavedBufferAttribute&&(o+="."+i.offset),l+=":"+(r.activeBufferIndex||0),c.push(r.bufferGPU),u.push(r)}null!==s&&(o+="|"+s.id,u.push(s));let h=this.cache.get(o);if(o!==r.vaoKey){if(void 0!==r.vaoKey&&this._releaseEntry(r.vaoKey),void 0===h){h={vaos:new Map,buffersData:u,usedTimes:0},this.cache.set(o,h);for(const e of u)void 0===e.vaoKeys&&(e.vaoKeys=new Set),e.vaoKeys.add(o)}h.usedTimes++,r.vaoKey=o}let d=h.vaos.get(l);return void 0===d&&(d=this._createVAO(t,a),h.vaos.set(l,d)),r.vaoGPU=d,r.vertexBuffers=c,r.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 n=e.vertexBuffers;if(void 0===n||n.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!==n[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,n=this.cache.get(e);for(const e of n.vaos.values())i.currentVAO===e&&i.resetVertexState(),t.deleteVertexArray(e);for(const t of n.buffersData)t.vaoKeys.delete(e);this.cache.delete(e)}_createVAO(e,t){const{gl:i,state:n}=this.backend,r=i.createVertexArray();n.setVertexState(r,t);for(let t=0;t<e.length;t++){const n=e[t],r=this.backend.getBufferAttribute(n),s=this.backend.get(r);let a,o;if(i.bindBuffer(i.ARRAY_BUFFER,s.bufferGPU),i.enableVertexAttribArray(t),!0===n.isInterleavedBufferAttribute){a=(!0===r.isInterleavedBuffer?r.stride:r.itemSize)*s.bytesPerElement,o=n.offset*s.bytesPerElement}else a=0,o=0;s.isInteger?i.vertexAttribIPointer(t,n.itemSize,s.type,a,o):i.vertexAttribPointer(t,n.itemSize,s.type,n.normalized,a,o),!0!==r.isInstancedBufferAttribute&&!0!==r.isInstancedInterleavedBuffer||i.vertexAttribDivisor(t,r.meshPerAttribute)}return i.bindBuffer(i.ARRAY_BUFFER,null),r}}class aA{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 Kn(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;eA={[H]:e.FUNC_ADD,[W]:e.FUNC_SUBTRACT,[j]:e.FUNC_REVERSE_SUBTRACT,[$]:e.MIN,[X]:e.MAX},tA={[q]:e.ZERO,[Y]:e.ONE,[K]:e.SRC_COLOR,[Q]:e.SRC_ALPHA,[re]:e.SRC_ALPHA_SATURATE,[ie]:e.DST_COLOR,[ee]:e.DST_ALPHA,[Z]:e.ONE_MINUS_SRC_COLOR,[J]:e.ONE_MINUS_SRC_ALPHA,[ne]: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 un).fromArray(t),this.currentViewport=(new un).fromArray(i),this._tempVec4=new un}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 n=this.gl,r=this.backend.drawBuffersIndexedExt;if(r){for(let s=0;s<e.length;s++){const a=e[s];let o=null;if(null!==t){const e=t.getBlendMode(a.name);6===e.blending?o=i:0!==e.blending&&(o=e)}else o=i;null!==o?this._setMRTBlendingIndex(s,o):r.blendFuncSeparateiOES(s,n.ONE,n.ZERO,n.ONE,n.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,n=this.backend.drawBuffersIndexedExt,r=t.blending,s=t.blendSrc,a=t.blendDst,o=t.blendEquation,l=t.premultipliedAlpha;if(5===r){const i=null!==t.blendSrcAlpha?t.blendSrcAlpha:s,r=null!==t.blendDstAlpha?t.blendDstAlpha:a,l=null!==t.blendEquationAlpha?t.blendEquationAlpha:o;n.blendEquationSeparateiOES(e,eA[o],eA[l]),n.blendFuncSeparateiOES(e,tA[s],tA[a],tA[i],tA[r])}else if(n.blendEquationSeparateiOES(e,i.FUNC_ADD,i.FUNC_ADD),l)switch(r){case 1:default:n.blendFuncSeparateiOES(e,i.ONE,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA);break;case 2:n.blendFuncSeparateiOES(e,i.ONE,i.ONE,i.ONE,i.ONE);break;case 3:n.blendFuncSeparateiOES(e,i.ZERO,i.ONE_MINUS_SRC_COLOR,i.ZERO,i.ONE);break;case 4:n.blendFuncSeparateiOES(e,i.DST_COLOR,i.ONE_MINUS_SRC_ALPHA,i.ZERO,i.ONE)}else switch(r){case 1:default:n.blendFuncSeparateiOES(e,i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA);break;case 2:n.blendFuncSeparateiOES(e,i.SRC_ALPHA,i.ONE,i.ONE,i.ONE);break;case 3:n.blendFuncSeparateiOES(e,i.ZERO,i.ONE_MINUS_SRC_COLOR,i.ZERO,i.ONE);break;case 4:n.blendFuncSeparateiOES(e,i.DST_COLOR,i.ONE_MINUS_SRC_ALPHA,i.ZERO,i.ONE)}}setBlending(e,t,i,n,r,s,a,o,l,c){const{gl:u}=this;if(0!==e){if(!1===this.currentBlendingEnabled&&(this.enable(u.BLEND),this.currentBlendingEnabled=!0),5===e)r=r||t,s=s||i,a=a||n,t===this.currentBlendEquation&&r===this.currentBlendEquationAlpha||(u.blendEquationSeparate(eA[t],eA[r]),this.currentBlendEquation=t,this.currentBlendEquationAlpha=r),i===this.currentBlendSrc&&n===this.currentBlendDst&&s===this.currentBlendSrcAlpha&&a===this.currentBlendDstAlpha||(u.blendFuncSeparate(tA[i],tA[n],tA[s],tA[a]),this.currentBlendSrc=i,this.currentBlendDst=n,this.currentBlendSrcAlpha=s,this.currentBlendDstAlpha=a),!1!==o.equals(this.currentBlendColor)&&l===this.currentBlendAlpha||(u.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||c!==this.currentPremultipledAlpha){if(this.currentBlendEquation===H&&this.currentBlendEquationAlpha===H||(u.blendEquation(u.FUNC_ADD),this.currentBlendEquation=H,this.currentBlendEquationAlpha=H),c)switch(e){case 1:u.blendFuncSeparate(u.ONE,u.ONE_MINUS_SRC_ALPHA,u.ONE,u.ONE_MINUS_SRC_ALPHA);break;case 2:u.blendFunc(u.ONE,u.ONE);break;case 3:u.blendFuncSeparate(u.ZERO,u.ONE_MINUS_SRC_COLOR,u.ZERO,u.ONE);break;case 4:u.blendFuncSeparate(u.DST_COLOR,u.ONE_MINUS_SRC_ALPHA,u.ZERO,u.ONE);break;default:Mi("WebGLState: Invalid blending: ",e)}else switch(e){case 1:u.blendFuncSeparate(u.SRC_ALPHA,u.ONE_MINUS_SRC_ALPHA,u.ONE,u.ONE_MINUS_SRC_ALPHA);break;case 2:u.blendFuncSeparate(u.SRC_ALPHA,u.ONE,u.ONE,u.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=c}}else!0===this.currentBlendingEnabled&&(this.disable(u.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,n){const r=this._tempVec4.set(e,t,i,n);if(!1===this.currentScissor.equals(r)){const{gl:e}=this;e.scissor(r.x,r.y,r.z,r.w),this.currentScissor.copy(r)}}viewport(e,t,i,n){const r=this._tempVec4.set(e,t,i,n);if(!1===this.currentViewport.equals(r)){const{gl:e}=this;e.viewport(r.x,r.y,r.z,r.w),this.currentViewport.copy(r)}}setScissorTest(e){const t=this.gl;e?this.enable(t.SCISSOR_TEST):this.disable(t.SCISSOR_TEST)}setStencilTest(e){const{gl:t}=this;e?this.enable(t.STENCIL_TEST):this.disable(t.STENCIL_TEST)}setStencilMask(e){this.currentStencilMask!==e&&(this.gl.stencilMask(e),this.currentStencilMask=e)}setStencilFunc(e,t,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:n}=this;2===e.side?this.disable(n.CULL_FACE):this.enable(n.CULL_FACE);let r=1===e.side;t&&(r=!r),this.setFlipSided(r),1===e.blending&&!1===e.transparent?this.setBlending(0):this.setBlending(e.blending,e.blendEquation,e.blendSrc,e.blendDst,e.blendEquationAlpha,e.blendSrcAlpha,e.blendDstAlpha,e.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(n.SAMPLE_ALPHA_TO_COVERAGE):this.disable(n.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:n}=this;e?(this.enable(n.POLYGON_OFFSET_FILL),this.currentPolygonOffsetFactor===t&&this.currentPolygonOffsetUnits===i||(this.currentPolygonOffsetFactor=t,this.currentPolygonOffsetUnits=i,this.currentDepthReversed&&(t=-t,i=-i),n.polygonOffset(t,i))):this.disable(n.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:n}=this;return n[e]!==t&&(i.bindFramebuffer(e,t),n[e]=t,e===i.DRAW_FRAMEBUFFER&&(n[i.FRAMEBUFFER]=t),e===i.FRAMEBUFFER&&(n[i.DRAW_FRAMEBUFFER]=t),!0)}drawBuffers(e,t){const{gl:i}=this;let n=[],r=!1;if(null!==e.textures){n=this.currentDrawbuffers.get(t),void 0===n&&(n=[i.COLOR_ATTACHMENT0],this.currentDrawbuffers.set(t,n));const s=e.textures;if(n.length!==s.length){for(let e=0,t=s.length;e<t;e++)n[e]=i.COLOR_ATTACHMENT0+e;n.length=s.length,r=!0}}else n[0]!==i.BACK&&(n[0]=i.BACK,r=!0);r&&i.drawBuffers(n)}activeTexture(e){const{gl:t,currentTextureSlot:i,maxTextures:n}=this;void 0===e&&(e=t.TEXTURE0+n-1),i!==e&&(t.activeTexture(e),this.currentTextureSlot=e)}bindTexture(e,t,i){const{gl:n,currentTextureSlot:r,currentBoundTextures:s,maxTextures:a}=this;void 0===i&&(i=null===r?n.TEXTURE0+a-1:r);let o=s[i];void 0===o&&(o={type:void 0,texture:void 0},s[i]=o),o.type===e&&o.texture===t||(r!==i&&(n.activeTexture(i),this.currentTextureSlot=i),n.bindTexture(e,t),o.type=e,o.texture=t)}bindBufferBase(e,t,i){const{gl:n}=this,r=`${e}-${t}`;return this.currentBoundBufferBases[r]!==i&&(n.bindBufferBase(e,t,i),this.currentBoundBufferBases[r]=i,!0)}unbindTexture(){const{gl:e,currentTextureSlot:t,currentBoundTextures:i}=this,n=i[t];void 0!==n&&void 0!==n.type&&(e.bindTexture(n.type,null),n.type=void 0,n.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:n}=this;n[e]!==t&&(i.pixelStorei(e,t),n[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 oA{constructor(e){this.backend=e,this.gl=this.backend.gl,this.extensions=e.extensions}convert(e,t=""){const{gl:i,extensions:n}=this;let r;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===nt)return i.DEPTH_STENCIL;if(e===rt)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===ct)return i.RGBA_INTEGER;if(e===ut||e===ht||e===dt||e===pt)if(s===Kt){if(r=n.get("WEBGL_compressed_texture_s3tc_srgb"),null===r)return null;if(e===ut)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(e===ht)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(e===dt)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(e===pt)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(r=n.get("WEBGL_compressed_texture_s3tc"),null===r)return null;if(e===ut)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(e===ht)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(e===dt)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(e===pt)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(e===ft||e===mt||e===gt||e===_t){if(r=n.get("WEBGL_compressed_texture_pvrtc"),null===r)return null;if(e===ft)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(e===mt)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(e===gt)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(e===_t)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(e===vt||e===bt||e===yt||e===xt||e===St||e===Tt||e===Mt){if(r=n.get("WEBGL_compressed_texture_etc"),null===r)return null;if(e===vt||e===bt)return s===Kt?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(e===yt)return s===Kt?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC;if(e===xt)return r.COMPRESSED_R11_EAC;if(e===St)return r.COMPRESSED_SIGNED_R11_EAC;if(e===Tt)return r.COMPRESSED_RG11_EAC;if(e===Mt)return r.COMPRESSED_SIGNED_RG11_EAC}if(e===Et||e===wt||e===At||e===Rt||e===Ct||e===Nt||e===Pt||e===Lt||e===Dt||e===It||e===Ft||e===Ut||e===Ot||e===Bt){if(r=n.get("WEBGL_compressed_texture_astc"),null===r)return null;if(e===Et)return s===Kt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(e===wt)return s===Kt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(e===At)return s===Kt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(e===Rt)return s===Kt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(e===Ct)return s===Kt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(e===Nt)return s===Kt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(e===Pt)return s===Kt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(e===Lt)return s===Kt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(e===Dt)return s===Kt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(e===It)return s===Kt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(e===Ft)return s===Kt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(e===Ut)return s===Kt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(e===Ot)return s===Kt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(e===Bt)return s===Kt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}if(e===kt||e===zt||e===Gt){if(r=n.get("EXT_texture_compression_bptc"),null===r)return null;if(e===kt)return s===Kt?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(e===zt)return r.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(e===Gt)return r.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}if(e===Vt||e===Ht||e===Wt||e===jt){if(r=n.get("EXT_texture_compression_rgtc"),null===r)return null;if(e===Vt)return r.COMPRESSED_RED_RGTC1_EXT;if(e===Ht)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(e===Wt)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(e===jt)return r.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,n)=>{!function r(){const s=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(s===e.WAIT_FAILED)return e.deleteSync(t),void n();s!==e.TIMEOUT_EXPIRED?(e.deleteSync(t),i()):requestAnimationFrame(r)}()})}}let lA,cA,uA,hA=!1;class dA{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},this._srcFramebuffer=null,this._dstFramebuffer=null,!1===hA&&(this._init(),hA=!0)}_init(){const e=this.gl;lA={[Pe]:e.REPEAT,[Le]:e.CLAMP_TO_EDGE,[De]:e.MIRRORED_REPEAT},cA={[Ie]:e.NEAREST,[Fe]:e.NEAREST_MIPMAP_NEAREST,[Ue]:e.NEAREST_MIPMAP_LINEAR,[Oe]:e.LINEAR,[Be]:e.LINEAR_MIPMAP_NEAREST,[ke]:e.LINEAR_MIPMAP_LINEAR},uA={[Qt]:e.NEVER,[si]:e.ALWAYS,[Jt]:e.LESS,[ti]:e.LEQUAL,[ei]:e.EQUAL,[ri]:e.GEQUAL,[ii]:e.GREATER,[ni]: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,n,r,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;n&&(l=o.get("EXT_texture_norm16"),l||Ti("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let c=t;if(t===a.RED&&(i===a.FLOAT&&(c=a.R32F),i===a.HALF_FLOAT&&(c=a.R16F),i===a.UNSIGNED_BYTE&&(c=a.R8),i===a.BYTE&&(c=a.R8_SNORM),i===a.UNSIGNED_SHORT&&l&&(c=l.R16_EXT),i===a.SHORT&&l&&(c=l.R16_SNORM_EXT)),t===a.RED_INTEGER&&(i===a.UNSIGNED_BYTE&&(c=a.R8UI),i===a.UNSIGNED_SHORT&&(c=a.R16UI),i===a.UNSIGNED_INT&&(c=a.R32UI),i===a.BYTE&&(c=a.R8I),i===a.SHORT&&(c=a.R16I),i===a.INT&&(c=a.R32I)),t===a.RG&&(i===a.FLOAT&&(c=a.RG32F),i===a.HALF_FLOAT&&(c=a.RG16F),i===a.UNSIGNED_BYTE&&(c=a.RG8),i===a.BYTE&&(c=a.RG8_SNORM),i===a.UNSIGNED_SHORT&&l&&(c=l.RG16_EXT),i===a.SHORT&&l&&(c=l.RG16_SNORM_EXT)),t===a.RG_INTEGER&&(i===a.UNSIGNED_BYTE&&(c=a.RG8UI),i===a.UNSIGNED_SHORT&&(c=a.RG16UI),i===a.UNSIGNED_INT&&(c=a.RG32UI),i===a.BYTE&&(c=a.RG8I),i===a.SHORT&&(c=a.RG16I),i===a.INT&&(c=a.RG32I)),t===a.RGB){const e=s?Yt:Qi.getTransfer(r);i===a.FLOAT&&(c=a.RGB32F),i===a.HALF_FLOAT&&(c=a.RGB16F),i===a.UNSIGNED_BYTE&&(c=e===Kt?a.SRGB8:a.RGB8),i===a.BYTE&&(c=a.RGB8_SNORM),i===a.UNSIGNED_SHORT&&l&&(c=l.RGB16_EXT),i===a.SHORT&&l&&(c=l.RGB16_SNORM_EXT),i===a.UNSIGNED_SHORT_5_6_5&&(c=a.RGB565),i===a.UNSIGNED_SHORT_5_5_5_1&&(c=a.RGB5_A1),i===a.UNSIGNED_SHORT_4_4_4_4&&(c=a.RGB4),i===a.UNSIGNED_INT_5_9_9_9_REV&&(c=a.RGB9_E5),i===a.UNSIGNED_INT_10F_11F_11F_REV&&(c=a.R11F_G11F_B10F)}if(t===a.RGB_INTEGER&&(i===a.UNSIGNED_BYTE&&(c=a.RGB8UI),i===a.UNSIGNED_SHORT&&(c=a.RGB16UI),i===a.UNSIGNED_INT&&(c=a.RGB32UI),i===a.BYTE&&(c=a.RGB8I),i===a.SHORT&&(c=a.RGB16I),i===a.INT&&(c=a.RGB32I)),t===a.RGBA){const e=s?Yt:Qi.getTransfer(r);i===a.FLOAT&&(c=a.RGBA32F),i===a.HALF_FLOAT&&(c=a.RGBA16F),i===a.UNSIGNED_BYTE&&(c=e===Kt?a.SRGB8_ALPHA8:a.RGBA8),i===a.BYTE&&(c=a.RGBA8_SNORM),i===a.UNSIGNED_SHORT&&l&&(c=l.RGBA16_EXT),i===a.SHORT&&l&&(c=l.RGBA16_SNORM_EXT),i===a.UNSIGNED_SHORT_4_4_4_4&&(c=a.RGBA4),i===a.UNSIGNED_SHORT_5_5_5_1&&(c=a.RGB5_A1)}return t===a.RGBA_INTEGER&&(i===a.UNSIGNED_BYTE&&(c=a.RGBA8UI),i===a.UNSIGNED_SHORT&&(c=a.RGBA16UI),i===a.UNSIGNED_INT&&(c=a.RGBA32UI),i===a.BYTE&&(c=a.RGBA8I),i===a.SHORT&&(c=a.RGBA16I),i===a.INT&&(c=a.RGBA32I)),t===a.DEPTH_COMPONENT&&(i===a.UNSIGNED_SHORT&&(c=a.DEPTH_COMPONENT16),i===a.UNSIGNED_INT&&(c=a.DEPTH_COMPONENT24),i===a.FLOAT&&(c=a.DEPTH_COMPONENT32F)),t===a.DEPTH_STENCIL&&(i===a.UNSIGNED_INT_24_8&&(c=a.DEPTH24_STENCIL8),i===a.FLOAT&&(c=a.DEPTH32F_STENCIL8)),c!==a.R16F&&c!==a.R32F&&c!==a.RG16F&&c!==a.RG32F&&c!==a.RGBA16F&&c!==a.RGBA32F||o.get("EXT_color_buffer_float"),c}setTextureParameters(e,t){const{gl:i,extensions:n,backend:r}=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,lA[t.wrapS]),i.texParameteri(e,i.TEXTURE_WRAP_T,lA[t.wrapT]),e!==i.TEXTURE_3D&&e!==i.TEXTURE_2D_ARRAY||t.isArrayTexture||i.texParameteri(e,i.TEXTURE_WRAP_R,lA[t.wrapR]),i.texParameteri(e,i.TEXTURE_MAG_FILTER,cA[t.magFilter]);const c=t.mipmaps.length>0,u=t.minFilter===Oe&&c?ke:t.minFilter;if(i.texParameteri(e,i.TEXTURE_MIN_FILTER,cA[u]),t.compareFunction&&(i.texParameteri(e,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE),i.texParameteri(e,i.TEXTURE_COMPARE_FUNC,uA[t.compareFunction])),!0===n.has("EXT_texture_filter_anisotropic")){if(t.magFilter===Ie)return;if(t.minFilter!==Ue&&t.minFilter!==ke)return;if(t.type===$e&&!1===n.has("OES_texture_float_linear"))return;if(t.anisotropy>1){const s=n.get("EXT_texture_filter_anisotropic");i.texParameterf(e,s.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,r.capabilities.getMaxAnisotropy()))}}}createDefaultTexture(e){const{gl:t,backend:i,defaultTextures:n}=this,r=this.getGLTextureType(e);let s=n[r];void 0===s&&(s=t.createTexture(),i.state.bindTexture(r,s),t.texParameteri(r,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(r,t.TEXTURE_MAG_FILTER,t.NEAREST),n[r]=s),i.set(e,{textureGPU:s,glTextureType:r})}createTexture(e,t){const{gl:i,backend:n}=this;let r,s,a,o,l;if(!0===e.isExternalTexture)r=e.sourceTexture,s=this.getGLTextureType(e);else{const{levels:c,width:u,height:h,depth:d}=t;a=n.utils.convert(e.format,e.colorSpace),o=n.utils.convert(e.type),l=this.getInternalFormat(e.internalFormat,a,o,e.normalized,e.colorSpace,e.isVideoTexture),r=i.createTexture(),s=this.getGLTextureType(e),n.state.bindTexture(s,r),this.setTextureParameters(s,e),e.isArrayTexture||e.isDataArrayTexture||e.isCompressedArrayTexture?i.texStorage3D(i.TEXTURE_2D_ARRAY,c,l,u,h,d):e.isData3DTexture?i.texStorage3D(i.TEXTURE_3D,c,l,u,h,d):e.isVideoTexture||i.texStorage2D(s,c,l,u,h)}n.set(e,{textureGPU:r,glTextureType:s,glFormat:a,glType:o,glInternalFormat:l})}copyBufferToTexture(e,t){const{gl:i,backend:n}=this,{state:r}=n,{textureGPU:s,glTextureType:a,glFormat:o,glType:l}=n.get(t),{width:c,height:u}=t.source.data;i.bindBuffer(i.PIXEL_UNPACK_BUFFER,e),n.state.bindTexture(a,s),r.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,!1),r.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),i.texSubImage2D(a,0,0,0,c,u,o,l,0),i.bindBuffer(i.PIXEL_UNPACK_BUFFER,null),n.state.unbindTexture()}updateTexture(e,t){const{gl:i}=this,{width:n,height:r}=t,{textureGPU:s,glTextureType:a,glFormat:o,glType:l,glInternalFormat:c}=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 n=e.image[t].mipmaps;for(let e=0;e<n.length;e++){const r=n[e];o===i.RGBA?i.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+t,e,0,0,r.width,r.height,o,l,r.data):null!==o?i.compressedTexSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+t,e,0,0,r.width,r.height,o,r.data):Ti("WebGLBackend: Unsupported compressed texture format")}}else if(e.isCompressedTexture){const n=e.mipmaps,r=t.image,s=null!==o&&o!==i.RGBA;for(let t=0;t<n.length;t++){const a=n[t];if(e.isCompressedArrayTexture)if(s)if(e.layerUpdates.size>0){const n=wo(a.width,a.height,e.format,e.type);for(const r of e.layerUpdates){const e=a.data.subarray(r*n/a.data.BYTES_PER_ELEMENT,(r+1)*n/a.data.BYTES_PER_ELEMENT);i.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,t,0,0,r,a.width,a.height,1,o,e)}}else i.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,t,0,0,0,a.width,a.height,r.depth,o,a.data);else o===i.RGBA?i.texSubImage3D(i.TEXTURE_2D_ARRAY,t,0,0,0,a.width,a.height,r.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=pA(s[e]);i.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,0,0,n,r,o,l,t);for(let t=0;t<a.length;t++){const n=pA(a[t].images[e]);i.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+e,t+1,0,0,n.width,n.height,o,l,n)}}}else if(e.isDataArrayTexture||e.isArrayTexture){const n=t.image;if(e.layerUpdates.size>0){const t=wo(n.width,n.height,e.format,e.type);for(const r of e.layerUpdates){const e=n.data.subarray(r*t/n.data.BYTES_PER_ELEMENT,(r+1)*t/n.data.BYTES_PER_ELEMENT);i.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,r,n.width,n.height,1,o,l,e)}e.clearLayerUpdates()}else i.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,0,n.width,n.height,n.depth,o,l,n.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,c,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],n=pA(t);i.texSubImage2D(a,e,0,0,t.width,t.height,o,l,n)}else{const e=pA(t.image);i.texSubImage2D(a,0,0,0,n,r,o,l,e)}}}generateMipmaps(e){const{gl:t,backend:i}=this,{textureGPU:n,glTextureType:r}=i.get(e);i.state.bindTexture(r,n),t.generateMipmap(r)}deallocateRenderBuffers(e){const{gl:t,backend:i}=this;if(e){const n=i.get(e);if(n.renderBufferStorageSetup=void 0,n.framebuffers){for(const e in n.framebuffers)t.deleteFramebuffer(n.framebuffers[e]);delete n.framebuffers}if(n.depthRenderbuffer&&(t.deleteRenderbuffer(n.depthRenderbuffer),delete n.depthRenderbuffer),n.stencilRenderbuffer&&(t.deleteRenderbuffer(n.stencilRenderbuffer),delete n.stencilRenderbuffer),n.msaaFrameBuffer&&(t.deleteFramebuffer(n.msaaFrameBuffer),delete n.msaaFrameBuffer),n.msaaRenderbuffers){for(let e=0;e<n.msaaRenderbuffers.length;e++)t.deleteRenderbuffer(n.msaaRenderbuffers[e]);delete n.msaaRenderbuffers}}}destroyTexture(e,t=!1){const{gl:i,backend:n}=this,{textureGPU:r,renderTarget:s}=n.get(e);this.deallocateRenderBuffers(s),!1===t&&!0!==e.isExternalTexture&&i.deleteTexture(r),n.delete(e)}copyTextureToTexture(e,t,i=null,n=null,r=0,s=0){const{gl:a,backend:o}=this,{state:l}=this.backend,{textureGPU:c,glTextureType:u,glType:h,glFormat:d}=o.get(t);let p,f,m,g,_,v,b,y,x;l.bindTexture(u,c);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,-r);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!==n?(b=n.x,y=n.y,x=n.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===nt?a.DEPTH_STENCIL_ATTACHMENT:a.DEPTH_ATTACHMENT,n=l.currentBoundFramebuffers[a.READ_FRAMEBUFFER]??null,u=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,r,v+e):a.framebufferTexture2D(a.READ_FRAMEBUFFER,i,a.TEXTURE_2D,t.textureGPU,r),C?a.framebufferTextureLayer(a.DRAW_FRAMEBUFFER,i,c,s,x+e):a.framebufferTexture2D(a.DRAW_FRAMEBUFFER,i,a.TEXTURE_2D,c,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,n),l.bindFramebuffer(a.DRAW_FRAMEBUFFER,u)}else if(0!==r||e.isRenderTargetTexture||o.has(e)){const t=o.get(e);null===this._srcFramebuffer&&(this._srcFramebuffer=a.createFramebuffer()),null===this._dstFramebuffer&&(this._dstFramebuffer=a.createFramebuffer());const i=l.currentBoundFramebuffers[a.READ_FRAMEBUFFER]??null,n=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,r,v+e):a.framebufferTexture2D(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,t.textureGPU,r),C?a.framebufferTextureLayer(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,c,s,x+e):a.framebufferTexture2D(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,c,s),0!==r?a.blitFramebuffer(g,_,g+p,_+f,b,y,b+p,y+f,a.COLOR_BUFFER_BIT,a.NEAREST):C?a.copyTexSubImage3D(u,s,b,y,x+e,g,_,p,f):a.copyTexSubImage2D(u,s,b,y,g,_,p,f);l.bindFramebuffer(a.READ_FRAMEBUFFER,i),l.bindFramebuffer(a.DRAW_FRAMEBUFFER,n)}else C?e.isDataTexture||e.isData3DTexture?a.texSubImage3D(u,s,b,y,x,p,f,m,d,h,S.data):t.isCompressedArrayTexture?a.compressedTexSubImage3D(u,s,b,y,x,p,f,m,d,S.data):a.texSubImage3D(u,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(u),l.unbindTexture()}copyFramebufferToTexture(e,t,i){const{gl:n}=this,{state:r}=this.backend,{textureGPU:s}=this.backend.get(e),{x:a,y:o,z:l,w:c}=i,u=!0===e.isDepthTexture||t.renderTarget&&t.renderTarget.samples>0,h=t.renderTarget?t.renderTarget.height:this.backend.getDrawingBufferSize().y;if(u){const i=0!==a||0!==o;let u,d;if(!0===e.isDepthTexture?(u=n.DEPTH_BUFFER_BIT,d=n.DEPTH_ATTACHMENT,t.stencil&&(u|=n.STENCIL_BUFFER_BIT)):(u=n.COLOR_BUFFER_BIT,d=n.COLOR_ATTACHMENT0),i){const e=this.backend.get(t.renderTarget),i=e.framebuffers[t.getCacheKey()],d=e.msaaFrameBuffer;r.bindFramebuffer(n.DRAW_FRAMEBUFFER,i),r.bindFramebuffer(n.READ_FRAMEBUFFER,d);const p=h-o-c;n.blitFramebuffer(a,p,a+l,p+c,a,p,a+l,p+c,u,n.NEAREST),r.bindFramebuffer(n.READ_FRAMEBUFFER,i),r.bindTexture(n.TEXTURE_2D,s),n.copyTexSubImage2D(n.TEXTURE_2D,0,0,0,a,p,l,c),r.unbindTexture()}else{const e=n.createFramebuffer();r.bindFramebuffer(n.DRAW_FRAMEBUFFER,e),n.framebufferTexture2D(n.DRAW_FRAMEBUFFER,d,n.TEXTURE_2D,s,0),n.blitFramebuffer(0,0,l,c,0,0,l,c,u,n.NEAREST),n.deleteFramebuffer(e)}}else r.bindTexture(n.TEXTURE_2D,s),n.copyTexSubImage2D(n.TEXTURE_2D,0,0,0,a,h-c-o,l,c),r.unbindTexture();!0===e.generateMipmaps&&!0===e.mipmapsAutoUpdate&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t,i,n=!1){const{gl:r}=this,{depthTexture:s,renderTarget:a}=t,{depthBuffer:o,stencilBuffer:l,width:c,height:u}=a;if(r.bindRenderbuffer(r.RENDERBUFFER,e),o&&!l){let t=r.DEPTH_COMPONENT24;if(!0===n){this.extensions.get("WEBGL_multisampled_render_to_texture").renderbufferStorageMultisampleEXT(r.RENDERBUFFER,a.samples,t,c,u)}else i>0?(s&&s.isDepthTexture&&s.type===$e&&(t=r.DEPTH_COMPONENT32F),r.renderbufferStorageMultisample(r.RENDERBUFFER,i,t,c,u)):r.renderbufferStorage(r.RENDERBUFFER,t,c,u);r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.RENDERBUFFER,e)}else if(o&&l){if(i>0){let e=r.DEPTH24_STENCIL8;s&&s.isDepthTexture&&s.type===$e&&(e=r.DEPTH32F_STENCIL8),r.renderbufferStorageMultisample(r.RENDERBUFFER,i,e,c,u)}else r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,c,u);r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,e)}r.bindRenderbuffer(r.RENDERBUFFER,null)}async copyTextureToBuffer(e,t,i,n,r,s){const{backend:a,gl:o}=this,{textureGPU:l,glFormat:c,glType:u}=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(u),p=n*r*this._getBytesPerTexel(u,c),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,n,r,c,u,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 n=0;return e!==i.UNSIGNED_BYTE&&e!==i.BYTE||(n=1),e!==i.UNSIGNED_SHORT&&e!==i.SHORT&&e!==i.HALF_FLOAT||(n=2),e!==i.UNSIGNED_INT&&e!==i.INT&&e!==i.FLOAT||(n=4),t===i.RGBA||t===i.RGBA_INTEGER?4*n:t===i.RGB?3*n:t===i.RG||t===i.RG_INTEGER?2*n:t===i.RED||t===i.RED_INTEGER||t===i.ALPHA?n:void 0}dispose(){const{gl:e}=this;null!==this._srcFramebuffer&&e.deleteFramebuffer(this._srcFramebuffer),null!==this._dstFramebuffer&&e.deleteFramebuffer(this._dstFramebuffer)}}function pA(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 fA{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 mA{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 gA={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 _A{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:n,object:r,type:s,info:a,index:o}=this;0!==o?i.drawElements(n,t,s,e):i.drawArrays(n,e,t),a.update(r,t,1)}renderInstances(e,t,i){const{gl:n,mode:r,type:s,index:a,object:o,info:l}=this;0!==i&&(0!==a?n.drawElementsInstanced(r,t,s,e,i):n.drawArraysInstanced(r,e,t,i),l.update(o,t,i))}renderMultiDraw(e,t,i){const{extensions:n,mode:r,object:s,info:a}=this;if(0===i)return;const o=n.get("WEBGL_multi_draw");if(null===o)for(let n=0;n<i;n++)this.render(e[n],t[n]);else{0!==this.index?o.multiDrawElementsWEBGL(r,t,0,this.type,e,0,i):o.multiDrawArraysWEBGL(r,e,0,t,0,i);let n=0;for(let e=0;e<i;e++)n+=t[e];a.update(s,n,1)}}}class vA{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 bA extends vA{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 n=this.queries[i];e.set(t,this.resolveQuery(n))}}if(0===e.size)return this.lastValue;const t={},i=[];this.timestamps.clear();for(const[n,r]of e){const e=n.match(/^(.*):f(\d+)$/),s=parseInt(e[2]);!1===i.includes(s)&&i.push(s),void 0===t[s]&&(t[s]=0);const a=await r;this.timestamps.set(n,a),t[s]+=a}const n=t[i[i.length-1]];return this.lastValue=n,this.frames=i,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,n}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,n=!1;const r=e=>{n||(n=!0,i&&(clearTimeout(i),i=null),t(e))},s=()=>{if(this.isDisposed)r(this.lastValue);else try{if(this.gl.getParameter(this.ext.GPU_DISJOINT_EXT))return void r(this.lastValue);if(!this.gl.getQueryParameter(e,this.gl.QUERY_RESULT_AVAILABLE))return void(i=setTimeout(s,1));const n=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT);t(Number(n)/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 yA=[];class xA extends Jw{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},n=void 0!==t.context?t.context:e.domElement.getContext("webgl2",i);function r(t){t.preventDefault();const i={api:"WebGL",message:t.statusMessage||"Unknown reason",reason:null,originalEvent:t};e.onDeviceLost(i)}this._onContextLost=r,e.domElement.addEventListener("webglcontextlost",r,!1),this.gl=n,this.extensions=new fA(this),this.capabilities=new mA(this),this.attributeUtils=new rA(this),this.vertexArrayUtils=new sA(this),this.textureUtils=new dA(this),this.bufferRenderer=new _A(this),this.state=new aA(this),this.utils=new oA(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 ci}get hasTimestamp(){return null!==this.disjoint}async getArrayBufferAsync(e,t=null,i=0,n=-1){return await this.attributeUtils.getArrayBufferAsync(e,t,i,n)}async makeXRCompatible(){!0!==this.gl.getContextAttributes().xrCompatible&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,i=null){const n=this.gl;this.set(e.texture,{textureGPU:t,glTextureType:this.textureUtils.getGLTextureType(e.texture),glInternalFormat:n.RGBA8}),null!==i&&(this.set(e.depthTexture,{textureGPU:i,glTextureType:this.textureUtils.getGLTextureType(e.depthTexture),glInternalFormat:e.stencilBuffer?n.DEPTH24_STENCIL8:n.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 bA(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:n}=e;t.viewport(0,0,i,n)}if(e.scissor)this.updateScissor(e);else{const{width:i,height:n}=e;t.scissor(0,0,i,n)}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 n=e.occlusionQueryCount,r=this.getOcclusionData(e);n>0?(r.currentOcclusionQueries=r.occlusionQueries,r.currentOcclusionQueryObjects=r.occlusionQueryObjects,r.lastOcclusionObject=null,r.occlusionQueries=new Array(n),r.occlusionQueryObjects=new Array(n),r.occlusionQueryIndex=0):void 0!==r.lastOcclusionObject&&(r.lastOcclusionObject=void 0)}finishRender(e){const{gl:t,state:i}=this,n=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 r=e.textures;if(null!==r)for(let e=0;e<r.length;e++){const t=r[e];!0===t.generateMipmaps&&!0===t.mipmapsAutoUpdate&&this.generateMipmaps(t)}if(this._currentContext=n,this._resolveRenderTarget(e),null!==n){if(this._setFramebuffer(n),n.viewport)this.updateViewport(n);else{const{width:e,height:t}=n;i.viewport(0,0,e,t)}if(n.scissor)this.updateScissor(n);else{const{width:e,height:t}=n;i.scissor(0,0,e,t)}i.setScissorTest(n.scissor)}this.prepareTimestampBuffer(di,this.getTimestampUID(e))}resolveOccludedAsync(e){const t=this.getOcclusionData(e),{currentOcclusionQueries:i,currentOcclusionQueryObjects:n}=t;if(i&&n){const e=new WeakSet,{gl:r}=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&&(r.getQueryParameter(s,r.QUERY_RESULT_AVAILABLE)?(0===r.getQueryParameter(s,r.QUERY_RESULT)&&e.add(n[t]),i[t]=null,r.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:n,width:r,height:s}=e.viewportValue;t.viewport(i,e.height-s-n,r,s)}updateScissor(e){const{state:t}=this,{x:i,y:n,width:r,height:s}=e.scissorValue;t.scissor(i,e.height-s-n,r,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,n=null,r=!0,s=!0){const{gl:a,renderer:o}=this;if(null===n){n={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 c;c=n.clearColorValue?n.clearColorValue:this.getClearColor();const u=o.getClearDepth(),h=o.getClearStencil();if(e&&this.state.setColorMask(!0),t&&this.state.setDepthMask(!0),i&&this.state.setStencilMask(4294967295),null===n.textures)e&&a.clearColor(c.r,c.g,c.b,c.a),t&&a.clearDepth(u),i&&a.clearStencil(h),a.clear(l);else{if(r&&this._setFramebuffer(n),e)for(let e=0;e<n.textures.length;e++){const t=n.mrt?n.mrt.getClearColor(n.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,[c.r,c.g,c.b,c.a]):a.clearBufferfv(a.COLOR,e,[0,0,0,1])}t&&i?a.clearBufferfi(a.DEPTH_STENCIL,0,u,h):t?a.clearBufferfv(a.DEPTH,0,[u]):i&&a.clearBufferiv(a.STENCIL,0,[h]),r&&s&&this._resolveRenderTarget(n),r&&null!==this._currentContext&&this._currentContext!==n&&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,n,r=null){const{state:s,gl:a}=this;!1===this.discard&&(s.enable(a.RASTERIZER_DISCARD),this.discard=!0);const{programGPU:o,transformAttributes:l,attributes:c}=this.get(n);for(let e=0;e<c.length;e++)this._updateComputeAttribute(c[e]);for(let e=0;e<l.length;e++)this._updateComputeAttribute(l[e]);const u=this.vertexArrayUtils.getVAO(n,c);s.setVertexState(u),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),r=null!==r?r:t.count,Array.isArray(r)?(Ei("WebGLBackend.compute(): The count parameter must be a single number, not an array."),r=r[0]):r&&"object"==typeof r&&r.isIndirectStorageBufferAttribute&&(Ei("WebGLBackend.compute(): The count parameter must be a single number, not IndirectStorageBufferAttribute"),r=t.count),c[0].isStorageInstancedBufferAttribute?a.drawArraysInstanced(a.POINTS,0,1,r):a.drawArrays(a.POINTS,0,r),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?sM:nM;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,n,r,s){if(e.isBatchedMesh)if(!1===this.hasFeature("WEBGL_multi_draw")){const{gl:i}=this,n=i.getUniformLocation(s,"nodeUniformDrawId"),r=e._multiDrawStarts,a=e._multiDrawCounts,o=e._multiDrawCount;for(let e=0;e<o;e++)i.uniform1ui(n,e),t.render(r[e],a[e])}else t.renderMultiDraw(e._multiDrawStarts,e._multiDrawCounts,e._multiDrawCount);else r>1?t.renderInstances(i,n,r):t.render(i,n)}draw(e){const{object:t,pipeline:i,material:n,context:r,hardwareClippingPlanes:s}=e,{programGPU:a}=this.get(i),{gl:o,state:l}=this,c=e.getDrawParameters();if(null===c)return;this._bindUniforms(e.getBindings());const u=t.isMesh&&t.matrixWorld.determinantAffine()<0;l.setMaterial(n,u,s),null!==r.mrt&&null!==r.textures&&l.setMRTBlending(r.textures,r.mrt,n),l.useProgram(a);const h=e.getIndex(),d=this.vertexArrayUtils.getVAO(e,e.getAttributes(),h);if(l.setVertexState(d),r.occlusionQueryCount>0){const e=this.getOcclusionData(r),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===n.wireframe?(l.setLineWidth(n.wireframeLinewidth*this.renderer.getPixelRatio()),p.mode=o.LINES):p.mode=o.TRIANGLES;const{vertexCount:f,instanceCount:m}=c;let{firstVertex:g}=c;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),n=e.camera.cameras,s=e.getBindingGroup("cameraIndex").bindings[0];if(void 0===i.indexesGPU||i.indexesGPU.length!==n.length){const e=new Uint32Array([0,0,0,0]),t=[];for(let i=0,r=n.length;i<r;i++){const n=o.createBuffer();e[0]=i,o.bindBuffer(o.UNIFORM_BUFFER,n),o.bufferData(o.UNIFORM_BUFFER,e,o.STATIC_DRAW),t.push(n)}i.indexesGPU=t}let c=0;e:for(const t of e.getBindings())for(const e of t.bindings){if(e===s)break e;(e.isUniformsGroup||e.isUniformBuffer)&&c++}const u=this._currentContext.renderTarget,h=null===u||!0===u.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}=u;for(let e=0,i=n.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=r.frustumArray;for(let r=0,s=n.length;r<s;r++){const s=n[r];if(t.layers.test(s.layers)&&(!1===e.camera.perCameraFrustumCulled||!1===t.frustumCulled||t.intersectsFrustum(v.getFrustum(r)))){d&&(this.renderer._activeCubeFace=r,this._currentContext.activeCubeFace=r,this._setFramebuffer(this._currentContext));const n=s.viewport;if(void 0!==n){const t=n.x*h,i=n.y*h,r=n.width*h,s=n.height*h;l.viewport(Math.floor(t),Math.floor(e.context.height-s-i),Math.floor(r),Math.floor(s))}l.bindBufferBase(o.UNIFORM_BUFFER,c,i.indexesGPU[r]),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,n,r,s){return this.textureUtils.copyTextureToBuffer(e,t,i,n,r,s)}updateSampler(){return""}createNodeBuilder(e,t){return new Kw(e,t)}createProgram(e){const t=this.gl,{stage:i,code:n}=e,r="fragment"===i?t.createShader(t.FRAGMENT_SHADER):t.createShader(t.VERTEX_SHADER);t.shaderSource(r,n),t.compileShader(r),this.set(e,{shaderGPU:r})}destroyProgram(e){const t=this.gl,i=this.get(e);t.deleteShader(i.shaderGPU),this.delete(e)}createRenderPipeline(e,t){const i=this.gl,n=e.pipeline,{fragmentProgram:r,vertexProgram:s}=n,a=i.createProgram(),o=this.get(r).shaderGPU,l=this.get(s).shaderGPU;if(i.attachShader(a,o),i.attachShader(a,l),i.linkProgram(a),this.set(n,{programGPU:a,fragmentShader:o,vertexShader:l}),null!==t&&this.parallel){const r=new Promise(t=>{const r=this.parallel,s=()=>{i.getProgramParameter(a,r.COMPLETION_STATUS_KHR)?(this._completeCompile(e,n),t()):requestAnimationFrame(s)};s()});return void t.push(r)}this._completeCompile(e,n)}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"),n=[],r=Math.max(t-6,0),s=Math.min(t+6,i.length);for(let e=r;e<s;e++){const r=e+1;n.push(`${r===t?">":" "} ${r}: ${i[e]}`)}return n.join("\n")}_getShaderErrors(e,t,i){const n=e.getShaderParameter(t,e.COMPILE_STATUS),r=(e.getShaderInfoLog(t)||"").trim();if(n&&""===r)return"";const s=/ERROR: 0:(\d+)/.exec(r);if(s){const n=parseInt(s[1]);return i.toUpperCase()+"\n\n"+r+"\n\n"+this._handleSource(e.getShaderSource(t),n)}return r}_logProgramError(e,t,i){if(this.renderer.debug.checkShaderErrors){const n=this.gl,r=(n.getProgramInfoLog(e)||"").trim();if(!1===n.getProgramParameter(e,n.LINK_STATUS))if("function"==typeof this.renderer.debug.onShaderError)this.renderer.debug.onShaderError(n,e,i,t);else{const s=this._getShaderErrors(n,i,"vertex"),a=this._getShaderErrors(n,t,"fragment");Mi("WebGLProgram: Shader Error "+n.getError()+" - VALIDATE_STATUS "+n.getProgramParameter(e,n.VALIDATE_STATUS)+"\n\nProgram Info Log: "+r+"\n"+s+"\n"+a)}else""!==r&&Ti("WebGLProgram: Program Info Log:",r)}}_completeCompile(e,t){const{state:i,gl:n}=this,r=this.get(t),{programGPU:s,fragmentShader:a,vertexShader:o}=r;!1===n.getProgramParameter(s,n.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:n}=this,r={stage:"fragment",code:"#version 300 es\nprecision highp float;\nvoid main() {}"};this.createProgram(r);const{computeProgram:s}=e,a=n.createProgram(),o=this.get(r).shaderGPU,l=this.get(s).shaderGPU,c=e.transforms,u=[],h=[];for(let e=0;e<c.length;e++){const t=c[e];u.push(t.varyingName),h.push(t.attributeNode)}n.attachShader(a,o),n.attachShader(a,l),n.transformFeedbackVaryings(a,u,n.SEPARATE_ATTRIBS),n.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 r=this.parallel,s=new Promise(i=>{const s=()=>{n.getProgramParameter(a,r.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:n}=this,{programGPU:r,fragmentShader:s,vertexShader:a}=this.get(e);!1===n.getProgramParameter(r,n.LINK_STATUS)&&this._logProgramError(r,s,a),i.useProgram(r),this._setupBindings(t,r)}createBindings(e,t){if(!1===this._knownBindings.has(t)){this._knownBindings.add(t);let e=0,i=0;for(const n of t){this.set(n,{textures:i,uniformBuffers:e});for(const t of n.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 n=i.buffer,r=e.bufferGPU;t.bindBuffer(t.UNIFORM_BUFFER,r);const s=i.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,r),0===s.length)t.bufferData(t.UNIFORM_BUFFER,n,t.DYNAMIC_DRAW);else{const e=_i(n),i=e?1:n.BYTES_PER_ELEMENT;for(let r=0,a=s.length;r<a;r++){const a=s[r],o=a.start*i,l=a.count*i,c=o*(e?n.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,c,n,o,l)}}this.set(i,e)}else if(i.isSampledTexture){const{textureGPU:t,glTextureType:n}=this.get(i.texture);e.textureGPU=t,e.glTextureType=n,this.set(i,e)}}}updateBinding(e){const t=this.gl;if(e.isUniformsGroup||e.isUniformBuffer){const i=this.get(e).bufferGPU,n=e.buffer,r=e.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,i),0===r.length)t.bufferData(t.UNIFORM_BUFFER,n,t.DYNAMIC_DRAW);else{const e=_i(n),i=e?1:n.BYTES_PER_ELEMENT;let s=r[0].start;for(let a=0,o=r.length;a<o;a++){const o=r[a],l=r[a+1],c=o.start+o.count;if(void 0!==l&&l.start===c)continue;const u=s*i,h=(c-s)*i,d=u*(e?n.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,d,n,u,h),void 0!==l&&(s=l.start)}}}}createUniformBuffer(e){const t=this.get(e);if(void 0===t.bufferGPU){const i=this.gl,n=e.buffer;t.bufferGPU=i.createBuffer(),i.bindBuffer(i.UNIFORM_BUFFER,t.bufferGPU),i.bufferData(i.UNIFORM_BUFFER,n.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(gA).filter(t=>gA[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,n=null,r=0,s=0){this.textureUtils.copyTextureToTexture(e,t,i,n,r,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 n=null;if(null!==e.textures){const r=e.renderTarget,s=this.get(r),{depthBuffer:a,stencilBuffer:o}=r,l=!0===r.isCubeRenderTarget,c=!0===r.isXRRenderTarget,u=!0===c&&!0===r._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(r);let g=r.samples;null!==e.depthTexture&&e.depthTexture.renderTarget!==r&&!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 _=DM(e);let v;if(l?(s.cubeFramebuffers||(s.cubeFramebuffers={}),v=s.cubeFramebuffers[_]):c&&!1===u?v=this._xrFramebuffer:(s.framebuffers||(s.framebuffers={}),v=s.framebuffers[_]),void 0===v){v=t.createFramebuffer(),i.bindFramebuffer(t.FRAMEBUFFER,v);const n=e.textures,a=[];if(l){s.cubeFramebuffers[_]=v;const{textureGPU:i}=this.get(n[0]),r=e.activeCubeFace,a=e.activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+r,i,a)}else{s.framebuffers[_]=v;for(let i=0;i<n.length;i++){const s=n[i],a=this.get(s),o=t.COLOR_ATTACHMENT0+i;if(r.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,n=e.activeMipmapLevel;t.framebufferTextureLayer(t.FRAMEBUFFER,o,a.textureGPU,n,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 c=o?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(!0===r._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,c,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(r.multiview)f.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,c,i.textureGPU,0,g,0,2);else if(u&&m)p.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,c,t.TEXTURE_2D,i.textureGPU,0,g);else if(e.depthTexture.isArrayTexture){const n=e.activeCubeFace;t.framebufferTextureLayer(t.FRAMEBUFFER,c,i.textureGPU,0,n)}else if(e.depthTexture.isCubeTexture){const n=e.activeCubeFace;t.framebufferTexture2D(t.FRAMEBUFFER,c,t.TEXTURE_CUBE_MAP_POSITIVE_X+n,i.textureGPU,0)}else t.framebufferTexture2D(t.FRAMEBUFFER,c,t.TEXTURE_2D,i.textureGPU,0)}s.depthInvalidationArray=a}else{if(this._isRenderCameraDepthArray(e)){i.bindFramebuffer(t.FRAMEBUFFER,v);const n=e.activeCubeFace,r=this.get(e.depthTexture),s=o?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;t.framebufferTextureLayer(t.FRAMEBUFFER,s,r.textureGPU,0,n)}if((c||m||r.multiview)&&!0!==r._isOpaqueFramebuffer){if(i.bindFramebuffer(t.FRAMEBUFFER,v),e.textures.length>0){const i=this.get(e.textures[0]);r.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 n=o?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(!0===r._autoAllocateDepthBuffer){const e=s.xrDepthRenderbuffer;t.bindRenderbuffer(t.RENDERBUFFER,e),t.framebufferRenderbuffer(t.FRAMEBUFFER,n,t.RENDERBUFFER,e)}else{const i=this.get(e.depthTexture);r.multiview?f.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,n,i.textureGPU,0,g,0,2):m?p.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,n,t.TEXTURE_2D,i.textureGPU,0,g):t.framebufferTexture2D(t.FRAMEBUFFER,n,t.TEXTURE_2D,i.textureGPU,0)}}}if(g>0&&!1===m&&!r.multiview){if(void 0===h){h=t.createFramebuffer(),i.bindFramebuffer(t.FRAMEBUFFER,h);const n=[],r=e.textures;for(let i=0;i<r.length;i++){n[i]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,n[i]);const r=e.textures[i],s=this.get(r);t.renderbufferStorageMultisample(t.RENDERBUFFER,g,s.glInternalFormat,e.width,e.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+i,t.RENDERBUFFER,n[i])}t.bindRenderbuffer(t.RENDERBUFFER,null),s.msaaFrameBuffer=h,s.msaaRenderbuffers=n,a&&void 0===d&&(d=t.createRenderbuffer(),this.textureUtils.setupRenderBufferStorage(d,e,g),s.depthRenderbuffer=d)}n=s.msaaFrameBuffer}else n=v;i.drawBuffers(e,v)}i.bindFramebuffer(t.FRAMEBUFFER,n)}_setupBindings(e,t){const i=this.gl;let n=0,r=0;for(const s of e)for(const e of s.bindings)if(e.isUniformsGroup||e.isUniformBuffer){const r=n++,s=i.getUniformBlockIndex(t,e.name);i.uniformBlockBinding(t,s,r)}else if(e.isSampledTexture){const n=r++,s=i.getUniformLocation(t,e.name);i.uniform1i(s,n)}}_bindUniforms(e){const{gl:t,state:i}=this;let n=0,r=0;for(const s of e)for(const e of s.bindings){const s=this.get(e);if(e.isUniformsGroup||e.isUniformBuffer){const e=n++;i.bindBufferBase(t.UNIFORM_BUFFER,e,s.bufferGPU)}else if(e.isSampledTexture){const e=r++;i.bindTexture(s.glTextureType,s.textureGPU,t.TEXTURE0+e)}}}_resolveRenderTarget(e){const{gl:t,state:i}=this,n=e.renderTarget;if(null!==e.textures&&n){const r=this.get(n);if(n.samples>0&&void 0!==r.msaaFrameBuffer&&!1===this._useMultisampledExtension(n)){const s=r.framebuffers[e.getCacheKey()],a=e.textures;let o=!1===n.resolveColorBuffer||0===a.length?0:t.COLOR_BUFFER_BIT;n.resolveDepthBuffer&&(n.depthBuffer&&(o|=t.DEPTH_BUFFER_BIT),n.stencilBuffer&&n.resolveStencilBuffer&&(o|=t.STENCIL_BUFFER_BIT));const l=r.msaaFrameBuffer,c=r.msaaRenderbuffers,u=a.length>1,h=Math.max(a.length,1);if(i.bindFramebuffer(t.READ_FRAMEBUFFER,l),i.bindFramebuffer(t.DRAW_FRAMEBUFFER,s),u)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(u){const{textureGPU:e}=this.get(a[i]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,c[i]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0)}if(e.scissor){const{x:i,y:n,width:r,height:s}=e.scissorValue,a=e.height-s-n;t.blitFramebuffer(i,a,i+r,a+s,i,a,i+r,a+s,o,t.NEAREST)}else t.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,o,t.NEAREST)}if(u)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,c[e]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.TEXTURE_2D,i,0)}if(!0===this._supportsInvalidateFramebuffer){if(!1===n.storeMultisampledColorBuffer)for(let e=0;e<a.length;e++)yA.push(t.COLOR_ATTACHMENT0+e);n.depthBuffer&&!1===n.storeMultisampledDepthBuffer&&yA.push(n.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT),yA.length>0&&(t.invalidateFramebuffer(t.READ_FRAMEBUFFER,yA),yA.length=0)}}else if(!0===this._supportsInvalidateFramebuffer&&r.framebuffers&&(!0===n._autoAllocateDepthBuffer||n.samples>0&&!1===n.storeMultisampledDepthBuffer)){const n=r.framebuffers[e.getCacheKey()];i.bindFramebuffer(t.DRAW_FRAMEBUFFER,n),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,r.depthInvalidationArray)}}}_useMultisampledExtension(e){return!0===e.multiview||e.samples>0&&!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!1!==e._autoAllocateDepthBuffer}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 SA="point-list",TA="line-list",MA="line-strip",EA="triangle-list",wA="undefined"!=typeof self&&self.GPUShaderStage?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},AA="never",RA="less",CA="equal",NA="less-equal",PA="greater",LA="not-equal",DA="greater-equal",IA="always",FA="store",UA="discard",OA="load",BA="clear",kA="ccw",zA="cw",GA="none",VA="back",HA="uint16",WA="uint32",jA="r8unorm",$A="r8snorm",XA="r8uint",qA="r8sint",YA="r16uint",KA="r16sint",ZA="r16float",QA="rg8unorm",JA="rg8snorm",eR="rg8uint",tR="rg8sint",iR="r16unorm",nR="r16snorm",rR="r32uint",sR="r32sint",aR="r32float",oR="rg16uint",lR="rg16sint",cR="rg16float",uR="rgba8unorm",hR="rgba8unorm-srgb",dR="rgba8snorm",pR="rgba8uint",fR="rgba8sint",mR="bgra8unorm",gR="bgra8unorm-srgb",_R="rg16unorm",vR="rg16snorm",bR="rgb9e5ufloat",yR="rgb10a2unorm",xR="rg11b10ufloat",SR="rg32uint",TR="rg32sint",MR="rg32float",ER="rgba16uint",wR="rgba16sint",AR="rgba16float",RR="rgba16unorm",CR="rgba16snorm",NR="rgba32uint",PR="rgba32sint",LR="rgba32float",DR="depth16unorm",IR="depth24plus",FR="depth24plus-stencil8",UR="depth32float",OR="depth32float-stencil8",BR="bc1-rgba-unorm",kR="bc1-rgba-unorm-srgb",zR="bc2-rgba-unorm",GR="bc2-rgba-unorm-srgb",VR="bc3-rgba-unorm",HR="bc3-rgba-unorm-srgb",WR="bc4-r-unorm",jR="bc4-r-snorm",$R="bc5-rg-unorm",XR="bc5-rg-snorm",qR="bc6h-rgb-ufloat",YR="bc6h-rgb-float",KR="bc7-rgba-unorm",ZR="bc7-rgba-unorm-srgb",QR="etc2-rgb8unorm",JR="etc2-rgb8unorm-srgb",eC="etc2-rgb8a1unorm",tC="etc2-rgb8a1unorm-srgb",iC="etc2-rgba8unorm",nC="etc2-rgba8unorm-srgb",rC="eac-r11unorm",sC="eac-r11snorm",aC="eac-rg11unorm",oC="eac-rg11snorm",lC="astc-4x4-unorm",cC="astc-4x4-unorm-srgb",uC="astc-5x4-unorm",hC="astc-5x4-unorm-srgb",dC="astc-5x5-unorm",pC="astc-5x5-unorm-srgb",fC="astc-6x5-unorm",mC="astc-6x5-unorm-srgb",gC="astc-6x6-unorm",_C="astc-6x6-unorm-srgb",vC="astc-8x5-unorm",bC="astc-8x5-unorm-srgb",yC="astc-8x6-unorm",xC="astc-8x6-unorm-srgb",SC="astc-8x8-unorm",TC="astc-8x8-unorm-srgb",MC="astc-10x5-unorm",EC="astc-10x5-unorm-srgb",wC="astc-10x6-unorm",AC="astc-10x6-unorm-srgb",RC="astc-10x8-unorm",CC="astc-10x8-unorm-srgb",NC="astc-10x10-unorm",PC="astc-10x10-unorm-srgb",LC="astc-12x10-unorm",DC="astc-12x10-unorm-srgb",IC="astc-12x12-unorm",FC="astc-12x12-unorm-srgb",UC="clamp-to-edge",OC="repeat",BC="mirror-repeat",kC="linear",zC="nearest",GC="zero",VC="one",HC="src",WC="one-minus-src",jC="src-alpha",$C="one-minus-src-alpha",XC="dst",qC="one-minus-dst",YC="dst-alpha",KC="one-minus-dst-alpha",ZC="src-alpha-saturated",QC="constant",JC="one-minus-constant",eN="add",tN="subtract",iN="reverse-subtract",nN="min",rN="max",sN=0,aN=15,oN="keep",lN="zero",cN="replace",uN="invert",hN="increment-clamp",dN="decrement-clamp",pN="increment-wrap",fN="decrement-wrap",mN="storage",gN="read-only-storage",_N="write-only",vN="read-only",bN="read-write",yN="non-filtering",xN="comparison",SN="float",TN="unfilterable-float",MN="depth",EN="sint",wN="uint",AN="2d",RN="3d",CN="2d",NN="2d-array",PN="cube",LN="3d",DN="all",IN="depth-only",FN="vertex",UN="instance",ON={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"},BN={"texture-compression-s3tc":"texture-compression-bc","texture-compression-etc1":"texture-compression-etc2"};class kN extends Uw{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 zN extends Cw{constructor(e,t){super(e,t?t.array:null),this._attribute=t,this.isStorageBuffer=!0}get attribute(){return this._attribute}}let GN=0;class VN extends zN{constructor(e,t){super("StorageBuffer_"+(e&&e.name?e.name:GN++)),this.nodeUniform=e,this.access=e?e.access:bu,this.groupNode=t}get attribute(){return this.nodeUniform.value}get buffer(){return this.nodeUniform.value.array}}const HN=[null];class WN{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?OR:FR:!0===this.backend.renderer.reversedDepthBuffer?UR:IR),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,n=t>1&&null!==e.renderTarget&&!0===e.isDepthTexture&&!0===e.isArrayTexture;return{samples:t,primarySamples:i||n?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?SA:e.isLineSegments||e.isMesh&&!0===t.wireframe?TA:e.isLine?MA:e.isMesh?EA:void 0}getStripIndexFormat(e,t){if(null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments)return t.index.array instanceof Uint16Array?HA:WA}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 mR;if(e===Xe)return AR;throw new Error("THREE.WebGPUUtils: Unsupported output buffer type.")}}function jN(e,t){HN[0]=t,e.queue.submit(HN),HN[0]=null}class $N{constructor(){this.label="",this.layout=null,this.entries=[]}reset(){this.label="",this.layout=null,this.entries.length=0}}class XN{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 qN{constructor(){this.label=""}reset(){this.label=""}}class YN{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 KN{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 ZN{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 QN{constructor(){this.label="",this.layout=null,this.vertex=null,this.primitive={},this.depthStencil=void 0,this.multisample=new JN,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 JN{constructor(){this.count=1,this.mask=4294967295,this.alphaToCoverageEnabled=!1}reset(){this.count=1,this.mask=4294967295,this.alphaToCoverageEnabled=!1}}class eP{constructor(){this.label="",this.code="",this.compilationHints=[]}reset(){this.label="",this.code="",this.compilationHints.length=0}}class tP{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 iP{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 nP=new $N,rP=new XN,sP=new qN,aP=new YN,oP=new ZN,lP=new QN,cP=new KN,uP=new eP,hP=new tP,dP=new iP;class pP extends iM{constructor(e){super(),this.device=e;this.mipmapSampler=e.createSampler({minFilter:kC}),this.flipYSampler=e.createSampler({minFilter:zC}),rP.size=4,rP.usage=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,this.flipUniformBuffer=e.createBuffer(rP),rP.reset(),e.queue.writeBuffer(this.flipUniformBuffer,0,new Uint32Array([1])),rP.size=4,rP.usage=GPUBufferUsage.UNIFORM,this.noFlipUniformBuffer=e.createBuffer(rP),rP.reset(),this.transferPipelines={},uP.label="mipmap",uP.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(uP),uP.reset()}getTransferPipeline(e,t){const i=`${e}-${t=t||"2d-array"}`;let n=this.transferPipelines[i];return void 0===n&&(lP.label=`mipmap-${e}-${t}`,lP.vertex={module:this.mipmapShaderModule},lP.fragment={module:this.mipmapShaderModule,entryPoint:`main_${t.replace("-","_")}`,targets:[{format:e}]},lP.layout="auto",n=this.device.createRenderPipeline(lP),lP.reset(),this.transferPipelines[i]=n),n}flipY(e,t,i=0){const n=t.format,{width:r,height:s}=t.size;hP.size.width=r,hP.size.height=s,hP.format=n,hP.usage=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING;const a=this.device.createTexture(hP);hP.reset();const o=this.getTransferPipeline(n,e.textureBindingViewDimension),l=this.getTransferPipeline(n,a.textureBindingViewDimension),c=this.device.createCommandEncoder(sP),u=(e,t,i,n,r,s)=>{const a=e.getBindGroupLayout(0);dP.dimension=t.textureBindingViewDimension||"2d-array",dP.mipLevelCount=1;const o=t.createView(dP);dP.reset(),nP.layout=a,nP.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(nP);nP.reset(),dP.dimension="2d",dP.mipLevelCount=1,dP.baseArrayLayer=r,dP.arrayLayerCount=1;const u=n.createView(dP);dP.reset(),cP.view=u,cP.loadOp=BA,cP.storeOp=FA,oP.colorAttachments.push(cP);const h=c.beginRenderPass(oP);oP.reset(),cP.reset(),h.setPipeline(e),h.setBindGroup(0,l),h.draw(3,1,0,i),h.end()};u(o,e,i,a,0,!1),u(l,a,0,e,i,!0),jN(this.device,c.finish()),a.destroy()}generateMipmaps(e,t=null){const i=this.get(e),n=i.layers||this._mipmapCreateBundles(e);let r=t;null===r&&(sP.label="mipmapEncoder",r=this.device.createCommandEncoder(sP),sP.reset()),this._mipmapRunBundles(r,n),null===t&&jN(this.device,r.finish()),i.layers=n}_mipmapCreateBundles(e){const t=e.textureBindingViewDimension||"2d-array",i=this.getTransferPipeline(e.format,t),n=i.getBindGroupLayout(0),r=[];for(let s=1;s<e.mipLevelCount;s++)for(let a=0;a<e.depthOrArrayLayers;a++){dP.dimension=t,dP.baseMipLevel=s-1,dP.mipLevelCount=1;const o=e.createView(dP);dP.reset(),nP.layout=n,nP.entries.push({binding:0,resource:this.mipmapSampler},{binding:1,resource:o},{binding:2,resource:{buffer:this.noFlipUniformBuffer}});const l=this.device.createBindGroup(nP);nP.reset(),dP.dimension="2d",dP.baseMipLevel=s,dP.mipLevelCount=1,dP.baseArrayLayer=a,dP.arrayLayerCount=1;const c=e.createView(dP);dP.reset();const u=new KN;u.view=c,u.loadOp=BA,u.storeOp=FA;const h=new ZN;h.colorAttachments.push(u),aP.colorFormats=[e.format];const d=this.device.createRenderBundleEncoder(aP);aP.reset(),d.setPipeline(i),d.setBindGroup(0,l),d.draw(3,1,0,a),r.push({renderBundles:[d.finish()],passDescriptor:h})}return r}_mipmapRunBundles(e,t){const i=t.length;for(let n=0;n<i;n++){const i=t[n],r=e.beginRenderPass(i.passDescriptor);r.executeBundles(i.renderBundles),r.end()}}}class fP{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 mP{constructor(){this.width=0,this.height=1,this.depthOrArrayLayers=1}reset(){this.width=0,this.height=1,this.depthOrArrayLayers=1}}const gP=new XN,_P=new qN,vP=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}},bP=new fP,yP=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}},xP=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}},SP=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}},TP=new class extends fP{constructor(){super(),this.colorSpace="srgb",this.premultipliedAlpha=!1}reset(){super.reset(),this.colorSpace="srgb",this.premultipliedAlpha=!1}},MP=new tP,EP=new mP,wP={[Qt]:"never",[Jt]:"less",[ei]:"equal",[ti]:"less-equal",[ii]:"greater",[ri]:"greater-equal",[si]:"always",[ni]:"not-equal"},AP=[0,1,3,2,4,5];function RP(e,t,i,n,r,s,a,o,l,c){bP.texture=t,bP.mipLevel=i,bP.origin.z=n,xP.offset=s,xP.bytesPerRow=a,xP.rowsPerImage=o,EP.width=l,EP.height=c,e.queue.writeTexture(bP,r.data,xP,EP),bP.reset(),xP.reset(),EP.reset()}class CP{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,n=e.textureNode,r=!0===i.isDepthTexture&&null!==i.compareFunction&&n.isSampleCompare()&&t.hasCompatibility(pi),s=i.minFilter+"-"+i.magFilter+"-"+i.wrapS+"-"+i.wrapT+"-"+(i.wrapR||"0")+"-"+i.anisotropy+"-"+(!0===i.isDepthTexture?1:0)+"-"+(r?i.compareFunction:0);let a=this._samplerCache.get(s);if(void 0===a){vP.addressModeU=this._convertAddressMode(i.wrapS),vP.addressModeV=this._convertAddressMode(i.wrapT),vP.addressModeW=this._convertAddressMode(i.wrapR),vP.magFilter=this._convertFilterMode(i.magFilter),vP.minFilter=this._convertFilterMode(i.minFilter),vP.mipmapFilter=this._convertMipmapFilterMode(i.minFilter),i.isDepthTexture&&!1===r&&(vP.magFilter=zC,vP.minFilter=zC,vP.mipmapFilter=zC),vP.magFilter===kC&&vP.minFilter===kC&&vP.mipmapFilter===kC&&(vP.maxAnisotropy=i.anisotropy),r&&(vP.compare=wP[i.compareFunction]);const e=t.device.createSampler(vP);vP.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=NP(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,n=i.get(e);if(n.initialized){if(!0===n.externalTexture)return;throw new Error("THREE.WebGPUTextureUtils: Texture already initialized.")}if(e.isExternalTexture)return n.texture=e.sourceTexture,void(n.initialized=!0);void 0===t.needsMipmaps&&(t.needsMipmaps=!1),void 0===t.levels&&(t.levels=1),void 0===t.depth&&(t.depth=1);const{width:r,height:s,depth:a,levels:o}=t;e.isFramebufferTexture&&(t.renderTarget?t.format=this.backend.utils.getCurrentColorFormat(t.renderTarget):t.format=this.backend.utils.getPreferredCanvasFormat());const l=this._getDimension(e),c=e.internalFormat||t.format||NP(e,i.device);n.format=c;const{samples:u,primarySamples:h,isMSAA:d}=i.utils.getTextureSampleData(e),p=e.renderTarget,f=u>1&&null!==p&&a>1&&l===AN,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&&c!==bR&&(v|=GPUTextureUsage.RENDER_ATTACHMENT),h>1&&g&&(v=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TRANSIENT_ATTACHMENT);const b=new tP;if(b.label=e.name,b.size.width=r,b.size.height=s,b.size.depthOrArrayLayers=a,b.mipLevelCount=o,b.sampleCount=h,b.dimension=l,b.format=c,b.usage=v,void 0===c)return Ti("WebGPURenderer: Texture format not supported."),void this.createDefaultTexture(e);e.isCubeTexture&&(b.textureBindingViewDimension=PN);try{n.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=u,e.mipLevelCount=1,(g||_)&&(e.usage=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TRANSIENT_ATTACHMENT),f){e.size=Object.assign({},e.size,{depthOrArrayLayers:1}),n.msaaTextures=[];for(let t=0;t<a;t++)e.label=b.label+"-msaa-"+t,n.msaaTextures.push(i.device.createTexture(e))}else n.msaaTexture=i.device.createTexture(e)}n.initialized=!0,n.textureDescriptorGPU=b}destroyTexture(e,t=!1){const i=this.backend,n=i.get(e);if(void 0!==n.texture&&!1===t&&!0!==e.isExternalTexture&&!0!==n.externalTexture&&n.texture.destroy(),void 0!==n.msaaTexture&&n.msaaTexture.destroy(),void 0!==n.msaaTextures)for(const e of n.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:n}=e.getDrawingBufferSize(),r=e.renderer.currentSamples,s=t.colorTexture,a=e.get(s);if(void 0!==a.texture&&s.width===i&&s.height===n&&s.samples===r)return a.texture;let o=a.texture;return o&&o.destroy(),MP.label="colorBuffer",MP.size.width=i,MP.size.height=n,MP.sampleCount=e.utils.getSampleCount(e.renderer.currentSamples),MP.format=e.utils.getPreferredCanvasFormat(),MP.usage=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,o=e.device.createTexture(MP),MP.reset(),s.image.width=i,s.image.height=n,s.samples=r,a.texture=o,o}getDepthBuffer(e=!0,t=!1){const i=this.backend,n=i.renderer.getCanvasTarget(),{width:r,height:s}=i.getDrawingBufferSize(),a=i.renderer.currentSamples,o=n.depthTexture;if(o.width===r&&o.height===s&&o.samples===a&&o.depth===e&&o.stencil===t)return i.get(o).texture;const l=i.get(o).texture;let c,u;if(t?(c=nt,u=!0===i.renderer.reversedDepthBuffer?$e:Ke):e&&(c=it,u=!0===i.renderer.reversedDepthBuffer?$e:je),void 0!==l){if(o.image.width===r&&o.image.height===s&&o.format===c&&o.type===u&&o.samples===a)return l;this.destroyTexture(o)}return o.name="depthBuffer",o.format=c,o.type=u,o.image.width=r,o.image.height=s,o.samples=a,this.createTexture(o,{width:r,height:s}),i.get(o).texture}updateTexture(e,t){const i=this.backend.get(e),n=e.mipmaps,{textureDescriptorGPU:r}=i;if(!e.isRenderTargetTexture&&void 0!==r){if(e.isDataTexture)if(n.length>0)for(let t=0,s=n.length;t<s;t++){const s=n[t];this._copyBufferToTexture(s,i.texture,r,0,e.flipY,0,t)}else this._copyBufferToTexture(t.image,i.texture,r,0,e.flipY);else if(e.isArrayTexture||e.isDataArrayTexture||e.isData3DTexture)if(e.layerUpdates&&e.layerUpdates.size>0){for(const n of e.layerUpdates)this._copyBufferToTexture(t.image,i.texture,r,n,e.flipY,n);e.clearLayerUpdates()}else for(let n=0;n<t.image.depth;n++)this._copyBufferToTexture(t.image,i.texture,r,n,e.flipY,n);else if(e.isCompressedTexture||e.isCompressedArrayTexture)if(e.isCompressedCubeTexture)for(let t=0;t<6;t++)this._copyCompressedBufferToTexture(e.image[t].mipmaps,i.texture,r,null,t);else e.isCompressedArrayTexture&&e.layerUpdates.size>0?(this._copyCompressedBufferToTexture(e.mipmaps,i.texture,r,e.layerUpdates),e.clearLayerUpdates()):this._copyCompressedBufferToTexture(e.mipmaps,i.texture,r);else if(e.isCubeTexture)this._copyCubeMapToTexture(e,i.texture,r);else if(e.isHTMLTexture){const t=this.backend.device,n=this.backend.renderer.domElement,s=e.image;if("function"!=typeof t.queue.copyElementImageToTexture)return;if(!i.hasPaintCallback)return i.hasPaintCallback=!0,void n.requestPaint();const a=r.size.width,o=r.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,r)}else if(n.length>0)for(let t=0,s=n.length;t<s;t++){const s=n[t];this._copyImageToTexture(s,i.texture,r,0,e.flipY,e.premultiplyAlpha,t)}else this._copyImageToTexture(t.image,i.texture,r,0,e.flipY,e.premultiplyAlpha);i.version=e.version}}async copyTextureToBuffer(e,t,i,n,r,s){const a=this.backend.device,o=this.backend.get(e),l=o.texture,c=o.textureDescriptorGPU.format,u=n*this._getBytesPerTexel(c),h=256*Math.ceil(u/256);gP.size=r*h,gP.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ;const d=a.createBuffer(gP);gP.reset();const p=a.createCommandEncoder(_P);bP.texture=l,bP.origin.x=t,bP.origin.y=i,bP.origin.z=s,yP.buffer=d,yP.bytesPerRow=h,EP.width=n,EP.height=r,p.copyTextureToBuffer(bP,yP,EP),bP.reset(),yP.reset(),EP.reset();const f=this._getTypedArrayType(c);jN(a,p.finish()),await d.mapAsync(GPUMapMode.READ);const m=new Uint8Array(d.getMappedRange()),g=new Uint8Array(u*r);for(let e=0;e<r;e++){const t=e*h;g.set(m.subarray(t,t+u),e*u)}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 cn;i.minFilter=Ie,i.magFilter=Ie,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 sa;i.minFilter=Ie,i.magFilter=Ie,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 n=e.images,r=e.mipmaps;for(let s=0;s<6;s++){const a=n[s],o=!0===e.flipY?AP[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 n=0;n<r.length;n++){const a=r[n].images[s];a.isDataTexture?this._copyBufferToTexture(a.image,t,i,o,e.flipY,0,n+1):this._copyImageToTexture(a,t,i,o,e.flipY,e.premultiplyAlpha,n+1)}}}_copyImageToTexture(e,t,i,n,r,s,a=0){const o=this.backend.device,l=a>0?e.width:i.size.width,c=a>0?e.height:i.size.height;SP.source=e,SP.flipY=r,TP.texture=t,TP.mipLevel=a,TP.origin.z=n,TP.premultipliedAlpha=s,EP.width=l,EP.height=c;try{o.queue.copyExternalImageToTexture(SP,TP,EP)}catch(e){}finally{SP.reset(),TP.reset(),EP.reset()}}_getPassUtils(){let e=this._passUtils;return null===e&&(this._passUtils=e=new pP(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,n,r,s=0,a=0){const o=this.backend.device,l=e.data,c=this._getBytesPerTexel(i.format),u=e.width*c;bP.texture=t,bP.mipLevel=a,bP.origin.z=n,xP.offset=e.width*e.height*c*s,xP.bytesPerRow=u,EP.width=e.width,EP.height=e.height,o.queue.writeTexture(bP,l,xP,EP),bP.reset(),xP.reset(),EP.reset(),!0===r&&this._flipY(t,i,n)}_copyCompressedBufferToTexture(e,t,i,n=null,r=-1){const s=this.backend.device,a=this._getBlockData(i.format),o=i.size.depthOrArrayLayers>1,l=n&&n.size>0?n:null;for(let n=0;n<e.length;n++){const c=e[n],u=c.width,h=c.height,d=o?i.size.depthOrArrayLayers:1,p=Math.ceil(u/a.width)*a.byteLength,f=Math.ceil(h/a.height),m=p*f,g=Math.ceil(u/a.width)*a.width,_=f*a.height;if(-1!==r)RP(s,t,n,r,c,0,p,f,g,_);else if(null!==l)for(const e of l)RP(s,t,n,e,c,e*m,p,f,g,_);else for(let e=0;e<d;e++)RP(s,t,n,e,c,e*m,p,f,g,_)}}_getBlockData(e){return e===BR||e===kR?{byteLength:8,width:4,height:4}:e===zR||e===GR||e===VR||e===HR?{byteLength:16,width:4,height:4}:e===WR||e===jR?{byteLength:8,width:4,height:4}:e===$R||e===XR||e===qR||e===YR||e===KR||e===ZR?{byteLength:16,width:4,height:4}:e===QR||e===JR||e===eC||e===tC?{byteLength:8,width:4,height:4}:e===iC||e===nC?{byteLength:16,width:4,height:4}:e===rC||e===sC?{byteLength:8,width:4,height:4}:e===aC||e===oC||e===lC||e===cC?{byteLength:16,width:4,height:4}:e===uC||e===hC?{byteLength:16,width:5,height:4}:e===dC||e===pC?{byteLength:16,width:5,height:5}:e===fC||e===mC?{byteLength:16,width:6,height:5}:e===gC||e===_C?{byteLength:16,width:6,height:6}:e===vC||e===bC?{byteLength:16,width:8,height:5}:e===yC||e===xC?{byteLength:16,width:8,height:6}:e===SC||e===TC?{byteLength:16,width:8,height:8}:e===MC||e===EC?{byteLength:16,width:10,height:5}:e===wC||e===AC?{byteLength:16,width:10,height:6}:e===RC||e===CC?{byteLength:16,width:10,height:8}:e===NC||e===PC?{byteLength:16,width:10,height:10}:e===LC||e===DC?{byteLength:16,width:12,height:10}:e===IC||e===FC?{byteLength:16,width:12,height:12}:{byteLength:this._getBytesPerTexel(e),width:1,height:1}}_convertAddressMode(e){let t=UC;return e===Pe?t=OC:e===De&&(t=BC),t}_convertFilterMode(e){let t=kC;return e!==Ie&&e!==Fe&&e!==Ue||(t=zC),t}_convertMipmapFilterMode(e){return e===Ue||e===ke?kC:zC}_getBytesPerTexel(e){return e===jA||e===$A||e===XA||e===qA?1:e===YA||e===KA||e===ZA||e===QA||e===JA||e===eR||e===tR||e===iR||e===nR?2:e===rR||e===sR||e===aR||e===oR||e===lR||e===cR||e===uR||e===hR||e===dR||e===pR||e===fR||e===mR||e===gR||e===_R||e===vR||e===bR||e===yR||e===xR||e===UR||e===IR||e===FR||e===OR?4:e===SR||e===TR||e===MR||e===ER||e===wR||e===AR||e===RR||e===CR?8:e===NR||e===PR||e===LR?16:void 0}_getTypedArrayType(e){return e===XA?Uint8Array:e===qA?Int8Array:e===jA?Uint8Array:e===$A?Int8Array:e===eR?Uint8Array:e===tR?Int8Array:e===QA?Uint8Array:e===JA?Int8Array:e===pR?Uint8Array:e===fR?Int8Array:e===uR||e===hR?Uint8Array:e===dR?Int8Array:e===YA?Uint16Array:e===KA?Int16Array:e===oR?Uint16Array:e===lR?Int16Array:e===ER?Uint16Array:e===wR?Int16Array:e===ZA||e===cR||e===AR||e===iR?Uint16Array:e===nR?Int16Array:e===_R?Uint16Array:e===vR?Int16Array:e===RR?Uint16Array:e===CR?Int16Array:e===rR?Uint32Array:e===sR?Int32Array:e===aR?Float32Array:e===SR?Uint32Array:e===TR?Int32Array:e===MR?Float32Array:e===NR?Uint32Array:e===PR?Int32Array:e===LR?Float32Array:e===mR||e===gR?Uint8Array:e===yR||e===bR||e===xR?Uint32Array:e===UR?Float32Array:e===IR||e===FR?Uint32Array:e===OR?Float32Array:void 0}_getDimension(e){let t;return t=e.is3DTexture||e.isData3DTexture?RN:AN,t}}function NP(e,t){const i=e.format,n=e.type,r=e.normalized,s=e.colorSpace,a=Qi.getTransfer(s);let o,l=!1;if(r&&(l=t.features.has(ON.TextureFormatsTier1),!1===l&&Ti("WebGPURenderer: Unable to use normalized textures without texture-formats-tier1 feature.")),!0===e.isCompressedTexture||!0===e.isCompressedArrayTexture)switch(i){case ut:case ht:o=a===Kt?kR:BR;break;case dt:o=a===Kt?GR:zR;break;case pt:o=a===Kt?HR:VR;break;case Vt:o=WR;break;case Ht:o=jR;break;case Wt:o=$R;break;case jt:o=XR;break;case kt:o=a===Kt?ZR:KR;break;case zt:o=YR;break;case Gt:o=qR;break;case bt:case vt:o=a===Kt?JR:QR;break;case yt:o=a===Kt?nC:iC;break;case xt:o=rC;break;case St:o=sC;break;case Tt:o=aC;break;case Mt:o=oC;break;case Et:o=a===Kt?cC:lC;break;case wt:o=a===Kt?hC:uC;break;case At:o=a===Kt?pC:dC;break;case Rt:o=a===Kt?mC:fC;break;case Ct:o=a===Kt?_C:gC;break;case Nt:o=a===Kt?bC:vC;break;case Pt:o=a===Kt?xC:yC;break;case Lt:o=a===Kt?TC:SC;break;case Dt:o=a===Kt?EC:MC;break;case It:o=a===Kt?AC:wC;break;case Ft:o=a===Kt?CC:RC;break;case Ut:o=a===Kt?PC:NC;break;case Ot:o=a===Kt?DC:LC;break;case Bt:o=a===Kt?FC:IC;break;case tt:o=n===Xe?AR:a===Kt?hR:uR;break;default:Mi("WebGPURenderer: Unsupported texture format.",i)}else switch(i){case tt:switch(n){case Ge:o=dR;break;case Ve:o=l?CR:wR;break;case He:o=l?RR:ER;break;case je:o=NR;break;case We:o=PR;break;case ze:o=a===Kt?hR:uR;break;case Xe:o=AR;break;case $e:o=LR;break;default:Mi("WebGPURenderer: Unsupported texture type with RGBAFormat.",n)}break;case et:switch(n){case Ze:o=bR;break;case Qe:o=xR;break;default:Mi("WebGPURenderer: Unsupported texture type with RGBFormat.",n)}break;case rt:switch(n){case Ge:o=$A;break;case Ve:o=l?nR:KA;break;case He:o=l?iR:YA;break;case je:o=rR;break;case We:o=sR;break;case ze:o=jA;break;case Xe:o=ZA;break;case $e:o=aR;break;default:Mi("WebGPURenderer: Unsupported texture type with RedFormat.",n)}break;case at:switch(n){case Ge:o=JA;break;case Ve:o=l?vR:lR;break;case He:o=l?_R:oR;break;case je:o=SR;break;case We:o=TR;break;case ze:o=QA;break;case Xe:o=cR;break;case $e:o=MR;break;default:Mi("WebGPURenderer: Unsupported texture type with RGFormat.",n)}break;case it:switch(n){case He:o=DR;break;case je:o=IR;break;case $e:o=UR;break;default:Mi("WebGPURenderer: Unsupported texture type with DepthFormat.",n)}break;case nt:switch(n){case Ke:o=FR;break;case $e:t&&!1===t.features.has(ON.Depth32FloatStencil8)&&Mi('WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.'),o=OR;break;default:Mi("WebGPURenderer: Unsupported texture type with DepthStencilFormat.",n)}break;case st:switch(n){case We:o=sR;break;case je:o=rR;break;default:Mi("WebGPURenderer: Unsupported texture type with RedIntegerFormat.",n)}break;case ot:switch(n){case We:o=TR;break;case je:o=SR;break;default:Mi("WebGPURenderer: Unsupported texture type with RGIntegerFormat.",n)}break;case ct:switch(n){case We:o=PR;break;case je:o=NR;break;default:Mi("WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.",n)}break;default:Mi("WebGPURenderer: Unsupported texture format.",i)}return o}const PP=/^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,LP=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,DP={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 IP extends WE{constructor(e){const{type:t,inputs:i,name:n,inputsCode:r,blockCode:s,outputType:a}=(e=>{const t=(e=e.replace(/^(?:\s*\/\/[^\r\n]*|\s*\/\*[\s\S]*?\*\/|\s*)+/,"")).match(PP);if(null!==t&&4===t.length){const i=t[2],n=[];let r=null;for(;null!==(r=LP.exec(i));)n.push({name:r[1],type:r[2]});const s=[];for(let e=0;e<n.length;e++){const{name:t,type:i}=n[e];let r=i;r.startsWith("ptr")?r="pointer":(r.startsWith("texture")&&(r=i.split("<")[0]),r=DP[r]),s.push(new PE(r,t))}const a=e.substring(t[0].length),o=t[3]||"void",l=void 0!==t[1]?t[1]:"";return{type:DP[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,n),this.inputsCode=r,this.blockCode=s,this.outputType=a}getCode(e=this.name){const t="void"!==this.outputType?"-> "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class FP extends HE{parseFunction(e){return new IP(e)}}const UP={[_u]:"read",[vu]:"write",[bu]:"read_write"},OP={[Pe]:"repeat",[Le]:"clamp",[De]:"mirror"},BP={vertex:wA.VERTEX,fragment:wA.FRAGMENT,compute:wA.COMPUTE},kP={instance:!0,swizzleAssign:!1,storageBuffer:!0},zP={"^^":"tsl_xor"},GP={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>"},VP={},HP={tsl_xor:new Vy("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new Vy("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new Vy("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new Vy("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new Vy("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new Vy("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new Vy("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new Vy("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 Vy("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 Vy("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new Vy("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 Vy("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),inverse_mat2:new Vy("\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 Vy("\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 Vy("\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 Vy("\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 Vy("\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")},WP={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"},jP=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 $P="";!0!==("undefined"!=typeof navigator&&/Firefox|Deno/g.test(navigator.userAgent))&&($P+="diagnostic( off, derivative_uniformity );\n");class XP extends CE{constructor(e,t){super(e,t,new FP),this.uniformGroups={},this.uniformGroupsBindings={},this.builtins={},this.directives={},this.scopedArrays=new Map,this.allowEarlyReturns=!0,this.allowGlobalVariables=!0}_generateTextureSample(e,t,i,n,r,s=this.shaderStage){return"fragment"===s?n?r?`textureSample( ${t}, ${t}_sampler, ${i}, ${n}, ${r} )`:`textureSample( ${t}, ${t}_sampler, ${i}, ${n} )`:r?`textureSample( ${t}, ${t}_sampler, ${i}, ${r} )`:`textureSample( ${t}, ${t}_sampler, ${i} )`:this.generateTextureSampleLevel(e,t,i,"0",n)}generateTextureSampleLevel(e,t,i,n,r,s){return!1===this.isUnfilterable(e)?r?s?`textureSampleLevel( ${t}, ${t}_sampler, ${i}, ${r}, ${n}, ${s} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${i}, ${r}, ${n} )`:s?`textureSampleLevel( ${t}, ${t}_sampler, ${i}, ${n}, ${s} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${i}, ${n} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,i,s,n,r):this.generateTextureLod(e,t,i,r,s,n)}generateWrapFunction(e){const t=`tsl_coord_${OP[e.wrapS]}S_${OP[e.wrapT]}T_${e.is3DTexture||e.isData3DTexture?"3d":"2d"}`;let i=VP[t];if(void 0===i){const n=[],r=e.is3DTexture||e.isData3DTexture?"vec3f":"vec2f";let s=`fn ${t}( coord : ${r} ) -> ${r} {\n\n\treturn ${r}(\n`;const a=(e,t)=>{e===Pe?(n.push(HP.repeatWrapping_float),s+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===Le?(n.push(HP.clampWrapping_float),s+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===De?(n.push(HP.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",VP[t]=i=new Vy(s,n)}return i.build(this),t}generateArrayDeclaration(e,t){return`array< ${this.getType(e)}, ${t} >`}generateTextureDimension(e,t,i){const n=this.getDataFromNode(e,this.shaderStage,this.cache);void 0===n.dimensionsSnippet&&(n.dimensionsSnippet={});let r=n.dimensionsSnippet[i];if(void 0===n.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} )`:""}`,r=new Gf(new xm(`textureDimensions( ${s} )`,a)),n.dimensionsSnippet[i]=r,(e.isArrayTexture||e.isDataArrayTexture||e.is3DTexture||e.isData3DTexture)&&(n.arrayLayerCount=new Gf(new xm(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(n.cubeFaceCount=new Gf(new xm("6u","u32")))}return r.build(this)}generateTextureSize(e,t,i){const{primarySamples:n}=this.renderer.backend.utils.getTextureSampleData(e);return`textureDimensions( ${n>1||e.isStorageTexture?t:`${t}, ${i}`} )`}generateFilteredTexture(e,t,i,n,r="0u",s){const a=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,r);return n&&(i=`${i} + vec2<f32>(${n}) / ${o}`),s?(this._include("biquadraticTextureArray"),`tsl_biquadraticTexture_array( ${t}, ${a}( ${i} ), ${o}, u32( ${s} ), u32( ${r} ) )`):(this._include("biquadraticTexture"),`tsl_biquadraticTexture( ${t}, ${a}( ${i} ), ${o}, u32( ${r} ) )`)}generateTextureLod(e,t,i,n,r,s="0u"){if(!0===e.isCubeTexture){r&&(i=`${i} + vec3<f32>(${r})`);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";r&&(i=`${i} + ${l}<f32>(${r}) / ${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,n,null)}generateStorageTextureLoad(e,t,i,n,r,s){let a;return s&&(i=`${i} + ${s}`),a=r?`textureLoad( ${t}, ${i}, ${r} )`:`textureLoad( ${t}, ${i} )`,a}generateTextureLoad(e,t,i,n,r,s){let a;return null===n&&(n="0u"),s&&(i=`${i} + ${s}`),r?a=`textureLoad( ${t}, ${i}, ${r}, u32( ${n} ) )`:(a=`textureLoad( ${t}, ${i}, u32( ${n} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(a+=".x")),a}generateTextureStore(e,t,i,n,r){let s;return s=n?`textureStore( ${t}, ${i}, ${n}, ${r} )`:`textureStore( ${t}, ${i}, ${r} )`,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===Ie&&e.magFilter===Ie||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1||!0===e.normalized&&(e.type===Ve||e.type===He)}generateTexture(e,t,i,n,r,s=this.shaderStage){let a=null;return a=this.isUnfilterable(e)?this.generateTextureLod(e,t,i,n,r,"0",s):this._generateTextureSample(e,t,i,n,r,s),a}generateTextureGrad(e,t,i,n,r,s,a=this.shaderStage){if("fragment"===a)return this.isUnfilterable(e)?this.generateTexture(e,t,i,r,s,a):r?s?`textureSampleGrad( ${t}, ${t}_sampler, ${i}, ${r}, ${n[0]}, ${n[1]}, ${s} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${i}, ${r}, ${n[0]}, ${n[1]} )`:s?`textureSampleGrad( ${t}, ${t}_sampler, ${i}, ${n[0]}, ${n[1]}, ${s} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${i}, ${n[0]}, ${n[1]} )`;Mi(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${a} shader.`)}generateTextureCompare(e,t,i,n,r,s,a=this.shaderStage){if("fragment"===a)return!0===e.isDepthTexture&&!0===e.isArrayTexture?s?`textureSampleCompare( ${t}, ${t}_sampler, ${i}, ${r}, ${n}, ${s} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${i}, ${r}, ${n} )`:s?`textureSampleCompare( ${t}, ${t}_sampler, ${i}, ${n}, ${s} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${i}, ${n} )`;Mi(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${a} shader.`)}generateTextureGather(e,t,i,n,r,s){const{primarySamples:a}=this.renderer.backend.utils.getTextureSampleData(e);if(a>1){const r=this.generateTextureDimension(e,t,"0u");let a=`vec2<i32>( floor( ${i} * vec2<f32>( ${r} ) - 0.5 ) )`;s&&(a=`${a} + ${s}`);const o=new Gf(new xm(a,"ivec2")).build(this),l=`vec2<i32>( ${r} ) - 1`,c=(i,r)=>{const s=this.generateTextureLoad(e,t,`clamp( ${o} + vec2<i32>( ${i}, ${r} ), vec2<i32>( 0 ), ${l} )`,null,null,null);return!0===e.isDepthTexture?s:`${s}[ ${n} ]`};return`vec4<${this.getComponentTypeFromTexture(e).charAt(0)}32>( ${c(0,1)}, ${c(1,1)}, ${c(1,0)}, ${c(0,0)} )`}const o=!0===e.isDepthTexture?"":`${n}, `;return r?s?`textureGather( ${o}${t}, ${t}_sampler, ${i}, ${r}, ${s} )`:`textureGather( ${o}${t}, ${t}_sampler, ${i}, ${r} )`:s?`textureGather( ${o}${t}, ${t}_sampler, ${i}, ${s} )`:`textureGather( ${o}${t}, ${t}_sampler, ${i})`}generateTextureGatherCompare(e,t,i,n,r,s){return r?s?`textureGatherCompare( ${t}, ${t}_sampler, ${i}, ${r}, ${n}, ${s} )`:`textureGatherCompare( ${t}, ${t}_sampler, ${i}, ${r}, ${n})`:s?`textureGatherCompare( ${t}, ${t}_sampler, ${i}, ${n}, ${s} )`:`textureGatherCompare( ${t}, ${t}_sampler, ${i}, ${n})`}generateTextureLevel(e,t,i,n,r,s){return!1===this.isUnfilterable(e)?r?s?`textureSampleLevel( ${t}, ${t}_sampler, ${i}, ${r}, ${n}, ${s} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${i}, ${r}, ${n} )`:s?`textureSampleLevel( ${t}, ${t}_sampler, ${i}, ${n}, ${s} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${i}, ${n} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,i,s,n,r):this.generateTextureLod(e,t,i,r,s,n)}generateTextureBias(e,t,i,n,r,s,a=this.shaderStage){if("fragment"===a)return r?s?`textureSampleBias( ${t}, ${t}_sampler, ${i}, ${r}, ${n}, ${s} )`:`textureSampleBias( ${t}, ${t}_sampler, ${i}, ${r}, ${n} )`:s?`textureSampleBias( ${t}, ${t}_sampler, ${i}, ${n}, ${s} )`:`textureSampleBias( ${t}, ${t}_sampler, ${i}, ${n} )`;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 jP.has(e)}getOutputStructName(){return"output"}getFunctionOperator(e){const t=zP[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."),_u):bu:"fragment"===t&&!0===e.isStorageTextureNode&&e.access===bu?bu:_u:e.access}getStorageAccess(e,t){return UP[this.getNodeAccess(e,t)]}getUniformFromNode(e,t,i,n=null){const r=super.getUniformFromNode(e,t,i,n),s=this.getDataFromNode(e,i,this.globalCache);if(void 0===s.uniformGPU){let n;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 Gw(r.name,r.node,a,o):new kw(r.name,r.node,a,o):"cubeTexture"===t||"cubeDepthTexture"===t?s=new zw(r.name,r.node,a,o):"texture3D"===t&&(s=new Gw(r.name,r.node,a,o)),s.store=!0===e.isStorageTextureNode,s.mipLevel=s.store?e.mipLevel:0,s.setVisibility(BP[i]);if(!0===e.value.isCubeTexture||!1===this.isUnfilterable(e.value)&&!1===s.store||null!==e.gatherNode){const e=new kN(`${r.name}_sampler`,r.node,a);e.setVisibility(BP[i]),l.push(e,s),n=[e,s]}else l.push(s),n=[s]}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const r=new("buffer"===t?Lw:VN)(e,a);r.setVisibility(BP[i]),l.push(r),n=r}else{let e=this.uniformGroups[o];void 0===e&&(e=new Fw(o,a),e.setVisibility(wA.VERTEX|wA.FRAGMENT|wA.COMPUTE),this.uniformGroups[o]=e),-1===l.indexOf(e)&&l.push(e),n=this.getNodeUniform(r,t);const i=n.name,s=e.uniforms.some(e=>e.name===i);s||e.addUniform(n)}s.uniformGPU=n}return r}getBuiltin(e,t,i,n=this.shaderStage){const r=this.builtins[n]||(this.builtins[n]=new Map);return!1===r.has(e)&&r.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),n=[];for(const e of t.inputs)n.push(e.name+" : "+this.getType(e.type));let r=`fn ${t.name}( ${n.join(", ")} ) -> ${this.getType(t.type)} {\n${i.vars}\n${i.code}\n`;return i.result&&(r+=`\treturn ${i.result};\n`),r+="\n}\n",r}getInstanceIndex(){return"vertex"===this.shaderStage?this.getBuiltin("instance_index","instanceIndex","u32","attribute"):"instanceIndex"}getInvocationLocalIndex(){return this.getBuiltin("local_invocation_index","invocationLocalIndex","u32","attribute")}getSubgroupSize(){return this.enableSubGroups(),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute")}getInvocationSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_invocation_id","invocationSubgroupIndex","u32","attribute")}getSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_id","subgroupIndex","u32","attribute")}getDrawIndex(){return null}getFrontFacing(){return this.getBuiltin("front_facing","isFront","bool")}getFragCoord(){return this.getBuiltin("position","fragCoord","vec4<f32>")+".xy"}getFragDepth(){return"output."+this.getBuiltin("frag_depth","depth","f32","output")}getClipDistance(){return"varyings.hw_clip_distances"}isFlipY(){return!1}enableDirective(e,t=this.shaderStage){(this.directives[t]||(this.directives[t]=new Set)).add(e)}getDirectives(e){const t=[],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:n,property:r,type:s}of i.values()){const i=!0===this.context.invariant&&"vertex"===e&&"position"===n?"@invariant ":"";t.push(`${i}@builtin( ${n} ) ${r} : ${s}`)}return t.join(",\n\t")}getScopedArray(e,t,i,n,r){return!1===this.scopedArrays.has(e)&&this.scopedArrays.set(e,{name:e,scope:t,bufferType:i,bufferCount:n,isAtomic:r}),e}getScopedArrays(e){if("compute"!==e)return;const t=[];for(const{name:e,scope:i,bufferType:n,bufferCount:r,isAtomic:s}of this.scopedArrays.values()){let a=this.getType(n);!0===s&&(a=`atomic<${a}>`),t.push(`var<${i}> ${e}: array< ${a}, ${r} >;`)}return t.join("\n")}getAttributes(e){const t=[];if("compute"===e&&(this.getBuiltin("global_invocation_id","globalId","vec3<u32>","attribute"),this.getBuiltin("workgroup_id","workgroupId","vec3<u32>","attribute"),this.getBuiltin("local_invocation_id","localId","vec3<u32>","attribute"),this.getBuiltin("num_workgroups","numWorkgroups","vec3<u32>","attribute"),this.renderer.hasFeature("subgroups")&&(this.enableDirective("subgroups",e),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute"))),"vertex"===e||"compute"===e){const e=this.getBuiltins("attribute");e&&t.push(e);const i=this.getAttributesArray();for(let e=0,n=i.length;e<n;e++){const n=i[e],r=n.name,s=this.getType(n.type);t.push(`@location( ${e} ) ${r} : ${s}`)}}return t.join(",\n\t")}getStructMembers(e){const t=[];for(const i of e.members){const n=e.output?"@location( "+i.index+" ) ":"";let r=this.getType(i.type);i.atomic&&(r="atomic< "+r+" >"),t.push(`\t${n+i.name} : ${r}`)}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,n=""){let r=`var${n} ${t} : `;return r+=null!==i?this.generateArrayDeclaration(e,i):this.getType(e),r}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 n=[],r=this.vars[e];if(void 0!==r)for(const e of r)n.push(`${this.getVar(e.type,e.name,e.count,i)};`);return t?n.join("\n"):`\n\t${n.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,n=this.vars[e];let r=0;for(let s=0;s<i.length;s++){const a=i[s];if(a.needsInterpolation){let e=`@location( ${r++} )`;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===n.includes(a)&&n.push(a)}}const i=this.getBuiltins(e);i&&t.push(i);const n=t.join(",\n\t");return"vertex"===e?this._getWGSLStruct("VaryingsStruct","\t"+n):n}getUniforms(e){const t=this.renderer.backend,i=this.uniforms[e],n=[],r=[],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,r=i.value;let a;(!0===r.isCubeTexture||!1===this.isUnfilterable(r)&&!0!==i.isStorageTextureNode||null!==i.gatherNode)&&(this.isSampleCompare(r)&&i.isSampleCompare()?n.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${s.name}_sampler : sampler_comparison;`):n.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${s.name}_sampler : sampler;`));let l="";const{primarySamples:c}=t.utils.getTextureSampleData(r);if(c>1&&(l="_multisampled"),!0===r.isCubeTexture&&!0===r.isDepthTexture)a="texture_depth_cube";else if(!0===r.isCubeTexture)a="texture_cube<f32>";else if(!0===r.isDepthTexture)a=t.compatibilityMode&&null===r.compareFunction?`texture${l}_2d<f32>`:`texture_depth${l}_2d${!0===r.isArrayTexture?"_array":""}`;else if(!0===s.node.isStorageTextureNode){const i=NP(r,t.device),n=this.getStorageAccess(s.node,e),o=s.node.value.is3DTexture,l=s.node.value.isArrayTexture;a=`texture_storage_${o?"3d":"2d"+(l?"_array":"")}<${i}, ${n}>`}else if(!0===r.isArrayTexture||!0===r.isDataArrayTexture||!0===r.isCompressedArrayTexture){a=`texture_2d_array<${this.getComponentTypeFromTexture(r).charAt(0)}32>`}else if(!0===r.is3DTexture||!0===r.isData3DTexture){a=`texture_3d<${this.getComponentTypeFromTexture(r).charAt(0)}32>`}else{a=`texture${l}_2d<${this.getComponentTypeFromTexture(r).charAt(0)}32>`}n.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)),n=t.bufferCount,a=n>0&&"buffer"===s.type?", "+n:"",l=t.isStorageBufferNode?`storage, ${this.getStorageAccess(t,e)}`:"uniform",c=`\tvalue : array< ${t.isAtomic?`atomic<${i}>`:`${i}`}${a} >`;r.push(this._getWGSLStructBinding(s.name,c,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(),n=this.getType(this.getVectorType(t));i.push(`\t${e.name} : ${n}`)}let n=this.uniformGroupsBindings[e];void 0===n&&(n={index:o.binding++,id:o.group},this.uniformGroupsBindings[e]=n),a[e]={index:n.index,id:n.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[...n,...r,...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,n=e[t];n.uniforms=this.getUniforms(t),n.attributes=this.getAttributes(t),n.varyings=this.getVaryings(t),n.structs=this.getStructs(t),n.vars=this.getVars(t,i),n.codes=this.getCodes(t),n.directives=this.getDirectives(t),n.scopedArrays=this.getScopedArrays(t);let r="// code\n\n";r+=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&&(r.length>0&&(r+="\n"),r+=`\t// flow -> ${s}\n`),r+=`${i.code}\n\t`,e===a&&"compute"!==t)if(r+="// result\n\n\t","vertex"===t)r+=`varyings.builtinClipSpace = ${i.result};`;else if("fragment"===t)if(l)n.returnType=o.getNodeType(this),n.structs+="var<private> output : "+n.returnType+";",r+=`return ${i.result};`;else{let e=`\t@location( 0 ) color: ${this.getType(this.getOutputType())}`;const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),n.returnType="OutputStruct",n.structs+=this._getWGSLStruct("OutputStruct",e),n.structs+="\nvar<private> output : OutputStruct;",r+=`output.color = ${this.format(i.result,a.getNodeType(this),this.getOutputType())};\n\n\treturn output;`}}n.flow=r}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 GP[e]||e}isAvailable(e){let t=kP[e];return void 0===t&&("float32Filterable"===e?t=this.renderer.hasFeature("float32-filterable"):"clipDistance"===e&&(t=this.renderer.hasFeature("clip-distances")),kP[e]=t),t}_getWGSLMethod(e){return void 0!==HP[e]&&this._include(e),WP[e]}_include(e){const t=HP[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${$P}\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,n,r]=t;return`${this.getSignature()}\n// directives\n${e.directives}\n\n// system\nvar<private> instanceIndex : u32;\n\n// locals\n${e.scopedArrays}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// vars\n${this.allowGlobalVariables?e.vars:""}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${i}, ${n}, ${r} )\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 ) * ( ${n} * 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,n=0,r=0){const s=e+"Struct";return`${this._getWGSLStruct(s,t)}\n@binding( ${n} ) @group( ${r} )\nvar<${i}> ${e} : ${s};`}}const qP=new XN,YP=new qN,KP=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32"]],[Uint32Array,["uint32"]],[Float32Array,["float32"]]]);"undefined"!=typeof Float16Array&&KP.set(Float16Array,["float16"]);const ZP=new Map([[Br,["float16"]]]),QP=new Map([[Int32Array,"sint32"],[Uint32Array,"uint32"],[Float32Array,"float32"]]),JP=new Uint8Array(4);function eL(e,t,i,n,r){const s=new Uint8Array(i.buffer,i.byteOffset,i.byteLength),a=4*Math.floor(n*i.BYTES_PER_ELEMENT/4),o=(n+r)*i.BYTES_PER_ELEMENT,l=4*Math.floor(o/4);l>a&&e.queue.writeBuffer(t,a,s,a,l-a),o>l&&(JP.fill(0),JP.set(s.subarray(l,l+4)),e.queue.writeBuffer(t,l,JP))}class tL{constructor(e){this.backend=e}createAttribute(e,t){const i=this.backend,n=i.getBufferAttribute(e),r=i.get(n);let s=r.buffer;if(void 0===s){const a=i.device;let o,l=n.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,n=e&&!i?Uint16Array:Uint32Array;if(l.constructor!==n&&(l=new n(l)),e&&i)for(let e=0;e<l.length;e++)65535===l[e]&&(l[e]=4294967295)}if(n.array=l,(n.isStorageBufferAttribute||n.isStorageInstancedBufferAttribute)&&3===n.itemSize)o=4;else if(n.itemSize>1&&n.itemSize*l.BYTES_PER_ELEMENT%4!=0){const e=n.itemSize*l.BYTES_PER_ELEMENT;o=4*Math.floor((e+3)/4)/l.BYTES_PER_ELEMENT}if(void 0!==o){const e=n.itemSize,t=new l.constructor(n.count*o);for(let i=0;i<n.count;i++)t.set(l.subarray(i*e,i*e+e),i*o);(n.isStorageBufferAttribute||n.isStorageInstancedBufferAttribute)&&(n.itemSize=o,n.array=t),l=t,r._itemSize=e,r._paddedItemSize=o}const c=l.byteLength,u=c+(4-c%4)%4;qP.label=n.name,qP.size=u,qP.usage=t,qP.mappedAtCreation=!0,s=a.createBuffer(qP),qP.reset(),new l.constructor(s.getMappedRange()).set(l),s.unmap(),r.buffer=s}}updateAttribute(e){const t=this.backend,i=t.device,n=t.getBufferAttribute(e),r=t.get(n),s=t.get(n).buffer;let a=n.array;const o=r._itemSize,l=r._paddedItemSize;if(void 0!==l){a=new a.constructor(n.count*l);for(let e=0;e<n.count;e++)a.set(n.array.subarray(e*o,e*o+o),e*l);(n.isStorageBufferAttribute||n.isStorageInstancedBufferAttribute)&&(n.array=a)}const c=n.updateRanges,u=_i(a)&&a.BYTES_PER_ELEMENT<4;if(0===c.length)u?eL(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 n=0,r=c.length;n<r;n++){const r=c[n];let h,d;if(void 0!==l){const e=Math.floor(r.start/o);h=e*l*t,d=(Math.ceil((r.start+r.count)/o)-e)*l*t}else h=r.start*t,d=r.count*t;if(u)eL(i,s,a,h,d);else{const t=h*(e?a.BYTES_PER_ELEMENT:1);i.queue.writeBuffer(s,t,a,h,d)}}n.clearUpdateRanges()}}getVertexBufferLayout(e){const t=e.getAttributes(),i=new Map;for(let e=0;e<t.length;e++){const n=t[e],r=n.array.BYTES_PER_ELEMENT,s=this.backend.getBufferAttribute(n);let a=i.get(s);if(void 0===a){let e,t;!0===s.isInterleavedBuffer?(e=s.stride*r,t=s.isInstancedInterleavedBuffer?UN:FN):(e=s.itemSize*r,t=s.isInstancedBufferAttribute?UN:FN,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(n),l=!0===n.isInterleavedBufferAttribute?n.offset*r: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,n=-1){const r=this.backend,s=r.device,a=r.get(r.getBufferAttribute(e)).buffer,o=-1===n?a.size-i:n;let l;if(null!==t&&t.isReadbackBuffer){const e=r.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){qP.label=`${t.name}_readback`,qP.size=t.maxByteLength,qP.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,l=s.createBuffer(qP),qP.reset();const i=()=>{t.buffer=null,t._mapped=!1,l.unmap()},n=()=>{t.buffer=null,t._mapped=!1,l.destroy(),r.delete(t),t.removeEventListener("release",i),t.removeEventListener("dispose",n)};t.addEventListener("release",i),t.addEventListener("dispose",n),e.readBufferGPU=l}else l=e.readBufferGPU}else qP.label=`${e.name}_readback`,qP.size=o,qP.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,l=s.createBuffer(qP),qP.reset();YP.label=`readback_encoder_${e.name}`;const c=s.createCommandEncoder(YP);YP.reset(),c.copyBufferToBuffer(a,i,l,0,o);if(jN(s,c.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,n=e.array.constructor,r=e.constructor;let s;if(1===t)s=QP.get(n);else{const e=(ZP.get(r)||KP.get(n))[i?1:0];if(e){const i=n.BYTES_PER_ELEMENT*t,r=4*Math.floor((i+3)/4)/n.BYTES_PER_ELEMENT;if(r%1)throw new Error("THREE.WebGPUAttributeUtils: Bad vertex format item size.");s=`${e}x${r}`}}return s||Mi("WebGPUAttributeUtils: Vertex format not supported yet."),s}}const iL=new $N,nL=new XN,rL=new iP;class sL{constructor(e){this.layoutGPU=e,this.usedTimes=0}}class aL{constructor(e){this.backend=e,this._bindGroupLayoutCache=new Map}createBindingsLayout(e){const t=this.backend,i=t.device,n=t.get(e);if(n.layout)return n.layout.layoutGPU;const r=this._createLayoutEntries(e),s=wu(JSON.stringify(r));let a=this._bindGroupLayoutCache.get(s);return void 0===a&&(a=new sL(i.createBindGroupLayout({entries:r})),this._bindGroupLayoutCache.set(s,a)),a.usedTimes++,n.layout=a,n.layoutKey=s,a.layoutGPU}createBindings(e,t,i,n=0){const{backend:r}=this,s=r.get(e),a=this.createBindingsLayout(e);let o;""!==i&&(void 0===s.groups&&(s.groups={},s.versions={}),s.versions[i]===n&&(o=s.groups[i])),void 0===o&&(o=this.createBindGroup(e,a),""!==i&&(s.groups[i]=o,s.versions[i]=n)),s.group=o}updateBinding(e){const t=this.backend,i=t.device,n=e.buffer,r=t.get(e).buffer,s=e.updateRanges;if(0===s.length)i.queue.writeBuffer(r,0,n,0);else{const e=_i(n),t=e?1:n.BYTES_PER_ELEMENT;let a=s[0].start;for(let o=0,l=s.length;o<l;o++){const l=s[o],c=s[o+1],u=l.start+l.count;if(void 0!==c&&c.start===u)continue;const h=a*t,d=(u-a)*t,p=h*(e?n.BYTES_PER_ELEMENT:1);i.queue.writeBuffer(r,p,n,h,d),void 0!==c&&(a=c.start)}}}createBindGroupIndex(e,t){const i=this.backend.device,n=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,r=e[0];nL.label="bindingCameraIndex_"+r,nL.size=16,nL.usage=n;const s=i.createBuffer(nL);nL.reset(),i.queue.writeBuffer(s,0,e,0),iL.label="bindGroupCameraIndex_"+r,iL.layout=t,iL.entries.push({binding:0,resource:{buffer:s}});const a=i.createBindGroup(iL);return iL.reset(),a}createBindGroup(e,t){const i=this.backend,n=i.device;let r=0;iL.label="bindGroup_"+e.name,iL.layout=t;for(const t of e.bindings){if(t.isUniformBuffer){const e=i.get(t);iL.entries.push({binding:r,resource:{buffer:e.buffer}})}else if(t.isStorageBuffer){const e=i.get(t.attribute).buffer;iL.entries.push({binding:r,resource:{buffer:e}})}else if(t.isSampledTexture){const e=i.get(t.texture);let s;if(void 0!==e.externalTexture)s=n.importExternalTexture({source:e.externalTexture});else{const i=t.store?1:e.texture.mipLevelCount,n=t.store?t.mipLevel:0;let r=`view-${e.texture.width}-${e.texture.height}`;if(e.texture.depthOrArrayLayers>1&&(r+=`-${e.texture.depthOrArrayLayers}`),r+=`-${i}-${n}`,s=e[r],void 0===s){const a=t.texture.isDepthTexture?IN:DN;let o;o=t.isSampledCubeTexture?PN:t.texture.isArrayTexture||t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?NN:t.isSampledTexture3D?LN:CN,rL.aspect=a,rL.dimension=o,rL.mipLevelCount=i,rL.baseMipLevel=n,s=e[r]=e.texture.createView(rL),rL.reset()}}iL.entries.push({binding:r,resource:s})}else if(t.isSampler){const e=i.get(t);iL.entries.push({binding:r,resource:e.sampler})}r++}const s=n.createBindGroup(iL);return iL.reset(),s}_createLayoutEntries(e){const t=[];let i=0;for(const n of e.bindings){const e=this.backend,r={binding:i,visibility:n.visibility};if(n.isUniformBuffer||n.isStorageBuffer){const e={};n.isStorageBuffer&&(n.visibility&wA.COMPUTE?n.access===bu||n.access===vu?e.type=mN:e.type=gN:n.nodeUniform&&n.nodeUniform.isAtomic&&n.visibility&wA.FRAGMENT?e.type=mN:e.type=gN),r.buffer=e}else if(n.isSampledTexture&&n.store){const e={};e.format=this.backend.get(n.texture).texture.format;const t=n.access;e.access=t===bu?bN:t===vu?_N:vN,n.texture.isArrayTexture?e.viewDimension=NN:n.texture.is3DTexture&&(e.viewDimension=LN),r.storageTexture=e}else if(n.isSampledTexture){const t={},{primarySamples:i}=e.utils.getTextureSampleData(n.texture);if(i>1&&(t.multisampled=!0,n.texture.isDepthTexture||(t.sampleType=TN)),n.texture.isDepthTexture)e.compatibilityMode&&null===n.texture.compareFunction?t.sampleType=TN:t.sampleType=MN;else{const e=n.texture.type;e===We?t.sampleType=EN:e===je?t.sampleType=wN:!0!==n.texture.normalized||e!==Ve&&e!==He?e===$e&&(this.backend.hasFeature("float32-filterable")?t.sampleType=SN:t.sampleType=TN):t.sampleType=TN}n.isSampledCubeTexture?t.viewDimension=PN:n.texture.isArrayTexture||n.texture.isDataArrayTexture||n.texture.isCompressedArrayTexture?t.viewDimension=NN:n.isSampledTexture3D&&(t.viewDimension=LN),r.texture=t}else if(n.isSampler){const t={};n.texture.isDepthTexture&&(null!==n.texture.compareFunction&&n.textureNode.isSampleCompare()&&e.hasCompatibility(pi)?t.type=xN:t.type=yN),r.sampler=t}else Mi(`WebGPUBindingUtils: Unsupported binding "${n}".`);t.push(r),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 oL{constructor(e){this.backend=e}getMaxAnisotropy(){return 16}getUniformBufferLimit(){return this.backend.device.limits.maxUniformBufferBindingSize}}const lL=new class{constructor(){this.label="",this.layout=null,this.compute=null}reset(){this.label="",this.layout=null,this.compute=null}},cL=new class{constructor(){this.label="",this.bindGroupLayouts=null}reset(){this.label="",this.bindGroupLayouts=null}},uL=new YN,hL=new QN;class dL{constructor(e){this.backend=e}_getSampleCount(e){return this.backend.utils.getSampleCountRenderContext(e)}createRenderPipeline(e,t){const{object:i,material:n,geometry:r,pipeline:s}=e,{vertexProgram:a,fragmentProgram:o}=s,l=this.backend,c=l.device,u=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===n.blending||1===n.blending&&!1===n.transparent||(f=this._getBlending(n));let m={};!0===n.stencilWrite&&(m={compare:this._getStencilCompare(n),failOp:this._getStencilOperation(n.stencilFail),depthFailOp:this._getStencilOperation(n.stencilZFail),passOp:this._getStencilOperation(n.stencilZPass)});const g=this._getColorWriteMask(n),_=[];if(null!==e.context.textures){const t=e.context.textures,i=e.context.mrt;for(let e=0;e<t.length;e++){const n=t[e],r=u.getTextureFormatGPU(n);let s;if(null!==i)if(!0!==this.backend.compatibilityMode){const e=i.getBlendMode(n.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:r,blend:s,writeMask:g})}}else{const t=u.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,r,n),x=this._getDepthCompare(n),S=u.getCurrentDepthStencilFormat(e.context),T=this._getSampleCount(e.context);cL.bindGroupLayouts=d;const M=c.createPipelineLayout(cL);cL.reset(),hL.label=`renderPipeline_${n.name||n.type}_${n.id}`,hL.vertex=Object.assign({},v,{buffers:p}),hL.fragment=Object.assign({},b,{targets:_}),hL.primitive=y,hL.multisample.count=T,hL.multisample.alphaToCoverageEnabled=n.alphaToCoverage&&T>1,hL.layout=M;const E={},w=e.context.depth,A=e.context.stencil;!0!==w&&!0!==A||(!0===w&&(E.format=S,E.depthWriteEnabled=n.depthWrite,E.depthCompare=x),!0===A&&(E.stencilFront=m,E.stencilBack=m,E.stencilReadMask=n.stencilFuncMask,E.stencilWriteMask=n.stencilWriteMask),!0===n.polygonOffset&&y.topology===EA&&(E.depthBias=this.backend.parameters.reversedDepthBuffer?-n.polygonOffsetUnits:n.polygonOffsetUnits,E.depthBiasSlopeScale=this.backend.parameters.reversedDepthBuffer?-n.polygonOffsetFactor:n.polygonOffsetFactor,E.depthBiasClamp=0),hL.depthStencil=E),c.pushErrorScope("validation");const R=[{program:a,module:v.module},{program:o,module:b.module}],C=hL.label;if(null===t)h.pipeline=c.createRenderPipeline(hL),hL.reset(),c.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=c.createRenderPipelineAsync(hL)}catch(t){e=t}hL.reset();const i=c.popErrorScope();if(null!==t)try{h.pipeline=await t}catch(t){e=t}const n=await i;if(null!==n||null!==e){h.error=!0;const t=n&&n.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:n,device:r}=i,s=n.getCurrentDepthStencilFormat(e),a=n.getCurrentColorFormats(e),o=this._getSampleCount(e);uL.label=t,uL.colorFormats=a,uL.depthStencilFormat=s,uL.sampleCount=o;const l=r.createRenderBundleEncoder(uL);return uL.reset(),l}createComputePipeline(e,t,i=null){const n=this.backend,r=n.device,s=n.get(e.computeProgram).module,a=n.get(e),o=[];for(const e of t){const t=n.get(e),{layoutGPU:i}=t.layout;o.push(i)}const l=e.computeProgram,c=`computePipeline_${l.stage}${l.name?`_${l.name}`:""}`;r.pushErrorScope("validation"),cL.bindGroupLayouts=o;const u=r.createPipelineLayout(cL);if(cL.reset(),lL.label=c,lL.compute=s,lL.layout=u,null===i)a.pipeline=r.createComputePipeline(lL),lL.reset(),r.popErrorScope().then(e=>{null!==e&&(a.error=!0,Mi(`WebGPURenderer: Compute pipeline creation failed (${c}): ${e.message}`),this._reportShaderDiagnostics([{program:l,module:s.module}],c))});else{const e=new Promise(async e=>{try{let e=null,t=null;try{t=r.createComputePipelineAsync(lL)}catch(t){e=t}lL.reset();const i=r.popErrorScope();if(null!==t)try{a.pipeline=await t}catch(t){e=t}const n=await i;if(null!==n||null!==e){a.error=!0;const t=n&&n.message||e&&e.message||"unknown";Mi(`WebGPURenderer: Async compute pipeline creation failed (${c}): ${t}`),await this._reportShaderDiagnostics([{program:l,module:s.module}],c)}}finally{e()}});i.push(e)}}async _reportShaderDiagnostics(e,t){for(const{program:i,module:n}of e){const e=await n.getCompilationInfo();if(0===e.messages.length)continue;const r=i.code.split("\n");for(const n of e.messages){const e=n.lineNum>0?` at line ${n.lineNum}${n.linePos>0?`:${n.linePos}`:""}`:"",s=`WebGPURenderer [${t} / ${i.stage} ${n.type}]${e}: ${n.message}`;let a="";n.lineNum>0&&n.lineNum<=r.length&&(a=`\n ${r[n.lineNum-1]}`,n.linePos>0&&(a+=`\n ${" ".repeat(n.linePos-1)}^`)),("error"===n.type?Mi:Ti)(s+a)}}}_getBlending(e){let t,i;const n=e.blending,r=e.blendSrc,s=e.blendDst,a=e.blendEquation;if(5===n){const n=null!==e.blendSrcAlpha?e.blendSrcAlpha:r,o=null!==e.blendDstAlpha?e.blendDstAlpha:s,l=null!==e.blendEquationAlpha?e.blendEquationAlpha:a;t={srcFactor:this._getBlendFactor(r),dstFactor:this._getBlendFactor(s),operation:this._getBlendOperation(a)},i={srcFactor:this._getBlendFactor(n),dstFactor:this._getBlendFactor(o),operation:this._getBlendOperation(l)}}else{const r=(e,n,r,s)=>{t={srcFactor:e,dstFactor:n,operation:eN},i={srcFactor:r,dstFactor:s,operation:eN}};if(e.premultipliedAlpha)switch(n){case 1:r(VC,$C,VC,$C);break;case 2:r(VC,VC,VC,VC);break;case 3:r(GC,WC,GC,VC);break;case 4:r(XC,$C,GC,VC)}else switch(n){case 1:r(jC,$C,VC,$C);break;case 2:r(jC,VC,VC,VC);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: ",n)}_getBlendFactor(e){let t;switch(e){case q:t=GC;break;case 201:t=VC;break;case 202:t=HC;break;case 203:t=WC;break;case Q:t=jC;break;case J:t=$C;break;case 208:t=XC;break;case 209:t=qC;break;case 206:t=YC;break;case 207:t=KC;break;case 210:t=ZC;break;case 211:case 213:t=QC;break;case 212:case 214:t=JC;break;default:Mi("WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const i=e.stencilFunc;switch(i){case 512:t=AA;break;case 519:t=IA;break;case 513:t=RA;break;case 515:t=NA;break;case 514:t=CA;break;case 518:t=DA;break;case 516:t=PA;break;case 517:t=LA;break;default:Mi("WebGPURenderer: Invalid stencil function.",i)}return t}_getStencilOperation(e){let t;switch(e){case Zt:t=oN;break;case 0:t=lN;break;case 7681:t=cN;break;case 5386:t=uN;break;case 7682:t=hN;break;case 7683:t=dN;break;case 34055:t=pN;break;case 34056:t=fN;break;default:Mi("WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case H:t=eN;break;case 101:t=tN;break;case 102:t=iN;break;case 103:t=nN;break;case 104:t=rN;break;default:Mi("WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,i){const n={},r=this.backend.utils;n.topology=r.getPrimitiveTopology(e,i),n.stripIndexFormat=r.getStripIndexFormat(e,t);let s=1===i.side;return e.isMesh&&e.matrixWorld.determinantAffine()<0&&(s=!s),n.frontFace=!0===s?zA:kA,n.cullMode=2===i.side?GA:VA,n}_getColorWriteMask(e){return!0===e.colorWrite?aN:sN}_getDepthCompare(e){let t;if(!1===e.depthTest)t=IA;else{const i=this.backend.parameters.reversedDepthBuffer?Ai[e.depthFunc]:e.depthFunc;switch(i){case 0:t=AA;break;case 1:t=IA;break;case 2:t=RA;break;case 3:t=NA;break;case 4:t=CA;break;case 5:t=DA;break;case 6:t=PA;break;case 7:t=LA;break;default:Mi("WebGPUPipelineUtils: Invalid depth function.",i)}}return t}}class pL{constructor(){this.label="",this.type=void 0,this.count=0}reset(){this.label="",this.type=void 0,this.count=0}}const fL=new XN,mL=new qN,gL=new pL;class _L extends vA{constructor(e,t,i=2048){super(i),this.device=e,this.type=t,gL.label=`queryset_global_timestamp_${t}`,gL.type="timestamp",gL.count=this.maxQueries,this.querySet=this.device.createQuerySet(gL),gL.reset();const n=8*this.maxQueries;fL.label=`buffer_timestamp_resolve_${t}`,fL.size=n,fL.usage=GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC,this.resolveBuffer=this.device.createBuffer(fL),fL.reset(),fL.label=`buffer_timestamp_result_${t}`,fL.size=n,fL.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,this.resultBuffer=this.device.createBuffer(fL),fL.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 n=this.device.createCommandEncoder(mL);n.resolveQuerySet(this.querySet,0,t,this.resolveBuffer,0),n.copyBufferToBuffer(this.resolveBuffer,0,this.resultBuffer,0,i);const r=n.finish();if(jN(this.device,r),"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+)$/),n=parseInt(e[2]);!1===o.includes(n)&&o.push(n),void 0===a[n]&&(a[n]=0);const r=s[i],l=s[i+1],c=Number(l-r)/1e6;this.timestamps.set(t,c),a[n]+=c}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 vL{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 bL={r:0,g:0,b:0,a:1},yL={r:0,g:0,b:0,a:0},xL=new XN,SL=new qN,TL=new class{constructor(){this.label="",this.timestampWrites=void 0}reset(){this.label="",this.timestampWrites=void 0}},ML=new pL,EL=new eP,wL=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}},AL=new fP,RL=new fP,CL=new tP,NL=new iP,PL=new mP;class LL extends Jw{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 WN(this),this.attributeUtils=new tL(this),this.bindingUtils=new aL(this),this.capabilities=new oL(this),this.pipelineUtils=new dL(this),this.textureUtils=new CP(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 n={powerPreference:t.powerPreference,featureLevel:"compatibility",xrCompatible:e.xr.enabled},r="undefined"!=typeof navigator?await navigator.gpu.requestAdapter(n):null;if(null===r)throw new Error("THREE.WebGPUBackend: Unable to create WebGPU adapter.");const s=Object.values(ON),a=[];for(const e of s)r.features.has(e)&&a.push(e);const o={requiredFeatures:a,requiredLimits:t.requiredLimits};i=await r.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,n=i&&i.constructor?i.constructor.name:"GPUError",r=i&&i.message||"Unknown uncaptured GPU error";e.onError({api:"WebGPU",type:n,message:r,originalEvent:t})},this.device=i,this.trackTimestamp=this.trackTimestamp&&this.hasFeature(ON.TimestampQuery),this.updateSize()}setXRRenderTargetTextures(e,t,i=null){const n=this.get(e.texture);n.texture=t,n.format=t.format,n.externalTexture=!0,n.xrViewDescriptors=i,n.initialized=!0}get context(){const e=this.renderer.getCanvasTarget(),t=this.get(e);let i=t.context;if(void 0===i){const n=this.parameters;i=!0===e.isDefaultCanvasTarget&&void 0!==n.context?n.context:e.domElement.getContext("webgpu"),"setAttribute"in e.domElement&&e.domElement.setAttribute("data-engine",`three.js r${N} webgpu`);const r=n.alpha?"premultiplied":"opaque",s=n.outputType===Xe?"extended":"standard";i.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:r,toneMapping:{mode:s}}),t.context=i}return i}get coordinateSystem(){return ui}get hasTimestamp(){return!0}async getArrayBufferAsync(e,t=null,i=0,n=-1){return await this.attributeUtils.getArrayBufferAsync(e,t,i,n)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){const e=this.renderer,t=e.getCanvasTarget(),i=this.get(t),n=e.currentSamples;let r=i.descriptor;if(void 0===r||i.samples!==n){if(r=new ZN,r.colorAttachments.push(new KN),!0===e.depth||!0===e.stencil){const t=new vL;t.view=this.textureUtils.getDepthBuffer(e.depth,e.stencil).createView(),r.depthStencilAttachment=t}const t=r.colorAttachments[0];n>0?t.view=this.textureUtils.getColorBuffer().createView():t.resolveTarget=void 0,i.descriptor=r,i.samples=n}const s=r.colorAttachments[0];return n>0?s.resolveTarget=this.context.getCurrentTexture().createView():s.view=this.context.getCurrentTexture().createView(),r}_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 n=this.utils.getSampleCount(e.sampleCount);if(1===n){if(void 0!==t.msaaTextures){for(const e of t.msaaTextures)e.destroy();t.msaaTextures=void 0}return null}const r=e.renderTarget,s=r.width,a=r.height,o=t.format;if(void 0===t.msaaTextures||t.msaaTextures.length!==i||t.msaaWidth!==s||t.msaaHeight!==a||t.msaaSamples!==n||t.msaaFormat!==o){if(void 0!==t.msaaTextures)for(const e of t.msaaTextures)e.destroy();CL.size.width=s,CL.size.height=a,CL.sampleCount=n,CL.format=o,CL.usage=GPUTextureUsage.RENDER_ATTACHMENT,t.msaaTextures=[];for(let e=0;e<i;e++)CL.label=r.texture.name+"-msaa-"+e,t.msaaTextures.push(this.device.createTexture(CL));CL.reset(),t.msaaWidth=s,t.msaaHeight=a,t.msaaSamples=n,t.msaaFormat=o}return t.msaaTextures}_createExternalTextureViews(e,t){const i=[],n=e.camera,r=t.xrViewDescriptors,s=Math.max(r?.length||0,e.activeCubeFace+1,1),a=this._getExternalMSAATextures(e,t,s);if(r&&null!==n&&!0===n.isArrayCamera)for(let n=0;n<r.length;n++){const s=t.texture.createView(r[n]);i.push({view:null!==a?a[n].createView():s,resolveTarget:null!==a&&!0===e.renderTarget.resolveColorBuffer?s:void 0,depthSlice:void 0})}else{const n=e.activeCubeFace,r=t.texture.createView({dimension:CN,baseArrayLayer:n,arrayLayerCount:1});i.push({view:null!==a?a[n].createView():r,resolveTarget:null!==a&&!0===e.renderTarget.resolveColorBuffer?r:void 0,depthSlice:void 0})}return i}_getRenderPassDescriptor(e,t={}){const i=e.renderTarget,n=this.get(i),r=this._hasExternalTexture(e);let s=n.descriptors;(void 0===s||n.width!==i.width||n.height!==i.height||n.samples!==i.samples||r)&&(s={},n.descriptors=s);const a=e.getCacheKey();let o=s[a];if(void 0===o||r){const t=e.textures,r=[];let l;const c=this._isRenderCameraDepthArray(e);for(let n=0;n<t.length;n++){const s=this.get(t[n]);if(!0!==s.externalTexture){if(NL.label=`colorAttachment_${n}`,NL.baseMipLevel=e.activeMipmapLevel,NL.mipLevelCount=1,NL.baseArrayLayer=e.activeCubeFace,NL.arrayLayerCount=1,NL.dimension=CN,i.isRenderTarget3D)l=e.activeCubeFace,NL.baseArrayLayer=0,NL.dimension=LN;else if(i.isRenderTarget&&t[n].image.depth>1)if(!0===c){const t=e.camera.cameras;for(let e=0;e<t.length;e++){NL.baseArrayLayer=e,NL.arrayLayerCount=1,NL.dimension=CN;const t=s.texture.createView(NL),n=s.msaaTextures?.[e];r.push({view:void 0!==n?n.createView():t,resolveTarget:void 0!==n&&!0===i.resolveColorBuffer?t:void 0,depthSlice:void 0})}}else NL.dimension=NN;if(!0!==c){const t=s.texture.createView(NL);let n,a;void 0!==s.msaaTexture?(n=s.msaaTexture.createView(),a=!0===i.resolveColorBuffer?t:void 0):void 0!==s.msaaTextures?(n=s.msaaTextures[e.activeCubeFace].createView(),a=!0===i.resolveColorBuffer?t:void 0):(n=t,a=void 0),r.push({view:n,resolveTarget:a,depthSlice:l})}NL.reset()}else r.push(...this._createExternalTextureViews(e,s))}const u=[];for(let e=0;e<r.length;e++){const t=r[e],i=new KN;i.view=t.view,i.depthSlice=t.depthSlice,i.resolveTarget=t.resolveTarget,u.push(i)}if(o={textureViews:r,colorAttachments:u,descriptor:new ZN},e.depth){const t=this.get(e.depthTexture);(e.depthTexture.isArrayTexture||e.depthTexture.isCubeTexture)&&(NL.dimension=CN,NL.arrayLayerCount=1,NL.baseArrayLayer=e.activeCubeFace);const i=new vL,n=t.msaaTextures?.[e.activeCubeFace];i.view=void 0!==n?n.createView():t.texture.createView(NL),o.depthStencilAttachment=i,NL.reset()}s[a]=o,n.width=i.width,n.height=i.height,n.samples=i.samples,n.activeMipmapLevel=e.activeMipmapLevel,n.activeCubeFace=e.activeCubeFace}const l=o.descriptor;l.reset();for(let e=0;e<o.colorAttachments.length;e++){const i=o.colorAttachments[e];let n={r:0,g:0,b:0,a:1};0===e&&t.clearValue&&(n=t.clearValue),i.loadOp=t.loadOp||OA,i.storeOp=t.storeOp||FA,i.clearValue=n,l.colorAttachments.push(i)}return o.depthStencilAttachment&&(l.depthStencilAttachment=o.depthStencilAttachment),l}beginRender(e){const t=this.get(e),i=this.device,n=e.occlusionQueryCount,r=this.getOcclusionData(e);let s,a;n>0?(r.currentOcclusionQuerySet&&r.currentOcclusionQuerySet.destroy(),r.currentOcclusionQueryBuffer&&r.currentOcclusionQueryBuffer.destroy(),r.currentOcclusionQuerySet=r.occlusionQuerySet,r.currentOcclusionQueryBuffer=r.occlusionQueryBuffer,r.currentOcclusionQueryObjects=r.occlusionQueryObjects,ML.label=`occlusionQuerySet_${e.id}`,ML.type="occlusion",ML.count=n,s=i.createQuerySet(ML),ML.reset(),r.occlusionQuerySet=s,r.occlusionQueryIndex=0,r.occlusionQueryObjects=new Array(n),r.lastOcclusionObject=null):void 0!==r.lastOcclusionObject&&(r.lastOcclusionObject=void 0,r.occlusionQuerySet.destroy(),r.occlusionQuerySet=void 0),a=null===e.textures?this._getDefaultRenderPassDescriptor():this._getRenderPassDescriptor(e,{loadOp:OA}),this.initTimestampQuery(di,this.getTimestampUID(e),a),a.occlusionQuerySet=s;const o=a.depthStencilAttachment,l=e.renderTarget,c=e.sampleCount>1&&!1===l?.storeMultisampledColorBuffer,u=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 n=t[i];if(e.clearColor||c||d){const t=e.mrt?e.mrt.getClearColor(e.textures[i].name):null;null!==t?n.clearValue=t:0===i?n.clearValue=e.clearColorValue:(bL.r=0,bL.g=0,bL.b=0,bL.a=1,n.clearValue=bL),n.loadOp=BA}else n.loadOp=OA;n.storeOp=c?UA:FA}}else{const t=a.colorAttachments[0];e.clearColor?(t.clearValue=e.clearColorValue,t.loadOp=BA):t.loadOp=OA,t.storeOp=FA}e.depth&&(e.clearDepth||u?(o.depthClearValue=e.clearDepthValue,o.depthLoadOp=BA):o.depthLoadOp=OA,o.depthStoreOp=u?UA:FA),e.stencil&&(e.clearStencil||h?(o.stencilClearValue=e.clearStencilValue,o.stencilLoadOp=BA):o.stencilLoadOp=OA,o.stencilStoreOp=h?UA:FA),SL.label="renderContext_"+e.id;const p=i.createCommandEncoder(SL);if(SL.reset(),!0===this._isRenderCameraDepthArray(e)){const i=e.camera.cameras,n=this.get(e.depthTexture).texture;t.layerDescriptors&&t.layerDescriptors.length===i.length&&t.layerDepthTexture===n?this._updateArrayCameraLayerDescriptors(e,t,a,i):(this._createArrayCameraLayerDescriptors(e,t,a,i),t.layerDepthTexture=n),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 Kn),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 n=0;n<i.length;n++){const i=this.pipelineUtils.createBundleEncoder(e,"renderBundleArrayCamera_"+n),r={attributes:{},bindingGroups:[],pipeline:null,index:null};t.bundleEncoders.push(i),t.bundleSets.push(r)}}_finishArrayCameraBundleEncoders(e){const t=[];for(const i of e.bundleEncoders)t.push(i.finish());return t}_createArrayCameraLayerDescriptors(e,t,i,n){const r=i.depthStencilAttachment;t.layerDescriptors=[];const s=this.get(e.depthTexture);s.viewCache||(s.viewCache=[]);for(let a=0;a<n.length;a++){const n=new ZN;if(n.label=i.label,n.occlusionQuerySet=i.occlusionQuerySet,n.timestampWrites=i.timestampWrites,i.colorAttachments.length>0){const e=i.colorAttachments[0],t=i.colorAttachments[a],r=new KN;r.view=t.view,r.depthSlice=t.depthSlice,r.resolveTarget=t.resolveTarget,r.loadOp=e.loadOp,r.storeOp=e.storeOp,r.clearValue=e.clearValue,n.colorAttachments.push(r)}if(i.depthStencilAttachment){const t=a;if(!s.viewCache[t]){const e=s.msaaTextures?.[t];void 0!==e?s.viewCache[t]=e.createView():(NL.dimension=CN,NL.baseArrayLayer=a,NL.arrayLayerCount=1,s.viewCache[t]=s.texture.createView(NL)),NL.reset()}const i=new vL;i.view=s.viewCache[t],i.depthLoadOp=r.depthLoadOp||BA,i.depthStoreOp=r.depthStoreOp||FA,i.depthClearValue=r.depthClearValue??1,e.stencil&&(i.stencilLoadOp=r.stencilLoadOp,i.stencilStoreOp=r.stencilStoreOp,i.stencilClearValue=r.stencilClearValue),n.depthStencilAttachment=i}else{const e=new vL;e.view=r.view,e.depthLoadOp=r.depthLoadOp,e.depthStoreOp=r.depthStoreOp,e.depthClearValue=r.depthClearValue,e.depthReadOnly=r.depthReadOnly,e.stencilLoadOp=r.stencilLoadOp,e.stencilStoreOp=r.stencilStoreOp,e.stencilClearValue=r.stencilClearValue,e.stencilReadOnly=r.stencilReadOnly,n.depthStencilAttachment=e}t.layerDescriptors.push(n)}}_updateArrayCameraLayerDescriptors(e,t,i,n){const r=e.renderTarget,s=e.sampleCount>1&&!1===r?.storeMultisampledDepthBuffer,a=e.sampleCount>1&&!1===r?.storeMultisampledStencilBuffer;for(let r=0;r<n.length;r++){const n=t.layerDescriptors[r];if(n.timestampWrites=i.timestampWrites,i.colorAttachments.length>0){const e=i.colorAttachments[0],t=i.colorAttachments[r],s=n.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(n.depthStencilAttachment){const t=n.depthStencilAttachment;e.depth&&(e.clearDepth||s?(t.depthClearValue=e.clearDepthValue,t.depthLoadOp=BA):t.depthLoadOp=OA),e.stencil&&(e.clearStencil||a?(t.stencilClearValue=e.clearStencilValue,t.stencilLoadOp=BA):t.stencilLoadOp=OA)}}}finishRender(e){const t=this.get(e),i=e.occlusionQueryCount,n=this.getOcclusionData(e);t.renderBundles.length>0&&t.currentPass.executeBundles(t.renderBundles);const r=n.lastOcclusionObject;r&&!0===r.occlusionTest&&t.currentPass.endOcclusionQuery();const s=t.encoder;if(!0===this._isRenderCameraDepthArray(e)){const i=this._finishArrayCameraBundleEncoders(t),n=t.arrayCameraRenderStages;n.push({bundles:i});for(let i=0;i<t.layerDescriptors.length;i++){const r=t.layerDescriptors[i],a=r.colorAttachments.map(e=>e.loadOp),o=r.colorAttachments.map(e=>e.storeOp),l=r.depthStencilAttachment?.depthLoadOp,c=r.depthStencilAttachment?.depthStoreOp,u=r.depthStencilAttachment?.stencilLoadOp,h=r.depthStencilAttachment?.stencilStoreOp;for(let t=0;t<n.length;t++){const d=n[t],p=d.bundles[i],f=t===n.length-1;for(let e=0;e<r.colorAttachments.length;e++){const i=r.colorAttachments[e];i.loadOp=0===t?a[e]:OA,i.storeOp=f?o[e]:FA}e.depth&&(r.depthStencilAttachment.depthLoadOp=0===t?l:OA,r.depthStencilAttachment.depthStoreOp=f?c:FA),e.stencil&&(r.depthStencilAttachment.stencilLoadOp=0===t?u:OA,r.depthStencilAttachment.stencilStoreOp=f?h:FA);const m=s.beginRenderPass(r);if(e.viewport){const{x:t,y:i,width:n,height:r,minDepth:s,maxDepth:a}=e.viewportValue;m.setViewport(t,i,n,r,s,a)}if(e.scissor){const{x:t,y:i,width:n,height:r}=e.scissorValue;m.setScissorRect(t,i,n,r)}if(m.executeBundles([p]),m.end(),void 0!==d.framebufferCopy){const{texture:e,sourceGPU:t,destinationGPU:n,rectangle:r,generateMipmaps:a}=d.framebufferCopy;this._copyFramebufferToTexture(s,e,t,n,r,i,a)}}for(let e=0;e<r.colorAttachments.length;e++)r.colorAttachments[e].loadOp=a[e],r.colorAttachments[e].storeOp=o[e];e.depth&&(r.depthStencilAttachment.depthLoadOp=l,r.depthStencilAttachment.depthStoreOp=c),e.stencil&&(r.depthStencilAttachment.stencilLoadOp=u,r.depthStencilAttachment.stencilStoreOp=h)}}else t.currentPass&&t.currentPass.end();if(i>0){const r=8*i;let s=this.occludedResolveCache.get(r);void 0===s&&(xL.size=r,xL.usage=GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC,s=this.device.createBuffer(xL),xL.reset(),this.occludedResolveCache.set(r,s)),xL.size=r,xL.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ;const a=this.device.createBuffer(xL);xL.reset(),t.encoder.resolveQuerySet(n.occlusionQuerySet,0,i,s,0),t.encoder.copyBufferToBuffer(s,0,a,0,r),n.occlusionQueryBuffer=a,this.resolveOccludedAsync(e)}if(jN(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:n}=t;if(i&&n){const e=new WeakSet;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueryBuffer=null,await i.mapAsync(GPUMapMode.READ);const r=i.getMappedRange(),s=new BigUint64Array(r);for(let t=0;t<n.length;t++){const i=n[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:n,width:r,height:s,minDepth:a,maxDepth:o}=e.viewportValue;t.setViewport(i,n,r,s,a,o)}updateScissor(e){const{currentPass:t}=this.get(e),{x:i,y:n,width:r,height:s}=e.scissorValue;t.setScissorRect(i,n,r,s)}getClearColor(){const e=super.getClearColor();return!0===this.renderer.alpha&&(e.r*=e.a,e.g*=e.a,e.b*=e.a),e}clear(e,t,i,n=null){const r=this.device,s=this.renderer;let a,o,l,c=[];if(e){const e=this.getClearColor();bL.r=e.r,bL.g=e.g,bL.b=e.b,bL.a=e.a}if(null===n){o=s.depth,l=s.stencil;const t=this._getDefaultRenderPassDescriptor();if(e){c=t.colorAttachments;const e=c[0];e.clearValue=bL,e.loadOp=BA,e.storeOp=FA}(o||l)&&(a=t.depthStencilAttachment)}else{o=n.depth,l=n.stencil;const r={loadOp:e?BA:OA,clearValue:e?bL:void 0};o&&(r.depthLoadOp=t?BA:OA,r.depthClearValue=t?s.getClearDepth():void 0,r.depthStoreOp=FA),l&&(r.stencilLoadOp=i?BA:OA,r.stencilClearValue=i?s.getClearStencil():void 0,r.stencilStoreOp=FA);const u=this._getRenderPassDescriptor(n,r);c=u.colorAttachments,a=u.depthStencilAttachment}o&&a&&(t?(a.depthLoadOp=BA,a.depthClearValue=s.getClearDepth(),a.depthStoreOp=FA):(a.depthLoadOp=OA,a.depthStoreOp=FA)),l&&a&&(i?(a.stencilLoadOp=BA,a.stencilClearValue=s.getClearStencil(),a.stencilStoreOp=FA):(a.stencilLoadOp=OA,a.stencilStoreOp=FA)),SL.label="clear";const u=r.createCommandEncoder(SL);SL.reset();u.beginRenderPass({colorAttachments:c,depthStencilAttachment:a}).end(),jN(r,u.finish())}beginCompute(e){const t=this.get(e),i="computeGroup_"+e.id;TL.label=i,SL.label=i,this.initTimestampQuery(hi,this.getTimestampUID(e),TL),t.cmdEncoderGPU=this.device.createCommandEncoder(SL),t.passEncoderGPU=t.cmdEncoderGPU.beginComputePass(TL),t.currentPipeline=null,SL.reset(),TL.reset()}compute(e,t,i,n,r=null){const s=this.get(t),a=this.get(e),{passEncoderGPU:o}=a,l=this.get(n).pipeline;a.currentPipeline!==l&&(o.setPipeline(l),a.currentPipeline=l);for(let e=0,t=i.length;e<t;e++){const t=i[e],n=this.get(t);o.setBindGroup(e,n.group)}if(null===r&&(r=t.dispatchSize||t.count),r&&r.isIndirectStorageBufferAttribute){const e=this.get(r).buffer;return void o.dispatchWorkgroupsIndirect(e,0)}if("number"==typeof r){const e=r;if(void 0===s.dispatchSize||s.count!==e){s.dispatchSize=[0,1,1],s.count=e;const i=t.workgroupSize;let n=i[0];for(let e=1;e<i.length;e++)n*=i[e];const a=Math.ceil(e/n),o=this.device.limits.maxComputeWorkgroupsPerDimension;r=[a,1,1],a>o&&(r[0]=Math.min(a,o),r[1]=Math.ceil(a/o)),s.dispatchSize=r}r=s.dispatchSize}o.dispatchWorkgroups(r[0],r[1]||1,r[2]||1)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),jN(this.device,t.cmdEncoderGPU.finish())}_draw(e,t,i,n,r,s,a,o,l,c=-1){const{object:u,material:h,context:d}=e,p=e.getIndex(),f=null!==p;l.pipeline!==n&&(o.setPipeline(n),l.pipeline=n);const m=l.bindingGroups;for(let e=0,t=r.length;e<t;e++){if(e===c)continue;const t=r[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?HA:WA;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||(yL.r=e.r,yL.g=e.g,yL.b=e.b,yL.a=t,o.setBlendConstant(yL),i.currentBlendColor.copy(e),i.currentBlendAlpha=t)}if(!0===u.isBatchedMesh){const e=u._mergedDrawStarts,i=u._mergedDrawCounts,n=u._mergedDrawInstanceCounts,r=u._mergedDrawCount,s=u._multiDrawBytesPerElement;let a=0;for(let l=0;l<r;l++){const r=n[l];!0===f?o.drawIndexed(i[l],r,e[l]/s,0,a):o.draw(i[l],r,e[l],a),t.update(u,i[l],r),a+=r}}else if(!0===f){const{vertexCount:i,instanceCount:n,firstVertex:r}=a,s=e.getIndirect();if(null!==s){const t=this.get(s).buffer,i=e.getIndirectOffset(),n=Array.isArray(i)?i:[i];for(let e=0;e<n.length;e++)o.drawIndexedIndirect(t,n[e])}else o.drawIndexed(i,n,r,0,0),t.update(u,i,n)}else{const{vertexCount:i,instanceCount:n,firstVertex:r}=a,s=e.getIndirect();if(null!==s){const t=this.get(s).buffer,i=e.getIndirectOffset(),n=Array.isArray(i)?i:[i];for(let e=0;e<n.length;e++)o.drawIndirect(t,n[e])}else o.draw(i,n,r,0),t.update(u,i,n)}}draw(e,t){const{object:i,context:n,pipeline:r}=e,s=this.get(n),a=this.get(r),o=a.pipeline;if(!0===a.error)return;const l=e.getDrawParameters();if(null===l)return;const c=e.getBindings(),u=e.getVertexBuffers();if(e.camera.isArrayCamera&&e.camera.cameras.length>0){const r=this.get(e.camera),a=e.camera.cameras,h=e.getBindingGroup("cameraIndex");if(void 0===r.indexesGPU||r.indexesGPU.length!==a.length){const e=this.get(h),t=[],i=new Uint32Array([0,0,0,0]);for(let n=0,r=a.length;n<r;n++){i[0]=n;const{layoutGPU:r}=e.layout,s=this.bindingUtils.createBindGroupIndex(i,r);t.push(s)}r.indexesGPU=t}const d=n.renderTarget,p=null===d||!0===d.isPostProcessingRenderTarget?this.renderer.getPixelRatio():1,f=h?c.indexOf(h):-1,m=n.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),n.viewportValue.minDepth,n.viewportValue.maxDepth),-1!==f&&r.indexesGPU){const e=r.indexesGPU[h];m.bindingGroups[f]!==e&&(a.setBindGroup(f,e),m.bindingGroups[f]=e)}this._draw(e,t,s,o,c,u,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(n.occlusionQueryCount>0){const e=this.getOcclusionData(n),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,c,u,l,s.currentPass,s.currentSets)}}needsRenderUpdate(e){const t=this.get(e),{object:i,material:n,geometry:r}=e,s=this.utils,a=s.getSampleCountRenderContext(e.context),o=s.getCurrentColorSpace(e.context),l=s.getCurrentColorFormat(e.context),c=s.getCurrentDepthStencilFormat(e.context),u=s.getPrimitiveTopology(i,n),h=s.getStripIndexFormat(i,r),d=i.isMesh&&i.matrixWorld.determinantAffine()<0;let p=!1;return t.material===n&&t.materialVersion===n.version&&t.transparent===n.transparent&&t.blending===n.blending&&t.premultipliedAlpha===n.premultipliedAlpha&&t.blendSrc===n.blendSrc&&t.blendDst===n.blendDst&&t.blendEquation===n.blendEquation&&t.blendSrcAlpha===n.blendSrcAlpha&&t.blendDstAlpha===n.blendDstAlpha&&t.blendEquationAlpha===n.blendEquationAlpha&&t.colorWrite===n.colorWrite&&t.depthWrite===n.depthWrite&&t.depthTest===n.depthTest&&t.depthFunc===n.depthFunc&&t.stencilWrite===n.stencilWrite&&t.stencilFunc===n.stencilFunc&&t.stencilFail===n.stencilFail&&t.stencilZFail===n.stencilZFail&&t.stencilZPass===n.stencilZPass&&t.stencilFuncMask===n.stencilFuncMask&&t.stencilWriteMask===n.stencilWriteMask&&t.polygonOffset===n.polygonOffset&&t.polygonOffsetFactor===n.polygonOffsetFactor&&t.polygonOffsetUnits===n.polygonOffsetUnits&&t.side===n.side&&t.alphaToCoverage===n.alphaToCoverage&&t.sampleCount===a&&t.colorSpace===o&&t.colorFormat===l&&t.depthStencilFormat===c&&t.primitiveTopology===u&&t.stripIndexFormat===h&&t.frontFaceCW===d&&t.geometryVersion===e.geometryVersion&&t.clippingContextCacheKey===e.clippingContextCacheKey||(t.material=n,t.materialVersion=n.version,t.transparent=n.transparent,t.blending=n.blending,t.premultipliedAlpha=n.premultipliedAlpha,t.blendSrc=n.blendSrc,t.blendDst=n.blendDst,t.blendEquation=n.blendEquation,t.blendSrcAlpha=n.blendSrcAlpha,t.blendDstAlpha=n.blendDstAlpha,t.blendEquationAlpha=n.blendEquationAlpha,t.colorWrite=n.colorWrite,t.depthWrite=n.depthWrite,t.depthTest=n.depthTest,t.depthFunc=n.depthFunc,t.stencilWrite=n.stencilWrite,t.stencilFunc=n.stencilFunc,t.stencilFail=n.stencilFail,t.stencilZFail=n.stencilZFail,t.stencilZPass=n.stencilZPass,t.stencilFuncMask=n.stencilFuncMask,t.stencilWriteMask=n.stencilWriteMask,t.polygonOffset=n.polygonOffset,t.polygonOffsetFactor=n.polygonOffsetFactor,t.polygonOffsetUnits=n.polygonOffsetUnits,t.side=n.side,t.alphaToCoverage=n.alphaToCoverage,t.sampleCount=a,t.colorSpace=o,t.colorFormat=l,t.depthStencilFormat=c,t.primitiveTopology=u,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:n}=e,r=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,r.getSampleCountRenderContext(s),r.getCurrentColorSpace(s),r.getCurrentColorFormat(s),r.getCurrentDepthStencilFormat(s),r.getPrimitiveTopology(t,i),r.getStripIndexFormat(t,n),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,n,r,s){return this.textureUtils.copyTextureToBuffer(e,t,i,n,r,s)}initTimestampQuery(e,t,i){if(!this.trackTimestamp)return void(i.timestampWrites=void 0);this.timestampQueryPool[e]||(this.timestampQueryPool[e]=new _L(this.device,e,2048));const n=this.timestampQueryPool[e],r=n.allocateQueriesForContext(t);wL.querySet=n.querySet,wL.beginningOfPassWriteIndex=r,wL.endOfPassWriteIndex=r+1,i.timestampWrites=wL}createNodeBuilder(e,t){return new XP(e,t)}createProgram(e){const t=this.get(e);EL.label=e.stage+(""!==e.name?`_${e.name}`:""),EL.code=e.code,t.module={module:this.device.createShaderModule(EL),entryPoint:"main"},EL.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),n=i.currentPass.finish();this.get(t).bundleGPU=n,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,n=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,r=[];e.visibility&wA.VERTEX&&r.push("vertex"),e.visibility&wA.FRAGMENT&&r.push("fragment"),e.visibility&wA.COMPUTE&&r.push("compute");const s=`(${r.join(",")})`;xL.label=`bindingBuffer${e.id}_${e.name}_${s}`,xL.size=i,xL.usage=n;const a=this.device.createBuffer(xL);xL.reset(),t.buffer=a}}destroyUniformBuffer(e){this.get(e).buffer.destroy(),this.delete(e)}createBindings(e,t,i,n){this.bindingUtils.createBindings(e,t,i,n)}updateBindings(e,t,i,n){this.bindingUtils.createBindings(e,t,i,n)}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!==BN[e]&&(e=BN[e]),this.device.features.has(e)}copyTextureToTexture(e,t,i=null,n=null,r=0,s=0){let a=0,o=0,l=0,c=0,u=0,h=0,d=e.image.width,p=e.image.height,f=1;null!==i&&(!0===i.isBox3?(c=i.min.x,u=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):(c=i.min.x,u=i.min.y,d=i.max.x-i.min.x,p=i.max.y-i.min.y,f=1)),null!==n&&(a=n.x,o=n.y,l=n.z||0),SL.label="copyTextureToTexture_"+e.id+"_"+t.id;const m=this.device.createCommandEncoder(SL);SL.reset();const g=this.get(e).texture,_=this.get(t).texture;AL.texture=g,AL.mipLevel=r,AL.origin.x=c,AL.origin.y=u,AL.origin.z=h,RL.texture=_,RL.mipLevel=s,RL.origin.x=a,RL.origin.y=o,RL.origin.z=l,PL.width=d,PL.height=p,PL.depthOrArrayLayers=f,m.copyTextureToTexture(AL,RL,PL),AL.reset(),RL.reset(),PL.reset(),jN(this.device,m.finish()),0===s&&!0===t.generateMipmaps&&!0===t.mipmapsAutoUpdate&&this.textureUtils.generateMipmaps(t)}copyFramebufferToTexture(e,t,i){const n=this.get(t);let r=null;r=t.renderTarget?e.isDepthTexture?this.get(t.depthTexture).texture:this.get(t.textures[0]).texture:e.isDepthTexture?this.textureUtils.getDepthBuffer(t.depth,t.stencil):this.context.getCurrentTexture();const s=this.get(e).texture;if(r.format!==s.format)return void Mi("WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.",r.format,s.format);const a=!0===e.generateMipmaps&&!0===e.mipmapsAutoUpdate&&s.mipLevelCount>1;if(n.encoder&&!0===this._isRenderCameraDepthArray(t)){const o=this._finishArrayCameraBundleEncoders(n);return n.arrayCameraRenderStages.push({bundles:o,framebufferCopy:{texture:e,sourceGPU:r,destinationGPU:s,rectangle:{x:i.x,y:i.y,z:i.z,w:i.w},generateMipmaps:a}}),void this._createArrayCameraBundleEncoders(t,n)}let o;if(n.currentPass?(n.currentPass.end(),o=n.encoder):(SL.label="copyFramebufferToTexture_"+e.id,o=this.device.createCommandEncoder(SL),SL.reset()),this._copyFramebufferToTexture(o,e,r,s,i,0,a),n.currentPass){const{descriptor:e}=n;for(let t=0;t<e.colorAttachments.length;t++)e.colorAttachments[t].loadOp=OA;t.depth&&(e.depthStencilAttachment.depthLoadOp=OA),t.stencil&&(e.depthStencilAttachment.stencilLoadOp=OA),n.currentPass=o.beginRenderPass(e),this._resetRenderContextData(n),t.viewport&&this.updateViewport(t),t.scissor&&this.updateScissor(t)}else jN(this.device,o.finish())}_copyFramebufferToTexture(e,t,i,n,r,s=0,a=t.generateMipmaps){AL.texture=i,AL.origin.x=r.x,AL.origin.y=r.y,AL.origin.z=s,RL.texture=n,PL.width=r.z,PL.height=r.w,e.copyTextureToTexture(AL,RL,PL),AL.reset(),RL.reset(),PL.reset(),!0===a&&n.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 DL extends io{constructor(e,t,i,n,r,s){super(e,t,i,n,r,s),this.iesMap=null}copy(e,t){return super.copy(e,t),this.iesMap=e.iesMap,this}}class IL extends io{constructor(e,t,i,n,r,s){super(e,t,i,n,r,s),this.aspect=null}copy(e,t){return super.copy(e,t),this.aspect=e.aspect,this}}ro.registerNode(Bx),oo.registerNode(DE),co.registerNode(VE),io.registerNode(FE),lo.registerNode(LE),Va.registerNode(IE),ho.registerNode(OE),DL.registerNode(UE),IL.registerNode(kE);class FL extends aw{constructor(){super(),this.addMaterial(oT,"MeshPhongMaterial"),this.addMaterial(RT,"MeshStandardMaterial"),this.addMaterial(NT,"MeshPhysicalMaterial"),this.addMaterial(IT,"MeshToonMaterial"),this.addMaterial(eT,"MeshBasicMaterial"),this.addMaterial(sT,"MeshLambertMaterial"),this.addMaterial(HS,"MeshNormalMaterial"),this.addMaterial(UT,"MeshMatcapMaterial"),this.addMaterial(DS,"LineBasicMaterial"),this.addMaterial(FS,"LineDashedMaterial"),this.addMaterial(GT,"PointsMaterial"),this.addMaterial(BT,"SpriteMaterial"),this.addMaterial(jT,"ShadowMaterial"),this.addToneMapping(Ly,1),this.addToneMapping(Dy,2),this.addToneMapping(Iy,3),this.addToneMapping(Uy,4),this.addToneMapping(zy,6),this.addToneMapping(Gy,7)}}class UL extends Aw{constructor(e={}){let t;e.forceWebGL?t=xA:(t=LL,e.getFallback=()=>(Ti("WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new xA(e)));super(new t(e),e),this.library=new FL,this.isWebGPURenderer=!0,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}ro.registerNode(Bx),oo.registerNode(DE),co.registerNode(VE),io.registerNode(FE),lo.registerNode(LE),Va.registerNode(IE),ho.registerNode(OE),DL.registerNode(UE),IL.registerNode(kE);const OL={type:"change"},BL={type:"start"},kL={type:"end"},zL=1e-6,GL=-1,VL=0,HL=1,WL=2,jL=3,$L=4,XL=new Vi,qL=new Vi,YL=new Wi,KL=new Wi,ZL=new Wi,QL=new Hi,JL=new Wi,eD=new Wi,tD=new Wi,iD=new Wi;class nD extends Eo{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=GL,this.keyState=GL,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=sD.bind(this),this._onPointerDown=rD.bind(this),this._onPointerUp=aD.bind(this),this._onPointerCancel=oD.bind(this),this._onContextMenu=fD.bind(this),this._onMouseWheel=pD.bind(this),this._onKeyDown=cD.bind(this),this._onKeyUp=lD.bind(this),this._onTouchStart=mD.bind(this),this._onTouchMove=gD.bind(this),this._onTouchEnd=_D.bind(this),this._onMouseDown=uD.bind(this),this._onMouseMove=hD.bind(this),this._onMouseUp=dD.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)>zL,t=this._lastUp.distanceToSquared(this.object.up)>zL;(e||t)&&(this.dispatchEvent(OL),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)>zL,t=this._lastUp.distanceToSquared(this.object.up)>zL,i=this._lastZoom!==this.object.zoom;(e||t||i)&&(this.dispatchEvent(OL),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=GL,this.keyState=GL,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(OL),this._lastPosition.copy(this.object.position),this._lastUp.copy(this.object.up),this._lastZoom=this.object.zoom}_panCamera(){if(qL.copy(this._panEnd).sub(this._panStart),qL.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;qL.x*=e,qL.y*=t}qL.multiplyScalar(this._eye.length()*this.panSpeed),KL.copy(this._eye).cross(this.object.up).setLength(qL.x),KL.add(YL.copy(this.object.up).setLength(qL.y)),this.object.position.add(KL),this.target.add(KL),this.staticMoving?this._panStart.copy(this._panEnd):this._panStart.add(qL.subVectors(this._panEnd,this._panStart).multiplyScalar(this.dynamicDampingFactor))}}_rotateCamera(){iD.set(this._moveCurr.x-this._movePrev.x,this._moveCurr.y-this._movePrev.y,0);let e=iD.length();e?(this._eye.copy(this.object.position).sub(this.target),JL.copy(this._eye).normalize(),eD.copy(this.object.up).normalize(),tD.crossVectors(eD,JL).normalize(),eD.setLength(this._moveCurr.y-this._movePrev.y),tD.setLength(this._moveCurr.x-this._movePrev.x),iD.copy(eD.add(tD)),ZL.crossVectors(iD,this._eye).normalize(),e*=this.rotateSpeed,QL.setFromAxisAngle(ZL,e),this._eye.applyQuaternion(QL),this.object.up.applyQuaternion(QL),this._lastAxis.copy(ZL),this._lastAngle=e):!this.staticMoving&&this._lastAngle&&(this._lastAngle*=Math.sqrt(1-this.dynamicDampingFactor),this._eye.copy(this.object.position).sub(this.target),QL.setFromAxisAngle(this._lastAxis,this._lastAngle),this._eye.applyQuaternion(QL),this.object.up.applyQuaternion(QL)),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)}JL.copy(this._eye).normalize(),QL.setFromAxisAngle(JL,this._lastRollAngle),this.object.up.applyQuaternion(QL)}_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}`,n=this._pointerPositions[e.pointerId],r=this._pointerPositions[t.pointerId],s=Math.atan2(r.y-n.y,r.x-n.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===$L?(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 XL.set((e-this.screen.left)/this.screen.width,(t-this.screen.top)/this.screen.height),XL}_getMouseOnCircle(e,t){return XL.set((e-.5*this.screen.width-this.screen.left)/(.5*this.screen.width),(this.screen.height+2*(this.screen.top-t))/this.screen.width),XL}_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 rD(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 sD(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchMove(e):this._onMouseMove(e))}function aD(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 oD(e){this._removePointer(e)}function lD(){!1!==this.enabled&&(this.keyState=GL,window.addEventListener("keydown",this._onKeyDown))}function cD(e){!1!==this.enabled&&(window.removeEventListener("keydown",this._onKeyDown),this.keyState===GL&&(e.code!==this.keys[VL]||this.noRotate?e.code!==this.keys[HL]||this.noZoom?e.code!==this.keys[WL]||this.noPan||(this.keyState=WL):this.keyState=HL:this.keyState=VL))}function uD(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=HL;break;case P:this.state=VL;break;case D:this.state=WL;break;default:this.state=GL}const i=this.keyState!==GL?this.keyState:this.state;i!==VL||this.noRotate?i!==HL||this.noZoom?i!==WL||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(BL)}function hD(e){const t=this.keyState!==GL?this.keyState:this.state;t!==VL||this.noRotate?t!==HL||this.noZoom?t!==WL||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 dD(){this.state=GL,this.dispatchEvent(kL)}function pD(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(BL),this.dispatchEvent(kL)}}function fD(e){!1!==this.enabled&&e.preventDefault()}function mD(e){if(this._trackPointer(e),1===this._pointers.length)this.state=jL,this._moveCurr.copy(this._getMouseOnCircle(this._pointers[0].pageX,this._pointers[0].pageY)),this._movePrev.copy(this._moveCurr);else{this.state=$L;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,n=(this._pointers[0].pageY+this._pointers[1].pageY)/2;this._panStart.copy(this._getMouseOnScreen(i,n)),this._panEnd.copy(this._panStart)}this.dispatchEvent(BL)}function gD(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,n=e.pageY-t.y;this._touchZoomDistanceEnd=Math.sqrt(i*i+n*n);const r=(e.pageX+t.x)/2,s=(e.pageY+t.y)/2;this._panEnd.copy(this._getMouseOnScreen(r,s))}}function _D(e){switch(this._pointers.length){case 0:this.state=GL;break;case 1:this.state=jL,this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY)),this._movePrev.copy(this._moveCurr);break;case 2:this.state=$L;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(kL)}const vD={IDLE:Symbol(),ROTATE:Symbol(),PAN:Symbol(),SCALE:Symbol(),FOV:Symbol(),FOCUS:Symbol(),ZROTATE:Symbol(),ANIMATION_FOCUS:Symbol(),ANIMATION_ROTATE:Symbol()},bD={NONE:Symbol(),ONE_FINGER:Symbol(),ONE_FINGER_SWITCHED:Symbol(),TWO_FINGER:Symbol(),MULT_FINGER:Symbol(),CURSOR:Symbol()},yD={x:0,y:0},xD={camera:new mn,gizmos:new mn},SD={type:"change"},TD={type:"start"},MD={type:"end"},ED=new bo,wD=new Wi,AD=new mn,RD=new mn,CD=new Wi,ND=1e-6;class PD extends Eo{constructor(e,t=null,i=null){super(e,t),this.scene=i,this.target=new Wi,this._currentTarget=new Wi,this.radiusFactor=.67,this.mouseActions=[],this._mouseOp=null,this._v2_1=new Vi,this._v3_1=new Wi,this._v3_2=new Wi,this._m4_1=new mn,this._m4_2=new mn,this._quat=new Hi,this._translationMatrix=new mn,this._rotationMatrix=new mn,this._scaleMatrix=new mn,this._rotationAxis=new Wi,this._cameraMatrixState=new mn,this._cameraProjectionState=new mn,this._fovState=1,this._upState=new Wi,this._zoomState=1,this._nearPos=0,this._farPos=0,this._gizmoMatrixState=new mn,this._up0=new Wi,this._zoom0=1,this._fov0=0,this._initialNear=0,this._nearPos0=0,this._initialFar=0,this._farPos0=0,this._cameraMatrixState0=new mn,this._gizmoMatrixState0=new mn,this._target0=new Wi,this._button=-1,this._touchStart=[],this._touchCurrent=[],this._input=bD.NONE,this._switchSensibility=32,this._startFingerDistance=0,this._currentFingerDistance=0,this._startFingerRotation=0,this._currentFingerRotation=0,this._devPxRatio=0,this._downValid=!0,this._nclicks=0,this._downEvents=[],this._downStart=0,this._clickStart=0,this._maxDownTime=250,this._maxInterval=300,this._posThreshold=24,this._movementThreshold=24,this._currentCursorPosition=new Wi,this._startCursorPosition=new Wi,this._grid=null,this._gridPosition=new Wi,this._gizmos=new Hn,this._curvePts=128,this._timeStart=-1,this._animationId=-1,this.focusAnimationTime=500,this._timePrev=0,this._timeCurrent=0,this._anglePrev=0,this._angleCurrent=0,this._cursorPosPrev=new Wi,this._cursorPosCurr=new Wi,this._wPrev=0,this._wCurr=0,this.adjustNearFar=!1,this.scaleFactor=1.1,this.dampingFactor=25,this.wMax=20,this.enableAnimations=!0,this.enableGrid=!1,this.cursorZoom=!1,this.minFov=5,this.maxFov=90,this.rotateSpeed=1,this.enablePan=!0,this.enableRotate=!0,this.enableZoom=!0,this.enableGizmos=!0,this.enableFocus=!0,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this._tbRadius=1,this._state=vD.IDLE,this.setCamera(e),null!=this.scene&&this.scene.add(this._gizmos),this.initializeMouseActions(),this._onContextMenu=DD.bind(this),this._onWheel=BD.bind(this),this._onPointerUp=OD.bind(this),this._onPointerMove=UD.bind(this),this._onPointerDown=FD.bind(this),this._onPointerCancel=ID.bind(this),this._onWindowResize=LD.bind(this),null!==t&&this.connect(t)}connect(e){super.connect(e),this._devPxRatio=window.devicePixelRatio,this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onWheel,{passive:!1}),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerCancel),window.addEventListener("resize",this._onWindowResize),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointercancel",this._onPointerCancel),this.domElement.removeEventListener("wheel",this._onWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),window.removeEventListener("pointermove",this._onPointerMove),window.removeEventListener("pointerup",this._onPointerUp),window.removeEventListener("resize",this._onWindowResize),this.domElement.style.touchAction=""}onSinglePanStart(e,t){if(this.enabled)switch(this.dispatchEvent(TD),this.setCenter(e.clientX,e.clientY),t){case"PAN":if(!this.enablePan)return;-1!=this._animationId&&(cancelAnimationFrame(this._animationId),this._animationId=-1,this._timeStart=-1,this.activateGizmos(!1),this.dispatchEvent(SD)),this.updateTbState(vD.PAN,!0),this._startCursorPosition.copy(this.unprojectOnTbPlane(this.object,yD.x,yD.y,this.domElement)),this.enableGrid&&(this.drawGrid(),this.dispatchEvent(SD));break;case"ROTATE":if(!this.enableRotate)return;-1!=this._animationId&&(cancelAnimationFrame(this._animationId),this._animationId=-1,this._timeStart=-1),this.updateTbState(vD.ROTATE,!0),this._startCursorPosition.copy(this.unprojectOnTbSurface(this.object,yD.x,yD.y,this.domElement,this._tbRadius)),this.activateGizmos(!0),this.enableAnimations&&(this._timePrev=this._timeCurrent=performance.now(),this._angleCurrent=this._anglePrev=0,this._cursorPosPrev.copy(this._startCursorPosition),this._cursorPosCurr.copy(this._cursorPosPrev),this._wCurr=0,this._wPrev=this._wCurr),this.dispatchEvent(SD);break;case"FOV":if(!this.object.isPerspectiveCamera||!this.enableZoom)return;-1!=this._animationId&&(cancelAnimationFrame(this._animationId),this._animationId=-1,this._timeStart=-1,this.activateGizmos(!1),this.dispatchEvent(SD)),this.updateTbState(vD.FOV,!0),this._startCursorPosition.setY(.5*this.getCursorNDC(yD.x,yD.y,this.domElement).y),this._currentCursorPosition.copy(this._startCursorPosition);break;case"ZOOM":if(!this.enableZoom)return;-1!=this._animationId&&(cancelAnimationFrame(this._animationId),this._animationId=-1,this._timeStart=-1,this.activateGizmos(!1),this.dispatchEvent(SD)),this.updateTbState(vD.SCALE,!0),this._startCursorPosition.setY(.5*this.getCursorNDC(yD.x,yD.y,this.domElement).y),this._currentCursorPosition.copy(this._startCursorPosition)}}onSinglePanMove(e,t){if(this.enabled){const i=t!=this._state;switch(this.setCenter(e.clientX,e.clientY),t){case vD.PAN:this.enablePan&&(i?(this.dispatchEvent(MD),this.dispatchEvent(TD),this.updateTbState(t,!0),this._startCursorPosition.copy(this.unprojectOnTbPlane(this.object,yD.x,yD.y,this.domElement)),this.enableGrid&&this.drawGrid(),this.activateGizmos(!1)):(this._currentCursorPosition.copy(this.unprojectOnTbPlane(this.object,yD.x,yD.y,this.domElement)),this.applyTransformMatrix(this.pan(this._startCursorPosition,this._currentCursorPosition))));break;case vD.ROTATE:if(this.enableRotate)if(i)this.dispatchEvent(MD),this.dispatchEvent(TD),this.updateTbState(t,!0),this._startCursorPosition.copy(this.unprojectOnTbSurface(this.object,yD.x,yD.y,this.domElement,this._tbRadius)),this.enableGrid&&this.disposeGrid(),this.activateGizmos(!0);else{this._currentCursorPosition.copy(this.unprojectOnTbSurface(this.object,yD.x,yD.y,this.domElement,this._tbRadius));const e=this._startCursorPosition.distanceTo(this._currentCursorPosition),t=this._startCursorPosition.angleTo(this._currentCursorPosition),i=Math.max(e/this._tbRadius,t)*this.rotateSpeed;this.applyTransformMatrix(this.rotate(this.calculateRotationAxis(this._startCursorPosition,this._currentCursorPosition),i)),this.enableAnimations&&(this._timePrev=this._timeCurrent,this._timeCurrent=performance.now(),this._anglePrev=this._angleCurrent,this._angleCurrent=i,this._cursorPosPrev.copy(this._cursorPosCurr),this._cursorPosCurr.copy(this._currentCursorPosition),this._wPrev=this._wCurr,this._wCurr=this.calculateAngularSpeed(this._anglePrev,this._angleCurrent,this._timePrev,this._timeCurrent))}break;case vD.SCALE:if(this.enableZoom)if(i)this.dispatchEvent(MD),this.dispatchEvent(TD),this.updateTbState(t,!0),this._startCursorPosition.setY(.5*this.getCursorNDC(yD.x,yD.y,this.domElement).y),this._currentCursorPosition.copy(this._startCursorPosition),this.enableGrid&&this.disposeGrid(),this.activateGizmos(!1);else{const e=8;this._currentCursorPosition.setY(.5*this.getCursorNDC(yD.x,yD.y,this.domElement).y);const t=this._currentCursorPosition.y-this._startCursorPosition.y;let i=1;t<0?i=1/Math.pow(this.scaleFactor,-t*e):t>0&&(i=Math.pow(this.scaleFactor,t*e)),this._v3_1.setFromMatrixPosition(this._gizmoMatrixState),this.applyTransformMatrix(this.scale(i,this._v3_1))}break;case vD.FOV:if(this.enableZoom&&this.object.isPerspectiveCamera)if(i)this.dispatchEvent(MD),this.dispatchEvent(TD),this.updateTbState(t,!0),this._startCursorPosition.setY(.5*this.getCursorNDC(yD.x,yD.y,this.domElement).y),this._currentCursorPosition.copy(this._startCursorPosition),this.enableGrid&&this.disposeGrid(),this.activateGizmos(!1);else{const e=8;this._currentCursorPosition.setY(.5*this.getCursorNDC(yD.x,yD.y,this.domElement).y);const t=this._currentCursorPosition.y-this._startCursorPosition.y;let i=1;t<0?i=1/Math.pow(this.scaleFactor,-t*e):t>0&&(i=Math.pow(this.scaleFactor,t*e)),this._v3_1.setFromMatrixPosition(this._cameraMatrixState);const n=this._v3_1.distanceTo(this._gizmos.position);let r=n/i;r=Gi.clamp(r,this.minDistance,this.maxDistance);const s=n*Math.tan(Gi.DEG2RAD*this._fovState*.5);let a=Gi.RAD2DEG*(2*Math.atan(s/r));a=Gi.clamp(a,this.minFov,this.maxFov);const o=s/Math.tan(Gi.DEG2RAD*(a/2));i=n/o,this._v3_2.setFromMatrixPosition(this._gizmoMatrixState),this.setFov(a),this.applyTransformMatrix(this.scale(i,this._v3_2,!1)),wD.copy(this._gizmos.position).sub(this.object.position).normalize().multiplyScalar(o/n),this._m4_1.makeTranslation(wD.x,wD.y,wD.z)}}this.dispatchEvent(SD)}}onSinglePanEnd(){if(this._state==vD.ROTATE){if(!this.enableRotate)return;if(this.enableAnimations){if(performance.now()-this._timeCurrent<120){const e=Math.abs((this._wPrev+this._wCurr)/2),t=this;this._animationId=window.requestAnimationFrame(function(i){t.updateTbState(vD.ANIMATION_ROTATE,!0);const n=t.calculateRotationAxis(t._cursorPosPrev,t._cursorPosCurr);t.onRotationAnim(i,n,Math.min(e,t.wMax))})}else this.updateTbState(vD.IDLE,!1),this.activateGizmos(!1),this.dispatchEvent(SD)}else this.updateTbState(vD.IDLE,!1),this.activateGizmos(!1),this.dispatchEvent(SD)}else this._state!=vD.PAN&&this._state!=vD.IDLE||(this.updateTbState(vD.IDLE,!1),this.enableGrid&&this.disposeGrid(),this.activateGizmos(!1),this.dispatchEvent(SD));this.dispatchEvent(MD)}onDoubleTap(e){if(this.enabled&&this.enablePan&&this.enableFocus&&null!=this.scene){this.dispatchEvent(TD),this.setCenter(e.clientX,e.clientY);const t=this.unprojectOnObj(this.getCursorNDC(yD.x,yD.y,this.domElement),this.object);if(null!=t&&this.enableAnimations){const e=this;-1!=this._animationId&&window.cancelAnimationFrame(this._animationId),this._timeStart=-1,this._animationId=window.requestAnimationFrame(function(i){e.updateTbState(vD.ANIMATION_FOCUS,!0),e.onFocusAnim(i,t,e._cameraMatrixState,e._gizmoMatrixState)})}else null==t||this.enableAnimations||(this.updateTbState(vD.FOCUS,!0),this.focus(t,this.scaleFactor),this.updateTbState(vD.IDLE,!1),this.dispatchEvent(SD))}this.dispatchEvent(MD)}onDoublePanStart(){this.enabled&&this.enablePan&&(this.dispatchEvent(TD),this.updateTbState(vD.PAN,!0),this.setCenter((this._touchCurrent[0].clientX+this._touchCurrent[1].clientX)/2,(this._touchCurrent[0].clientY+this._touchCurrent[1].clientY)/2),this._startCursorPosition.copy(this.unprojectOnTbPlane(this.object,yD.x,yD.y,this.domElement,!0)),this._currentCursorPosition.copy(this._startCursorPosition),this.activateGizmos(!1))}onDoublePanMove(){this.enabled&&this.enablePan&&(this.setCenter((this._touchCurrent[0].clientX+this._touchCurrent[1].clientX)/2,(this._touchCurrent[0].clientY+this._touchCurrent[1].clientY)/2),this._state!=vD.PAN&&(this.updateTbState(vD.PAN,!0),this._startCursorPosition.copy(this._currentCursorPosition)),this._currentCursorPosition.copy(this.unprojectOnTbPlane(this.object,yD.x,yD.y,this.domElement,!0)),this.applyTransformMatrix(this.pan(this._startCursorPosition,this._currentCursorPosition,!0)),this.dispatchEvent(SD))}onDoublePanEnd(){this.updateTbState(vD.IDLE,!1),this.dispatchEvent(MD)}onRotateStart(){this.enabled&&this.enableRotate&&(this.dispatchEvent(TD),this.updateTbState(vD.ZROTATE,!0),this._startFingerRotation=this.getAngle(this._touchCurrent[1],this._touchCurrent[0])+this.getAngle(this._touchStart[1],this._touchStart[0]),this._currentFingerRotation=this._startFingerRotation,this.object.getWorldDirection(this._rotationAxis),this.enablePan||this.enableZoom||this.activateGizmos(!0))}onRotateMove(){if(this.enabled&&this.enableRotate){let e;this.setCenter((this._touchCurrent[0].clientX+this._touchCurrent[1].clientX)/2,(this._touchCurrent[0].clientY+this._touchCurrent[1].clientY)/2),this._state!=vD.ZROTATE&&(this.updateTbState(vD.ZROTATE,!0),this._startFingerRotation=this._currentFingerRotation),this._currentFingerRotation=this.getAngle(this._touchCurrent[1],this._touchCurrent[0])+this.getAngle(this._touchStart[1],this._touchStart[0]),this.enablePan?(this._v3_2.setFromMatrixPosition(this._gizmoMatrixState),e=this.unprojectOnTbPlane(this.object,yD.x,yD.y,this.domElement).applyQuaternion(this.object.quaternion).multiplyScalar(1/this.object.zoom).add(this._v3_2)):e=(new Wi).setFromMatrixPosition(this._gizmoMatrixState);const t=Gi.DEG2RAD*(this._startFingerRotation-this._currentFingerRotation);this.applyTransformMatrix(this.zRotate(e,t)),this.dispatchEvent(SD)}}onRotateEnd(){this.updateTbState(vD.IDLE,!1),this.activateGizmos(!1),this.dispatchEvent(MD)}onPinchStart(){this.enabled&&this.enableZoom&&(this.dispatchEvent(TD),this.updateTbState(vD.SCALE,!0),this._startFingerDistance=this.calculatePointersDistance(this._touchCurrent[0],this._touchCurrent[1]),this._currentFingerDistance=this._startFingerDistance,this.activateGizmos(!1))}onPinchMove(){if(this.enabled&&this.enableZoom){this.setCenter((this._touchCurrent[0].clientX+this._touchCurrent[1].clientX)/2,(this._touchCurrent[0].clientY+this._touchCurrent[1].clientY)/2);const e=12;this._state!=vD.SCALE&&(this._startFingerDistance=this._currentFingerDistance,this.updateTbState(vD.SCALE,!0)),this._currentFingerDistance=Math.max(this.calculatePointersDistance(this._touchCurrent[0],this._touchCurrent[1]),e*this._devPxRatio);const t=this._currentFingerDistance/this._startFingerDistance;let i;this.enablePan?this.object.isOrthographicCamera?i=this.unprojectOnTbPlane(this.object,yD.x,yD.y,this.domElement).applyQuaternion(this.object.quaternion).multiplyScalar(1/this.object.zoom).add(this._gizmos.position):this.object.isPerspectiveCamera&&(i=this.unprojectOnTbPlane(this.object,yD.x,yD.y,this.domElement).applyQuaternion(this.object.quaternion).add(this._gizmos.position)):i=this._gizmos.position,this.applyTransformMatrix(this.scale(t,i)),this.dispatchEvent(SD)}}onPinchEnd(){this.updateTbState(vD.IDLE,!1),this.dispatchEvent(MD)}onTriplePanStart(){if(this.enabled&&this.enableZoom){this.dispatchEvent(TD),this.updateTbState(vD.SCALE,!0);let e=0,t=0;const i=this._touchCurrent.length;for(let n=0;n<i;n++)e+=this._touchCurrent[n].clientX,t+=this._touchCurrent[n].clientY;this.setCenter(e/i,t/i),this._startCursorPosition.setY(.5*this.getCursorNDC(yD.x,yD.y,this.domElement).y),this._currentCursorPosition.copy(this._startCursorPosition)}}onTriplePanMove(){if(this.enabled&&this.enableZoom){let e=0,t=0;const i=this._touchCurrent.length;for(let n=0;n<i;n++)e+=this._touchCurrent[n].clientX,t+=this._touchCurrent[n].clientY;this.setCenter(e/i,t/i);const n=8;this._currentCursorPosition.setY(.5*this.getCursorNDC(yD.x,yD.y,this.domElement).y);const r=this._currentCursorPosition.y-this._startCursorPosition.y;let s=1;r<0?s=1/Math.pow(this.scaleFactor,-r*n):r>0&&(s=Math.pow(this.scaleFactor,r*n)),this._v3_1.setFromMatrixPosition(this._cameraMatrixState);const a=this._v3_1.distanceTo(this._gizmos.position);let o=a/s;o=Gi.clamp(o,this.minDistance,this.maxDistance);const l=a*Math.tan(Gi.DEG2RAD*this._fovState*.5);let c=Gi.RAD2DEG*(2*Math.atan(l/o));c=Gi.clamp(c,this.minFov,this.maxFov);const u=l/Math.tan(Gi.DEG2RAD*(c/2));s=a/u,this._v3_2.setFromMatrixPosition(this._gizmoMatrixState),this.setFov(c),this.applyTransformMatrix(this.scale(s,this._v3_2,!1)),wD.copy(this._gizmos.position).sub(this.object.position).normalize().multiplyScalar(u/a),this._m4_1.makeTranslation(wD.x,wD.y,wD.z),this.dispatchEvent(SD)}}onTriplePanEnd(){this.updateTbState(vD.IDLE,!1),this.dispatchEvent(MD)}setCenter(e,t){yD.x=e,yD.y=t}initializeMouseActions(){this.setMouseAction("PAN",0,"CTRL"),this.setMouseAction("PAN",2),this.setMouseAction("ROTATE",0),this.setMouseAction("ZOOM","WHEEL"),this.setMouseAction("ZOOM",1),this.setMouseAction("FOV","WHEEL","SHIFT"),this.setMouseAction("FOV",1,"SHIFT")}compareMouseAction(e,t){return e.operation==t.operation&&(e.mouse==t.mouse&&e.key==t.key)}setMouseAction(e,t,i=null){let n;if(!["PAN","ROTATE","ZOOM","FOV"].includes(e)||![0,1,2,"WHEEL"].includes(t)||!["CTRL","SHIFT",null].includes(i))return!1;if("WHEEL"==t&&"ZOOM"!=e&&"FOV"!=e)return!1;switch(e){case"PAN":n=vD.PAN;break;case"ROTATE":n=vD.ROTATE;break;case"ZOOM":n=vD.SCALE;break;case"FOV":n=vD.FOV}const r={operation:e,mouse:t,key:i,state:n};for(let e=0;e<this.mouseActions.length;e++)if(this.mouseActions[e].mouse==r.mouse&&this.mouseActions[e].key==r.key)return this.mouseActions.splice(e,1,r),!0;return this.mouseActions.push(r),!0}unsetMouseAction(e,t=null){for(let i=0;i<this.mouseActions.length;i++)if(this.mouseActions[i].mouse==e&&this.mouseActions[i].key==t)return this.mouseActions.splice(i,1),!0;return!1}getOpFromAction(e,t){let i;for(let n=0;n<this.mouseActions.length;n++)if(i=this.mouseActions[n],i.mouse==e&&i.key==t)return i.operation;if(null!=t)for(let t=0;t<this.mouseActions.length;t++)if(i=this.mouseActions[t],i.mouse==e&&null==i.key)return i.operation;return null}getOpStateFromAction(e,t){let i;for(let n=0;n<this.mouseActions.length;n++)if(i=this.mouseActions[n],i.mouse==e&&i.key==t)return i.state;if(null!=t)for(let t=0;t<this.mouseActions.length;t++)if(i=this.mouseActions[t],i.mouse==e&&null==i.key)return i.state;return null}getAngle(e,t){return 180*Math.atan2(t.clientY-e.clientY,t.clientX-e.clientX)/Math.PI}updateTouchEvent(e){for(let t=0;t<this._touchCurrent.length;t++)if(this._touchCurrent[t].pointerId==e.pointerId){this._touchCurrent.splice(t,1,e);break}}applyTransformMatrix(e){if(null!=e.camera&&(this._m4_1.copy(this._cameraMatrixState).premultiply(e.camera),this._m4_1.decompose(this.object.position,this.object.quaternion,this.object.scale),this.object.updateMatrix(),this._state!=vD.ROTATE&&this._state!=vD.ZROTATE&&this._state!=vD.ANIMATION_ROTATE||this.object.up.copy(this._upState).applyQuaternion(this.object.quaternion)),null!=e.gizmos&&(this._m4_1.copy(this._gizmoMatrixState).premultiply(e.gizmos),this._m4_1.decompose(this._gizmos.position,this._gizmos.quaternion,this._gizmos.scale),this._gizmos.updateMatrix()),this._state==vD.SCALE||this._state==vD.FOCUS||this._state==vD.ANIMATION_FOCUS)if(this._tbRadius=this.calculateTbRadius(this.object),this.adjustNearFar){const e=this.object.position.distanceTo(this._gizmos.position),t=new pr;t.setFromObject(this._gizmos);const i=new Hr;t.getBoundingSphere(i);const n=Math.max(this._nearPos0,i.radius+i.center.length()),r=e-this._initialNear,s=Math.min(n,r);this.object.near=e-s;const a=Math.min(this._farPos0,-i.radius+i.center.length()),o=e-this._initialFar,l=Math.min(a,o);this.object.far=e-l,this.object.updateProjectionMatrix()}else{let e=!1;this.object.near!=this._initialNear&&(this.object.near=this._initialNear,e=!0),this.object.far!=this._initialFar&&(this.object.far=this._initialFar,e=!0),e&&this.object.updateProjectionMatrix()}}calculateAngularSpeed(e,t,i,n){const r=(n-i)/1e3;return 0==r?0:(t-e)/r}calculatePointersDistance(e,t){return Math.sqrt(Math.pow(t.clientX-e.clientX,2)+Math.pow(t.clientY-e.clientY,2))}calculateRotationAxis(e,t){return this._rotationMatrix.extractRotation(this._cameraMatrixState),this._quat.setFromRotationMatrix(this._rotationMatrix),this._rotationAxis.crossVectors(e,t).applyQuaternion(this._quat),this._rotationAxis.normalize().clone()}calculateTbRadius(e){const t=e.position.distanceTo(this._gizmos.position);if("PerspectiveCamera"==e.type){const i=Gi.DEG2RAD*e.fov*.5,n=Math.atan(e.aspect*Math.tan(i));return Math.tan(Math.min(i,n))*t*this.radiusFactor}if("OrthographicCamera"==e.type)return Math.min(e.top,e.right)*this.radiusFactor}focus(e,t,i=1){wD.copy(e).sub(this._gizmos.position).multiplyScalar(i),this._translationMatrix.makeTranslation(wD.x,wD.y,wD.z),AD.copy(this._gizmoMatrixState),this._gizmoMatrixState.premultiply(this._translationMatrix),this._gizmoMatrixState.decompose(this._gizmos.position,this._gizmos.quaternion,this._gizmos.scale),RD.copy(this._cameraMatrixState),this._cameraMatrixState.premultiply(this._translationMatrix),this._cameraMatrixState.decompose(this.object.position,this.object.quaternion,this.object.scale),this.enableZoom&&this.applyTransformMatrix(this.scale(t,this._gizmos.position)),this._gizmoMatrixState.copy(AD),this._cameraMatrixState.copy(RD)}drawGrid(){if(null!=this.scene){const e=8947848,t=3;let i,n,r,s;if(this.object.isOrthographicCamera){const e=this.object.right-this.object.left,a=this.object.bottom-this.object.top;r=Math.max(e,a),s=r/20,i=r/this.object.zoom*t,n=i/s*this.object.zoom}else if(this.object.isPerspectiveCamera){const e=this.object.position.distanceTo(this._gizmos.position),a=Gi.DEG2RAD*this.object.fov*.5,o=Math.atan(this.object.aspect*Math.tan(a));r=Math.tan(Math.max(a,o))*e*2,s=r/20,i=r*t,n=i/s}null==this._grid&&(this._grid=new Mo(i,n,e,e),this._grid.position.copy(this._gizmos.position),this._gridPosition.copy(this._grid.position),this._grid.quaternion.copy(this.object.quaternion),this._grid.rotateX(.5*Math.PI),this.scene.add(this._grid))}}dispose(){-1!=this._animationId&&window.cancelAnimationFrame(this._animationId),this.disconnect(),null!==this.scene&&this.scene.remove(this._gizmos),this.disposeGrid()}disposeGrid(){null!=this._grid&&null!=this.scene&&(this.scene.remove(this._grid),this._grid=null)}easeOutCubic(e){return 1-Math.pow(1-e,3)}activateGizmos(e){const t=this._gizmos.children[0],i=this._gizmos.children[1],n=this._gizmos.children[2];e?(t.material.setValues({opacity:1}),i.material.setValues({opacity:1}),n.material.setValues({opacity:1})):(t.material.setValues({opacity:.6}),i.material.setValues({opacity:.6}),n.material.setValues({opacity:.6}))}getCursorNDC(e,t,i){const n=i.getBoundingClientRect();return this._v2_1.setX((e-n.left)/n.width*2-1),this._v2_1.setY((n.bottom-t)/n.height*2-1),this._v2_1.clone()}getCursorPosition(e,t,i){return this._v2_1.copy(this.getCursorNDC(e,t,i)),this._v2_1.x*=.5*(this.object.right-this.object.left),this._v2_1.y*=.5*(this.object.top-this.object.bottom),this._v2_1.clone()}setCamera(e){e.lookAt(this.target),e.updateMatrix(),"PerspectiveCamera"==e.type&&(this._fov0=e.fov,this._fovState=e.fov),this._cameraMatrixState0.copy(e.matrix),this._cameraMatrixState.copy(this._cameraMatrixState0),this._cameraProjectionState.copy(e.projectionMatrix),this._zoom0=e.zoom,this._zoomState=this._zoom0,this._initialNear=e.near,this._nearPos0=e.position.distanceTo(this.target)-e.near,this._nearPos=this._initialNear,this._initialFar=e.far,this._farPos0=e.position.distanceTo(this.target)-e.far,this._farPos=this._initialFar,this._up0.copy(e.up),this._upState.copy(e.up),this.object=e,this.object.updateProjectionMatrix(),this._tbRadius=this.calculateTbRadius(e),this.makeGizmos(this.target,this._tbRadius)}setGizmosVisible(e){this._gizmos.visible=e,this.dispatchEvent(SD)}setTbRadius(e){this.radiusFactor=e,this._tbRadius=this.calculateTbRadius(this.object);const t=new pa(0,0,this._tbRadius,this._tbRadius).getPoints(this._curvePts),i=(new Zr).setFromPoints(t);for(const e in this._gizmos.children)this._gizmos.children[e].geometry=i;this.dispatchEvent(SD)}makeGizmos(e,t){const i=new pa(0,0,t,t).getPoints(this._curvePts),n=(new Zr).setFromPoints(i),r=new Ws({color:16744576,fog:!1,transparent:!0,opacity:.6}),s=new Ws({color:8454016,fog:!1,transparent:!0,opacity:.6}),a=new Ws({color:8421631,fog:!1,transparent:!0,opacity:.6}),o=new Qs(n,r),l=new Qs(n,s),c=new Qs(n,a),u=.5*Math.PI;if(o.rotation.y=u,l.rotation.x=u,this._gizmoMatrixState0.identity().setPosition(e),this._gizmoMatrixState.copy(this._gizmoMatrixState0),1!==this.object.zoom){const t=1/this.object.zoom;this._scaleMatrix.makeScale(t,t,t),this._translationMatrix.makeTranslation(-e.x,-e.y,-e.z),this._gizmoMatrixState.premultiply(this._translationMatrix).premultiply(this._scaleMatrix),this._translationMatrix.makeTranslation(e.x,e.y,e.z),this._gizmoMatrixState.premultiply(this._translationMatrix)}this._gizmoMatrixState.decompose(this._gizmos.position,this._gizmos.quaternion,this._gizmos.scale),this._gizmos.traverse(function(e){e.isLine&&(e.geometry.dispose(),e.material.dispose())}),this._gizmos.clear(),this._gizmos.add(o),this._gizmos.add(l),this._gizmos.add(c)}onFocusAnim(e,t,i,n){if(-1==this._timeStart&&(this._timeStart=e),this._state==vD.ANIMATION_FOCUS){const r=(e-this._timeStart)/this.focusAnimationTime;if(this._gizmoMatrixState.copy(n),r>=1)this._gizmoMatrixState.decompose(this._gizmos.position,this._gizmos.quaternion,this._gizmos.scale),this.focus(t,this.scaleFactor),this._timeStart=-1,this.updateTbState(vD.IDLE,!1),this.activateGizmos(!1),this.dispatchEvent(SD);else{const e=this.easeOutCubic(r),s=1-e+this.scaleFactor*e;this._gizmoMatrixState.decompose(this._gizmos.position,this._gizmos.quaternion,this._gizmos.scale),this.focus(t,s,e),this.dispatchEvent(SD);const a=this;this._animationId=window.requestAnimationFrame(function(e){a.onFocusAnim(e,t,i,n.clone())})}}else this._animationId=-1,this._timeStart=-1}onRotationAnim(e,t,i){if(-1==this._timeStart&&(this._anglePrev=0,this._angleCurrent=0,this._timeStart=e),this._state==vD.ANIMATION_ROTATE){const n=(e-this._timeStart)/1e3;if(i+-this.dampingFactor*n>0){this._angleCurrent=.5*-this.dampingFactor*Math.pow(n,2)+i*n+0,this.applyTransformMatrix(this.rotate(t,this._angleCurrent)),this.dispatchEvent(SD);const e=this;this._animationId=window.requestAnimationFrame(function(n){e.onRotationAnim(n,t,i)})}else this._animationId=-1,this._timeStart=-1,this.updateTbState(vD.IDLE,!1),this.activateGizmos(!1),this.dispatchEvent(SD)}else this._animationId=-1,this._timeStart=-1,this._state!=vD.ROTATE&&(this.activateGizmos(!1),this.dispatchEvent(SD))}pan(e,t,i=!1){const n=e.clone().sub(t);if(this.object.isOrthographicCamera)n.multiplyScalar(1/this.object.zoom);else if(this.object.isPerspectiveCamera&&i){this._v3_1.setFromMatrixPosition(this._cameraMatrixState0),this._v3_2.setFromMatrixPosition(this._gizmoMatrixState0);const e=this._v3_1.distanceTo(this._v3_2)/this.object.position.distanceTo(this._gizmos.position);n.multiplyScalar(1/e)}return this._v3_1.set(n.x,n.y,0).applyQuaternion(this.object.quaternion),this._m4_1.makeTranslation(this._v3_1.x,this._v3_1.y,this._v3_1.z),this.setTransformationMatrices(this._m4_1,this._m4_1),xD}reset(){this.target.copy(this._target0),this.object.zoom=this._zoom0,this.object.isPerspectiveCamera&&(this.object.fov=this._fov0),this.object.near=this._nearPos,this.object.far=this._farPos,this._cameraMatrixState.copy(this._cameraMatrixState0),this._cameraMatrixState.decompose(this.object.position,this.object.quaternion,this.object.scale),this.object.up.copy(this._up0),this.object.updateMatrix(),this.object.updateProjectionMatrix(),this._gizmoMatrixState.copy(this._gizmoMatrixState0),this._gizmoMatrixState0.decompose(this._gizmos.position,this._gizmos.quaternion,this._gizmos.scale),this._gizmos.updateMatrix(),this._tbRadius=this.calculateTbRadius(this.object),this.makeGizmos(this._gizmos.position,this._tbRadius),this.object.lookAt(this._gizmos.position),this.updateTbState(vD.IDLE,!1),this.dispatchEvent(SD)}rotate(e,t){const i=this._gizmos.position;return this._translationMatrix.makeTranslation(-i.x,-i.y,-i.z),this._rotationMatrix.makeRotationAxis(e,-t),this._m4_1.makeTranslation(i.x,i.y,i.z),this._m4_1.multiply(this._rotationMatrix),this._m4_1.multiply(this._translationMatrix),this.setTransformationMatrices(this._m4_1),xD}copyState(){let e;this.object.isOrthographicCamera?e=JSON.stringify({arcballState:{cameraFar:this.object.far,cameraMatrix:this.object.matrix,cameraNear:this.object.near,cameraUp:this.object.up,cameraZoom:this.object.zoom,gizmoMatrix:this._gizmos.matrix,target:this.target}}):this.object.isPerspectiveCamera&&(e=JSON.stringify({arcballState:{cameraFar:this.object.far,cameraFov:this.object.fov,cameraMatrix:this.object.matrix,cameraNear:this.object.near,cameraUp:this.object.up,cameraZoom:this.object.zoom,gizmoMatrix:this._gizmos.matrix,target:this.target}})),navigator.clipboard.writeText(e)}pasteState(){const e=this;navigator.clipboard.readText().then(function(t){e.setStateFromJSON(t)})}saveState(){this.object.updateMatrix(),this._gizmos.updateMatrix(),this._target0.copy(this.target),this._cameraMatrixState0.copy(this.object.matrix),this._gizmoMatrixState0.copy(this._gizmos.matrix),this._nearPos=this.object.near,this._farPos=this.object.far,this._zoom0=this.object.zoom,this._up0.copy(this.object.up),this.object.isPerspectiveCamera&&(this._fov0=this.object.fov)}scale(e,t,i=!0){CD.copy(t);let n=1/e;if(this.object.isOrthographicCamera){this.object.zoom=this._zoomState,this.object.zoom*=e,this.object.zoom>this.maxZoom?(this.object.zoom=this.maxZoom,n=this._zoomState/this.maxZoom):this.object.zoom<this.minZoom&&(this.object.zoom=this.minZoom,n=this._zoomState/this.minZoom),this.object.updateProjectionMatrix(),this._v3_1.setFromMatrixPosition(this._gizmoMatrixState),this._scaleMatrix.makeScale(n,n,n),this._translationMatrix.makeTranslation(-this._v3_1.x,-this._v3_1.y,-this._v3_1.z),this._m4_2.makeTranslation(this._v3_1.x,this._v3_1.y,this._v3_1.z).multiply(this._scaleMatrix),this._m4_2.multiply(this._translationMatrix),CD.sub(this._v3_1);const t=CD.clone().multiplyScalar(n);return CD.sub(t),this._m4_1.makeTranslation(CD.x,CD.y,CD.z),this._m4_2.premultiply(this._m4_1),this.setTransformationMatrices(this._m4_1,this._m4_2),xD}if(this.object.isPerspectiveCamera){this._v3_1.setFromMatrixPosition(this._cameraMatrixState),this._v3_2.setFromMatrixPosition(this._gizmoMatrixState);let e=this._v3_1.distanceTo(CD),t=e-e*n;const r=e-t;if(r<this.minDistance?(n=this.minDistance/e,t=e-e*n):r>this.maxDistance&&(n=this.maxDistance/e,t=e-e*n),wD.copy(CD).sub(this._v3_1).normalize().multiplyScalar(t),this._m4_1.makeTranslation(wD.x,wD.y,wD.z),i){const i=this._v3_2;e=i.distanceTo(CD),t=e-e*n,wD.copy(CD).sub(this._v3_2).normalize().multiplyScalar(t),this._translationMatrix.makeTranslation(i.x,i.y,i.z),this._scaleMatrix.makeScale(n,n,n),this._m4_2.makeTranslation(wD.x,wD.y,wD.z).multiply(this._translationMatrix),this._m4_2.multiply(this._scaleMatrix),this._translationMatrix.makeTranslation(-i.x,-i.y,-i.z),this._m4_2.multiply(this._translationMatrix),this.setTransformationMatrices(this._m4_1,this._m4_2)}else this.setTransformationMatrices(this._m4_1);return xD}}setFov(e){this.object.isPerspectiveCamera&&(this.object.fov=Gi.clamp(e,this.minFov,this.maxFov),this.object.updateProjectionMatrix())}setTransformationMatrices(e=null,t=null){null!=e?null!=xD.camera?xD.camera.copy(e):xD.camera=e.clone():xD.camera=null,null!=t?null!=xD.gizmos?xD.gizmos.copy(t):xD.gizmos=t.clone():xD.gizmos=null}zRotate(e,t){return this._rotationMatrix.makeRotationAxis(this._rotationAxis,t),this._translationMatrix.makeTranslation(-e.x,-e.y,-e.z),this._m4_1.makeTranslation(e.x,e.y,e.z),this._m4_1.multiply(this._rotationMatrix),this._m4_1.multiply(this._translationMatrix),this._v3_1.setFromMatrixPosition(this._gizmoMatrixState).sub(e),this._v3_2.copy(this._v3_1).applyAxisAngle(this._rotationAxis,t),this._v3_2.sub(this._v3_1),this._m4_2.makeTranslation(this._v3_2.x,this._v3_2.y,this._v3_2.z),this.setTransformationMatrices(this._m4_1,this._m4_2),xD}getRaycaster(){return ED}unprojectOnObj(e,t){const i=this.getRaycaster();i.near=t.near,i.far=t.far,i.setFromCamera(e,t);const n=i.intersectObjects(this.scene.children,!0);for(let e=0;e<n.length;e++)if(n[e].object.uuid!=this._gizmos.uuid&&null!=n[e].face)return n[e].point.clone();return null}unprojectOnTbSurface(e,t,i,n,r){if("OrthographicCamera"==e.type){this._v2_1.copy(this.getCursorPosition(t,i,n)),this._v3_1.set(this._v2_1.x,this._v2_1.y,0);const e=Math.pow(this._v2_1.x,2),r=Math.pow(this._v2_1.y,2),s=Math.pow(this._tbRadius,2);return e+r<=.5*s?this._v3_1.setZ(Math.sqrt(s-(e+r))):this._v3_1.setZ(.5*s/Math.sqrt(e+r)),this._v3_1}if("PerspectiveCamera"==e.type){this._v2_1.copy(this.getCursorNDC(t,i,n)),this._v3_1.set(this._v2_1.x,this._v2_1.y,-1),this._v3_1.applyMatrix4(e.projectionMatrixInverse);const s=this._v3_1.clone().normalize(),a=e.position.distanceTo(this._gizmos.position),o=Math.pow(r,2),l=this._v3_1.z,c=Math.sqrt(Math.pow(this._v3_1.x,2)+Math.pow(this._v3_1.y,2));if(0==c)return s.set(this._v3_1.x,this._v3_1.y,r),s;const u=l/c,h=a;let d=Math.pow(u,2)+1,p=2*u*h,f=Math.pow(h,2)-o,m=Math.pow(p,2)-4*d*f;if(m>=0){this._v2_1.setX((-p-Math.sqrt(m))/(2*d)),this._v2_1.setY(u*this._v2_1.x+h);if(Gi.RAD2DEG*this._v2_1.angle()>=45){const e=Math.sqrt(Math.pow(this._v2_1.x,2)+Math.pow(a-this._v2_1.y,2));return s.multiplyScalar(e),s.z+=a,s}}d=u,p=h,f=.5*-o,m=Math.pow(p,2)-4*d*f,this._v2_1.setX((-p-Math.sqrt(m))/(2*d)),this._v2_1.setY(u*this._v2_1.x+h);const g=Math.sqrt(Math.pow(this._v2_1.x,2)+Math.pow(a-this._v2_1.y,2));return s.multiplyScalar(g),s.z+=a,s}}unprojectOnTbPlane(e,t,i,n,r=!1){if("OrthographicCamera"==e.type)return this._v2_1.copy(this.getCursorPosition(t,i,n)),this._v3_1.set(this._v2_1.x,this._v2_1.y,0),this._v3_1.clone();if("PerspectiveCamera"==e.type){this._v2_1.copy(this.getCursorNDC(t,i,n)),this._v3_1.set(this._v2_1.x,this._v2_1.y,-1),this._v3_1.applyMatrix4(e.projectionMatrixInverse);const s=this._v3_1.clone().normalize(),a=this._v3_1.z,o=Math.sqrt(Math.pow(this._v3_1.x,2)+Math.pow(this._v3_1.y,2));let l;if(l=r?this._v3_1.setFromMatrixPosition(this._cameraMatrixState0).distanceTo(this._v3_2.setFromMatrixPosition(this._gizmoMatrixState0)):e.position.distanceTo(this._gizmos.position),0==o)return s.set(0,0,0),s;const c=l,u=-c/(a/o),h=Math.sqrt(Math.pow(c,2)+Math.pow(u,2));return s.multiplyScalar(h),s.z=0,s}}updateMatrixState(){this._cameraMatrixState.copy(this.object.matrix),this._gizmoMatrixState.copy(this._gizmos.matrix),this.object.isOrthographicCamera?(this._cameraProjectionState.copy(this.object.projectionMatrix),this.object.updateProjectionMatrix(),this._zoomState=this.object.zoom):this.object.isPerspectiveCamera&&(this._fovState=this.object.fov)}updateTbState(e,t){this._state=e,t&&this.updateMatrixState()}update(){if(!1===this.target.equals(this._currentTarget)&&(this._gizmos.position.copy(this.target),this._tbRadius=this.calculateTbRadius(this.object),this.makeGizmos(this.target,this._tbRadius),this._currentTarget.copy(this.target)),this.object.isOrthographicCamera){if(this.object.zoom>this.maxZoom||this.object.zoom<this.minZoom){const e=Gi.clamp(this.object.zoom,this.minZoom,this.maxZoom);this.applyTransformMatrix(this.scale(e/this.object.zoom,this._gizmos.position,!0))}}else if(this.object.isPerspectiveCamera){const e=this.object.position.distanceTo(this._gizmos.position);if(e>this.maxDistance+ND||e<this.minDistance-ND){const t=Gi.clamp(e,this.minDistance,this.maxDistance);this.applyTransformMatrix(this.scale(t/e,this._gizmos.position)),this.updateMatrixState()}(this.object.fov<this.minFov||this.object.fov>this.maxFov)&&(this.object.fov=Gi.clamp(this.object.fov,this.minFov,this.maxFov),this.object.updateProjectionMatrix());const t=this._tbRadius;if(this._tbRadius=this.calculateTbRadius(this.object),t<this._tbRadius-ND||t>this._tbRadius+ND){const e=(this._gizmos.scale.x+this._gizmos.scale.y+this._gizmos.scale.z)/3,t=this._tbRadius/e,i=new pa(0,0,t,t).getPoints(this._curvePts),n=(new Zr).setFromPoints(i);for(const e in this._gizmos.children)this._gizmos.children[e].geometry=n}}this.object.lookAt(this._gizmos.position)}setStateFromJSON(e){const t=JSON.parse(e);if(null!=t.arcballState){this.target.fromArray(t.arcballState.target),this._cameraMatrixState.fromArray(t.arcballState.cameraMatrix.elements),this._cameraMatrixState.decompose(this.object.position,this.object.quaternion,this.object.scale),this.object.up.copy(t.arcballState.cameraUp),this.object.near=t.arcballState.cameraNear,this.object.far=t.arcballState.cameraFar,this.object.zoom=t.arcballState.cameraZoom,this.object.isPerspectiveCamera&&(this.object.fov=t.arcballState.cameraFov),this._gizmoMatrixState.fromArray(t.arcballState.gizmoMatrix.elements),this._gizmoMatrixState.decompose(this._gizmos.position,this._gizmos.quaternion,this._gizmos.scale),this.object.updateMatrix(),this.object.updateProjectionMatrix(),this._gizmos.updateMatrix(),this._tbRadius=this.calculateTbRadius(this.object);const e=(new mn).copy(this._gizmoMatrixState0);this.makeGizmos(this._gizmos.position,this._tbRadius),this._gizmoMatrixState0.copy(e),this.object.lookAt(this._gizmos.position),this.updateTbState(vD.IDLE,!1),this.dispatchEvent(SD)}}}function LD(){const e=(this._gizmos.scale.x+this._gizmos.scale.y+this._gizmos.scale.z)/3;this._tbRadius=this.calculateTbRadius(this.object);const t=this._tbRadius/e,i=new pa(0,0,t,t).getPoints(this._curvePts),n=(new Zr).setFromPoints(i);for(const e in this._gizmos.children)this._gizmos.children[e].geometry=n;this.dispatchEvent(SD)}function DD(e){if(this.enabled)for(let t=0;t<this.mouseActions.length;t++)if(2==this.mouseActions[t].mouse){e.preventDefault();break}}function ID(){this._touchStart.splice(0,this._touchStart.length),this._touchCurrent.splice(0,this._touchCurrent.length),this._input=bD.NONE}function FD(e){if(0==e.button&&e.isPrimary?(this._downValid=!0,this._downEvents.push(e),this._downStart=performance.now()):this._downValid=!1,"touch"==e.pointerType&&this._input!=bD.CURSOR)switch(this._touchStart.push(e),this._touchCurrent.push(e),this._input){case bD.NONE:this._input=bD.ONE_FINGER,this.onSinglePanStart(e,"ROTATE"),window.addEventListener("pointermove",this._onPointerMove),window.addEventListener("pointerup",this._onPointerUp);break;case bD.ONE_FINGER:case bD.ONE_FINGER_SWITCHED:this._input=bD.TWO_FINGER,this.onRotateStart(),this.onPinchStart(),this.onDoublePanStart();break;case bD.TWO_FINGER:this._input=bD.MULT_FINGER,this.onTriplePanStart(e)}else if("touch"!=e.pointerType&&this._input==bD.NONE){let t=null;e.ctrlKey||e.metaKey?t="CTRL":e.shiftKey&&(t="SHIFT"),this._mouseOp=this.getOpFromAction(e.button,t),null!=this._mouseOp&&(window.addEventListener("pointermove",this._onPointerMove),window.addEventListener("pointerup",this._onPointerUp),this._input=bD.CURSOR,this._button=e.button,this.onSinglePanStart(e,this._mouseOp))}}function UD(e){if("touch"==e.pointerType&&this._input!=bD.CURSOR)switch(this._input){case bD.ONE_FINGER:this.updateTouchEvent(e),this.onSinglePanMove(e,vD.ROTATE);break;case bD.ONE_FINGER_SWITCHED:if(this.calculatePointersDistance(this._touchCurrent[0],e)*this._devPxRatio>=this._switchSensibility){this._input=bD.ONE_FINGER,this.updateTouchEvent(e),this.onSinglePanStart(e,"ROTATE");break}break;case bD.TWO_FINGER:this.updateTouchEvent(e),this.onRotateMove(),this.onPinchMove(),this.onDoublePanMove();break;case bD.MULT_FINGER:this.updateTouchEvent(e),this.onTriplePanMove(e)}else if("touch"!=e.pointerType&&this._input==bD.CURSOR){let t=null;e.ctrlKey||e.metaKey?t="CTRL":e.shiftKey&&(t="SHIFT");const i=this.getOpStateFromAction(this._button,t);null!=i&&this.onSinglePanMove(e,i)}if(this._downValid){this.calculatePointersDistance(this._downEvents[this._downEvents.length-1],e)*this._devPxRatio>this._movementThreshold&&(this._downValid=!1)}}function OD(e){if("touch"==e.pointerType&&this._input!=bD.CURSOR){const t=this._touchCurrent.length;for(let i=0;i<t;i++)if(this._touchCurrent[i].pointerId==e.pointerId){this._touchCurrent.splice(i,1),this._touchStart.splice(i,1);break}switch(this._input){case bD.ONE_FINGER:case bD.ONE_FINGER_SWITCHED:window.removeEventListener("pointermove",this._onPointerMove),window.removeEventListener("pointerup",this._onPointerUp),this._input=bD.NONE,this.onSinglePanEnd();break;case bD.TWO_FINGER:this.onDoublePanEnd(e),this.onPinchEnd(e),this.onRotateEnd(e),this._input=bD.ONE_FINGER_SWITCHED;break;case bD.MULT_FINGER:0==this._touchCurrent.length&&(window.removeEventListener("pointermove",this._onPointerMove),window.removeEventListener("pointerup",this._onPointerUp),this._input=bD.NONE,this.onTriplePanEnd())}}else"touch"!=e.pointerType&&this._input==bD.CURSOR&&(window.removeEventListener("pointermove",this._onPointerMove),window.removeEventListener("pointerup",this._onPointerUp),this._input=bD.NONE,this.onSinglePanEnd(),this._button=-1);if(e.isPrimary)if(this._downValid){if(e.timeStamp-this._downEvents[this._downEvents.length-1].timeStamp<=this._maxDownTime)if(0==this._nclicks)this._nclicks=1,this._clickStart=performance.now();else{const t=e.timeStamp-this._clickStart,i=this.calculatePointersDistance(this._downEvents[1],this._downEvents[0])*this._devPxRatio;t<=this._maxInterval&&i<=this._posThreshold?(this._nclicks=0,this._downEvents.splice(0,this._downEvents.length),this.onDoubleTap(e)):(this._nclicks=1,this._downEvents.shift(),this._clickStart=performance.now())}else this._downValid=!1,this._nclicks=0,this._downEvents.splice(0,this._downEvents.length)}else this._nclicks=0,this._downEvents.splice(0,this._downEvents.length)}function BD(e){if(this.enabled&&this.enableZoom){let t=null;e.ctrlKey||e.metaKey?t="CTRL":e.shiftKey&&(t="SHIFT");const i=this.getOpFromAction("WHEEL",t);if(null!=i){e.preventDefault(),this.dispatchEvent(TD);const t=125;let n=e.deltaY/t,r=1;switch(n>0?r=1/this.scaleFactor:n<0&&(r=this.scaleFactor),i){case"ZOOM":if(this.updateTbState(vD.SCALE,!0),n>0?r=1/Math.pow(this.scaleFactor,n):n<0&&(r=Math.pow(this.scaleFactor,-n)),this.cursorZoom&&this.enablePan){let t;this.object.isOrthographicCamera?t=this.unprojectOnTbPlane(this.object,e.clientX,e.clientY,this.domElement).applyQuaternion(this.object.quaternion).multiplyScalar(1/this.object.zoom).add(this._gizmos.position):this.object.isPerspectiveCamera&&(t=this.unprojectOnTbPlane(this.object,e.clientX,e.clientY,this.domElement).applyQuaternion(this.object.quaternion).add(this._gizmos.position)),this.applyTransformMatrix(this.scale(r,t))}else this.applyTransformMatrix(this.scale(r,this._gizmos.position));null!=this._grid&&(this.disposeGrid(),this.drawGrid()),this.updateTbState(vD.IDLE,!1),this.dispatchEvent(SD),this.dispatchEvent(MD);break;case"FOV":if(this.object.isPerspectiveCamera){this.updateTbState(vD.FOV,!0),0!=e.deltaX&&(n=e.deltaX/t,r=1,n>0?r=1/Math.pow(this.scaleFactor,n):n<0&&(r=Math.pow(this.scaleFactor,-n))),this._v3_1.setFromMatrixPosition(this._cameraMatrixState);const i=this._v3_1.distanceTo(this._gizmos.position);let s=i/r;s=Gi.clamp(s,this.minDistance,this.maxDistance);const a=i*Math.tan(Gi.DEG2RAD*this.object.fov*.5);let o=Gi.RAD2DEG*(2*Math.atan(a/s));o>this.maxFov?o=this.maxFov:o<this.minFov&&(o=this.minFov);r=i/(a/Math.tan(Gi.DEG2RAD*(o/2))),this.setFov(o),this.applyTransformMatrix(this.scale(r,this._gizmos.position,!1))}null!=this._grid&&(this.disposeGrid(),this.drawGrid()),this.updateTbState(vD.IDLE,!1),this.dispatchEvent(SD),this.dispatchEvent(MD)}}}}const kD={type:"change"},zD={type:"start"},GD={type:"end"},VD=new ps,HD=new ss,WD=Math.cos(70*Gi.DEG2RAD),jD=new Wi,$D=2*Math.PI,XD=-1,qD=0,YD=1,KD=2,ZD=3,QD=4,JD=5,eI=6,tI=1e-6;class iI extends Eo{constructor(e,t=null){super(e,t),this.state=XD,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:I,TWO:U},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 So,this._sphericalDelta=new So,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=rI.bind(this),this._onPointerDown=nI.bind(this),this._onPointerUp=sI.bind(this),this._onContextMenu=dI.bind(this),this._onMouseWheel=lI.bind(this),this._onKeyDown=cI.bind(this),this._onTouchStart=uI.bind(this),this._onTouchMove=hI.bind(this),this._onMouseDown=aI.bind(this),this._onMouseMove=oI.bind(this),this._interceptControlDown=pI.bind(this),this._interceptControlUp=fI.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=XD,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(kD),this.update(),this.state=XD}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;jD.copy(t).sub(this.target),jD.applyQuaternion(this._quat),this._spherical.setFromVector3(jD),this.autoRotate&&this.state===XD&&this._rotateLeft(this._getAutoRotationAngle(e)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let i=this.minAzimuthAngle,n=this.maxAzimuthAngle;isFinite(i)&&isFinite(n)&&(i<-Math.PI?i+=$D:i>Math.PI&&(i-=$D),n<-Math.PI?n+=$D:n>Math.PI&&(n-=$D),this._spherical.theta=i<=n?Math.max(i,Math.min(n,this._spherical.theta)):this._spherical.theta>(i+n)/2?Math.max(i,this._spherical.theta):Math.min(n,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),!0===this.enableDamping?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let r=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const e=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),r=e!=this._spherical.radius}if(jD.setFromSpherical(this._spherical),jD.applyQuaternion(this._quatInverse),t.copy(this.target).add(jD),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=jD.length();e=this._clampDistance(t*this._scale);const i=t-e;this.object.position.addScaledVector(this._dollyDirection,i),this.object.updateMatrixWorld(),r=!!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(),r=i!==this.object.zoom;const n=new Wi(this._mouse.x,this._mouse.y,0);n.unproject(this.object),this.object.position.sub(n).add(t),this.object.updateMatrixWorld(),e=jD.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):(VD.origin.copy(this.object.position),VD.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(VD.direction))<WD?this.object.lookAt(this.target):(HD.setFromNormalAndCoplanarPoint(this.object.up,this.target),VD.intersectPlane(HD,this.target))))}else if(this.object.isOrthographicCamera){const e=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),e!==this.object.zoom&&(this.object.updateProjectionMatrix(),r=!0)}return this._scale=1,this._performCursorZoom=!1,!!(r||this._lastPosition.distanceToSquared(this.object.position)>tI||8*(1-this._lastQuaternion.dot(this.object.quaternion))>tI||this._lastTargetPosition.distanceToSquared(this.target)>tI)&&(this.dispatchEvent(kD),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0)}_getAutoRotationAngle(e){return null!==e?$D/60*this.autoRotateSpeed*e:$D/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){jD.setFromMatrixColumn(t,0),jD.multiplyScalar(-e),this._panOffset.add(jD)}_panUp(e,t){!0===this.screenSpacePanning?jD.setFromMatrixColumn(t,1):(jD.setFromMatrixColumn(t,0),jD.crossVectors(this.object.up,jD)),jD.multiplyScalar(e),this._panOffset.add(jD)}_pan(e,t){const i=this.domElement;if(this.object.isPerspectiveCamera){const n=this.object.position;jD.copy(n).sub(this.target);let r=jD.length();r*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*r/i.clientHeight,this.object.matrix),this._panUp(2*t*r/i.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/i.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/i.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){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(),n=e-i.left,r=t-i.top,s=i.width,a=i.height;this._mouse.x=n/s*2-1,this._mouse.y=-r/a*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientY),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft($D*this._rotateDelta.x/t.clientHeight),this._rotateUp($D*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($D*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(-$D*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($D*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(-$D*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),n=.5*(e.pageY+t.y);this._rotateStart.set(i,n)}}_handleTouchStartPan(e){if(1===this._pointers.length)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),n=.5*(e.pageY+t.y);this._panStart.set(i,n)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),i=e.pageX-t.x,n=e.pageY-t.y,r=Math.sqrt(i*i+n*n);this._dollyStart.set(0,r)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(1==this._pointers.length)this._rotateEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),n=.5*(e.pageY+t.y);this._rotateEnd.set(i,n)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft($D*this._rotateDelta.x/t.clientHeight),this._rotateUp($D*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(1===this._pointers.length)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),n=.5*(e.pageY+t.y);this._panEnd.set(i,n)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),i=e.pageX-t.x,n=e.pageY-t.y,r=Math.sqrt(i*i+n*n);this._dollyEnd.set(0,r),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,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 nI(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 rI(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchMove(e):this._onMouseMove(e))}function sI(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(GD),this.state=XD,"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 aI(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=YD;break;case P:if(e.ctrlKey||e.metaKey||e.shiftKey){if(!1===this.enablePan)return;this._handleMouseDownPan(e),this.state=KD}else{if(!1===this.enableRotate)return;this._handleMouseDownRotate(e),this.state=qD}break;case D:if(e.ctrlKey||e.metaKey||e.shiftKey){if(!1===this.enableRotate)return;this._handleMouseDownRotate(e),this.state=qD}else{if(!1===this.enablePan)return;this._handleMouseDownPan(e),this.state=KD}break;default:this.state=XD}this.state!==XD&&this.dispatchEvent(zD)}function oI(e){switch(this.state){case qD:if(!1===this.enableRotate)return;this._handleMouseMoveRotate(e);break;case YD:if(!1===this.enableZoom)return;this._handleMouseMoveDolly(e);break;case KD:if(!1===this.enablePan)return;this._handleMouseMovePan(e)}}function lI(e){!1!==this.enabled&&!1!==this.enableZoom&&this.state===XD&&(e.preventDefault(),this.dispatchEvent(zD),this._handleMouseWheel(this._customWheelEvent(e)),this.dispatchEvent(GD))}function cI(e){!1!==this.enabled&&this._handleKeyDown(e)}function uI(e){switch(this._trackPointer(e),this._pointers.length){case 1:switch(this.touches.ONE){case I:if(!1===this.enableRotate){this.state=XD;break}this._handleTouchStartRotate(e),this.state=ZD;break;case F:if(!1===this.enablePan){this.state=XD;break}this._handleTouchStartPan(e),this.state=QD;break;default:this.state=XD}break;case 2:switch(this.touches.TWO){case U:if(!1===this.enableZoom&&!1===this.enablePan)return;this._handleTouchStartDollyPan(e),this.state=JD;break;case O:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchStartDollyRotate(e),this.state=eI;break;default:this.state=XD}break;default:this.state=XD}this.state!==XD&&this.dispatchEvent(zD)}function hI(e){switch(this._trackPointer(e),this.state){case ZD:if(!1===this.enableRotate)return;this._handleTouchMoveRotate(e),this.update();break;case QD:if(!1===this.enablePan)return;this._handleTouchMovePan(e),this.update();break;case JD:if(!1===this.enableZoom&&!1===this.enablePan)return;this._handleTouchMoveDollyPan(e),this.update();break;case eI:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchMoveDollyRotate(e),this.update();break;default:this.state=XD}}function dI(e){!1!==this.enabled&&e.preventDefault()}function pI(e){"Control"===e.key&&(this._controlActive=!0,this.domElement.ownerDocument.addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function fI(e){"Control"===e.key&&(this._controlActive=!1,this.domElement.ownerDocument.removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}const mI={type:"change"},gI=1e-6,_I=new Hi;class vI extends Eo{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=bI.bind(this),this._onKeyUp=yI.bind(this),this._onPointerMove=SI.bind(this),this._onPointerDown=xI.bind(this),this._onPointerUp=TI.bind(this),this._onPointerCancel=MI.bind(this),this._onContextMenu=EI.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,n=e*this.rollSpeed;t.translateX(this._moveVector.x*i),t.translateY(this._moveVector.y*i),t.translateZ(this._moveVector.z*i),_I.set(this._rotationVector.x*n,this._rotationVector.y*n,this._rotationVector.z*n,1).normalize(),t.quaternion.multiply(_I),(this._lastPosition.distanceToSquared(t.position)>gI||8*(1-this._lastQuaternion.dot(t.quaternion))>gI)&&(this.dispatchEvent(mI),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 bI(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 yI(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 xI(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 SI(e){if(!1!==this.enabled&&(!this.dragToLook||this._status>0)){const t=this._getContainerDimensions(),i=t.size[0]/2,n=t.size[1]/2;this._moveState.yawLeft=-(e.pageX-t.offset[0]-i)/i,this._moveState.pitchDown=(e.pageY-t.offset[1]-n)/n,this._updateRotationVector()}}function TI(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 MI(){!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 EI(e){!1!==this.enabled&&e.preventDefault()}const wI={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 AI{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 RI=new so(-1,1,1,-1,0,1);const CI=new class extends Zr{constructor(){super(),this.setAttribute("position",new kr([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new kr([0,2,0,0,2,0],2))}};class NI{constructor(e){this._mesh=new ws(CI,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,RI)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class PI extends AI{constructor(e,t="tDiffuse"){super(),this.textureID=t,this.uniforms=null,this.material=null,e instanceof Sa?(this.uniforms=e.uniforms,this.material=e):e&&(this.uniforms=xa.clone(e.uniforms),this.material=new Sa({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 NI(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 LI extends AI{constructor(e,t){super(),this.scene=e,this.camera=t,this.clear=!0,this.needsSwap=!1,this.inverse=!1}render(e,t,i){const n=e.getContext(),r=e.state;let s,a;r.buffers.color.setMask(!1),r.buffers.depth.setMask(!1),r.buffers.color.setLocked(!0),r.buffers.depth.setLocked(!0),this.inverse?(s=0,a=1):(s=1,a=0),r.buffers.stencil.setTest(!0),r.buffers.stencil.setOp(n.REPLACE,n.REPLACE,n.REPLACE),r.buffers.stencil.setFunc(n.ALWAYS,s,4294967295),r.buffers.stencil.setClear(a),r.buffers.stencil.setLocked(!0),e.setRenderTarget(i),this.clear&&e.clear(),e.render(this.scene,this.camera),e.setRenderTarget(t),this.clear&&e.clear(),e.render(this.scene,this.camera),r.buffers.color.setLocked(!1),r.buffers.depth.setLocked(!1),r.buffers.color.setMask(!0),r.buffers.depth.setMask(!0),r.buffers.stencil.setLocked(!1),r.buffers.stencil.setFunc(n.EQUAL,1,4294967295),r.buffers.stencil.setOp(n.KEEP,n.KEEP,n.KEEP),r.buffers.stencil.setLocked(!0)}}class DI extends AI{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}}class II{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 dn(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:Xe})).texture.name="EffectComposer.rt1"}else this._width=t.width,this._height=t.height;this.renderTarget1=t,this.renderTarget2=t.clone(),this.renderTarget2.texture.name="EffectComposer.rt2",this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2,this.renderToScreen=!0,this.passes=[],this.copyPass=new PI(wI),this.copyPass.material.blending=0,this.timer=new go}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,n=this.passes.length;t<n;t++){const n=this.passes[t];if(!1!==n.enabled){if(n.renderToScreen=this.renderToScreen&&this.isLastEnabledPass(t),n.render(this.renderer,this.writeBuffer,this.readBuffer,e,i),n.needsSwap){if(i){const t=this.renderer.getContext(),i=this.renderer.state.buffers.stencil;i.setFunc(t.NOTEQUAL,1,4294967295),this.copyPass.render(this.renderer,this.writeBuffer,this.readBuffer,e),i.setFunc(t.EQUAL,1,4294967295)}this.swapBuffers()}void 0!==LI&&(n instanceof LI?i=!0:n instanceof DI&&(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,n=this._height*this._pixelRatio;this.renderTarget1.setSize(i,n),this.renderTarget2.setSize(i,n);for(let e=0;e<this.passes.length;e++)this.passes[e].setSize(i,n)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.copyPass.dispose()}}class FI extends AI{constructor(e,t,i=null,n=null,r=null){super(),this.scene=e,this.camera=t,this.overrideMaterial=i,this.clearColor=n,this.clearAlpha=r,this.clear=!0,this.clearDepth=!1,this.needsSwap=!1,this.isRenderPass=!0,this._oldClearColor=new Kn}render(e,t,i){const n=e.autoClear;let r,s;e.autoClear=!1,null!==this.overrideMaterial&&(s=this.scene.overrideMaterial,this.scene.overrideMaterial=this.overrideMaterial),null!==this.clearColor&&(e.getClearColor(this._oldClearColor),e.setClearColor(this.clearColor,e.getClearAlpha())),null!==this.clearAlpha&&(r=e.getClearAlpha(),e.setClearAlpha(this.clearAlpha)),1==this.clearDepth&&e.clearDepth(),e.setRenderTarget(this.renderToScreen?null: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(r),null!==this.overrideMaterial&&(this.scene.overrideMaterial=s),e.autoClear=n}}function UI(){return UI=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var n in i)({}).hasOwnProperty.call(i,n)&&(e[n]=i[n])}return e},UI.apply(null,arguments)}function OI(e,t){return OI=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},OI(e,t)}function BI(e){return BI=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},BI(e)}function kI(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(kI=function(){return!!e})()}function zI(e){var t="function"==typeof Map?new Map:void 0;return zI=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(kI())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,t);var r=new(e.bind.apply(e,n));return i&&OI(r,i.prototype),r}(e,arguments,BI(this).constructor)}return i.prototype=Object.create(e.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),OI(i,e)},zI(e)}var GI={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 VI(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];var n,r=t[0],s=[];for(n=1;n<t.length;n+=1)s.push(t[n]);return s.forEach(function(e){r=r.replace(/%[a-z]/,e)}),r}var HI=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 n=arguments.length,r=new Array(n>1?n-1:0),s=1;s<n;s++)r[s-1]=arguments[s];i=e.call(this,VI.apply(void 0,[GI[t]].concat(r)))||this}return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(i)}return function(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,OI(e,t)}(t,e),t}(zI(Error));function WI(e){return Math.round(255*e)}function jI(e,t,i){return WI(e)+","+WI(t)+","+WI(i)}function $I(e,t,i,n){if(void 0===n&&(n=jI),0===t)return n(i,i,i);var r=(e%360+360)%360/60,s=(1-Math.abs(2*i-1))*t,a=s*(1-Math.abs(r%2-1)),o=0,l=0,c=0;r>=0&&r<1?(o=s,l=a):r>=1&&r<2?(o=a,l=s):r>=2&&r<3?(l=s,c=a):r>=3&&r<4?(l=a,c=s):r>=4&&r<5?(o=a,c=s):r>=5&&r<6&&(o=s,c=a);var u=i-s/2;return n(o+u,l+u,c+u)}var XI={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 qI=/^#[a-fA-F0-9]{6}$/,YI=/^#[a-fA-F0-9]{8}$/,KI=/^#[a-fA-F0-9]{3}$/,ZI=/^#[a-fA-F0-9]{4}$/,QI=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,JI=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,eF=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,tF=/^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 iF(e){if("string"!=typeof e)throw new HI(3);var t=function(e){if("string"!=typeof e)return e;var t=e.toLowerCase();return XI[t]?"#"+XI[t]:e}(e);if(t.match(qI))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(YI)){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(KI))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(ZI)){var n=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:n}}var r=QI.exec(t);if(r)return{red:parseInt(""+r[1],10),green:parseInt(""+r[2],10),blue:parseInt(""+r[3],10)};var s=JI.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=eF.exec(t);if(a){var o="rgb("+$I(parseInt(""+a[1],10),parseInt(""+a[2],10)/100,parseInt(""+a[3],10)/100)+")",l=QI.exec(o);if(!l)throw new HI(4,t,o);return{red:parseInt(""+l[1],10),green:parseInt(""+l[2],10),blue:parseInt(""+l[3],10)}}var c=tF.exec(t.substring(0,50));if(c){var u="rgb("+$I(parseInt(""+c[1],10),parseInt(""+c[2],10)/100,parseInt(""+c[3],10)/100)+")",h=QI.exec(u);if(!h)throw new HI(4,t,u);return{red:parseInt(""+h[1],10),green:parseInt(""+h[2],10),blue:parseInt(""+h[3],10),alpha:parseFloat(""+c[4])>1?parseFloat(""+c[4])/100:parseFloat(""+c[4])}}throw new HI(5)}function nF(e){return function(e){var t,i=e.red/255,n=e.green/255,r=e.blue/255,s=Math.max(i,n,r),a=Math.min(i,n,r),o=(s+a)/2;if(s===a)return void 0!==e.alpha?{hue:0,saturation:0,lightness:o,alpha:e.alpha}:{hue:0,saturation:0,lightness:o};var l=s-a,c=o>.5?l/(2-s-a):l/(s+a);switch(s){case i:t=(n-r)/l+(n<r?6:0);break;case n:t=(r-i)/l+2;break;default:t=(i-n)/l+4}return t*=60,void 0!==e.alpha?{hue:t,saturation:c,lightness:o,alpha:e.alpha}:{hue:t,saturation:c,lightness:o}}(iF(e))}var rF=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 sF(e){var t=e.toString(16);return 1===t.length?"0"+t:t}function aF(e){return sF(Math.round(255*e))}function oF(e,t,i){return rF("#"+aF(e)+aF(t)+aF(i))}function lF(e,t,i){return $I(e,t,i,oF)}function cF(e,t,i){if("number"==typeof e&&"number"==typeof t&&"number"==typeof i)return rF("#"+sF(e)+sF(t)+sF(i));if("object"==typeof e&&void 0===t&&void 0===i)return rF("#"+sF(e.red)+sF(e.green)+sF(e.blue));throw new HI(6)}function uF(e,t,i,n){if("object"==typeof e&&void 0===t&&void 0===i&&void 0===n)return e.alpha>=1?cF(e.red,e.green,e.blue):"rgba("+e.red+","+e.green+","+e.blue+","+e.alpha+")";throw new HI(7)}function hF(e){if("object"!=typeof e)throw new HI(8);if(function(e){return"number"==typeof e.red&&"number"==typeof e.green&&"number"==typeof e.blue&&"number"==typeof e.alpha}(e))return uF(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 cF(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,n){if("object"==typeof e&&void 0===t&&void 0===i&&void 0===n)return e.alpha>=1?lF(e.hue,e.saturation,e.lightness):"rgba("+$I(e.hue,e.saturation,e.lightness)+","+e.alpha+")";throw new HI(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 lF(e.hue,e.saturation,e.lightness);throw new HI(1)}(e);throw new HI(8)}function dF(e,t,i){return function(){var n=i.concat(Array.prototype.slice.call(arguments));return n.length>=t?e.apply(this,n):dF(e,t,n)}}function pF(e){return dF(e,e.length,[])}function fF(e,t,i){return Math.max(e,Math.min(t,i))}pF(function(e,t){if("transparent"===t)return t;var i=nF(t);return hF(UI({},i,{hue:i.hue+parseFloat(e)}))}),pF(function(e,t){if("transparent"===t)return t;var i=nF(t);return hF(UI({},i,{lightness:fF(0,1,i.lightness-parseFloat(e))}))}),pF(function(e,t){if("transparent"===t)return t;var i=nF(t);return hF(UI({},i,{saturation:fF(0,1,i.saturation-parseFloat(e))}))}),pF(function(e,t){if("transparent"===t)return t;var i=nF(t);return hF(UI({},i,{lightness:fF(0,1,i.lightness+parseFloat(e))}))});var mF=pF(function(e,t,i){if("transparent"===t)return i;if("transparent"===i)return t;if(0===e)return i;var n=iF(t),r=UI({},n,{alpha:"number"==typeof n.alpha?n.alpha:1}),s=iF(i),a=UI({},s,{alpha:"number"==typeof s.alpha?s.alpha:1}),o=r.alpha-a.alpha,l=2*parseFloat(e)-1,c=((l*o===-1?l:l+o)/(1+l*o)+1)/2,u=1-c;return uF({red:Math.floor(r.red*c+a.red*u),green:Math.floor(r.green*c+a.green*u),blue:Math.floor(r.blue*c+a.blue*u),alpha:r.alpha*parseFloat(e)+a.alpha*(1-parseFloat(e))})}),gF=mF;var _F=pF(function(e,t){if("transparent"===t)return t;var i=iF(t);return uF(UI({},i,{alpha:fF(0,1,(100*("number"==typeof i.alpha?i.alpha:1)+100*parseFloat(e))/100)}))}),vF=_F;pF(function(e,t){if("transparent"===t)return t;var i=nF(t);return hF(UI({},i,{saturation:fF(0,1,i.saturation+parseFloat(e))}))}),pF(function(e,t){return"transparent"===t?t:hF(UI({},nF(t),{hue:parseFloat(e)}))}),pF(function(e,t){return"transparent"===t?t:hF(UI({},nF(t),{lightness:parseFloat(e)}))}),pF(function(e,t){return"transparent"===t?t:hF(UI({},nF(t),{saturation:parseFloat(e)}))}),pF(function(e,t){return"transparent"===t?t:gF(parseFloat(e),"rgb(0, 0, 0)",t)}),pF(function(e,t){return"transparent"===t?t:gF(parseFloat(e),"rgb(255, 255, 255)",t)}),pF(function(e,t){if("transparent"===t)return t;var i=iF(t);return uF(UI({},i,{alpha:fF(0,1,+(100*("number"==typeof i.alpha?i.alpha:1)-100*parseFloat(e)).toFixed(2)/100)}))});var bF=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-bF.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*bF.Bounce.In(2*e):.5*bF.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}}}}),yF=function(){return performance.now()},xF=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 n=0,r=t;n<r.length;n++){var s=r[n];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,n=e;i<n.length;i++){var r=n[i];r._group=void 0,delete this._tweens[r.getId()],delete this._tweensAddedDuringUpdate[r.getId()]}},e.prototype.allStopped=function(){return this.getAll().every(function(e){return!e.isPlaying()})},e.prototype.update=function(e,t){void 0===e&&(e=yF()),void 0===t&&(t=!0);var i=Object.keys(this._tweens);if(0!==i.length)for(;i.length>0;){this._tweensAddedDuringUpdate={};for(var n=0;n<i.length;n++){var r=this._tweens[i[n]],s=!t;r&&!1===r.update(e,s)&&!t&&this.remove(r)}i=Object.keys(this._tweensAddedDuringUpdate)}},e}(),SF={Linear:function(e,t){var i=e.length-1,n=i*t,r=Math.floor(n),s=SF.Utils.Linear;return t<0?s(e[0],e[1],n):t>1?s(e[i],e[i-1],i-n):s(e[r],e[r+1>i?i:r+1],n-r)},Utils:{Linear:function(e,t,i){return(t-e)*i+e}}},TF=function(){function e(){}return e.nextId=function(){return e._nextId++},e._nextId=0,e}(),MF=new xF,EF=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=bF.Linear.None,this._interpolationFunction=SF.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=TF.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=MF,MF.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=yF()),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 n={};for(var r in this._valuesEnd)n[r]=this._valuesEnd[r];this._valuesEnd=n}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,n,r){for(var s in i){var a=e[s],o=Array.isArray(a),l=o?"array":typeof a,c=!o&&Array.isArray(i[s]);if("undefined"!==l&&"function"!==l){if(c){if(0===(g=i[s]).length)continue;for(var u=[a],h=0,d=g.length;h<d;h+=1){var p=this._handleRelativeValue(a,g[h]);if(isNaN(p)){c=!1,console.warn("Found invalid interpolation list. Skipping.");break}u.push(p)}c&&(i[s]=u)}if("object"!==l&&!o||!a||c)(void 0===t[s]||r)&&(t[s]=a),o||(t[s]*=1),n[s]=c?i[s].slice().reverse():t[s]||0;else{t[s]=o?[]:{};var f=a;for(var m in f)t[s][m]=f[m];n[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,n[s],r)}}}},e.prototype.stop=function(){return this._isChainStopped||(this._isChainStopped=!0,this.stopChainedTweens()),this._isPlaying?(this._isPlaying=!1,this._isPaused=!1,this._onStopCallback&&this._onStopCallback(this._object),this):this},e.prototype.end=function(){return this._goToEnd=!0,this.update(this._startTime+this._duration),this},e.prototype.pause=function(e){return void 0===e&&(e=yF()),this._isPaused||!this._isPlaying||(this._isPaused=!0,this._pauseStart=e),this},e.prototype.resume=function(e){return void 0===e&&(e=yF()),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=bF.Linear.None),this._easingFunction=e,this},e.prototype.interpolation=function(e){return void 0===e&&(e=SF.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 n,r,s=this;if(void 0===t&&(t=yF()),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!==(n=this._repeatDelayTime)&&void 0!==n?n:this._delayTime),l=this._duration+this._repeat*o,c=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}(),u=this._easingFunction(c);if(this._updateProperties(this._object,this._valuesStart,this._valuesEnd,u),this._onUpdateCallback&&this._onUpdateCallback(this._object,c),0===this._duration||a>=this._duration){if(this._repeat>0){var h=Math.min(Math.trunc((a-this._duration)/o)+1,this._repeat);for(r in isFinite(this._repeat)&&(this._repeat-=h),this._valuesStartRepeat)this._yoyo||"string"!=typeof this._valuesEnd[r]||(this._valuesStartRepeat[r]=this._valuesStartRepeat[r]+parseFloat(this._valuesEnd[r])),this._yoyo&&this._swapEndStartRepeatValues(r),this._valuesStart[r]=this._valuesStartRepeat[r];return this._yoyo&&(this._reversed=!this._reversed),this._startTime+=o*h,this._onRepeatCallback&&this._onRepeatCallback(this._object),this._onEveryStartCallbackFired=!1,!0}this._onCompleteCallback&&this._onCompleteCallback(this._object);for(var d=0,p=this._chainedTweens.length;d<p;d++)this._chainedTweens[d].start(this._startTime+this._duration,!1);return this._isPlaying=!1,!1}return!0},e.prototype._updateProperties=function(e,t,i,n){for(var r in i)if(void 0!==t[r]){var s=t[r]||0,a=i[r],o=Array.isArray(e[r]),l=Array.isArray(a);!o&&l?e[r]=this._interpolationFunction(a,n):"object"==typeof a&&a?this._updateProperties(e[r],s,a,n):"number"==typeof(a=this._handleRelativeValue(s,a))&&(e[r]=s+(a-s)*n)}},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}();TF.nextId;var wF=MF;wF.getAll.bind(wF),wF.removeAll.bind(wF),wF.add.bind(wF),wF.remove.bind(wF),wF.update.bind(wF);var AF="http://www.w3.org/1999/xhtml",RF={svg:"http://www.w3.org/2000/svg",xhtml:AF,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function CF(e){var t=e+="",i=t.indexOf(":");return i>=0&&"xmlns"!==(t=e.slice(0,i))&&(e=e.slice(i+1)),RF.hasOwnProperty(t)?{space:RF[t],local:e}:e}function NF(e){return function(){var t=this.ownerDocument,i=this.namespaceURI;return i===AF&&t.documentElement.namespaceURI===AF?t.createElement(e):t.createElementNS(i,e)}}function PF(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function LF(e){var t=CF(e);return(t.local?PF:NF)(t)}function DF(){}function IF(e){return null==e?DF:function(){return this.querySelector(e)}}function FF(){return[]}function UF(e){return function(){return function(e){return null==e?[]:Array.isArray(e)?e:Array.from(e)}(e.apply(this,arguments))}}function OF(e){return function(t){return t.matches(e)}}var BF=Array.prototype.find;function kF(){return this.firstElementChild}var zF=Array.prototype.filter;function GF(){return Array.from(this.children)}function VF(e){return new Array(e.length)}function HF(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}function WF(e,t,i,n,r,s){for(var a,o=0,l=t.length,c=s.length;o<c;++o)(a=t[o])?(a.__data__=s[o],n[o]=a):i[o]=new HF(e,s[o]);for(;o<l;++o)(a=t[o])&&(r[o]=a)}function jF(e,t,i,n,r,s,a){var o,l,c,u=new Map,h=t.length,d=s.length,p=new Array(h);for(o=0;o<h;++o)(l=t[o])&&(p[o]=c=a.call(l,l.__data__,o,t)+"",u.has(c)?r[o]=l:u.set(c,l));for(o=0;o<d;++o)c=a.call(e,s[o],o,s)+"",(l=u.get(c))?(n[o]=l,l.__data__=s[o],u.delete(c)):i[o]=new HF(e,s[o]);for(o=0;o<h;++o)(l=t[o])&&u.get(p[o])===l&&(r[o]=l)}function $F(e){return e.__data__}function XF(e){return"object"==typeof e&&"length"in e?e:Array.from(e)}function qF(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function YF(e){return function(){this.removeAttribute(e)}}function KF(e){return function(){this.removeAttributeNS(e.space,e.local)}}function ZF(e,t){return function(){this.setAttribute(e,t)}}function QF(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function JF(e,t){return function(){var i=t.apply(this,arguments);null==i?this.removeAttribute(e):this.setAttribute(e,i)}}function eU(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 tU(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function iU(e){return function(){this.style.removeProperty(e)}}function nU(e,t,i){return function(){this.style.setProperty(e,t,i)}}function rU(e,t,i){return function(){var n=t.apply(this,arguments);null==n?this.style.removeProperty(e):this.style.setProperty(e,n,i)}}function sU(e){return function(){delete this[e]}}function aU(e,t){return function(){this[e]=t}}function oU(e,t){return function(){var i=t.apply(this,arguments);null==i?delete this[e]:this[e]=i}}function lU(e){return e.trim().split(/^|\s+/)}function cU(e){return e.classList||new uU(e)}function uU(e){this._node=e,this._names=lU(e.getAttribute("class")||"")}function hU(e,t){for(var i=cU(e),n=-1,r=t.length;++n<r;)i.add(t[n])}function dU(e,t){for(var i=cU(e),n=-1,r=t.length;++n<r;)i.remove(t[n])}function pU(e){return function(){hU(this,e)}}function fU(e){return function(){dU(this,e)}}function mU(e,t){return function(){(t.apply(this,arguments)?hU:dU)(this,e)}}function gU(){this.textContent=""}function _U(e){return function(){this.textContent=e}}function vU(e){return function(){var t=e.apply(this,arguments);this.textContent=null==t?"":t}}function bU(){this.innerHTML=""}function yU(e){return function(){this.innerHTML=e}}function xU(e){return function(){var t=e.apply(this,arguments);this.innerHTML=null==t?"":t}}function SU(){this.nextSibling&&this.parentNode.appendChild(this)}function TU(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function MU(){return null}function EU(){var e=this.parentNode;e&&e.removeChild(this)}function wU(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function AU(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function RU(e){return function(){var t=this.__on;if(t){for(var i,n=0,r=-1,s=t.length;n<s;++n)i=t[n],e.type&&i.type!==e.type||i.name!==e.name?t[++r]=i:this.removeEventListener(i.type,i.listener,i.options);++r?t.length=r:delete this.__on}}}function CU(e,t,i){return function(){var n,r=this.__on,s=function(e){return function(t){e.call(this,t,this.__data__)}}(t);if(r)for(var a=0,o=r.length;a<o;++a)if((n=r[a]).type===e.type&&n.name===e.name)return this.removeEventListener(n.type,n.listener,n.options),this.addEventListener(n.type,n.listener=s,n.options=i),void(n.value=t);this.addEventListener(e.type,s,i),n={type:e.type,name:e.name,value:t,listener:s,options:i},r?r.push(n):this.__on=[n]}}function NU(e,t,i){var n=tU(e),r=n.CustomEvent;"function"==typeof r?r=new r(t,i):(r=n.document.createEvent("Event"),i?(r.initEvent(t,i.bubbles,i.cancelable),r.detail=i.detail):r.initEvent(t,!1,!1)),e.dispatchEvent(r)}function PU(e,t){return function(){return NU(this,e,t)}}function LU(e,t){return function(){return NU(this,e,t.apply(this,arguments))}}HF.prototype={constructor:HF,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)}},uU.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 DU=[null];function IU(e,t){this._groups=e,this._parents=t}IU.prototype={constructor:IU,select:function(e){"function"!=typeof e&&(e=IF(e));for(var t=this._groups,i=t.length,n=new Array(i),r=0;r<i;++r)for(var s,a,o=t[r],l=o.length,c=n[r]=new Array(l),u=0;u<l;++u)(s=o[u])&&(a=e.call(s,s.__data__,u,o))&&("__data__"in s&&(a.__data__=s.__data__),c[u]=a);return new IU(n,this._parents)},selectAll:function(e){e="function"==typeof e?UF(e):function(e){return null==e?FF:function(){return this.querySelectorAll(e)}}(e);for(var t=this._groups,i=t.length,n=[],r=[],s=0;s<i;++s)for(var a,o=t[s],l=o.length,c=0;c<l;++c)(a=o[c])&&(n.push(e.call(a,a.__data__,c,o)),r.push(a));return new IU(n,r)},selectChild:function(e){return this.select(null==e?kF:function(e){return function(){return BF.call(this.children,e)}}("function"==typeof e?e:OF(e)))},selectChildren:function(e){return this.selectAll(null==e?GF:function(e){return function(){return zF.call(this.children,e)}}("function"==typeof e?e:OF(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,n=new Array(i),r=0;r<i;++r)for(var s,a=t[r],o=a.length,l=n[r]=[],c=0;c<o;++c)(s=a[c])&&e.call(s,s.__data__,c,a)&&l.push(s);return new IU(n,this._parents)},data:function(e,t){if(!arguments.length)return Array.from(this,$F);var i=t?jF:WF,n=this._parents,r=this._groups;"function"!=typeof e&&(e=function(e){return function(){return e}}(e));for(var s=r.length,a=new Array(s),o=new Array(s),l=new Array(s),c=0;c<s;++c){var u=n[c],h=r[c],d=h.length,p=XF(e.call(u,u&&u.__data__,c,n)),f=p.length,m=o[c]=new Array(f),g=a[c]=new Array(f);i(u,h,m,g,l[c]=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 IU(a,n))._enter=o,a._exit=l,a},enter:function(){return new IU(this._enter||this._groups.map(VF),this._parents)},exit:function(){return new IU(this._exit||this._groups.map(VF),this._parents)},join:function(e,t,i){var n=this.enter(),r=this,s=this.exit();return"function"==typeof e?(n=e(n))&&(n=n.selection()):n=n.append(e+""),null!=t&&(r=t(r))&&(r=r.selection()),null==i?s.remove():i(s),n&&r?n.merge(r).order():r},merge:function(e){for(var t=e.selection?e.selection():e,i=this._groups,n=t._groups,r=i.length,s=n.length,a=Math.min(r,s),o=new Array(r),l=0;l<a;++l)for(var c,u=i[l],h=n[l],d=u.length,p=o[l]=new Array(d),f=0;f<d;++f)(c=u[f]||h[f])&&(p[f]=c);for(;l<r;++l)o[l]=i[l];return new IU(o,this._parents)},selection:function(){return this},order:function(){for(var e=this._groups,t=-1,i=e.length;++t<i;)for(var n,r=e[t],s=r.length-1,a=r[s];--s>=0;)(n=r[s])&&(a&&4^n.compareDocumentPosition(a)&&a.parentNode.insertBefore(n,a),a=n);return this},sort:function(e){function t(t,i){return t&&i?e(t.__data__,i.__data__):!t-!i}e||(e=qF);for(var i=this._groups,n=i.length,r=new Array(n),s=0;s<n;++s){for(var a,o=i[s],l=o.length,c=r[s]=new Array(l),u=0;u<l;++u)(a=o[u])&&(c[u]=a);c.sort(t)}return new IU(r,this._parents).order()},call:function(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this},nodes:function(){return Array.from(this)},node:function(){for(var e=this._groups,t=0,i=e.length;t<i;++t)for(var n=e[t],r=0,s=n.length;r<s;++r){var a=n[r];if(a)return a}return null},size:function(){let e=0;for(const t of this)++e;return e},empty:function(){return!this.node()},each:function(e){for(var t=this._groups,i=0,n=t.length;i<n;++i)for(var r,s=t[i],a=0,o=s.length;a<o;++a)(r=s[a])&&e.call(r,r.__data__,a,s);return this},attr:function(e,t){var i=CF(e);if(arguments.length<2){var n=this.node();return i.local?n.getAttributeNS(i.space,i.local):n.getAttribute(i)}return this.each((null==t?i.local?KF:YF:"function"==typeof t?i.local?eU:JF:i.local?QF:ZF)(i,t))},style:function(e,t,i){return arguments.length>1?this.each((null==t?iU:"function"==typeof t?rU:nU)(e,t,null==i?"":i)):function(e,t){return e.style.getPropertyValue(t)||tU(e).getComputedStyle(e,null).getPropertyValue(t)}(this.node(),e)},property:function(e,t){return arguments.length>1?this.each((null==t?sU:"function"==typeof t?oU:aU)(e,t)):this.node()[e]},classed:function(e,t){var i=lU(e+"");if(arguments.length<2){for(var n=cU(this.node()),r=-1,s=i.length;++r<s;)if(!n.contains(i[r]))return!1;return!0}return this.each(("function"==typeof t?mU:t?pU:fU)(i,t))},text:function(e){return arguments.length?this.each(null==e?gU:("function"==typeof e?vU:_U)(e)):this.node().textContent},html:function(e){return arguments.length?this.each(null==e?bU:("function"==typeof e?xU:yU)(e)):this.node().innerHTML},raise:function(){return this.each(SU)},lower:function(){return this.each(TU)},append:function(e){var t="function"==typeof e?e:LF(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})},insert:function(e,t){var i="function"==typeof e?e:LF(e),n=null==t?MU:"function"==typeof t?t:IF(t);return this.select(function(){return this.insertBefore(i.apply(this,arguments),n.apply(this,arguments)||null)})},remove:function(){return this.each(EU)},clone:function(e){return this.select(e?AU:wU)},datum:function(e){return arguments.length?this.property("__data__",e):this.node().__data__},on:function(e,t,i){var n,r,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?CU:RU,n=0;n<a;++n)this.each(o(s[n],t,i));return this}var o=this.node().__on;if(o)for(var l,c=0,u=o.length;c<u;++c)for(n=0,l=o[c];n<a;++n)if((r=s[n]).type===l.type&&r.name===l.name)return l.value},dispatch:function(e,t){return this.each(("function"==typeof t?LU:PU)(e,t))},[Symbol.iterator]:function*(){for(var e=this._groups,t=0,i=e.length;t<i;++t)for(var n,r=e[t],s=0,a=r.length;s<a;++s)(n=r[s])&&(yield n)}};var FU=0;function UU(){this._="@"+(++FU).toString(36)}UU.prototype={constructor:UU,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 OU,BU,kU,zU,GU,VU,HU,WU,jU,$U,XU,qU=Symbol.for("pv"),YU={},KU=[],ZU=/^m(i|n|o|s|text|space)$/,QU=Array.isArray,JU=KU.slice,eO=Object.assign;function tO(e){e&&e.parentNode&&e.remove()}function iO(e,t,i){var n,r,s,a=eO({},e.props),o=arguments.length;for(s in t)"key"==s?n=t[s]:"ref"==s&&"function"!=typeof e.type?r=t[s]:a[s]=t[s];return o>2&&(a.children=o>3?JU.call(arguments,2):i),nO(e.type,a,void 0!==n?n:e.key,void 0!==r?r:e.ref,null)}function nO(e,t,i,n,r){var s={type:e,props:t,key:i,ref:n,__k:null,__:null,__b:0,__e:null,__c:null,constructor:qU,__v:r||++BU,__i:-1,__u:0};return!r&&OU.vnode&&OU.vnode(s),s}function rO(e){return e.children}function sO(e,t){this.props=e,this.context=t,this.__g=0}function aO(e,t){if(null==t)return e.__&&aO(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:aO(e)}function oO(e){var t,i=e.__v,n=i.__e,r=[],s=[],a=e.__P;a&&((t=eO({constructor:qU},i)).__v=i.__v+1,OU.vnode&&OU.vnode(t),vO(a,t,i,e.__n,a.namespaceURI,32&i.__u?[n]:null,r,n||aO(i),32&i.__u,s),t.__v=i.__v,t.__.__k[t.__i]=t,xO(r,t,s),i.__=i.__e=null,t.__e!=n&&lO(t))}function lO(e){if((e=e.__)&&e.__c&&!e.props.__P)return e.__e=null,e.__k.some(function(t){return t&&(e.__e=t.__e)}),lO(e)}function cO(e){(8&e.__g||(e.__g|=8,zU.push(e),VU++))&&GU==OU.debounceRendering||((GU=OU.debounceRendering)||queueMicrotask)(uO)}function uO(){try{for(var e,t=1;zU.length;)zU.length>t&&zU.sort(HU),e=zU.shift(),t=zU.length,8&e.__g&&oO(e)}finally{(VU=zU.length)&&(GU||queueMicrotask)(uO)}}function hO(e,t,i,n,r,s,a,o,l,c,u){var h,d,p,f,m,g,_=n.__k||KU,v=t.length;for(l=dO(i,t,_,l,v),h=0;h<v;h++)null!=(p=i.__k[h])&&(d=~p.__i&&_[p.__i]||YU,p.__i=h,g=vO(e,p,d,r,s,a,o,l,c,u),f=p.__e,(d.ref!=p.ref||8&d.__u)&&(d.ref&&TO(d.ref,null,p,d),p.ref&&u.push(p.ref,p.__c||f,p)),m=m||f,4&p.__u?(l=pO(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 dO(e,t,i,n,r){var s,a,o,l,c,u,h,d,p,f=i.length,m=f,g=0,_=0,v=e.__k=Array(r);for(s=0;s<r;s++)null!=(a=t[s])&&"boolean"!=typeof a&&"function"!=typeof a?("object"!=typeof a||a.constructor===String?a=v[s]=nO(null,a):QU(a)?a=v[s]=nO(rO,{children:a}):a.constructor===qU&&a.__b?a=v[s]=nO(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,~(c=a.__i=fO(a,i,l,m))&&(m--,(o=i[c])&&(o.__u|=2)),o&&o.__v?(a.__u|=16,c==l-1?g--:c==l+1?g++:c!=l&&(c>l?g--:g++,_=1)):(~c||(r>f?g--:r<f&&g++),"function"!=typeof a.type&&(a.__u|=4))):v[s]=null;if(_){for(u=[],h=[],s=0;s<r;s++)if((a=v[s])&&16&a.__u){for(g=0,d=u.length;g<d;)u[p=g+d>>1]<a.__i?g=p+1:d=p;u[g]=a.__i,h[s]=g+1}for(g=u.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==n&&(n=aO(o)),MO(o,o));return n}function pO(e,t,i,n){var r,s,a,o;if("function"==typeof e.type){if(e.props.__P)return t;if(r=e.__k)for(s=0;s<r.length;s++)r[s]&&(r[s].__=e,t=pO(r[s],t,i,!1));return t}for(t&&!t.parentNode&&(t=aO(e))&&!t.parentNode&&(t=null),a=e.__e,o=t;o&&8==o.nodeType;)o=o.nextSibling;for(a!=o&&(!n&&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 fO(e,t,i,n){var r,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(n>(l?1:0)){for(r=i-1;r>=0;r--)if((o=t[r])&&!(2&o.__u)&&s==o.key&&a==o.type)return r;for(r=i+1;r<t.length;r++)if((o=t[r])&&!(2&o.__u)&&s==o.key&&a==o.type)return r}return-1}function mO(e,t,i){null==i&&(i=""),"-"==t[0]?e.setProperty(t,i):e[t]=i}function gO(e,t,i,n,r){var s,a;if("style"==t)if("string"==typeof i)e.style.cssText=i;else{if("string"==typeof n&&(e.style.cssText=n=""),n)for(t in n)i&&t in i||mO(e.style,t);if(i)for(t in i)n&&i[t]==n[t]||mO(e.style,t,i[t])}else if("o"==t[0]&&"n"==t[1])"function"!=typeof i&&(i=null),"function"!=typeof n&&(n=null),(e.__e||(e.__e={}))[t]=i,i&&n||(a=XU[t]||(XU[t]=_O(t)),(e.__a||(e.__a={}))[t]=$U,s=t!=(t=t.replace(jU,"$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"==r)t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if("width"!=t&&"height"!=t&&"href"!=t&&"list"!=t&&"form"!=t&&"tabIndex"!=t&&"download"!=t&&"rowSpan"!=t&&"colSpan"!=t&&"role"!=t&&"popover"!=t&&t in e)try{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 _O(e){return function(t){var i=this.__e;if(i){if(i=i[e],null==t[WU])t[WU]=$U++;else if(t[WU]<this.__a[e])return;return i(OU.event?OU.event(t):t)}}}function vO(e,t,i,n,r,s,a,o,l,c){var u,h,d,p,f,m,g,_,v,b,y,x,S,T,M,E,w,A,R=t.type;if(t.constructor!==qU)return null;128&i.__u&&(l=32&i.__u,u=i.__c.__z)&&(t.__u|=l,h=s=[],8==u.nodeType?o=bO(u,s):s.push(u),o=s[0]||o),(u=OU.__b)&&u(t);e:if("function"==typeof R){d=a.length;try{if(_=t.props,v=(u=R.prototype)&&u.render,b=(u=R.contextType)&&n[u.__c],y=u?b?b.props.value:u.__:n,(p=i.__c)?(t.__c=p,2&p.__g&&(p.__g|=1)):(v?t.__c=p=new R(_,y):(t.__c=p=new sO(_,y),p.constructor=R,p.render=EO),b&&b.sub(p),p.state||(p.state={}),p.__n=n,p.__g|=8,p.__h=[],p.__k=[]),v&&(p.__s||(p.__s=p.state),R.getDerivedStateFromProps&&(p.__s==p.state&&(p.__s=eO({},p.__s)),eO(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)}),KU.push.apply(p.__h,p.__k),p.__k=[],p.__h.length&&a.push(p),o=aO(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=OU.__r,S=v?25:0;do{p.__g&=-9,x&&x(t),u=p.render(p.props,p.state=p.__s,p.context)}while(8&p.__g&&++S<25);v&&(KU.push.apply(p.__h,p.__k),p.__k=[]),p.state=p.__s,p.getChildContext&&(n=eO({},n,p.getChildContext())),v&&i.__c&&p.getSnapshotBeforeUpdate&&(g=p.getSnapshotBeforeUpdate(f,m)),T=u&&u.type===rO&&null==u.key?u.props.children:u,_.__P&&(u=o,r=(e=_.__P).namespaceURI,l=s=null,i.props&&i.props.__P!=e&&(i.__k.some(function(e){e&&MO(e,e)}),i.__k=null),o=i.__k?aO(i,0):null),o=hO(e,QU(T)?T:[T],t,i,n,r,s,a,o,l,c),_.__P&&(t.__e=null,o=u),t.__u&=-161,h&&h.some(tO),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=bO(M=A))}}if(!M){for(;o&&8==o.nodeType&&o.nextSibling;)o=o.nextSibling;M=o}(u=bO(M=t.__c.__z||(t.__c.__z=M)))?(t.__e=M,o=u):t.__e=o,o=o&&o.nextSibling}else s&&s.some(tO);else t.__e=i.__e;t.__k||(t.__k=i.__k||[]),e&&e.then||yO(t),OU.__e(e,t,i)}}else o=t.__e=SO(i.__e,t,i,n,r,s,a,l,c,e);return(u=OU.diffed)&&u(t),o}function bO(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 yO(e){e&&(e.__c&&(e.__c.__g|=4),e.__k&&e.__k.some(yO))}function xO(e,t,i){for(var n=0;n<i.length;)TO(i[n++],i[n++],i[n++]);OU.__c&&OU.__c(t,e),e.some(function(t){try{e=t.__h,t.__h=[],e.some(function(e){e.call(t)})}catch(e){OU.__e(e,t.__v)}})}function SO(e,t,i,n,r,s,a,o,l,c){var u,h,d,p,f,m,g,_,v=i.props||YU,b=t.props,y=t.type;if("svg"==y?r="http://www.w3.org/2000/svg":"math"==y?r="http://www.w3.org/1998/Math/MathML":r||(r="http://www.w3.org/1999/xhtml"),s)for(u=0;u<s.length;u++)if((f=s[u])&&(y?f.localName==y:3==f.nodeType)){e=f,s[u]=null;break}if(!e){if(_=c.ownerDocument||document,!y)return _.createTextNode(b);e=_.createElementNS(r,y,b.is?b:c),o&&(OU.__m&&OU.__m(t,s),o=!1),s=null}if(y){if(c="template"==y&&e.content||e,s="textarea"==y&&null!=b.defaultValue?null:s&&JU.call(c.childNodes),!o&&s)for(v={},u=0;u<e.attributes.length;u++)v[(f=e.attributes[u]).name]=f.value;for(u in v)f=v[u],"dangerouslySetInnerHTML"==u?d=f:"children"==u||u in b||"value"==u&&"defaultValue"in b||"checked"==u&&"defaultChecked"in b||gO(e,u,null,f,r);for(u in b)f=b[u],"children"==u?p=f:"dangerouslySetInnerHTML"==u?h=f:"value"==u?m=f:"checked"==u?g=f:o&&"function"!=typeof f||v[u]===f||gO(e,u,f,v[u],r);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"==r&&ZU.test(y))&&(r="http://www.w3.org/1999/xhtml"),hO(c,QU(p)?p:[p],t,i,n,r,s,a,s?s[0]:i.__k&&aO(i,0),o,l),s&&s.some(tO)),o&&"textarea"!=y||(u="value","progress"==y&&null==m?e.removeAttribute(u):null==m||m===e[u]&&("progress"!=y||m)||gO(e,u,m,v[u],r),u="checked",null!=g&&g!=e[u]&&gO(e,u,g,v[u],r))}else v===b||o&&e.data==b||(e.data=b);return e}function TO(e,t,i,n){try{"function"==typeof e?t?t.__x=e(t)||1:n&&(n=n.__c||n.__e)&&(t=n.__x)&&(n.__x=null,"function"==typeof t?t():e(null)):e.current=t}catch(e){OU.__e(e,i)}}function MO(e,t,i){var n,r,s,a;if(OU.unmount&&OU.unmount(e),!(n=e.ref)||n.current&&n.current!=e.__e||TO(n,null,t,e),n=e.__c){if(n.componentWillUnmount)try{n.componentWillUnmount()}catch(e){OU.__e(e,t)}n.__P=n.__n=null}if(n=e.__k)for(a=0;a<n.length;a++)n[a]&&MO(n[a],t,"function"!=typeof e.type||i&&!e.props.__P);!i&&(n=e.__c)&&(n=n.__z)&&(r=bO(n,s=[]))&&(n==e.__e&&s.some(tO),tO(r),tO(n)),i||tO(e.__e),e.__e=e.__c=e.__=null}function EO(e,t,i){return this.constructor(e,i)}OU={__e:function(e,t,i,n){for(var r,s,a;t=t.__;)if((r=t.__c)&&!(1&r.__g)){r.__g|=4;try{if((a=(s=r.constructor)&&s.getDerivedStateFromError)&&r.setState(s.getDerivedStateFromError(e)),r.componentDidCatch&&(r.componentDidCatch(e,n||{}),a=1),a&&8&r.__g)return void(r.__g|=2)}catch(t){e=t}}throw VU=0,e}},BU=0,kU=function(e){return null!=e&&e.constructor===qU},sO.prototype.setState=function(e,t){var i=this.__s;i&&i!=this.state||(i=this.__s=eO({},this.state)),"function"==typeof e&&(e=e(eO({},i),this.props)),e&&(eO(i,e),this.__v&&(t&&this.__k.push(t),cO(this)))},sO.prototype.forceUpdate=function(e){this.__v&&(this.__g|=4,e&&this.__h.push(e),cO(this))},sO.prototype.render=rO,zU=[],VU=0,HU=function(e,t){return e.__v.__b-t.__v.__b},WU=Symbol(),jU=/(PointerCapture)$|Capture$/i,$U=0,XU={};const wO=e=>{if("object"!=typeof e)return e;const t=iO(e);return t.props&&(t.props={...t.props},t?.props?.children&&(t.props.children=Array.isArray(t.props.children)?t.props.children.map(wO):wO(t.props.children))),t},AO=(e,t)=>{delete t.__k,function(e,t){var i,n,r,s;OU.__&&OU.__(e,t),9==t.nodeType&&(t=t.documentElement),n=(i=e&&32&e.__u)?null:t.__k,t.__k=nO(rO,{children:[e]}),r=[],s=[],vO(t,t.__k,n||YU,YU,t.namespaceURI,n?null:t.firstChild?JU.call(t.childNodes):null,r,n?n.__e:t.firstChild,i,s),xO(r,t.__k,s),t.__k.props.children=null}(wO(e),t)};!function(e,t){void 0===t&&(t={});var i=t.insertAt;if("undefined"!=typeof document){var n=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css","top"===i&&n.firstChild?n.insertBefore(r,n.firstChild):n.appendChild(r),r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}}(".float-tooltip-kap {\n position: absolute;\n width: max-content; /* prevent shrinking near right edge */\n max-width: max(50%, 150px);\n padding: 3px 5px;\n border-radius: 3px;\n font: 12px sans-serif;\n color: #eee;\n background: rgba(0,0,0,0.6);\n pointer-events: none;\n}\n");var RO=R({props:{content:{default:!1},offsetX:{triggerUpdate:!1},offsetY:{triggerUpdate:!1}},methods:{positionFromEvent(e,t){const i=e.container,n=function(e,t){if(e=function(e){let t;for(;t=e.sourceEvent;)e=t;return e}(e),void 0===t&&(t=e.currentTarget),t){var i=t.ownerSVGElement||t;if(i.createSVGPoint){var n=i.createSVGPoint();return n.x=e.clientX,n.y=e.clientY,[(n=n.matrixTransform(t.getScreenCTM().inverse())).x,n.y]}if(t.getBoundingClientRect){var r=t.getBoundingClientRect();return[e.clientX-r.left-t.clientLeft,e.clientY-r.top-t.clientTop]}}return[e.pageX,e.pageY]}(t,i),r=i.offsetWidth,s=i.offsetHeight,a=[null===e.offsetX||void 0===e.offsetX?`-${n[0]/r*100}%`:"number"==typeof e.offsetX?`calc(-50% + ${e.offsetX}px)`:e.offsetX,null===e.offsetY||void 0===e.offsetY?s>130&&s-n[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",n[0]+"px").style("top",n[1]+"px").style("transform",`translate(${a.join(",")})`),this}},init:function(e,t,{style:i={}}={}){const n=function(e){return"string"==typeof e?new IU([[document.querySelector(e)]],[document.documentElement]):new IU([[e]],DU)}(!!e&&"object"==typeof e&&!!e.node&&"function"==typeof e.node?e.node():e);t.container=n.node(),"static"===n.style("position")&&n.style("position","relative"),t.tooltipEl=n.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 r=`tooltip-${Math.round(1e12*Math.random())}`;t.mouseInside=!1,n.on(`mousemove.${r}`,e=>{t.mouseInside=!0,this.positionFromEvent(e),t.content&&t.tooltipEl.style("display","inline")}),n.on(`mouseover.${r}`,()=>{t.mouseInside=!0,t.content&&t.tooltipEl.style("display","inline")}),n.on(`mouseout.${r}`,()=>{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=>kU(iO(e)))(e.content)?(e.tooltipEl.text(""),AO(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 n=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css","top"===i&&n.firstChild?n.insertBefore(r,n.firstChild):n.appendChild(r),r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}}(".scene-nav-info {\n position: absolute;\n bottom: 5px;\n width: 100%;\n text-align: center;\n color: slategrey;\n opacity: 0.7;\n font-size: 10px;\n font-family: sans-serif;\n pointer-events: none;\n user-select: none;\n}\n\n.scene-container canvas:focus {\n outline: none;\n}");const CO=e=>{e instanceof Array?e.forEach(CO):(e.map&&e.map.dispose(),e.dispose())},NO=e=>{e.geometry&&e.geometry.dispose(),e.material&&CO(e.material),e.texture&&e.texture.dispose(),e.children&&e.children.forEach(NO)},PO=window.THREE?window.THREE:{WebGLRenderer:class{constructor(e={}){const{canvas:t=bi(),context:i=null,depth:n=!0,stencil:r=!1,alpha:s=!1,antialias:a=!1,premultipliedAlpha:o=!0,preserveDrawingBuffer:l=!1,powerPreference:c="default",failIfMajorPerformanceCaveat:u=!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([ct,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,I=null,F=-1,U=null;const O=new un,B=new un;let k=null;const z=new Kn(0);let G=0,V=t.width,H=t.height,W=1,j=null,$=null;const X=new un(0,0,V,H),q=new un(0,0,V,H);let Y=!1;const K=new Gs,Z=new Hs;let Q=!1,J=!1;const ee=new mn,te=new Wi,ie=new un,ne={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let re=!1;function se(){return null===I?W:1}let ae,oe,le,ce,ue,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:n,stencil:r,antialias:a,premultipliedAlpha:o,preserveDrawingBuffer:l,powerPreference:c,failIfMajorPerformanceCaveat:u};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${N}`),t.addEventListener("webglcontextlost",Ie,!1),t.addEventListener("webglcontextrestored",Fe,!1),t.addEventListener("webglcontextcreationerror",Ue,!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",Ie,!1),t.removeEventListener("webglcontextrestored",Fe,!1),t.removeEventListener("webglcontextcreationerror",Ue,!1),Mi("WebGLRenderer: "+e.message),e}function Pe(){ae=new Yo(Ce),ae.init(),we=new nu(Ce,ae),oe=new Bo(Ce,ae,e,we),le=new tu(Ce,ae),oe.reversedDepthBuffer&&h&&le.buffers.depth.setReversed(!0),R=Ce.createFramebuffer(),C=Ce.createFramebuffer(),P=Ce.createFramebuffer(),ce=new Qo(Ce),ue=new Bc,he=new iu(Ce,ae,le,ue,oe,we,ce),de=new qo(E),pe=new Ro(Ce),Ae=new Uo(Ce,pe),fe=new Ko(Ce,pe,ce,Ae),me=new el(Ce,fe,pe,Ae,ce),Te=new Jo(Ce,oe,he),ye=new ko(ue),ge=new Oc(E,de,ae,oe,Ae,ye),_e=new lu(E,ue),ve=new Vc,be=new qc(ae),Se=new Fo(E,de,le,me,p,o),xe=new eu(E,me,oe),Re=new cu(Ce,ce,oe,le),Me=new Oo(Ce,ae,ce),Ee=new Zo(Ce,ae,ce),ce.programs=ge.programs,E.capabilities=oe,E.extensions=ae,E.properties=ue,E.renderLists=ve,E.shadowMap=xe,E.state=le,E.info=ce}f!==ze&&(M=new il(f,t.width,t.height,a,n,r));const De=new su(E,Ce);function Ie(e){e.preventDefault(),xi("WebGLRenderer: Context Lost."),w=!0}function Fe(){xi("WebGLRenderer: Context Restored."),w=!1;const e=ce.autoReset,t=xe.enabled,i=xe.autoUpdate,n=xe.needsUpdate,r=xe.type;Pe(),ce.autoReset=e,xe.enabled=t,xe.autoUpdate=i,xe.needsUpdate=n,xe.type=r}function Ue(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=ue.get(e).programs;void 0!==t&&(t.forEach(function(e){ge.releaseProgram(e)}),e.isShaderMaterial&&ge.releaseShaderCache(e))})(e),ue.remove(e)}(t)}function Ge(e,t,i,n){null!==A&&e.isNodeMaterial&&A.setObject(n,e),!0===Q&&ye.setState(e,i,!1),!0===e.transparent&&2===e.side&&!1===e.forceSinglePass?(e.side=1,e.needsUpdate=!0,rt(e,t,n),e.side=0,e.needsUpdate=!0,rt(e,t,n),e.side=2):rt(e,t,n)}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,n=!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===n&&(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,n){V=e,H=i,W=n,t.width=Math.floor(e*n),t.height=Math.floor(i*n),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,n){e.isVector4?X.set(e.x,e.y,e.z,e.w):X.set(e,t,i,n),le.viewport(O.copy(X).multiplyScalar(se()).round())},this.getScissor=function(e){return e.copy(q)},this.setScissor=function(e,t,i,n){e.isVector4?q.set(e.x,e.y,e.z,e.w):q.set(e,t,i,n),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 n=0;if(e){let e=!1;if(null!==I){const t=I.texture.format;e=m.has(t)}if(e){const e=I.texture.type,t=g.has(e),i=Se.getClearColor(),n=Se.getClearAlpha(),r=i.r,s=i.g,a=i.b;t?(_[0]=r,_[1]=s,_[2]=a,_[3]=n,Ce.clearBufferuiv(Ce.COLOR,0,_)):(v[0]=r,v[1]=s,v[2]=a,v[3]=n,Ce.clearBufferiv(Ce.COLOR,0,v))}else n|=Ce.COLOR_BUFFER_BIT}t&&(n|=Ce.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0)),i&&(n|=Ce.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),0!==n&&Ce.clear(n)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.setNodesHandler=function(e){e.setRenderer(this),A=e},this.dispose=function(){t.removeEventListener("webglcontextlost",Ie,!1),t.removeEventListener("webglcontextrestored",Fe,!1),t.removeEventListener("webglcontextcreationerror",Ue,!1),Se.dispose(),ve.dispose(),be.dispose(),he.dispose(),ue.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,n,r,s){null===t&&(t=ne);const a=r.isMesh&&r.matrixWorld.determinantAffine()<0,o=function(e,t,i,n,r){!0!==t.isScene&&(t=ne);he.resetTextureUnits();const s=t.fog,a=n.isMeshStandardMaterial||n.isMeshLambertMaterial||n.isMeshPhongMaterial?t.environment:null,o=null===I?E.outputColorSpace:!0===I.isXRRenderTarget?I.texture.colorSpace:Qi.workingColorSpace,l=n.isMeshStandardMaterial||n.isMeshLambertMaterial&&!n.envMap||n.isMeshPhongMaterial&&!n.envMap,c=de.get(n.envMap||a,l),u=!0===n.vertexColors&&!!i.attributes.color&&4===i.attributes.color.itemSize,h=!!i.attributes.tangent&&(!!n.normalMap||n.anisotropy>0),d=!!i.morphAttributes.position,p=!!i.morphAttributes.normal,f=!!i.morphAttributes.color;let m=0;n.toneMapped&&(null!==I&&!0!==I.isXRRenderTarget||(m=E.toneMapping));const g=i.morphAttributes.position||i.morphAttributes.normal||i.morphAttributes.color,_=void 0!==g?g.length:0,v=ue.get(n),y=x.state.lights;if(!0===Q&&(!0===J||e!==U)){const t=e===U&&n.id===F;ye.setState(n,e,t)}let S=!1,T=!1;n.version===v.__version?v.needsLights&&v.lightsStateVersion!==y.state.version||r.isBatchedMesh&&!1===v.batching?S=!0:r.isBatchedMesh||!0!==v.batching?r.isBatchedMesh&&!0===v.batchingColor&&null===r._colorsTexture||r.isBatchedMesh&&!1===v.batchingColor&&null!==r._colorsTexture||r.isInstancedMesh&&!1===v.instancing?S=!0:r.isInstancedMesh||!0!==v.instancing?r.isSkinnedMesh&&!1===v.skinning?S=!0:r.isSkinnedMesh||!0!==v.skinning?r.isInstancedMesh&&!0===v.instancingColor&&null===r.instanceColor||r.isInstancedMesh&&!1===v.instancingColor&&null!==r.instanceColor||r.isInstancedMesh&&!0===v.instancingMorph&&null===r.morphTexture||r.isInstancedMesh&&!1===v.instancingMorph&&null!==r.morphTexture||v.envMap!==c||!0===n.fog&&v.fog!==s?S=!0:void 0===v.numClippingPlanes||v.numClippingPlanes===ye.numPlanes&&v.numIntersection===ye.numIntersection?v.vertexAlphas!==u||v.vertexTangents!==h||v.morphTargets!==d||v.morphNormals!==p||v.morphColors!==f||v.morphTargetsCount!==_||v.numLightProbeGrids!==nt(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=n.version);let M=v.currentProgram;!0!==S&&!0!==T||(M=!0===T?function(e,t,i,n,r){const s=ue.get(e),a=s.currentProgram.id+","+n+","+r;let o=s.programVariants.get(a);void 0===o?(o=rt(e,t,i),s.programVariants.set(a,o)):(s.currentProgram=o,s.uniformsList=null,s.outputColorSpace=n,s.toneMapping=r);return o}(n,t,r,o,m):rt(n,t,r),A&&n.isNodeMaterial&&A.onUpdateProgram(n,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);n.id!==F&&(F=n.id,R=!0);if(w||U!==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)),(n.isMeshPhongMaterial||n.isMeshToonMaterial||n.isMeshLambertMaterial||n.isMeshBasicMaterial||n.isMeshStandardMaterial||n.isShaderMaterial)&&N.setValue(Ce,"isOrthographic",!0===e.isOrthographicCamera),U!==e&&(U=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(r.isSkinnedMesh){N.setOptional(Ce,r,"bindMatrix"),N.setOptional(Ce,r,"bindMatrixInverse");const e=r.skeleton;e&&(null===e.boneTexture&&e.computeBoneTexture(),N.setValue(Ce,"boneTexture",e.boneTexture,he))}r.isBatchedMesh&&(N.setOptional(Ce,r,"batchingTexture"),N.setValue(Ce,"batchingTexture",r._matricesTexture,he),N.setOptional(Ce,r,"batchingIdTexture"),N.setValue(Ce,"batchingIdTexture",r._indirectTexture,he),N.setOptional(Ce,r,"batchingColorTexture"),null!==r._colorsTexture&&N.setValue(Ce,"batchingColorTexture",r._colorsTexture,he));const L=i.morphAttributes;void 0===L.position&&void 0===L.normal&&void 0===L.color||Te.update(r,i,M);(R||v.receiveShadow!==r.receiveShadow)&&(v.receiveShadow=r.receiveShadow,N.setValue(Ce,"receiveShadow",r.receiveShadow));(n.isMeshStandardMaterial||n.isMeshLambertMaterial||n.isMeshPhongMaterial)&&null===n.envMap&&null!==t.environment&&(P.envMapIntensity.value=t.environmentIntensity);void 0!==P.dfgLUT&&(P.dfgLUT.value=(null===hu&&(hu=new Rs(uu,16,16,at,Xe),hu.name="DFG_LUT",hu.minFilter=Oe,hu.magFilter=Oe,hu.wrapS=Le,hu.wrapT=Le,hu.generateMipmaps=!1,hu.needsUpdate=!0),hu));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===n.fog&&_e.refreshFogUniforms(P,s),_e.refreshMaterialUniforms(P,n,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}cc.upload(Ce,lt(v),P,he)}var D,O;n.isShaderMaterial&&!0===n.uniformsNeedUpdate&&(cc.upload(Ce,lt(v),P,he),n.uniformsNeedUpdate=!1);n.isSpriteMaterial&&N.setValue(Ce,"center",r.center);if(N.setValue(Ce,"modelViewMatrix",r.modelViewMatrix),N.setValue(Ce,"normalMatrix",r.normalMatrix),N.setValue(Ce,"modelMatrix",r.matrixWorld),void 0!==n.uniformsGroups){const e=n.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,n,r);le.setMaterial(n,a);let l=i.index,c=1;if(!0===n.wireframe){if(l=fe.getWireframeAttribute(i),void 0===l)return;c=2}const u=i.drawRange,h=i.attributes.position;let d=u.start*c,p=(u.start+u.count)*c;null!==s&&(d=Math.max(d,s.start*c),p=Math.min(p,(s.start+s.count)*c)),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(r,n,o,i,l);let g=Me;if(null!==l&&(m=pe.get(l),g=Ee,g.setIndex(m)),r.isMesh)!0===n.wireframe?(le.setLineWidth(n.wireframeLinewidth*se()),g.setMode(Ce.LINES)):g.setMode(Ce.TRIANGLES);else if(r.isLine){let e=n.linewidth;void 0===e&&(e=1),le.setLineWidth(e*se()),r.isLineSegments?g.setMode(Ce.LINES):r.isLineLoop?g.setMode(Ce.LINE_LOOP):g.setMode(Ce.LINE_STRIP)}else r.isPoints?g.setMode(Ce.POINTS):r.isSprite&&g.setMode(Ce.TRIANGLES);if(r.isBatchedMesh)if(ae.get("WEBGL_multi_draw"))g.renderMultiDraw(r._multiDrawStarts,r._multiDrawCounts,r._multiDrawCount);else{const e=r._multiDrawStarts,t=r._multiDrawCounts,i=r._multiDrawCount,s=l?pe.get(l).bytesPerElement:1,a=ue.get(n).currentProgram.getUniforms();for(let n=0;n<i;n++)a.setValue(Ce,"_gl_DrawID",n),g.render(e[n]/s,t[n])}else if(r.isInstancedMesh)g.renderInstances(d,f,r.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 n=new Set;return e.traverse(function(e){if(!(e.isMesh||e.isPoints||e.isLine||e.isSprite))return;const r=e.material;if(r)if(Array.isArray(r))for(let s=0;s<r.length;s++){const a=r[s];Ge(a,i,t,e),n.add(a)}else Ge(r,i,t,e),n.add(r)}),x=T.pop(),null!==A&&A.renderEnd(),n},this.compileAsync=function(e,t,i=null){const n=this.compile(e,t,i);return new Promise(t=>{function i(){n.forEach(function(e){const t=ue.get(e).currentProgram;(void 0===t||t.isReady())&&n.delete(e)}),0!==n.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 Ao;function Qe(e,t,i,n){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)i=e.renderOrder;else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)x.pushLight(e),e.castShadow&&x.pushShadow(e);else if(e.isSprite){const r=t.isArrayCamera?Z:K;if(!e.frustumCulled||e.intersectsFrustum(r)){n&&ie.setFromMatrixPosition(e.matrixWorld).applyMatrix4(ee);const r=me.update(e),s=e.material;s.visible&&y.push(e,r,s,i,ie.z,null,t)}}else if(e.isMesh||e.isLine||e.isPoints){const r=t.isArrayCamera?Z:K;if(!e.frustumCulled||e.intersectsFrustum(r)){const r=me.update(e),s=e.material;if(n&&(void 0!==e.boundingSphere?(null===e.boundingSphere&&e.computeBoundingSphere(),ie.copy(e.boundingSphere.center)):(null===r.boundingSphere&&r.computeBoundingSphere(),ie.copy(r.boundingSphere.center)),ie.applyMatrix4(e.matrixWorld).applyMatrix4(ee)),Array.isArray(s)){const n=r.groups;for(let a=0,o=n.length;a<o;a++){const o=n[a],l=s[o.materialIndex];l&&l.visible&&y.push(e,r,l,i,ie.z,o,t)}}else s.visible&&y.push(e,r,s,i,ie.z,null,t)}}const r=e.children;for(let e=0,s=r.length;e<s;e++)Qe(r[e],t,i,n)}function Je(e,t,i,n){const{opaque:r,transmissive:s,transparent:a}=e;x.setupLightsView(i),!0===Q&&ye.setGlobalState(E.clippingPlanes,i),n&&le.viewport(O.copy(n)),r.length>0&&tt(r,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,n){if(null!==(!0===i.isScene?i.overrideMaterial:null))return;if(void 0===x.state.transmissionRenderTarget[n.id]){const e=ae.has("EXT_color_buffer_half_float")||ae.has("EXT_color_buffer_float");x.state.transmissionRenderTarget[n.id]=new dn(1,1,{generateMipmaps:!0,type:e?Xe:ze,minFilter:ke,samples:Math.max(4,oe.samples),stencilBuffer:r,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,colorSpace:Qi.workingColorSpace})}const s=x.state.transmissionRenderTarget[n.id],a=n.viewport||O;s.setSize(a.z*E.transmissionResolutionScale,a.w*E.transmissionResolutionScale);const o=E.getRenderTarget(),l=E.getActiveCubeFace(),c=E.getActiveMipmapLevel();E.setRenderTarget(s),E.getClearColor(z),G=E.getClearAlpha(),G<1&&E.setClearColor(16777215,.5),E.clear(),re&&Se.render(i);const u=E.toneMapping;E.toneMapping=0;const h=n.viewport;if(void 0!==n.viewport&&(n.viewport=void 0),x.setupLightsView(n),!0===Q&&ye.setGlobalState(E.clippingPlanes,n),tt(e,i,n),he.updateMultisampleRenderTarget(s),he.updateRenderTargetMipmap(s),!1===ae.has("WEBGL_multisampled_render_to_texture")){let e=!1;for(let r=0,s=t.length;r<s;r++){const s=t[r],{object:a,geometry:o,material:l,group:c}=s;if(2===l.side&&a.layers.test(n.layers)){const t=l.side;l.side=1,l.needsUpdate=!0,it(a,i,n,o,l,c),l.side=t,l.needsUpdate=!0,e=!0}}!0===e&&(he.updateMultisampleRenderTarget(s),he.updateRenderTargetMipmap(s))}E.setRenderTarget(o,l,c),E.setClearColor(z,G),void 0!==h&&(n.viewport=h),E.toneMapping=u}function tt(e,t,i){const n=!0===t.isScene?t.overrideMaterial:null;for(let r=0,s=e.length;r<s;r++){const s=e[r],{object:a,geometry:o,group:l}=s;let c=s.material;!0===c.allowOverride&&null!==n&&(c=n),a.layers.test(i.layers)&&it(a,t,i,o,c,l)}}function it(e,t,i,n,r,s){null!==A&&r.isNodeMaterial&&A.setObject(e,r),e.onBeforeRender(E,t,i,n,r,s),e.modelViewMatrix.multiplyMatrices(i.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix),r.onBeforeRender(E,t,i,n,e,s),!0===r.transparent&&2===r.side&&!1===r.forceSinglePass?(r.side=1,r.needsUpdate=!0,E.renderBufferDirect(i,t,n,r,e,s),r.side=0,r.needsUpdate=!0,E.renderBufferDirect(i,t,n,r,e,s),r.side=2):E.renderBufferDirect(i,t,n,r,e,s),e.onAfterRender(E,t,i,n,r,s)}function nt(e){let t=0;for(const i of e)null!==i.texture&&t++;return t}function rt(e,t,i){!0!==t.isScene&&(t=ne);const n=ue.get(e),r=x.state.lights,s=x.state.shadowsArray,a=r.state.version,o=ge.getParameters(e,r.state,s,t,i,x.state.lightProbeGridArray),l=ge.getProgramCacheKey(o);let c=n.programs;n.environment=e.isMeshStandardMaterial||e.isMeshLambertMaterial||e.isMeshPhongMaterial?t.environment:null,n.fog=t.fog;const u=e.isMeshStandardMaterial||e.isMeshLambertMaterial&&!e.envMap||e.isMeshPhongMaterial&&!e.envMap;n.envMap=de.get(e.envMap||n.environment,u),n.envMapRotation=null!==n.environment&&null===e.envMap?t.environmentRotation:e.envMapRotation,void 0===c&&(e.addEventListener("dispose",Be),c=new Map,n.programs=c,n.programVariants=new Map);let h=c.get(l);if(void 0!==h){if(n.currentProgram===h&&n.lightsStateVersion===a)return ut(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),c.set(l,h),n.uniforms=o.uniforms;const d=n.uniforms;return(e.isShaderMaterial||e.isRawShaderMaterial)&&!0!==e.clipping||(d.clippingPlanes=ye.uniform),ut(e,o),n.needsLights=function(e){return e.isMeshLambertMaterial||e.isMeshToonMaterial||e.isMeshPhongMaterial||e.isMeshStandardMaterial||e.isShadowMaterial||e.isShaderMaterial&&!0===e.lights}(e),n.lightsStateVersion=a,n.needsLights&&(d.ambientLightColor.value=r.state.ambient,d.lightProbe.value=r.state.probe,d.sunLights.value=r.state.sun,d.sunLightShadows.value=r.state.sunShadow,d.directionalLights.value=r.state.directional,d.directionalLightShadows.value=r.state.directionalShadow,d.spotLights.value=r.state.spot,d.spotLightShadows.value=r.state.spotShadow,d.rectAreaLights.value=r.state.rectArea,d.ltc_1.value=r.state.rectAreaLTC1,d.ltc_2.value=r.state.rectAreaLTC2,d.pointLights.value=r.state.point,d.pointLightShadows.value=r.state.pointShadow,d.hemisphereLights.value=r.state.hemi,d.sunShadowMatrix.value=r.state.sunShadowMatrix,d.sunShadowCascade.value=r.state.sunShadowCascade,d.directionalShadowMatrix.value=r.state.directionalShadowMatrix,d.spotLightMatrix.value=r.state.spotLightMatrix,d.spotLightMap.value=r.state.spotLightMap,d.pointShadowMatrix.value=r.state.pointShadowMatrix),n.numLightProbeGrids=nt(x.state.lightProbeGridArray),n.currentProgram=h,n.uniformsList=null,h}function lt(e){if(null===e.uniformsList){const t=e.currentProgram.getUniforms();e.uniformsList=cc.seqWithValue(t.seq,e.uniforms)}return e.uniformsList}function ut(e,t){const i=ue.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=ue.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,n=null!==M&&(null===I||i)&&M.begin(E,I);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,I),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,ci,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,$),re=!1===De.enabled||!1===De.isPresenting||!1===De.hasDepthSensing(),re&&Se.addToRenderList(y,e),!0===this.info.autoReset&&this.info.reset(),!0===Q&&ye.beginShadows();const r=x.state.shadowsArray;xe.render(r,e,t),!0===Q&&ye.endShadows();if(!1===(n&&M.hasRenderPass())){const i=y.opaque,n=y.transmissive;if(x.setupLights(),t.isArrayCamera){const r=t.cameras;if(n.length>0)for(let t=0,s=r.length;t<s;t++){et(i,n,e,r[t])}re&&Se.render(e);for(let t=0,i=r.length;t<i;t++){const i=r[t];Je(y,e,i,i.viewport)}}else n.length>0&&et(i,n,e,t),re&&Se.render(e),Je(y,e,t)}null!==I&&0===D&&(he.updateMultisampleRenderTarget(I),he.updateRenderTargetMipmap(I)),n&&M.end(E),!0===e.isScene&&e.onAfterRender(E,e,t),Ae.resetDefaultState(),F=-1,U=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 I},this.setRenderTargetTextures=function(e,t,i){const n=ue.get(e);n.__autoAllocateDepthBuffer=!1===e.resolveDepthBuffer,!1===n.__autoAllocateDepthBuffer&&(n.__useRenderToTexture=!1),ue.get(e.texture).__webglTexture=t,ue.get(e.depthTexture).__webglTexture=n.__autoAllocateDepthBuffer?void 0:i,n.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(e,t){const i=ue.get(e);i.__webglFramebuffer=t,i.__useDefaultFramebuffer=void 0===t},this.setRenderTarget=function(e,t=0,i=0){I=e,L=t,D=i;let n=null,r=!1,s=!1;if(e){const a=ue.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(F=-1);if(void 0===a.__webglFramebuffer)he.setupRenderTarget(e);else if(a.__hasExternalTextures)he.rebindTextures(e,ue.get(e.texture).__webglTexture,ue.get(e.depthTexture).__webglTexture);else if(e.depthBuffer){const t=e.depthTexture;if(a.__boundDepthTexture!==t){if(null!==t&&ue.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=ue.get(e).__webglFramebuffer;e.isWebGLCubeRenderTarget?(n=Array.isArray(l[t])?l[t][i]:l[t],r=!0):n=e.samples>0&&!1===he.useMultisampledRTT(e)?ue.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&&(n=R);if(le.bindFramebuffer(Ce.FRAMEBUFFER,n)&&le.drawBuffers(e,n),le.viewport(O),le.scissor(B),le.setScissorTest(k),r){const n=ue.get(e.texture);Ce.framebufferTexture2D(Ce.FRAMEBUFFER,Ce.COLOR_ATTACHMENT0,Ce.TEXTURE_CUBE_MAP_POSITIVE_X+t,n.__webglTexture,i)}else if(s){const n=t;for(let t=0;t<e.textures.length;t++){const r=ue.get(e.textures[t]);Ce.framebufferTextureLayer(Ce.FRAMEBUFFER,Ce.COLOR_ATTACHMENT0+t,r.__webglTexture,i,n)}}else if(null!==e&&0!==i){const t=ue.get(e.texture);Ce.framebufferTexture2D(Ce.FRAMEBUFFER,Ce.COLOR_ATTACHMENT0,Ce.TEXTURE_2D,t.__webglTexture,i)}F=-1},this.readRenderTargetPixels=function(e,t,i,n,r,s,a,o=0){if(!e||!e.isWebGLRenderTarget)return void Mi("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let l=ue.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,c=a.type;e.textures.length>1&&Ce.readBuffer(Ce.COLOR_ATTACHMENT0+o);const u=ht(a);if(!1===u.__formatReadable)return void Mi("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");if(!1===u.__typeReadable)return void Mi("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");t>=0&&t<=e.width-n&&i>=0&&i<=e.height-r&&Ce.readPixels(t,i,n,r,we.convert(l),we.convert(c),s)}finally{const e=null!==I?ue.get(I).__webglFramebuffer:null;le.bindFramebuffer(Ce.FRAMEBUFFER,e)}}},this.readRenderTargetPixelsAsync=async function(e,t,i,n,r,s,a,o=0){if(!e||!e.isWebGLRenderTarget)throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let l=ue.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-n&&i>=0&&i<=e.height-r){le.bindFramebuffer(Ce.FRAMEBUFFER,l);const a=e.textures[o],c=a.format,u=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,n,r,we.convert(c),we.convert(u),0),Ce.bindBuffer(Ce.PIXEL_PACK_BUFFER,null);const p=null!==I?ue.get(I).__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(n,r){setTimeout(function s(){switch(e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0)){case e.WAIT_FAILED:r();break;case e.TIMEOUT_EXPIRED:setTimeout(s,i);break;default:n()}},i)})}(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 n=Math.pow(2,-i),r=Math.floor(e.image.width*n),s=Math.floor(e.image.height*n),a=null!==t?t.x:0,o=null!==t?t.y:0;he.setTexture2D(e,0),Ce.copyTexSubImage2D(Ce.TEXTURE_2D,i,0,0,a,o,r,s),le.unbindTexture()},this.copyTextureToTexture=function(e,t,i=null,n=null,r=0,s=0){let a,o,l,c,u,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,c=i.min.x,u=i.min.y,h=i.isBox3?i.min.z:0;else{const t=Math.pow(2,-r);a=Math.floor(m.width*t),o=Math.floor(m.height*t),l=e.isDataArrayTexture?m.depth:e.isData3DTexture?Math.floor(m.depth*t):1,c=0,u=0,h=0}null!==n?(d=n.x,p=n.y,f=n.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,c),le.pixelStorei(Ce.UNPACK_SKIP_ROWS,u),le.pixelStorei(Ce.UNPACK_SKIP_IMAGES,h);const M=e.isDataArrayTexture||e.isData3DTexture,E=t.isDataArrayTexture||t.isData3DTexture;if(e.isDepthTexture){const i=ue.get(e),n=ue.get(t),m=ue.get(i.__renderTarget),g=ue.get(n.__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,ue.get(e).__webglTexture,r,h+i),Ce.framebufferTextureLayer(Ce.DRAW_FRAMEBUFFER,Ce.COLOR_ATTACHMENT0,ue.get(t).__webglTexture,s,f+i)),Ce.blitFramebuffer(c,u,c+a,u+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!==r||e.isRenderTargetTexture||ue.has(e)){const i=ue.get(e),n=ue.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,r,h+e):Ce.framebufferTexture2D(Ce.READ_FRAMEBUFFER,Ce.COLOR_ATTACHMENT0,Ce.TEXTURE_2D,i.__webglTexture,r),E?Ce.framebufferTextureLayer(Ce.DRAW_FRAMEBUFFER,Ce.COLOR_ATTACHMENT0,n.__webglTexture,s,f+e):Ce.framebufferTexture2D(Ce.DRAW_FRAMEBUFFER,Ce.COLOR_ATTACHMENT0,Ce.TEXTURE_2D,n.__webglTexture,s),0!==r?Ce.blitFramebuffer(c,u,c+a,u+o,d,p,d+a,p+o,Ce.COLOR_BUFFER_BIT,Ce.NEAREST):E?Ce.copyTexSubImage3D(v,s,d,p,f+e,c,u,a,o):Ce.copyTexSubImage2D(v,s,d,p,c,u,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===ue.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,I=null,le.reset(),Ae.reset()},"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return ci}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:Qn,PerspectiveCamera:eo,Raycaster:bo,SRGBColorSpace:Xt,TextureLoader:class extends Ba{constructor(e){super(e)}load(e,t,i,n){const r=new cn,s=new za(this.manager);return s.setPriority(this.priority),s.setCache(this.cache),s.setCrossOrigin(this.crossOrigin),s.setPath(this.path),s.load(e,function(e){r.image=e,r.needsUpdate=!0,void 0!==t&&t(r)},i,n),r}},Vector2:Vi,Vector3:Wi,Box3:pr,Color:Kn,Mesh:ws,SphereGeometry:ma,MeshBasicMaterial:fs,BackSide:1,Timer:go};var LO=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?.(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,t,i));const n=t.find(t=>e.hoverFilter(t.object))||null;i=n?n.object:null,e.intersection=n||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,n){const r=e.camera;if(t&&e.initialised){const l=t,c=i||{x:0,y:0,z:0};if(e.povPosTween?.end(),e.povTgtTween?.end(),n){const t=Object.assign({},r.position),i=o();e.tweenGroup.add(e.povPosTween=new EF(t).to(l,n).easing(bF.Quadratic.Out).onUpdate(s).onComplete(function(){e.povPosTween=void 0,e.tweenGroup.remove(this)}).start()),e.tweenGroup.add(e.povTgtTween=new EF(i).to(c,n/3).easing(bF.Quadratic.Out).onUpdate(a).onComplete(function(){e.povTgtTween=void 0,e.tweenGroup.remove(this)}).start())}else s(l),a(c);return this}return Object.assign({},r.position,{lookAt:o()});function s(e){const{x:t,y:i,z:n}=e;void 0!==t&&(r.position.x=t),void 0!==i&&(r.position.y=i),void 0!==n&&(r.position.z=n)}function a(t){const i=new PO.Vector3(t.x,t.y,t.z);e.controls.enabled&&e.controls.target?e.controls.target=i:r.lookAt(i)}function o(){return Object.assign(new PO.Vector3(0,0,-1e3).applyQuaternion(r.quaternion).add(r.position))}},zoomToFit:function(e,t=0,i=10,n,r){return this.fitToBbox(this.getBbox(n),t,i,r)},fitToBbox:function(e,t,i=0,n=10,r=!1){const s=e.camera;if(t){s.updateMatrixWorld();const a=new PO.Vector3,o=new PO.Vector3,l=new PO.Vector3,c=new PO.Vector3;s.getWorldPosition(c),s.getWorldDirection(l),a.crossVectors(l,s.up).normalize(),o.crossVectors(a,l).normalize();const u=(1-2*n/e.height)*s.fov/2*(Math.PI/180),h=Math.atan(Math.tan(u)*s.aspect),d=new PO.Vector3((t.x[0]+t.x[1])/2,(t.y[0]+t.y[1])/2,(t.z[0]+t.z[1])/2),p=r?l.clone().multiplyScalar(c.distanceTo(d)).add(c):d,f=Math.max(0,...[new PO.Vector3(t.x[0],t.y[0],t.z[0]),new PO.Vector3(t.x[0],t.y[0],t.z[1]),new PO.Vector3(t.x[0],t.y[1],t.z[0]),new PO.Vector3(t.x[0],t.y[1],t.z[1]),new PO.Vector3(t.x[1],t.y[0],t.z[0]),new PO.Vector3(t.x[1],t.y[0],t.z[1]),new PO.Vector3(t.x[1],t.y[1],t.z[0]),new PO.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(u),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 PO.Box3,n=e.objects.filter(t);return n.length?(n.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,n){const r=new PO.Vector3(t,i,n);return r.project(this.camera()),{x:(r.x+1)*e.width/2,y:-(r.y-1)*e.height/2}},getSceneCoords:function(e,t,i,n=0){const r=new PO.Vector2(t/e.width*2-1,-i/e.height*2+1),s=new PO.Raycaster;return s.setFromCamera(r,e.camera),Object.assign({},s.ray.at(n,new PO.Vector3))},intersectingObjects:function(e,t,i){const n=new PO.Vector2(t/e.width*2-1,-i/e.height*2+1),r=new PO.Raycaster;return r.params.Line.threshold=e.lineHoverPrecision,r.params.Points.threshold=e.pointsHoverPrecision,r.setFromCamera(n,e.camera),r.intersectObjects(e.objects,!0)},renderer:e=>e.renderer,scene:e=>e.scene,camera:e=>e.camera,postProcessingComposer:e=>e.postProcessingComposer,controls:e=>e.controls,_destructor:function(e){(e=>{for(;e.children.length;){const t=e.children[0];e.remove(t),NO(t)}})(e.scene),e.controls?.dispose(),e.renderer?.dispose(),e.postProcessingComposer?.dispose()}},stateInit:()=>({scene:new PO.Scene,camera:new PO.PerspectiveCamera,timer:new PO.Timer,tweenGroup:new xF,lastRaycasterCheck:0}),init(e,t,{controlType:i="trackball",useWebGPU:n=!1,rendererConfig:r={},extraRenderers:s=[],waitForLoadComplete:a=!0}={}){var o;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",arcball:"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 RO(t.container),t.pointerPos=new PO.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,n=window.pageYOffset||document.documentElement.scrollTop;return{top:t.top+n,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(n?UL:PO.WebGLRenderer)(Object.assign({antialias:!0,alpha:!0},r)),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 II(t.renderer),t.postProcessingComposer.addPass(new FI(t.scene,t.camera)),t.controls=new("function"==typeof(o=i)&&Function.prototype.toString.call(o).startsWith("class")?i:{trackball:nD,arcball:PD,orbit:iI,fly:vI}[i])(t.camera,t.renderer.domElement),"fly"===i&&(t.controls.movementSpeed=300,t.controls.rollSpeed=Math.PI/6,t.controls.dragToLook=!0),"trackball"!==i&&"arcball"!==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 PO.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 n=e.viewOffset.slice(0,2);n.some(e=>e)&&e.camera.setViewOffset(t,i,...n,t,i),e.camera.updateProjectionMatrix()}if(t.hasOwnProperty("viewOffset")){const t=e.width,i=e.height,n=e.viewOffset.slice(0,2);n.some(e=>e)?e.camera.setViewOffset(t,i,...n,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 PO.SphereGeometry(e.skyRadius)),t.hasOwnProperty("backgroundColor")){let t=iF(e.backgroundColor).alpha;void 0===t&&(t=1),e.renderer.setClearColor(new PO.Color(vF(1,e.backgroundColor)),t)}function i(){e.loadComplete=e.scene.visible=!0}t.hasOwnProperty("backgroundImageUrl")&&(e.backgroundImageUrl?(new PO.TextureLoader).load(e.backgroundImageUrl,t=>{t.colorSpace=PO.SRGBColorSpace,e.skysphere.material=new PO.MeshBasicMaterial({map:t,side:PO.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 DO=[[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]],IO=[[0,1,2,3,4,5,6,7]],FO=[],UO=new Map([[IO[0].join(""),0]]);for(let e=0;e<IO.length;e++){const t=IO[e],i=[];for(const e of DO){const n=e.map(e=>t[e]),r=n.join("");let s=UO.get(r);void 0===s&&(s=IO.length,IO.push(n),UO.set(r,s)),i.push(s)}FO.push(i)}const OO=[0n,1n,2n,3n,4n,5n,6n,7n],BO=new Wi(0,0,0);function kO(e=BO,t=10,i=1,n=0,r,s=0,a=1,o=2,l=3,c=4,u=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 n||"bigint"==typeof r){const f=HO(n),m=8n**BigInt(i+1),g=void 0===r?m:HO(r),_=f<0n?0n:f,v=_+(g>0n?g:0n),b=v>m?m:v;if(_>=b)return p;const y=[s,a,o,l,c,u,h,d];return b-_===1n?(VO(p,e.x,e.y,e.z,t,i,_,BigInt(3*i),0,y),p):(GO(p,e.x,e.y,e.z,t,i,0n,m/8n,0,_,b,y),p)}const f=8**(i+1),m=Math.floor(n),g=Math.max(0,m),_=void 0===r?f:Math.max(0,Math.floor(r)),v=Math.min(f,g+_);if(g>=v)return p;const b=[s,a,o,l,c,u,h,d];return zO(p,e.x,e.y,e.z,t,i,0,f/8,0,g,v,b),p}function zO(e,t,i,n,r,s,a,o,l,c,u,h){const d=IO[l],p=FO[l],f=r/2;for(let r=0;r<8;r++){const l=a+r*o;if(l+o<=c||l>=u)continue;const m=h[d[r]],g=t+(m<4?-f:f),_=i+(m<2||m>5?f:-f),v=n+(m%4==1||m%4==2?f:-f);0===s?e.push(new Wi(g,_,v)):zO(e,g,_,v,f,s-1,l,o/8,p[r],c,u,h)}}function GO(e,t,i,n,r,s,a,o,l,c,u,h){const d=IO[l],p=FO[l],f=r/2,m=o/8n,g=a+8n*o,_=c<=a?0:Number((c-a)/o),v=u>=g?7:Number((u-1n-a)/o);let b=a+OO[_]*o;for(let r=_;r<=v;r++,b+=o){const a=h[d[r]],o=t+(a<4?-f:f),l=i+(a<2||a>5?f:-f),g=n+(a%4==1||a%4==2?f:-f);0===s?e.push(new Wi(o,l,g)):GO(e,o,l,g,f,s-1,b,m,p[r],c,u,h)}}function VO(e,t,i,n,r,s,a,o,l,c){const u=IO[l],h=Number(a>>o&7n),d=c[u[h]],p=r/2,f=t+(d<4?-p:p),m=i+(d<2||d>5?p:-p),g=n+(d%4==1||d%4==2?p:-p);0===s?e.push(new Wi(f,m,g)):VO(e,f,m,g,p,s-1,a,o-3n,FO[l][h],c)}function HO(e){if("bigint"==typeof e)return e;if(!Number.isSafeInteger(e))throw new TypeError("BigInt ranges require integer values.");return BigInt(e)}const WO=[[0,1,5,4],[1,2,6,5],[2,3,7,6],[3,0,4,7],[0,3,2,1],[4,5,6,7]],jO=[[-1,-1,-1],[1,-1,-1],[1,1,-1],[-1,1,-1],[-1,-1,1],[1,-1,1],[1,1,1],[-1,1,1]],$O=new Float32Array(48),XO=new Float32Array(72),qO=new Uint16Array(36),YO=[[0,-1,0],[1,0,0],[0,1,0],[-1,0,0],[0,0,-1],[0,0,1]];for(let e=0;e<WO.length;e++){const t=WO[e],i=YO[e];for(let n=0;n<4;n++){const r=4*e+n,s=t[n];$O[2*r]=s%2,$O[2*r+1]=Math.floor(s/2)%2,XO.set(i,3*r)}const n=4*e,r=6*e;qO.set([n,n+1,n+2,n,n+2,n+3],r)}class KO extends Zr{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 kr([],3)),void this.setAttribute("uv",new kr([],2));const n=t/2,r=i.x,s=i.y,a=i.z,o=new Float32Array(72);let l=0;for(const e of WO)for(const t of e){const e=jO[t];o[l++]=r+e[0]*n,o[l++]=s+e[1]*n,o[l++]=a+e[2]*n}return this.setIndex(new Ur(qO.slice(),1)),this.setAttribute("position",new kr(o,3)),this.setAttribute("uv",new kr($O.slice(),2)),this.setAttribute("normal",new kr(XO.slice(),3)),this.boundingBox=new pr(new Wi(r-n,s-n,a-n),new Wi(r+n,s+n,a+n)),void(this.boundingSphere=new Hr(new Wi(r,s,a),Math.sqrt(3)*n))}const i=1e-6,n=[],r=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(!n.length||0!==a.distanceToSquared(n[n.length-1])){for(;n.length>=2;){r.subVectors(n[n.length-1],n[n.length-2]),s.subVectors(a,n[n.length-1]);if(r.dot(s)/Math.sqrt(r.lengthSq()*s.lengthSq())<.999999)break;n.pop()}n.push(a)}}if(this.parameters={points:n.map(e=>e.clone()),width:t},0===n.length||0===t)return this.setIndex([]),this.setAttribute("position",new kr([],3)),void this.setAttribute("uv",new kr([],2));if(1===n.length){const[e,i,r]=n[0].toArray(),s=t/2,a=new Float32Array(72);let o=0;for(const t of WO)for(const n of t){const t=jO[n];a[o++]=e+t[0]*s,a[o++]=i+t[1]*s,a[o++]=r+t[2]*s}return this.setIndex(new Ur(qO.slice(),1)),this.setAttribute("position",new kr(a,3)),this.setAttribute("uv",new kr($O.slice(),2)),this.setAttribute("normal",new kr(XO.slice(),3)),this.computeBoundingBox(),void this.computeBoundingSphere()}const a=new Array(n.length-1);for(let e=0;e<a.length;e++)a[e]=n[e+1].clone().sub(n[e]).normalize();const o=n.length>2&&0===n[0].distanceToSquared(n[n.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(n.length);for(let e=1;e<n.length;e++)l[e]=l[e-1]+n[e].distanceTo(n[e-1]);const c=l[l.length-1],u=t/2,h=c+(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),n=Math.abs(t.y),r=Math.abs(t.z);p.set(i<=n&&i<=r?1:0,n<i&&n<=r?1:0,r<i&&r<n?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?Or:Ur,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,I=[null,null,null,null],F=new Float32Array(8),U=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,n,r,s=0){for(let n=0;n<4;n++){const a=0===n||3===n?1:-1,o=n<2?1:-1;r[n].copy(e).addScaledVector(i,s*u).addScaledVector(t.normal,a*u).addScaledVector(t.binormal,o*u)}if(n){P.copy(i).add(n).normalize();const t=P.dot(i);for(const n of r)L.copy(n).sub(e),n.addScaledVector(i,-P.dot(L)/t)}}function H(e,t,i,n,r,s){const a=void 0!==s;if(A.copy(t).sub(e),R.copy(i).sub(e),C.crossVectors(A,R).dot(r)<0){const e=t;if(t=n,n=e,a){const e=s[2],t=s[3];s[2]=s[6],s[3]=s[7],s[6]=e,s[7]=t}}I[0]=e,I[1]=t,I[2]=i,I[3]=n;for(let e=0;e<4;e++){const t=I[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],r=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,c=r&&Math.abs(r.dot(t))<=i?r:void 0,p=s&&Math.abs(t.dot(s))<=i?s:void 0;if(V(n[e],d[e],t,c,M,0!==e||o?0:-1),V(n[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(n[e]).add(n[e+1]).multiplyScalar(.5);const f=0!==e||o?(l[e]+(o?0:u))/h:0,m=e!==a.length-1||o?(l[e+1]+(o?0:u))/h:1;for(const e of T){const t=(e+1)%4,i=0,n=1;F[0]=i,F[1]=f,F[2]=n,F[3]=f,F[4]=n,F[5]=m,F[6]=i,F[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,F)}}o||(L.copy(a[0]).negate(),H(w[0],w[3],w[2],w[1],L,U),H(E[0],E[1],E[2],E[3],a[a.length-1],O)),this.setIndex(new x(S,1)),this.setAttribute("position",new kr(v,3)),this.setAttribute("uv",new kr(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 ZO extends KO{constructor(e,t,i,{padding:n=0,paddingAbsolute:r=0,simplifyCurves:s=!0}={}){super(...function(){if("bigint"!=typeof t&&(t=Math.round(t)),"bigint"!=typeof i&&(i=Math.round(i)),s){const n="bigint"==typeof t?8n:8;for(;!(t%n)&&!(i%n)&&e>0;)t/=n,i/=n,e-=1}const a=kO(void 0,1,e-1,t,i),o=2**(1-e),l=(o-Math.min(r,.5*o))*(1-Math.min(1,n));return[a,l]}()),this.type="HilbertGeometry";const a=this.parameters;this.parameters={...a,order:e,start:t,length:i,padding:n,paddingAbsolute:r,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 QO(e,t){return null==e||null==t?NaN:e<t?-1:e>t?1:e>=t?0:NaN}function JO(e,t){return null==e||null==t?NaN:t<e?-1:t>e?1:t>=e?0:NaN}function eB(e){let t,i,n;function r(e,n,r=0,s=e.length){if(r<s){if(0!==t(n,n))return s;do{const t=r+s>>>1;i(e[t],n)<0?r=t+1:s=t}while(r<s)}return r}return 2!==e.length?(t=QO,i=(t,i)=>QO(e(t),i),n=(t,i)=>e(t)-i):(t=e===QO||e===JO?e:tB,i=e,n=e),{left:r,center:function(e,t,i=0,s=e.length){const a=r(e,t,i,s-1);return a>i&&n(e[a-1],t)>-n(e[a],t)?a-1:a},right:function(e,n,r=0,s=e.length){if(r<s){if(0!==t(n,n))return s;do{const t=r+s>>>1;i(e[t],n)<=0?r=t+1:s=t}while(r<s)}return r}}}function tB(){return 0}eB(QO),eB(function(e){return null===e?NaN:+e}).center;class iB extends Map{constructor(e,t=rB){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(nB(this,e))}has(e){return super.has(nB(this,e))}set(e,t){return super.set(function({_intern:e,_key:t},i){const n=t(i);return e.has(n)?e.get(n):(e.set(n,i),i)}(this,e),t)}delete(e){return super.delete(function({_intern:e,_key:t},i){const n=t(i);e.has(n)&&(i=e.get(n),e.delete(n));return i}(this,e))}}function nB({_intern:e,_key:t},i){const n=t(i);return e.has(n)?e.get(n):i}function rB(e){return null!==e&&"object"==typeof e?e.valueOf():e}function sB(e,t,i){e.prototype=t.prototype=i,i.constructor=e}function aB(e,t){var i=Object.create(e.prototype);for(var n in t)i[n]=t[n];return i}function oB(){}var lB=.7,cB=1/lB,uB="\\s*([+-]?\\d+)\\s*",hB="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",dB="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",pB=/^#([0-9a-f]{3,8})$/,fB=new RegExp(`^rgb\\(${uB},${uB},${uB}\\)$`),mB=new RegExp(`^rgb\\(${dB},${dB},${dB}\\)$`),gB=new RegExp(`^rgba\\(${uB},${uB},${uB},${hB}\\)$`),_B=new RegExp(`^rgba\\(${dB},${dB},${dB},${hB}\\)$`),vB=new RegExp(`^hsl\\(${hB},${dB},${dB}\\)$`),bB=new RegExp(`^hsla\\(${hB},${dB},${dB},${hB}\\)$`),yB={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 xB(){return this.rgb().formatHex()}function SB(){return this.rgb().formatRgb()}function TB(e){var t,i;return e=(e+"").trim().toLowerCase(),(t=pB.exec(e))?(i=t[1].length,t=parseInt(t[1],16),6===i?MB(t):3===i?new RB(t>>8&15|t>>4&240,t>>4&15|240&t,(15&t)<<4|15&t,1):8===i?EB(t>>24&255,t>>16&255,t>>8&255,(255&t)/255):4===i?EB(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=fB.exec(e))?new RB(t[1],t[2],t[3],1):(t=mB.exec(e))?new RB(255*t[1]/100,255*t[2]/100,255*t[3]/100,1):(t=gB.exec(e))?EB(t[1],t[2],t[3],t[4]):(t=_B.exec(e))?EB(255*t[1]/100,255*t[2]/100,255*t[3]/100,t[4]):(t=vB.exec(e))?IB(t[1],t[2]/100,t[3]/100,1):(t=bB.exec(e))?IB(t[1],t[2]/100,t[3]/100,t[4]):yB.hasOwnProperty(e)?MB(yB[e]):"transparent"===e?new RB(NaN,NaN,NaN,0):null}function MB(e){return new RB(e>>16&255,e>>8&255,255&e,1)}function EB(e,t,i,n){return n<=0&&(e=t=i=NaN),new RB(e,t,i,n)}function wB(e){return e instanceof oB||(e=TB(e)),e?new RB((e=e.rgb()).r,e.g,e.b,e.opacity):new RB}function AB(e,t,i,n){return 1===arguments.length?wB(e):new RB(e,t,i,null==n?1:n)}function RB(e,t,i,n){this.r=+e,this.g=+t,this.b=+i,this.opacity=+n}function CB(){return`#${DB(this.r)}${DB(this.g)}${DB(this.b)}`}function NB(){const e=PB(this.opacity);return`${1===e?"rgb(":"rgba("}${LB(this.r)}, ${LB(this.g)}, ${LB(this.b)}${1===e?")":`, ${e})`}`}function PB(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function LB(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function DB(e){return((e=LB(e))<16?"0":"")+e.toString(16)}function IB(e,t,i,n){return n<=0?e=t=i=NaN:i<=0||i>=1?e=t=NaN:t<=0&&(e=NaN),new UB(e,t,i,n)}function FB(e){if(e instanceof UB)return new UB(e.h,e.s,e.l,e.opacity);if(e instanceof oB||(e=TB(e)),!e)return new UB;if(e instanceof UB)return e;var t=(e=e.rgb()).r/255,i=e.g/255,n=e.b/255,r=Math.min(t,i,n),s=Math.max(t,i,n),a=NaN,o=s-r,l=(s+r)/2;return o?(a=t===s?(i-n)/o+6*(i<n):i===s?(n-t)/o+2:(t-i)/o+4,o/=l<.5?s+r:2-s-r,a*=60):o=l>0&&l<1?0:a,new UB(a,o,l,e.opacity)}function UB(e,t,i,n){this.h=+e,this.s=+t,this.l=+i,this.opacity=+n}function OB(e){return(e=(e||0)%360)<0?e+360:e}function BB(e){return Math.max(0,Math.min(1,e||0))}function kB(e,t,i){return 255*(e<60?t+(i-t)*e/60:e<180?i:e<240?t+(i-t)*(240-e)/60:t)}sB(oB,TB,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:xB,formatHex:xB,formatHex8:function(){return this.rgb().formatHex8()},formatHsl:function(){return FB(this).formatHsl()},formatRgb:SB,toString:SB}),sB(RB,AB,aB(oB,{brighter(e){return e=null==e?cB:Math.pow(cB,e),new RB(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=null==e?lB:Math.pow(lB,e),new RB(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new RB(LB(this.r),LB(this.g),LB(this.b),PB(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:CB,formatHex:CB,formatHex8:function(){return`#${DB(this.r)}${DB(this.g)}${DB(this.b)}${DB(255*(isNaN(this.opacity)?1:this.opacity))}`},formatRgb:NB,toString:NB})),sB(UB,function(e,t,i,n){return 1===arguments.length?FB(e):new UB(e,t,i,null==n?1:n)},aB(oB,{brighter(e){return e=null==e?cB:Math.pow(cB,e),new UB(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=null==e?lB:Math.pow(lB,e),new UB(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,n=i+(i<.5?i:1-i)*t,r=2*i-n;return new RB(kB(e>=240?e-240:e+120,r,n),kB(e,r,n),kB(e<120?e+240:e-120,r,n),this.opacity)},clamp(){return new UB(OB(this.h),BB(this.s),BB(this.l),PB(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=PB(this.opacity);return`${1===e?"hsl(":"hsla("}${OB(this.h)}, ${100*BB(this.s)}%, ${100*BB(this.l)}%${1===e?")":`, ${e})`}`}}));const zB=Math.PI/180,GB=180/Math.PI,VB=.96422,HB=.82521,WB=4/29,jB=6/29,$B=3*jB*jB,XB=jB*jB*jB;function qB(e){if(e instanceof YB)return new YB(e.l,e.a,e.b,e.opacity);if(e instanceof ek)return tk(e);e instanceof RB||(e=wB(e));var t,i,n=JB(e.r),r=JB(e.g),s=JB(e.b),a=KB((.2225045*n+.7168786*r+.0606169*s)/1);return n===r&&r===s?t=i=a:(t=KB((.4360747*n+.3850649*r+.1430804*s)/VB),i=KB((.0139322*n+.0971045*r+.7141733*s)/HB)),new YB(116*a-16,500*(t-a),200*(a-i),e.opacity)}function YB(e,t,i,n){this.l=+e,this.a=+t,this.b=+i,this.opacity=+n}function KB(e){return e>XB?Math.pow(e,1/3):e/$B+WB}function ZB(e){return e>jB?e*e*e:$B*(e-WB)}function QB(e){return 255*(e<=.0031308?12.92*e:1.055*Math.pow(e,1/2.4)-.055)}function JB(e){return(e/=255)<=.04045?e/12.92:Math.pow((e+.055)/1.055,2.4)}function ek(e,t,i,n){this.h=+e,this.c=+t,this.l=+i,this.opacity=+n}function tk(e){if(isNaN(e.h))return new YB(e.l,0,0,e.opacity);var t=e.h*zB;return new YB(e.l,Math.cos(t)*e.c,Math.sin(t)*e.c,e.opacity)}sB(YB,function(e,t,i,n){return 1===arguments.length?qB(e):new YB(e,t,i,null==n?1:n)},aB(oB,{brighter(e){return new YB(this.l+18*(null==e?1:e),this.a,this.b,this.opacity)},darker(e){return new YB(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 RB(QB(3.1338561*(t=VB*ZB(t))-1.6168667*(e=1*ZB(e))-.4906146*(i=HB*ZB(i))),QB(-.9787684*t+1.9161415*e+.033454*i),QB(.0719453*t-.2289914*e+1.4052427*i),this.opacity)}})),sB(ek,function(e,t,i,n){return 1===arguments.length?function(e){if(e instanceof ek)return new ek(e.h,e.c,e.l,e.opacity);if(e instanceof YB||(e=qB(e)),0===e.a&&0===e.b)return new ek(NaN,0<e.l&&e.l<100?0:NaN,e.l,e.opacity);var t=Math.atan2(e.b,e.a)*GB;return new ek(t<0?t+360:t,Math.sqrt(e.a*e.a+e.b*e.b),e.l,e.opacity)}(e):new ek(e,t,i,null==n?1:n)},aB(oB,{brighter(e){return new ek(this.h,this.c,this.l+18*(null==e?1:e),this.opacity)},darker(e){return new ek(this.h,this.c,this.l-18*(null==e?1:e),this.opacity)},rgb(){return tk(this).rgb()}}));var ik=-.14861,nk=1.78277,rk=-.29227,sk=-.90649,ak=1.97294,ok=ak*sk,lk=ak*nk,ck=nk*rk-sk*ik;function uk(e,t,i,n){return 1===arguments.length?function(e){if(e instanceof hk)return new hk(e.h,e.s,e.l,e.opacity);e instanceof RB||(e=wB(e));var t=e.r/255,i=e.g/255,n=e.b/255,r=(ck*n+ok*t-lk*i)/(ck+ok-lk),s=n-r,a=(ak*(i-r)-rk*s)/sk,o=Math.sqrt(a*a+s*s)/(ak*r*(1-r)),l=o?Math.atan2(a,s)*GB-120:NaN;return new hk(l<0?l+360:l,o,r,e.opacity)}(e):new hk(e,t,i,null==n?1:n)}function hk(e,t,i,n){this.h=+e,this.s=+t,this.l=+i,this.opacity=+n}sB(hk,uk,aB(oB,{brighter(e){return e=null==e?cB:Math.pow(cB,e),new hk(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=null==e?lB:Math.pow(lB,e),new hk(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=isNaN(this.h)?0:(this.h+120)*zB,t=+this.l,i=isNaN(this.s)?0:this.s*t*(1-t),n=Math.cos(e),r=Math.sin(e);return new RB(255*(t+i*(ik*n+nk*r)),255*(t+i*(rk*n+sk*r)),255*(t+i*(ak*n)),this.opacity)}}));var dk=e=>()=>e;function pk(e,t){return function(i){return e+i*t}}function fk(e){return 1===(e=+e)?mk: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(n){return Math.pow(e+n*t,i)}}(t,i,e):dk(isNaN(t)?i:t)}}function mk(e,t){var i=t-e;return i?pk(e,i):dk(isNaN(e)?t:e)}!function e(t){var i=fk(t);function n(e,t){var n=i((e=AB(e)).r,(t=AB(t)).r),r=i(e.g,t.g),s=i(e.b,t.b),a=mk(e.opacity,t.opacity);return function(t){return e.r=n(t),e.g=r(t),e.b=s(t),e.opacity=a(t),e+""}}return n.gamma=e,n}(1);var gk,_k=(gk=function(e){var t=e.length-1;return function(i){var n=i<=0?i=0:i>=1?(i=1,t-1):Math.floor(i*t),r=e[n],s=e[n+1],a=n>0?e[n-1]:2*r-s,o=n<t-1?e[n+2]:2*s-r;return function(e,t,i,n,r){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)*n+a*r)/6}((i-n/t)*t,a,r,s,o)}},function(e){var t,i,n=e.length,r=new Array(n),s=new Array(n),a=new Array(n);for(t=0;t<n;++t)i=AB(e[t]),r[t]=i.r||0,s[t]=i.g||0,a[t]=i.b||0;return r=gk(r),s=gk(s),a=gk(a),i.opacity=1,function(e){return i.r=r(e),i.g=s(e),i.b=a(e),i+""}});function vk(e){return((e=Math.exp(e))+1/e)/2}function bk(e){return function t(i){function n(t,n){var r=e((t=uk(t)).h,(n=uk(n)).h),s=mk(t.s,n.s),a=mk(t.l,n.l),o=mk(t.opacity,n.opacity);return function(e){return t.h=r(e),t.s=s(e),t.l=a(Math.pow(e,i)),t.opacity=o(e),t+""}}return i=+i,n.gamma=t,n}(1)}!function e(t,i,n){function r(e,r){var s,a,o=e[0],l=e[1],c=e[2],u=r[0],h=r[1],d=r[2],p=u-o,f=h-l,m=p*p+f*f;if(m<1e-12)a=Math.log(d/c)/t,s=function(e){return[o+e*p,l+e*f,c*Math.exp(t*e*a)]};else{var g=Math.sqrt(m),_=(d*d-c*c+n*m)/(2*c*i*g),v=(d*d-c*c-n*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 n=e*a,r=vk(b),s=c/(i*g)*(r*function(e){return((e=Math.exp(2*e))-1)/(e+1)}(t*n+b)-function(e){return((e=Math.exp(e))-1/e)/2}(b));return[o+s*p,l+s*f,c*r/vk(t*n+b)]}}return s.duration=1e3*Math.abs(a)*t/Math.SQRT2,s}return r.rho=function(t){var i=Math.max(.001,+t),n=i*i;return e(i,n,n*n)},r}(Math.SQRT2,2,4),bk(function(e,t){var i=t-e;return i?pk(e,i>180||i<-180?i-360*Math.round(i/360):i):dk(isNaN(e)?t:e)});var yk=bk(mk);function xk(e,t){switch(arguments.length){case 0:break;case 1:this.range(e);break;default:this.range(t).domain(e)}return this}const Sk=Symbol("implicit");function Tk(){var e=new iB,t=[],i=[],n=Sk;function r(r){let s=e.get(r);if(void 0===s){if(n!==Sk)return n;e.set(r,s=t.push(r)-1)}return i[s%i.length]}return r.domain=function(i){if(!arguments.length)return t.slice();t=[],e=new iB;for(const n of i)e.has(n)||e.set(n,t.push(n)-1);return r},r.range=function(e){return arguments.length?(i=Array.from(e),r):i.slice()},r.unknown=function(e){return arguments.length?(n=e,r):n},r.copy=function(){return Tk(t,i).unknown(n)},xk.apply(r,arguments),r}function Mk(e){for(var t=e.length/6|0,i=new Array(t),n=0;n<t;)i[n]="#"+e.slice(6*n,6*++n);return i}Mk("1f77b4ff7f0e2ca02cd627289467bd8c564be377c27f7f7fbcbd2217becf"),Mk("7fc97fbeaed4fdc086ffff99386cb0f0027fbf5b17666666"),Mk("1b9e77d95f027570b3e7298a66a61ee6ab02a6761d666666"),Mk("4269d0efb118ff725c6cc5b03ca951ff8ab7a463f297bbf59c6b4e9498a0");var Ek=Mk("a6cee31f78b4b2df8a33a02cfb9a99e31a1cfdbf6fff7f00cab2d66a3d9affff99b15928");Mk("fbb4aeb3cde3ccebc5decbe4fed9a6ffffcce5d8bdfddaecf2f2f2"),Mk("b3e2cdfdcdaccbd5e8f4cae4e6f5c9fff2aef1e2cccccccc"),Mk("e41a1c377eb84daf4a984ea3ff7f00ffff33a65628f781bf999999"),Mk("66c2a5fc8d628da0cbe78ac3a6d854ffd92fe5c494b3b3b3"),Mk("8dd3c7ffffb3bebadafb807280b1d3fdb462b3de69fccde5d9d9d9bc80bdccebc5ffed6f"),Mk("4e79a7f28e2ce1575976b7b259a14fedc949af7aa1ff9da79c755fbab0ab");var wk=e=>_k(e[e.length-1]);function Ak(e){var t=e.length;return function(i){return e[Math.max(0,Math.min(t-1,Math.floor(i*t)))]}}function Rk(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,n=Array(t);i<t;i++)n[i]=e[i];return n}function Ck(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 Nk(e,t){return e.get(Ck(e,t))}function Pk(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 Lk(e,t,i){return e.set(Ck(e,t),i),i}function Dk(e,t,i){return t&&function(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,Uk(n.key),n)}}(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function Ik(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 n,r,s,a,o=[],l=!0,c=!1;try{if(s=(i=i.call(e)).next,0===t);else for(;!(l=(n=s.call(i)).done)&&(o.push(n.value),o.length!==t);l=!0);}catch(e){c=!0,r=e}finally{try{if(!l&&null!=i.return&&(a=i.return(),Object(a)!==a))return}finally{if(c)throw r}}return o}}(e,t)||Ok(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 Fk(e){return function(e){if(Array.isArray(e))return Rk(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||Ok(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 Uk(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.call(e,t);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==typeof t?t:t+""}function Ok(e,t){if(e){if("string"==typeof e)return Rk(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)?Rk(e,t):void 0}}wk(new Array(3).concat("d8b365f5f5f55ab4ac","a6611adfc27d80cdc1018571","a6611adfc27df5f5f580cdc1018571","8c510ad8b365f6e8c3c7eae55ab4ac01665e","8c510ad8b365f6e8c3f5f5f5c7eae55ab4ac01665e","8c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e","8c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e","5430058c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e003c30","5430058c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e003c30").map(Mk)),wk(new Array(3).concat("af8dc3f7f7f77fbf7b","7b3294c2a5cfa6dba0008837","7b3294c2a5cff7f7f7a6dba0008837","762a83af8dc3e7d4e8d9f0d37fbf7b1b7837","762a83af8dc3e7d4e8f7f7f7d9f0d37fbf7b1b7837","762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b7837","762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b7837","40004b762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b783700441b","40004b762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b783700441b").map(Mk)),wk(new Array(3).concat("e9a3c9f7f7f7a1d76a","d01c8bf1b6dab8e1864dac26","d01c8bf1b6daf7f7f7b8e1864dac26","c51b7de9a3c9fde0efe6f5d0a1d76a4d9221","c51b7de9a3c9fde0eff7f7f7e6f5d0a1d76a4d9221","c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221","c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221","8e0152c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221276419","8e0152c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221276419").map(Mk)),wk(new Array(3).concat("998ec3f7f7f7f1a340","5e3c99b2abd2fdb863e66101","5e3c99b2abd2f7f7f7fdb863e66101","542788998ec3d8daebfee0b6f1a340b35806","542788998ec3d8daebf7f7f7fee0b6f1a340b35806","5427888073acb2abd2d8daebfee0b6fdb863e08214b35806","5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b35806","2d004b5427888073acb2abd2d8daebfee0b6fdb863e08214b358067f3b08","2d004b5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b358067f3b08").map(Mk)),wk(new Array(3).concat("ef8a62f7f7f767a9cf","ca0020f4a58292c5de0571b0","ca0020f4a582f7f7f792c5de0571b0","b2182bef8a62fddbc7d1e5f067a9cf2166ac","b2182bef8a62fddbc7f7f7f7d1e5f067a9cf2166ac","b2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac","b2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac","67001fb2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac053061","67001fb2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac053061").map(Mk)),wk(new Array(3).concat("ef8a62ffffff999999","ca0020f4a582bababa404040","ca0020f4a582ffffffbababa404040","b2182bef8a62fddbc7e0e0e09999994d4d4d","b2182bef8a62fddbc7ffffffe0e0e09999994d4d4d","b2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d","b2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d","67001fb2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d1a1a1a","67001fb2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d1a1a1a").map(Mk)),wk(new Array(3).concat("fc8d59ffffbf91bfdb","d7191cfdae61abd9e92c7bb6","d7191cfdae61ffffbfabd9e92c7bb6","d73027fc8d59fee090e0f3f891bfdb4575b4","d73027fc8d59fee090ffffbfe0f3f891bfdb4575b4","d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4","d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4","a50026d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4313695","a50026d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4313695").map(Mk)),wk(new Array(3).concat("fc8d59ffffbf91cf60","d7191cfdae61a6d96a1a9641","d7191cfdae61ffffbfa6d96a1a9641","d73027fc8d59fee08bd9ef8b91cf601a9850","d73027fc8d59fee08bffffbfd9ef8b91cf601a9850","d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850","d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850","a50026d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850006837","a50026d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850006837").map(Mk)),wk(new Array(3).concat("fc8d59ffffbf99d594","d7191cfdae61abdda42b83ba","d7191cfdae61ffffbfabdda42b83ba","d53e4ffc8d59fee08be6f59899d5943288bd","d53e4ffc8d59fee08bffffbfe6f59899d5943288bd","d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd","d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd","9e0142d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd5e4fa2","9e0142d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd5e4fa2").map(Mk)),wk(new Array(3).concat("e5f5f999d8c92ca25f","edf8fbb2e2e266c2a4238b45","edf8fbb2e2e266c2a42ca25f006d2c","edf8fbccece699d8c966c2a42ca25f006d2c","edf8fbccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45006d2c00441b").map(Mk)),wk(new Array(3).concat("e0ecf49ebcda8856a7","edf8fbb3cde38c96c688419d","edf8fbb3cde38c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d810f7c4d004b").map(Mk)),wk(new Array(3).concat("e0f3dba8ddb543a2ca","f0f9e8bae4bc7bccc42b8cbe","f0f9e8bae4bc7bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe0868ac084081").map(Mk)),wk(new Array(3).concat("fee8c8fdbb84e34a33","fef0d9fdcc8afc8d59d7301f","fef0d9fdcc8afc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301fb300007f0000").map(Mk)),wk(new Array(3).concat("ece2f0a6bddb1c9099","f6eff7bdc9e167a9cf02818a","f6eff7bdc9e167a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016c59014636").map(Mk)),wk(new Array(3).concat("ece7f2a6bddb2b8cbe","f1eef6bdc9e174a9cf0570b0","f1eef6bdc9e174a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0045a8d023858").map(Mk)),wk(new Array(3).concat("e7e1efc994c7dd1c77","f1eef6d7b5d8df65b0ce1256","f1eef6d7b5d8df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125698004367001f").map(Mk)),wk(new Array(3).concat("fde0ddfa9fb5c51b8a","feebe2fbb4b9f768a1ae017e","feebe2fbb4b9f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a017749006a").map(Mk)),wk(new Array(3).concat("edf8b17fcdbb2c7fb8","ffffcca1dab441b6c4225ea8","ffffcca1dab441b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea8253494081d58").map(Mk)),wk(new Array(3).concat("f7fcb9addd8e31a354","ffffccc2e69978c679238443","ffffccc2e69978c67931a354006837","ffffccd9f0a3addd8e78c67931a354006837","ffffccd9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443006837004529").map(Mk)),wk(new Array(3).concat("fff7bcfec44fd95f0e","ffffd4fed98efe9929cc4c02","ffffd4fed98efe9929d95f0e993404","ffffd4fee391fec44ffe9929d95f0e993404","ffffd4fee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c02993404662506").map(Mk)),wk(new Array(3).concat("ffeda0feb24cf03b20","ffffb2fecc5cfd8d3ce31a1c","ffffb2fecc5cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cbd0026800026").map(Mk)),wk(new Array(3).concat("deebf79ecae13182bd","eff3ffbdd7e76baed62171b5","eff3ffbdd7e76baed63182bd08519c","eff3ffc6dbef9ecae16baed63182bd08519c","eff3ffc6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b508519c08306b").map(Mk)),wk(new Array(3).concat("e5f5e0a1d99b31a354","edf8e9bae4b374c476238b45","edf8e9bae4b374c47631a354006d2c","edf8e9c7e9c0a1d99b74c47631a354006d2c","edf8e9c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45006d2c00441b").map(Mk)),wk(new Array(3).concat("f0f0f0bdbdbd636363","f7f7f7cccccc969696525252","f7f7f7cccccc969696636363252525","f7f7f7d9d9d9bdbdbd969696636363252525","f7f7f7d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525000000").map(Mk)),wk(new Array(3).concat("efedf5bcbddc756bb1","f2f0f7cbc9e29e9ac86a51a3","f2f0f7cbc9e29e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a354278f3f007d").map(Mk)),wk(new Array(3).concat("fee0d2fc9272de2d26","fee5d9fcae91fb6a4acb181d","fee5d9fcae91fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181da50f1567000d").map(Mk)),wk(new Array(3).concat("fee6cefdae6be6550d","feeddefdbe85fd8d3cd94701","feeddefdbe85fd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d94801a636037f2704").map(Mk)),yk(uk(300,.5,0),uk(-240,.5,1)),yk(uk(-100,.75,.35),uk(80,1.5,.8)),yk(uk(260,.75,.35),uk(80,1.5,.8)),uk(),AB(),Ak(Mk("44015444025645045745055946075a46085c460a5d460b5e470d60470e6147106347116447136548146748166848176948186a481a6c481b6d481c6e481d6f481f70482071482173482374482475482576482677482878482979472a7a472c7a472d7b472e7c472f7d46307e46327e46337f463480453581453781453882443983443a83443b84433d84433e85423f854240864241864142874144874045884046883f47883f48893e49893e4a893e4c8a3d4d8a3d4e8a3c4f8a3c508b3b518b3b528b3a538b3a548c39558c39568c38588c38598c375a8c375b8d365c8d365d8d355e8d355f8d34608d34618d33628d33638d32648e32658e31668e31678e31688e30698e306a8e2f6b8e2f6c8e2e6d8e2e6e8e2e6f8e2d708e2d718e2c718e2c728e2c738e2b748e2b758e2a768e2a778e2a788e29798e297a8e297b8e287c8e287d8e277e8e277f8e27808e26818e26828e26828e25838e25848e25858e24868e24878e23888e23898e238a8d228b8d228c8d228d8d218e8d218f8d21908d21918c20928c20928c20938c1f948c1f958b1f968b1f978b1f988b1f998a1f9a8a1e9b8a1e9c891e9d891f9e891f9f881fa0881fa1881fa1871fa28720a38620a48621a58521a68522a78522a88423a98324aa8325ab8225ac8226ad8127ad8128ae8029af7f2ab07f2cb17e2db27d2eb37c2fb47c31b57b32b67a34b67935b77937b87838b9773aba763bbb753dbc743fbc7340bd7242be7144bf7046c06f48c16e4ac16d4cc26c4ec36b50c46a52c56954c56856c66758c7655ac8645cc8635ec96260ca6063cb5f65cb5e67cc5c69cd5b6ccd5a6ece5870cf5773d05675d05477d1537ad1517cd2507fd34e81d34d84d44b86d54989d5488bd6468ed64590d74393d74195d84098d83e9bd93c9dd93ba0da39a2da37a5db36a8db34aadc32addc30b0dd2fb2dd2db5de2bb8de29bade28bddf26c0df25c2df23c5e021c8e020cae11fcde11dd0e11cd2e21bd5e21ad8e219dae319dde318dfe318e2e418e5e419e7e419eae51aece51befe51cf1e51df4e61ef6e620f8e621fbe723fde725")),Ak(Mk("00000401000501010601010802010902020b02020d03030f03031204041405041606051806051a07061c08071e0907200a08220b09240c09260d0a290e0b2b100b2d110c2f120d31130d34140e36150e38160f3b180f3d19103f1a10421c10441d11471e114920114b21114e22115024125325125527125829115a2a115c2c115f2d11612f116331116533106734106936106b38106c390f6e3b0f703d0f713f0f72400f74420f75440f764510774710784910784a10794c117a4e117b4f127b51127c52137c54137d56147d57157e59157e5a167e5c167f5d177f5f187f601880621980641a80651a80671b80681c816a1c816b1d816d1d816e1e81701f81721f817320817521817621817822817922827b23827c23827e24828025828125818326818426818627818827818928818b29818c29818e2a81902a81912b81932b80942c80962c80982d80992d809b2e7f9c2e7f9e2f7fa02f7fa1307ea3307ea5317ea6317da8327daa337dab337cad347cae347bb0357bb2357bb3367ab5367ab73779b83779ba3878bc3978bd3977bf3a77c03a76c23b75c43c75c53c74c73d73c83e73ca3e72cc3f71cd4071cf4070d0416fd2426fd3436ed5446dd6456cd8456cd9466bdb476adc4869de4968df4a68e04c67e24d66e34e65e44f64e55064e75263e85362e95462ea5661eb5760ec5860ed5a5fee5b5eef5d5ef05f5ef1605df2625df2645cf3655cf4675cf4695cf56b5cf66c5cf66e5cf7705cf7725cf8745cf8765cf9785df9795df97b5dfa7d5efa7f5efa815ffb835ffb8560fb8761fc8961fc8a62fc8c63fc8e64fc9065fd9266fd9467fd9668fd9869fd9a6afd9b6bfe9d6cfe9f6dfea16efea36ffea571fea772fea973feaa74feac76feae77feb078feb27afeb47bfeb67cfeb77efeb97ffebb81febd82febf84fec185fec287fec488fec68afec88cfeca8dfecc8ffecd90fecf92fed194fed395fed597fed799fed89afdda9cfddc9efddea0fde0a1fde2a3fde3a5fde5a7fde7a9fde9aafdebacfcecaefceeb0fcf0b2fcf2b4fcf4b6fcf6b8fcf7b9fcf9bbfcfbbdfcfdbf")),Ak(Mk("00000401000501010601010802010a02020c02020e03021004031204031405041706041907051b08051d09061f0a07220b07240c08260d08290e092b10092d110a30120a32140b34150b37160b39180c3c190c3e1b0c411c0c431e0c451f0c48210c4a230c4c240c4f260c51280b53290b552b0b572d0b592f0a5b310a5c320a5e340a5f3609613809623909633b09643d09653e0966400a67420a68440a68450a69470b6a490b6a4a0c6b4c0c6b4d0d6c4f0d6c510e6c520e6d540f6d550f6d57106e59106e5a116e5c126e5d126e5f136e61136e62146e64156e65156e67166e69166e6a176e6c186e6d186e6f196e71196e721a6e741a6e751b6e771c6d781c6d7a1d6d7c1d6d7d1e6d7f1e6c801f6c82206c84206b85216b87216b88226a8a226a8c23698d23698f24699025689225689326679526679727669827669a28659b29649d29649f2a63a02a63a22b62a32c61a52c60a62d60a82e5fa92e5eab2f5ead305dae305cb0315bb1325ab3325ab43359b63458b73557b93556ba3655bc3754bd3853bf3952c03a51c13a50c33b4fc43c4ec63d4dc73e4cc83f4bca404acb4149cc4248ce4347cf4446d04545d24644d34743d44842d54a41d74b3fd84c3ed94d3dda4e3cdb503bdd513ade5238df5337e05536e15635e25734e35933e45a31e55c30e65d2fe75e2ee8602de9612bea632aeb6429eb6628ec6726ed6925ee6a24ef6c23ef6e21f06f20f1711ff1731df2741cf3761bf37819f47918f57b17f57d15f67e14f68013f78212f78410f8850ff8870ef8890cf98b0bf98c0af98e09fa9008fa9207fa9407fb9606fb9706fb9906fb9b06fb9d07fc9f07fca108fca309fca50afca60cfca80dfcaa0ffcac11fcae12fcb014fcb216fcb418fbb61afbb81dfbba1ffbbc21fbbe23fac026fac228fac42afac62df9c72ff9c932f9cb35f8cd37f8cf3af7d13df7d340f6d543f6d746f5d949f5db4cf4dd4ff4df53f4e156f3e35af3e55df2e661f2e865f2ea69f1ec6df1ed71f1ef75f1f179f2f27df2f482f3f586f3f68af4f88ef5f992f6fa96f8fb9af9fc9dfafda1fcffa4")),Ak(Mk("0d088710078813078916078a19068c1b068d1d068e20068f2206902406912605912805922a05932c05942e05952f059631059733059735049837049938049a3a049a3c049b3e049c3f049c41049d43039e44039e46039f48039f4903a04b03a14c02a14e02a25002a25102a35302a35502a45601a45801a45901a55b01a55c01a65e01a66001a66100a76300a76400a76600a76700a86900a86a00a86c00a86e00a86f00a87100a87201a87401a87501a87701a87801a87a02a87b02a87d03a87e03a88004a88104a78305a78405a78606a68707a68808a68a09a58b0aa58d0ba58e0ca48f0da4910ea3920fa39410a29511a19613a19814a099159f9a169f9c179e9d189d9e199da01a9ca11b9ba21d9aa31e9aa51f99a62098a72197a82296aa2395ab2494ac2694ad2793ae2892b02991b12a90b22b8fb32c8eb42e8db52f8cb6308bb7318ab83289ba3388bb3488bc3587bd3786be3885bf3984c03a83c13b82c23c81c33d80c43e7fc5407ec6417dc7427cc8437bc9447aca457acb4679cc4778cc4977cd4a76ce4b75cf4c74d04d73d14e72d24f71d35171d45270d5536fd5546ed6556dd7566cd8576bd9586ada5a6ada5b69db5c68dc5d67dd5e66de5f65de6164df6263e06363e16462e26561e26660e3685fe4695ee56a5de56b5de66c5ce76e5be76f5ae87059e97158e97257ea7457eb7556eb7655ec7754ed7953ed7a52ee7b51ef7c51ef7e50f07f4ff0804ef1814df1834cf2844bf3854bf3874af48849f48948f58b47f58c46f68d45f68f44f79044f79143f79342f89441f89540f9973ff9983ef99a3efa9b3dfa9c3cfa9e3bfb9f3afba139fba238fca338fca537fca636fca835fca934fdab33fdac33fdae32fdaf31fdb130fdb22ffdb42ffdb52efeb72dfeb82cfeba2cfebb2bfebd2afebe2afec029fdc229fdc328fdc527fdc627fdc827fdca26fdcb26fccd25fcce25fcd025fcd225fbd324fbd524fbd724fad824fada24f9dc24f9dd25f8df25f8e125f7e225f7e425f6e626f6e826f5e926f5eb27f4ed27f3ee27f3f027f2f227f1f426f1f525f0f724f0f921"));var Bk=new WeakMap,kk=new WeakMap,zk=new WeakMap,Gk=new WeakMap,Vk=new WeakMap,Hk=new WeakMap,Wk=function(){return Dk(function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),Pk(this,Bk,new Map),Pk(this,kk,new Map),Pk(this,zk,function(e){return e}),Pk(this,Gk,function(){return{}}),Pk(this,Vk,function(){}),Pk(this,Hk,function(){})},[{key:"getObj",value:function(e){return Nk(Bk,this).get(Nk(zk,this).call(this,e))}},{key:"getData",value:function(e){return Nk(kk,this).get(e)}},{key:"entries",value:function(){return Fk(Nk(kk,this).entries()).map(function(e){var t=Ik(e,2),i=t[0];return[t[1],i]})}},{key:"id",value:function(e){return Lk(zk,this,C(e)),this}},{key:"onCreateObj",value:function(e){return Lk(Gk,this,e),this}},{key:"onUpdateObj",value:function(e){return Lk(Vk,this,e),this}},{key:"onRemoveObj",value:function(e){return Lk(Hk,this,e),this}},{key:"digest",value:function(e){var t=this;e.filter(function(e){return!Nk(Bk,t).has(Nk(zk,t).call(t,e))}).forEach(function(e){var i=Nk(Gk,t).call(t,e);Nk(Bk,t).set(Nk(zk,t).call(t,e),i),Nk(kk,t).set(i,e)});var i=new Map(e.map(function(e){return[Nk(zk,t).call(t,e),e]}));return Nk(Bk,this).forEach(function(e,n){i.has(n)?Nk(Vk,t).call(t,e,i.get(n)):(Nk(Hk,t).call(t,e,n),Nk(Bk,t).delete(n),Nk(kk,t).delete(e))}),this}},{key:"clear",value:function(){return this.digest([]),this}}])}();function jk(e){return jk="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},jk(e)}var $k=/^\s+/,Xk=/\s+$/;function qk(e,t){if(t=t||{},(e=e||"")instanceof qk)return e;if(!(this instanceof qk))return new qk(e,t);var i=function(e){var t={r:0,g:0,b:0},i=1,n=null,r=null,s=null,a=!1,o=!1;"string"==typeof e&&(e=function(e){e=e.replace($k,"").replace(Xk,"").toLowerCase();var t,i=!1;if(hz[e])e=hz[e],i=!0;else if("transparent"==e)return{r:0,g:0,b:0,a:0,format:"name"};if(t=Mz.rgb.exec(e))return{r:t[1],g:t[2],b:t[3]};if(t=Mz.rgba.exec(e))return{r:t[1],g:t[2],b:t[3],a:t[4]};if(t=Mz.hsl.exec(e))return{h:t[1],s:t[2],l:t[3]};if(t=Mz.hsla.exec(e))return{h:t[1],s:t[2],l:t[3],a:t[4]};if(t=Mz.hsv.exec(e))return{h:t[1],s:t[2],v:t[3]};if(t=Mz.hsva.exec(e))return{h:t[1],s:t[2],v:t[3],a:t[4]};if(t=Mz.hex8.exec(e))return{r:gz(t[1]),g:gz(t[2]),b:gz(t[3]),a:yz(t[4]),format:i?"name":"hex8"};if(t=Mz.hex6.exec(e))return{r:gz(t[1]),g:gz(t[2]),b:gz(t[3]),format:i?"name":"hex"};if(t=Mz.hex4.exec(e))return{r:gz(t[1]+""+t[1]),g:gz(t[2]+""+t[2]),b:gz(t[3]+""+t[3]),a:yz(t[4]+""+t[4]),format:i?"name":"hex8"};if(t=Mz.hex3.exec(e))return{r:gz(t[1]+""+t[1]),g:gz(t[2]+""+t[2]),b:gz(t[3]+""+t[3]),format:i?"name":"hex"};return!1}(e));"object"==jk(e)&&(Ez(e.r)&&Ez(e.g)&&Ez(e.b)?(t=function(e,t,i){return{r:255*fz(e,255),g:255*fz(t,255),b:255*fz(i,255)}}(e.r,e.g,e.b),a=!0,o="%"===String(e.r).substr(-1)?"prgb":"rgb"):Ez(e.h)&&Ez(e.s)&&Ez(e.v)?(n=vz(e.s),r=vz(e.v),t=function(e,t,i){e=6*fz(e,360),t=fz(t,100),i=fz(i,100);var n=Math.floor(e),r=e-n,s=i*(1-t),a=i*(1-r*t),o=i*(1-(1-r)*t),l=n%6,c=[i,a,s,s,o,i][l],u=[o,i,i,a,s,s][l],h=[s,s,o,i,i,a][l];return{r:255*c,g:255*u,b:255*h}}(e.h,n,r),a=!0,o="hsv"):Ez(e.h)&&Ez(e.s)&&Ez(e.l)&&(n=vz(e.s),s=vz(e.l),t=function(e,t,i){var n,r,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=fz(e,360),t=fz(t,100),i=fz(i,100),0===t)n=r=s=i;else{var o=i<.5?i*(1+t):i+t-i*t,l=2*i-o;n=a(l,o,e+1/3),r=a(l,o,e),s=a(l,o,e-1/3)}return{r:255*n,g:255*r,b:255*s}}(e.h,n,s),a=!0,o="hsl"),e.hasOwnProperty("a")&&(i=e.a));return i=pz(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 Yk(e,t,i){e=fz(e,255),t=fz(t,255),i=fz(i,255);var n,r,s=Math.max(e,t,i),a=Math.min(e,t,i),o=(s+a)/2;if(s==a)n=r=0;else{var l=s-a;switch(r=o>.5?l/(2-s-a):l/(s+a),s){case e:n=(t-i)/l+(t<i?6:0);break;case t:n=(i-e)/l+2;break;case i:n=(e-t)/l+4}n/=6}return{h:n,s:r,l:o}}function Kk(e,t,i){e=fz(e,255),t=fz(t,255),i=fz(i,255);var n,r,s=Math.max(e,t,i),a=Math.min(e,t,i),o=s,l=s-a;if(r=0===s?0:l/s,s==a)n=0;else{switch(s){case e:n=(t-i)/l+(t<i?6:0);break;case t:n=(i-e)/l+2;break;case i:n=(e-t)/l+4}n/=6}return{h:n,s:r,v:o}}function Zk(e,t,i,n){var r=[_z(Math.round(e).toString(16)),_z(Math.round(t).toString(16)),_z(Math.round(i).toString(16))];return n&&r[0].charAt(0)==r[0].charAt(1)&&r[1].charAt(0)==r[1].charAt(1)&&r[2].charAt(0)==r[2].charAt(1)?r[0].charAt(0)+r[1].charAt(0)+r[2].charAt(0):r.join("")}function Qk(e,t,i,n){return[_z(bz(n)),_z(Math.round(e).toString(16)),_z(Math.round(t).toString(16)),_z(Math.round(i).toString(16))].join("")}function Jk(e,t){t=0===t?0:t||10;var i=qk(e).toHsl();return i.s-=t/100,i.s=mz(i.s),qk(i)}function ez(e,t){t=0===t?0:t||10;var i=qk(e).toHsl();return i.s+=t/100,i.s=mz(i.s),qk(i)}function tz(e){return qk(e).desaturate(100)}function iz(e,t){t=0===t?0:t||10;var i=qk(e).toHsl();return i.l+=t/100,i.l=mz(i.l),qk(i)}function nz(e,t){t=0===t?0:t||10;var i=qk(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))),qk(i)}function rz(e,t){t=0===t?0:t||10;var i=qk(e).toHsl();return i.l-=t/100,i.l=mz(i.l),qk(i)}function sz(e,t){var i=qk(e).toHsl(),n=(i.h+t)%360;return i.h=n<0?360+n:n,qk(i)}function az(e){var t=qk(e).toHsl();return t.h=(t.h+180)%360,qk(t)}function oz(e,t){if(isNaN(t)||t<=0)throw new Error("Argument to polyad must be a positive number");for(var i=qk(e).toHsl(),n=[qk(e)],r=360/t,s=1;s<t;s++)n.push(qk({h:(i.h+s*r)%360,s:i.s,l:i.l}));return n}function lz(e){var t=qk(e).toHsl(),i=t.h;return[qk(e),qk({h:(i+72)%360,s:t.s,l:t.l}),qk({h:(i+216)%360,s:t.s,l:t.l})]}function cz(e,t,i){t=t||6,i=i||30;var n=qk(e).toHsl(),r=360/i,s=[qk(e)];for(n.h=(n.h-(r*t>>1)+720)%360;--t;)n.h=(n.h+r)%360,s.push(qk(n));return s}function uz(e,t){t=t||6;for(var i=qk(e).toHsv(),n=i.h,r=i.s,s=i.v,a=[],o=1/t;t--;)a.push(qk({h:n,s:r,v:s})),s=(s+o)%1;return a}qk.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,n=this.toRgb();return e=n.r/255,t=n.g/255,i=n.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=pz(e),this._roundA=Math.round(100*this._a)/100,this},toHsv:function(){var e=Kk(this._r,this._g,this._b);return{h:360*e.h,s:e.s,v:e.v,a:this._a}},toHsvString:function(){var e=Kk(this._r,this._g,this._b),t=Math.round(360*e.h),i=Math.round(100*e.s),n=Math.round(100*e.v);return 1==this._a?"hsv("+t+", "+i+"%, "+n+"%)":"hsva("+t+", "+i+"%, "+n+"%, "+this._roundA+")"},toHsl:function(){var e=Yk(this._r,this._g,this._b);return{h:360*e.h,s:e.s,l:e.l,a:this._a}},toHslString:function(){var e=Yk(this._r,this._g,this._b),t=Math.round(360*e.h),i=Math.round(100*e.s),n=Math.round(100*e.l);return 1==this._a?"hsl("+t+", "+i+"%, "+n+"%)":"hsla("+t+", "+i+"%, "+n+"%, "+this._roundA+")"},toHex:function(e){return Zk(this._r,this._g,this._b,e)},toHexString:function(e){return"#"+this.toHex(e)},toHex8:function(e){return function(e,t,i,n,r){var s=[_z(Math.round(e).toString(16)),_z(Math.round(t).toString(16)),_z(Math.round(i).toString(16)),_z(bz(n))];if(r&&s[0].charAt(0)==s[0].charAt(1)&&s[1].charAt(0)==s[1].charAt(1)&&s[2].charAt(0)==s[2].charAt(1)&&s[3].charAt(0)==s[3].charAt(1))return s[0].charAt(0)+s[1].charAt(0)+s[2].charAt(0)+s[3].charAt(0);return s.join("")}(this._r,this._g,this._b,this._a,e)},toHex8String:function(e){return"#"+this.toHex8(e)},toRgb:function(){return{r:Math.round(this._r),g:Math.round(this._g),b:Math.round(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+Math.round(this._r)+", "+Math.round(this._g)+", "+Math.round(this._b)+")":"rgba("+Math.round(this._r)+", "+Math.round(this._g)+", "+Math.round(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:Math.round(100*fz(this._r,255))+"%",g:Math.round(100*fz(this._g,255))+"%",b:Math.round(100*fz(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+Math.round(100*fz(this._r,255))+"%, "+Math.round(100*fz(this._g,255))+"%, "+Math.round(100*fz(this._b,255))+"%)":"rgba("+Math.round(100*fz(this._r,255))+"%, "+Math.round(100*fz(this._g,255))+"%, "+Math.round(100*fz(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":!(this._a<1)&&(dz[Zk(this._r,this._g,this._b,!0)]||!1)},toFilter:function(e){var t="#"+Qk(this._r,this._g,this._b,this._a),i=t,n=this._gradientType?"GradientType = 1, ":"";if(e){var r=qk(e);i="#"+Qk(r._r,r._g,r._b,r._a)}return"progid:DXImageTransform.Microsoft.gradient("+n+"startColorstr="+t+",endColorstr="+i+")"},toString:function(e){var t=!!e;e=e||this._format;var i=!1,n=this._a<1&&this._a>=0;return t||!n||"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 qk(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(iz,arguments)},brighten:function(){return this._applyModification(nz,arguments)},darken:function(){return this._applyModification(rz,arguments)},desaturate:function(){return this._applyModification(Jk,arguments)},saturate:function(){return this._applyModification(ez,arguments)},greyscale:function(){return this._applyModification(tz,arguments)},spin:function(){return this._applyModification(sz,arguments)},_applyCombination:function(e,t){return e.apply(null,[this].concat([].slice.call(t)))},analogous:function(){return this._applyCombination(cz,arguments)},complement:function(){return this._applyCombination(az,arguments)},monochromatic:function(){return this._applyCombination(uz,arguments)},splitcomplement:function(){return this._applyCombination(lz,arguments)},triad:function(){return this._applyCombination(oz,[3])},tetrad:function(){return this._applyCombination(oz,[4])}},qk.fromRatio=function(e,t){if("object"==jk(e)){var i={};for(var n in e)e.hasOwnProperty(n)&&(i[n]="a"===n?e[n]:vz(e[n]));e=i}return qk(e,t)},qk.equals=function(e,t){return!(!e||!t)&&qk(e).toRgbString()==qk(t).toRgbString()},qk.random=function(){return qk.fromRatio({r:Math.random(),g:Math.random(),b:Math.random()})},qk.mix=function(e,t,i){i=0===i?0:i||50;var n=qk(e).toRgb(),r=qk(t).toRgb(),s=i/100;return qk({r:(r.r-n.r)*s+n.r,g:(r.g-n.g)*s+n.g,b:(r.b-n.b)*s+n.b,a:(r.a-n.a)*s+n.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
|
-
qk.readability=function(e,t){var i=qk(e),n=qk(t);return(Math.max(i.getLuminance(),n.getLuminance())+.05)/(Math.min(i.getLuminance(),n.getLuminance())+.05)},qk.isReadable=function(e,t,i){var n,r,s=qk.readability(e,t);switch(r=!1,(n=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+n.size){case"AAsmall":case"AAAlarge":r=s>=4.5;break;case"AAlarge":r=s>=3;break;case"AAAsmall":r=s>=7}return r},qk.mostReadable=function(e,t,i){var n,r,s,a,o=null,l=0;r=(i=i||{}).includeFallbackColors,s=i.level,a=i.size;for(var c=0;c<t.length;c++)(n=qk.readability(e,t[c]))>l&&(l=n,o=qk(t[c]));return qk.isReadable(e,o,{level:s,size:a})||!r?o:(i.includeFallbackColors=!1,qk.mostReadable(e,["#fff","#000"],i))};var hz=qk.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"},dz=qk.hexNames=function(e){var t={};for(var i in e)e.hasOwnProperty(i)&&(t[e[i]]=i);return t}(hz);function pz(e){return e=parseFloat(e),(isNaN(e)||e<0||e>1)&&(e=1),e}function fz(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 mz(e){return Math.min(1,Math.max(0,e))}function gz(e){return parseInt(e,16)}function _z(e){return 1==e.length?"0"+e:""+e}function vz(e){return e<=1&&(e=100*e+"%"),e}function bz(e){return Math.round(255*parseFloat(e)).toString(16)}function yz(e){return gz(e)/255}var xz,Sz,Tz,Mz=(Sz="[\\s|\\(]+("+(xz="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+xz+")[,|\\s]+("+xz+")\\s*\\)?",Tz="[\\s|\\(]+("+xz+")[,|\\s]+("+xz+")[,|\\s]+("+xz+")[,|\\s]+("+xz+")\\s*\\)?",{CSS_UNIT:new RegExp(xz),rgb:new RegExp("rgb"+Sz),rgba:new RegExp("rgba"+Tz),hsl:new RegExp("hsl"+Sz),hsla:new RegExp("hsla"+Tz),hsv:new RegExp("hsv"+Sz),hsva:new RegExp("hsva"+Tz),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 Ez(e){return!!Mz.CSS_UNIT.exec(e)}const wz=e=>{e instanceof Array?e.forEach(wz):(e.map&&e.map.dispose(),e.dispose())},Az=e=>{e.geometry&&e.geometry.dispose(),e.material&&wz(e.material),e.texture&&e.texture.dispose(),e.children&&e.children.forEach(Az)};class Rz extends Wk{constructor(e,{dataBindAttr:t="__data",objBindAttr:i="__threeObj",removeDelay:n=0}={}){super(),this.scene=e,this.#e=t,this.#t=i,this.#i=n,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 n=super.getData(t);e(t,i);const r=()=>{this.scene.remove(t),Az(t),delete n[this.#t]};this.#i?setTimeout(r,this.#i):r()}),this}scene;#e;#t;#i}const Cz=e=>isNaN(e)?parseInt(qk(e).toHex(),16):e,Nz=e=>e&&isNaN(e)?TB(e).opacity:1,Pz=32,Lz=64,Dz=.92,Iz=.8;let Fz;const Uz=new Map;function Oz(e){let t=Uz.get(e);return t||(t={color:new Kn(Cz(e)),opacity:Nz(e)},Uz.set(e,t)),t}class Bz{constructor(e,t,i){const n=new Map;if(this.labels=new WeakMap,this.materials=new Map,e.forEach(e=>{const r=t(e),s=i(e);if(!r||!s)return;const a=Array.from(String(r)),o=a.length>Pz?`${a.slice(0,29).join("")}...`:a.join("");let l=n.get(o);void 0===l&&(l=n.size,n.set(o,l)),this.labels.set(e,{id:l,length:Array.from(o).length,text:o,color:s})}),this.labelCount=n.size,!this.labelCount)return;this.glyphTexture=function(){if(Fz)return Fz;const e=document.createElement("canvas");e.width=1024,e.height=1024;const t=e.getContext("2d");if(!t)throw new Error("Unable to create canvas context for label glyphs");t.font="bold 64px monospace",t.textAlign="center",t.textBaseline="middle";for(let e=0;e<256;e++){const i=String.fromCharCode(e);if(e<32||127===e)continue;const n=e%16*Lz+32,r=Math.floor(e/16)*Lz+32;t.fillStyle="#fff",t.fillText(i,n,r)}return Fz=new aa(e),Fz.magFilter=Oe,Fz.minFilter=Oe,Fz.colorSpace=Xt,Fz}(),this.labelsPerRow=128;const r=this.labelsPerRow*Pz,s=Math.ceil(n.size/this.labelsPerRow),a=new Uint8Array(r*s*4);n.forEach((e,t)=>{Array.from(t).forEach((t,i)=>{const n=t.codePointAt(0),s=e%this.labelsPerRow*Pz+i,o=Math.floor(e/this.labelsPerRow),l=n>=32&&n<=255&&(n<127||n>=160);a[4*(o*r+s)]=l?n:63})}),this.labelTexture=new Rs(a,r,s,tt,ze),this.labelTexture.magFilter=Ie,this.labelTexture.minFilter=Ie,this.labelTexture.generateMipmaps=!1,this.labelTexture.needsUpdate=!0}isEmpty(){return 0===this.labelCount}tagGeometry(e,t,{instanced:i=!1,backgroundColorAccessor:n,recomputeLabels:r=!0}={}){const s=e.getAttribute("position").count,a=i?t.length:s,o=(e,t)=>i?new Cs(e,t):new kr(e,t);if(n){const r=new Float32Array(3*a),s=new Float32Array(a);t.forEach((e,t)=>{const{color:o,opacity:l}=Oz(n(e)),c=i?t+1:a;for(let e=i?t:0;e<c;e++)o.toArray(r,3*e),s[e]=l}),e.setAttribute("backgroundColor",o(r,3)),e.setAttribute("opacity",o(s,1))}if(r){if(this.isEmpty())return;const n=new Float32Array(a),r=new Float32Array(a),s=new Float32Array(4*a),l=new Float32Array(a);t.forEach((e,t)=>{const o=this.labels.get(e);if(!o)return;const{color:c,opacity:u}=Oz(o.color),h=o?o.id:-1,d=o?o.length:0,p=i?t+1:a;for(let e=i?t:0;e<p;e++)n[e]=h,r[e]=d,s[4*e]=c.r,s[4*e+1]=c.g,s[4*e+2]=c.b,s[4*e+3]=u,l[e]=2}),e.setAttribute("labelId",o(n,1)),e.setAttribute("labelLength",o(r,1)),e.setAttribute("labelColor",o(s,4)),e.getAttribute("aspectRatio")||(console.warn("Geometry requires aspectRatio attribute. Setting 2.0 throughout the faces."),e.setAttribute("aspectRatio",o(l,1)))}}getMaterial(e=!1){let t=this.materials.get(e);return t||(t=new Ca({transparent:e}),this.materials.set(e,t),t.onBeforeCompile=e=>{e.vertexShader=e.vertexShader.replace("#include <common>","#include <common>\n attribute vec3 backgroundColor;\n attribute float opacity;\n varying vec3 vBackgroundColor;\n varying float vOpacity;\n "+(this.isEmpty()?"":"attribute float aspectRatio;\n attribute vec4 labelColor;\n attribute float labelId;\n attribute float labelLength;\n varying float vAspectRatio;\n varying vec4 vLabelColor;\n varying float vLabelId;\n varying float vLabelLength;\n varying vec2 vLabelUv;")).replace("#include <begin_vertex>","#include <begin_vertex>\n vBackgroundColor = backgroundColor;\n vOpacity = opacity;\n "+(this.isEmpty()?"":"vAspectRatio = aspectRatio;\n vLabelColor = labelColor;\n vLabelId = labelId;\n vLabelLength = labelLength;\n vLabelUv = uv;")),e.fragmentShader=e.fragmentShader.replace("#include <common>","#include <common>\n varying vec3 vBackgroundColor;\n varying float vOpacity;\n "+(this.isEmpty()?"":"uniform sampler2D labelGlyphTexture;\n uniform sampler2D labelDataTexture;\n uniform vec2 labelDataTextureSize;\n uniform float labelLabelsPerRow;\n varying float vAspectRatio;\n varying vec4 vLabelColor;\n varying float vLabelId;\n varying float vLabelLength;\n varying vec2 vLabelUv;")).replace("#include <map_fragment>","#include <map_fragment>\n diffuseColor.rgb *= vBackgroundColor;\n diffuseColor.a *= vOpacity;"),this.isEmpty()||(e.uniforms.labelGlyphTexture={value:this.glyphTexture},e.uniforms.labelDataTexture={value:this.labelTexture},e.uniforms.labelDataTextureSize={value:new Vi(this.labelTexture.image.width,this.labelTexture.image.height)},e.uniforms.labelLabelsPerRow={value:this.labelsPerRow},e.fragmentShader=e.fragmentShader.replace("#include <map_fragment>\n diffuseColor.rgb *= vBackgroundColor;\n diffuseColor.a *= vOpacity;",`#include <map_fragment>\n diffuseColor.rgb *= vBackgroundColor;\n diffuseColor.a *= vOpacity;\n if (vLabelId >= 0.0 && vLabelUv.x >= 0.0 && vLabelUv.x <= 1.0) {\n float aspect = max(vAspectRatio, 0.001);\n float visibleLength = vLabelLength;\n float textUnits = 1.0 + max(visibleLength - 1.0, 0.0) * ${Iz.toFixed(2)};\n float maxFontSize = ${.8.toFixed(2)};\n float fontSize = min(maxFontSize, aspect * ${Dz.toFixed(2)} / textUnits);\n bool isTruncated = fontSize < ${.05.toFixed(2)};\n if (isTruncated) visibleLength = min(visibleLength, max(3.0, floor((aspect * ${Dz.toFixed(2)} / ${.05.toFixed(2)} - 1.0) / ${Iz.toFixed(2)}) + 1.0));\n textUnits = 1.0 + max(visibleLength - 1.0, 0.0) * ${Iz.toFixed(2)};\n fontSize = min(maxFontSize, aspect * ${Dz.toFixed(2)} / textUnits);\n float characterSize = fontSize / aspect;\n float characterAdvance = characterSize * ${Iz.toFixed(2)};\n float textWidth = characterSize + characterAdvance * max(visibleLength - 1.0, 0.0);\n float textStart = (1.0 - textWidth) * 0.5;\n float textPosition = vLabelUv.x - textStart;\n if (textPosition >= 0.0 && textPosition < textWidth) {\n float glyphVerticalPosition = (vLabelUv.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 charIndex = floor(charPosition);\n float glyphHorizontalPosition = (textPosition - charIndex * characterAdvance) / max(characterSize, 0.001);\n float labelRow = floor(vLabelId / labelLabelsPerRow);\n float labelColumn = mod(vLabelId, 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 previousCharIndex = charIndex - 1.0;\n float previousGlyphPosition = (textPosition - previousCharIndex * characterAdvance) / max(characterSize, 0.001);\n if (charIndex > 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 * vLabelColor.a;\n diffuseColor.rgb = mix(diffuseColor.rgb, vLabelColor.rgb, glyphAlpha);\n }\n }\n }`))},t.customProgramCacheKey=()=>`three-label-glyph-atlas-${this.isEmpty()?"empty":"labels"}-geometry-color-${e}`,t)}dispose(){this.labelTexture?.dispose(),this.materials.forEach(e=>e.dispose())}}const{orientations:kz,transitions:zz}=(()=>{const e=[[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]],t=[[0,1,2,3,4,5,6,7]],i=[],n=new Map([[t[0].join(""),0]]);for(let r=0;r<t.length;r++){const s=t[r],a=[];for(const i of e){const e=i.map(e=>s[e]),r=e.join("");let o=n.get(r);void 0===o&&(o=t.length,t.push(e),n.set(r,o)),a.push(o)}i.push(a)}return{orientations:t,transitions:i}})();function Gz({useInstancing:e=!0,order:t,data:i,paddingAccessor:n,paddingAbsoluteAccessor:r,simplifyCurves:s}){const a=new Map,o=new Map,l=new Map,c=C(e);i.forEach(e=>{const i=n(e),u=r(e),h=c(e),d=h&&function(e,t,i,n,r,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),c=a?i:Math.round(i);const u=a?8n:8,h=a?0n:0;if(s)for(;o>0&&l%u===h&&c%u===h;)l/=u,c/=u,o--;const d=1/2**(o-1),p=(d-Math.min(r,.5*d))*(1-Math.min(1,n));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+(c>0n?c:0n),m>e&&(m=e),f>=m||m-f>4n)return null}else{const e=8**o;if(!Number.isSafeInteger(l)||!Number.isSafeInteger(c)||!Number.isFinite(e))return null;if(f=Math.max(0,l),m=Math.min(e,f+Math.max(0,c)),f>=m||m-f>4)return null}const g=[];for(let e=f;e<m;e=a?e+1n:e+1)g.push(Hz(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:_}}(t,e.start,e.length,i,u,s);if(!h||!d)return void o.set(e,Vz(t,e,i,u,s));const{points:p,width:f,scale:m}=d,g=function(e){const t=[];let i=e[0];for(let n=1;n<e.length;n++){const r=e[n];for(const e of["x","y","z"]){const n=r[e]-i[e];if(n){t.push("x"===e?n>0?"R":"L":"y"===e?n>0?"U":"D":n>0?"B":"F");break}}i=r}return t.join("")}(p),_=`${g}|${f/m}`;let v=a.get(_);v||(v=Vz(t,e,i,u,s),a.set(_,v));let b=l.get(_);b||(b={geometry:v,origin:p[0],scale:m,instances:[]},l.set(_,b)),b.instances.push({data:e,position:p[0],scale:m})});const u=new Map(Array.from(l.values()).map(e=>[e.instances.map(e=>e.data),e]));return u.forEach(e=>{const t=e.geometry;e.geometry=function(e,t,i){const n=new Zr;Object.entries(e.attributes).forEach(([e,t])=>{n.setAttribute(e,t.clone())}),e.index&&n.setIndex(e.index.clone());e.groups.forEach(e=>n.addGroup(e.start,e.count,e.materialIndex)),n.setDrawRange(e.drawRange.start,e.drawRange.count);const r=n.getAttribute("position");for(let e=0;e<r.count;e++)r.setXYZ(e,(r.getX(e)-t.x)/i,(r.getY(e)-t.y)/i,(r.getZ(e)-t.z)/i);r.needsUpdate=!0,n.computeBoundingBox(),n.computeBoundingSphere(),e.parameters&&(n.parameters={...e.parameters,points:e.parameters.points?.map(e=>e.clone().sub(t).divideScalar(i))});return n}(t,e.origin,e.scale),t.dispose(),delete e.origin,delete e.scale}),{instancedGeometries:u,fallbackGeometries:o}}function Vz(e,t,i,n,r){const s=new ZO(e,t.start,t.length,{padding:i,paddingAbsolute:n,simplifyCurves:r});if(r&&4===s.parameters?.points.length){s.computeBoundingBox();const e=s.boundingBox.clone(),t=new Wi;if(e.getSize(t),t.x!==t.y||t.x!==t.z){const i=new Wi;e.getCenter(i);const n=new ua(t.x,t.y,t.z);n.translate(i.x,i.y,i.z),s.dispose(),s.index=n.index,s.attributes=n.attributes}}return function(e){const t=e.getAttribute("uv");if(!t)return;const i=e.getAttribute("position"),n=e.getIndex(),r=e.parameters?.points,s=new Float32Array(t.count),a=[];if(r?.length>1&&(4!==r.length||36!==n.count)){const e=4*(r.length-1);for(let i=0;i+3<t.count&&i/4<e;i+=4){let e=1/0,n=-1/0,r=1/0,s=-1/0;for(let a=0;a<4;a++)e=Math.min(e,t.getX(i+a)),n=Math.max(n,t.getX(i+a)),r=Math.min(r,t.getY(i+a)),s=Math.max(s,t.getY(i+a));n<=e||s===r||a.push({vertex:i,minU:e,maxU:n,minV:r,maxV:s})}}else for(let e=0;e+3<t.count;e+=4){let i=1/0,n=-1/0,r=1/0,s=-1/0;for(let a=0;a<4;a++)i=Math.min(i,t.getX(e+a)),n=Math.max(n,t.getX(e+a)),r=Math.min(r,t.getY(e+a)),s=Math.max(s,t.getY(e+a));Math.abs(n-i-.25)>.01||s<=r||a.push({vertex:e,minU:i,maxU:n,minV:r,maxV:s})}const o=new Set(a.map(({vertex:e})=>e));if(a.forEach(({vertex:e,minU:n,maxU:a,minV:o,maxV:c},u)=>{if(i&&!l(i,e)){for(let i=0;i<4;i++)t.setX(e+i,-1);return}const h=Math.floor(u/4),d=r?.[h],p=r?.[h+1],f=p?p.x-d.x:0,m=p?p.y-d.y:0,g=p?p.z-d.z:0,_=Math.hypot(f,m,g),v=i&&d&&_?((i.getX(e)-d.x)*f+(i.getY(e)-d.y)*m+(i.getZ(e)-d.z)*g)/_:_*(t.getY(e)-o)/(c-o),b=i&&d&&_?((i.getX(e+1)-d.x)*f+(i.getY(e+1)-d.y)*m+(i.getZ(e+1)-d.z)*g)/_:_*(t.getY(e+1)-o)/(c-o),y=i&&d&&_?((i.getX(e+2)-d.x)*f+(i.getY(e+2)-d.y)*m+(i.getZ(e+2)-d.z)*g)/_:_*(t.getY(e+2)-o)/(c-o),x=i&&d&&_?((i.getX(e+3)-d.x)*f+(i.getY(e+3)-d.y)*m+(i.getZ(e+3)-d.z)*g)/_:_*(t.getY(e+3)-o)/(c-o),S=Math.min(v,b,y,x),T=Math.max(v,b,y,x)-S,M=i?i.getX(e+1)-i.getX(e):0,E=i?i.getY(e+1)-i.getY(e):0,w=i?i.getZ(e+1)-i.getZ(e):0,A=Math.sqrt(M*M+E*E+w*w);if(A>0)for(let t=0;t<4;t++)s[e+t]=T/A;if(T<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,s=((0===i?v:1===i?b:2===i?y:x)-S)/T,o=t.getX(r);t.setXY(r,s,1-(o-n)/(a-n))}}),a.length){for(let e=0;e+3<t.count;e+=4)if(!o.has(e))for(let i=0;i<4;i++)t.setX(e+i,-1)}else c(e,t,s);function l(e,t){const i=Array.from({length:4},(i,n)=>(new Wi).fromBufferAttribute(e,t+n)),n=i.map((e,t)=>i[(t+1)%4].clone().sub(e)),r=1e-4*Math.max(...n.map(e=>e.length())),s=n[0].clone().add(n[2]).length()<=r&&n[1].clone().add(n[3]).length()<=r,a=Math.abs(n[0].dot(n[1]))<=n[0].length()*n[1].length()*1e-4;return s&&a}function c(e,t,i){const n=e.getAttribute("position"),r=e.getAttribute("normal");if(n&&r&&24===n.count)for(let e=0;e+3<n.count;e+=4){const s=r.getX(e),a=r.getY(e),o=r.getZ(e),l=Math.abs(a)>.9||o>.9?1:o<-.9?-1:0,c=Math.abs(a)>.9?0:s>.9?-1:s<-.9?1:0,u=Math.abs(a)>.9?0:1,h=Math.abs(a)>.9?a>0?-1:1:0;let d=1/0,p=-1/0,f=1/0,m=-1/0;for(let t=0;t<4;t++){const i=e+t,r=n.getX(i)*l+n.getZ(i)*c,s=n.getY(i)*u+n.getZ(i)*h;d=Math.min(d,r),p=Math.max(p,r),f=Math.min(f,s),m=Math.max(m,s)}const g=p-d,_=m-f,v=_>g,b=v?f:d,y=v?d:f,x=v?_:g,S=v?g:_;for(let r=0;r<4;r++){const s=e+r,a=n.getX(s)*l+n.getZ(s)*c,o=n.getY(s)*u+n.getZ(s)*h,d=v?o:a,f=v?p-a:(v?a:o)-y;t.setXY(s,(d-b)/x,f/S),i[s]=x/S}}}e.setAttribute("aspectRatio",new kr(s,1)),t.needsUpdate=!0}(s),s}function Hz(e,t){const i="bigint"==typeof e;let n=i?8n**BigInt(t-1):8**(t-1),r=0,s=0,a=0,o=1,l=0;for(let c=0;c<t;c++){const t=i?Number(e/n%8n):Math.floor(e/n)%8,c=kz[l][t],u=o/2;r+=c<4?-u:u,s+=c<2||c>5?u:-u,a+=c%4==1||c%4==2?u:-u,o=u,l=zz[l][t],n=i?n/8n:n/8}return{x:r,y:s,z:a}}const Wz=100,jz=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 ZO(e.order,t,1);return i.computeBoundingSphere(),i.boundingSphere.center.clone().multiplyScalar(Wz)},getRangeBbox:(e,t,i)=>{const n=new ZO(e.order,t,i);n.computeBoundingBox();const r=n.boundingBox.clone();return n.dispose(),r.min.multiplyScalar(Wz),r.max.multiplyScalar(Wz),r},_destructor:function(){this.prevLabelAtlas?.dispose()}},stateInit:()=>({defaultColorScale:Tk(Ek)}),init:function(e,t){(e=>{if(e&&e.children)for(;e.children.length;){const t=e.children[0];e.remove(t),Az(t)}})(e),t.scene=e,t.scene.scale.set(Wz,Wz,Wz);const i=t.instancedG=new Hn;t.scene.add(i),t.instancedDataMapper=new Rz(i,{objBindAttr:"__threeObjHilbert"});const n=new Hn;t.scene.add(n),t.fallbackDataMapper=new Rz(n,{objBindAttr:"__threeObjHilbert"}).onCreateObj(()=>new ws)},update:function(e,t){const i=C(e.padding),n=C(e.paddingAbsolute),r=C(e.color),s=C(e.label),a=C(e.labelColor),o=t=>r?.(t)||e.defaultColorScale(s(t)||""),l=e=>e.some(e=>t.hasOwnProperty(e)),c=l(["data","label","labelColor"]),u=l(["useInstancedMeshes","data","order","padding","paddingAbsolute","simplifyCurves"]),h=c?e.prevLabelAtlas=(e.prevLabelAtlas?.dispose(),new Bz(e.data,s,a)):e.prevLabelAtlas,{instancedGeometries:d,fallbackGeometries:p}=u?e.prevHilbertGeometries=Gz({useInstancing:e.useInstancedMeshes,data:e.data,order:e.order,paddingAccessor:i,paddingAbsoluteAccessor:n,simplifyCurves:e.simplifyCurves}):e.prevHilbertGeometries;e.instancedDataMapper.onCreateObj(e=>{const{geometry:t,instances:i}=d.get(e),n=new Os(t,void 0,e.length),r=n.instanceMatrix.array;return i.forEach(({scale:e,position:t},i)=>{const n=16*i;r[n]=e,r[n+5]=e,r[n+10]=e,r[n+12]=t.x,r[n+13]=t.y,r[n+14]=t.z,r[n+15]=1}),n.instanceMatrix.needsUpdate=!0,n.computeBoundingSphere(),n}).onUpdateObj((e,t)=>{h.tagGeometry(e.geometry,t,{instanced:!0,backgroundColorAccessor:o,recomputeLabels:u||c});const i=e.geometry.getAttribute("opacity").array.some(e=>e<1);e.material=h.getMaterial(i)}).digest([...d.keys()]),e.fallbackDataMapper.onUpdateObj((e,t)=>{u&&(e.geometry?.dispose(),e.geometry=p.get(t)),h.tagGeometry(e.geometry,[t],{backgroundColorAccessor:o,recomputeLabels:u||c});const i=e.geometry.getAttribute("opacity").array.some(e=>e<1);e.material=h.getMaterial(i)}).digest([...p.keys()])}});var $z=function(e,t=Object,i=!1){class n extends t{constructor(...t){super(...t),this.__kapsuleInstance=new e(...[...i?[this]:[],...t])}}const r=e();return r._destructor?.(),Object.keys(r).forEach(e=>n.prototype[e]=function(...t){const i=this.__kapsuleInstance[e](...t);return i===this.__kapsuleInstance?this:i}),n}(jz,Hn,!0);!function(e,t){void 0===t&&(t={});var i=t.insertAt;if("undefined"!=typeof document){var n=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css","top"===i&&n.firstChild?n.insertBefore(r,n.firstChild):n.appendChild(r),r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}}(".hilbert-scene-container .clickable {\n cursor: pointer;\n}");var Xz=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,n){return setTimeout(()=>{const r=e.hilbert.getRangeBbox(t,i),s={x:[r.min.x,r.max.x],y:[r.min.y,r.max.y],z:[r.min.z,r.max.z]};e.renderObjs.fitToBbox(s,n)}),this},zoomToFit:function(e,t,i){return e.renderObjs.zoomToFit(t,i),this},getPositionAtVal:(e,...t)=>e.hilbert.getPositionAtVal(...t),_animationCycle(e){e.renderObjs.tick(),e.animationFrameRequestId=requestAnimationFrame(this._animationCycle)},cameraPosition:function(e,...t){return t.length?(e.renderObjs.cameraPosition(...t),this):e.renderObjs.cameraPosition()},lights:function(e,...t){return t.length?(e.renderObjs.lights(...t),this):e.renderObjs.lights()},scene:e=>e.renderObjs.scene(),camera:e=>e.renderObjs.camera(),renderer:e=>e.renderObjs.renderer(),controls:e=>e.renderObjs.controls(),hoverOrderComparator:function(e,t){return e.renderObjs.hoverOrderComparator(t&&((e,i,n,r)=>{const[s,a]=[n,r].map(e=>qz(e?.object,e));return!s-!a||t(s,a)||n.distance-r.distance})),this},_destructor:function(e){cancelAnimationFrame(e.animationFrameRequestId),this.data([]),e.hilbert._destructor?.(),e.renderObjs._destructor?.()}},stateInit({controlType:e="trackball",rendererConfig:t}){const i=new $z;return{hilbert:i,renderObjs:LO({controlType:e,rendererConfig:t}).objects([i]).lights([new lo(13421772,Math.PI),new oo(16777215,.6*Math.PI)]),controlType:e}},init:function(e,t){e.innerHTML="",e.style.position="relative";const i=document.createElement("div");i.className="hilbert-scene-container",e.appendChild(i),t.renderObjs(i).tooltipContent((e,i)=>{const n=qz(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 r=qz(e,n);r!==t.hoverD&&(t.onHover?.(r,t.hoverD||null),t.renderObjs.renderer().domElement.classList[r&&t.onClick||!r&&t.onBackgroundClick?"add":"remove"]("clickable"),t.hoverD=r)}).onClick((e,i,n)=>{const r=qz(e,n);r?t.onClick?.(r,i):t.onBackgroundClick?.(i)}),t.renderObjs.camera().position.z=500,"fly"===t.controlType&&(t.renderObjs.controls().movementSpeed=80),this._animationCycle()}});function qz(e,t){if(!e)return null;const i=function(e){let t=e;for(;t&&!t.hasOwnProperty("__data");)t=t.parent;return t}(e),n=i?.__data||null;return t&&i.isInstancedMesh?n?.[t.instanceId]:n}return Xz});
|
|
5
|
+
qk.readability=function(e,t){var i=qk(e),n=qk(t);return(Math.max(i.getLuminance(),n.getLuminance())+.05)/(Math.min(i.getLuminance(),n.getLuminance())+.05)},qk.isReadable=function(e,t,i){var n,r,s=qk.readability(e,t);switch(r=!1,(n=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+n.size){case"AAsmall":case"AAAlarge":r=s>=4.5;break;case"AAlarge":r=s>=3;break;case"AAAsmall":r=s>=7}return r},qk.mostReadable=function(e,t,i){var n,r,s,a,o=null,l=0;r=(i=i||{}).includeFallbackColors,s=i.level,a=i.size;for(var c=0;c<t.length;c++)(n=qk.readability(e,t[c]))>l&&(l=n,o=qk(t[c]));return qk.isReadable(e,o,{level:s,size:a})||!r?o:(i.includeFallbackColors=!1,qk.mostReadable(e,["#fff","#000"],i))};var hz=qk.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"},dz=qk.hexNames=function(e){var t={};for(var i in e)e.hasOwnProperty(i)&&(t[e[i]]=i);return t}(hz);function pz(e){return e=parseFloat(e),(isNaN(e)||e<0||e>1)&&(e=1),e}function fz(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 mz(e){return Math.min(1,Math.max(0,e))}function gz(e){return parseInt(e,16)}function _z(e){return 1==e.length?"0"+e:""+e}function vz(e){return e<=1&&(e=100*e+"%"),e}function bz(e){return Math.round(255*parseFloat(e)).toString(16)}function yz(e){return gz(e)/255}var xz,Sz,Tz,Mz=(Sz="[\\s|\\(]+("+(xz="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+xz+")[,|\\s]+("+xz+")\\s*\\)?",Tz="[\\s|\\(]+("+xz+")[,|\\s]+("+xz+")[,|\\s]+("+xz+")[,|\\s]+("+xz+")\\s*\\)?",{CSS_UNIT:new RegExp(xz),rgb:new RegExp("rgb"+Sz),rgba:new RegExp("rgba"+Tz),hsl:new RegExp("hsl"+Sz),hsla:new RegExp("hsla"+Tz),hsv:new RegExp("hsv"+Sz),hsva:new RegExp("hsva"+Tz),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 Ez(e){return!!Mz.CSS_UNIT.exec(e)}const wz=e=>{e instanceof Array?e.forEach(wz):(e.map&&e.map.dispose(),e.dispose())},Az=e=>{e.geometry&&e.geometry.dispose(),e.material&&wz(e.material),e.texture&&e.texture.dispose(),e.children&&e.children.forEach(Az)};class Rz extends Wk{constructor(e,{dataBindAttr:t="__data",objBindAttr:i="__threeObj",removeDelay:n=0}={}){super(),this.scene=e,this.#e=t,this.#t=i,this.#i=n,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 n=super.getData(t);e(t,i);const r=()=>{this.scene.remove(t),Az(t),delete n[this.#t]};this.#i?setTimeout(r,this.#i):r()}),this}scene;#e;#t;#i}const Cz=e=>isNaN(e)?parseInt(qk(e).toHex(),16):e,Nz=e=>e&&isNaN(e)?TB(e).opacity:1,Pz=32,Lz=64,Dz=.92,Iz=.8;let Fz;const Uz=new Map;function Oz(e){let t=Uz.get(e);return t||(t={color:new Kn(Cz(e)),opacity:Nz(e)},Uz.set(e,t)),t}class Bz{constructor(e,t,i){const n=new Map;if(this.labels=new WeakMap,this.materials=new Map,e.forEach(e=>{const r=t(e),s=i(e);if(!r||!s)return;const a=Array.from(String(r)),o=a.length>Pz?`${a.slice(0,29).join("")}...`:a.join("");let l=n.get(o);void 0===l&&(l=n.size,n.set(o,l)),this.labels.set(e,{id:l,length:Array.from(o).length,text:o,color:s})}),this.labelCount=n.size,!this.labelCount)return;this.glyphTexture=function(){if(Fz)return Fz;const e=document.createElement("canvas");e.width=1024,e.height=1024;const t=e.getContext("2d");if(!t)throw new Error("Unable to create canvas context for label glyphs");t.font="bold 64px monospace",t.textAlign="center",t.textBaseline="middle";for(let e=0;e<256;e++){const i=String.fromCharCode(e);if(e<32||127===e)continue;const n=e%16*Lz+32,r=Math.floor(e/16)*Lz+32;t.fillStyle="#fff",t.fillText(i,n,r)}return Fz=new aa(e),Fz.magFilter=Oe,Fz.minFilter=Oe,Fz.colorSpace=Xt,Fz}(),this.labelsPerRow=128;const r=this.labelsPerRow*Pz,s=Math.ceil(n.size/this.labelsPerRow),a=new Uint8Array(r*s*4);n.forEach((e,t)=>{Array.from(t).forEach((t,i)=>{const n=t.codePointAt(0),s=e%this.labelsPerRow*Pz+i,o=Math.floor(e/this.labelsPerRow),l=n>=32&&n<=255&&(n<127||n>=160);a[4*(o*r+s)]=l?n:63})}),this.labelTexture=new Rs(a,r,s,tt,ze),this.labelTexture.magFilter=Ie,this.labelTexture.minFilter=Ie,this.labelTexture.generateMipmaps=!1,this.labelTexture.needsUpdate=!0}isEmpty(){return 0===this.labelCount}tagGeometry(e,t,{instanced:i=!1,backgroundColorAccessor:n,recomputeLabels:r=!0}={}){const s=e.getAttribute("position").count,a=i?t.length:s,o=(e,t)=>i?new Cs(e,t):new kr(e,t);if(n){const r=new Float32Array(3*a),s=new Float32Array(a);t.forEach((e,t)=>{const{color:o,opacity:l}=Oz(n(e)),c=i?t+1:a;for(let e=i?t:0;e<c;e++)o.toArray(r,3*e),s[e]=l}),e.setAttribute("backgroundColor",o(r,3)),e.setAttribute("opacity",o(s,1))}if(r){if(this.isEmpty())return;const n=new Float32Array(a),r=new Float32Array(a),s=new Float32Array(4*a),l=new Float32Array(a);t.forEach((e,t)=>{const o=this.labels.get(e);if(!o)return;const{color:c,opacity:u}=Oz(o.color),h=o?o.id:-1,d=o?o.length:0,p=i?t+1:a;for(let e=i?t:0;e<p;e++)n[e]=h,r[e]=d,s[4*e]=c.r,s[4*e+1]=c.g,s[4*e+2]=c.b,s[4*e+3]=u,l[e]=2}),e.setAttribute("labelId",o(n,1)),e.setAttribute("labelLength",o(r,1)),e.setAttribute("labelColor",o(s,4)),e.getAttribute("aspectRatio")||(console.warn("Geometry requires aspectRatio attribute. Setting 2.0 throughout the faces."),e.setAttribute("aspectRatio",o(l,1)))}}getMaterial(e=!1){let t=this.materials.get(e);return t||(t=new Ca({transparent:e}),this.materials.set(e,t),t.onBeforeCompile=e=>{e.vertexShader=e.vertexShader.replace("#include <common>","#include <common>\n attribute vec3 backgroundColor;\n attribute float opacity;\n varying vec3 vBackgroundColor;\n varying float vOpacity;\n "+(this.isEmpty()?"":"attribute float aspectRatio;\n attribute vec4 labelColor;\n attribute float labelId;\n attribute float labelLength;\n varying float vAspectRatio;\n varying vec4 vLabelColor;\n varying float vLabelId;\n varying float vLabelLength;\n varying vec2 vLabelUv;")).replace("#include <begin_vertex>","#include <begin_vertex>\n vBackgroundColor = backgroundColor;\n vOpacity = opacity;\n "+(this.isEmpty()?"":"vAspectRatio = aspectRatio;\n vLabelColor = labelColor;\n vLabelId = labelId;\n vLabelLength = labelLength;\n vLabelUv = uv;")),e.fragmentShader=e.fragmentShader.replace("#include <common>","#include <common>\n varying vec3 vBackgroundColor;\n varying float vOpacity;\n "+(this.isEmpty()?"":"uniform sampler2D labelGlyphTexture;\n uniform sampler2D labelDataTexture;\n uniform vec2 labelDataTextureSize;\n uniform float labelLabelsPerRow;\n varying float vAspectRatio;\n varying vec4 vLabelColor;\n varying float vLabelId;\n varying float vLabelLength;\n varying vec2 vLabelUv;")).replace("#include <map_fragment>","#include <map_fragment>\n diffuseColor.rgb *= vBackgroundColor;\n diffuseColor.a *= vOpacity;"),this.isEmpty()||(e.uniforms.labelGlyphTexture={value:this.glyphTexture},e.uniforms.labelDataTexture={value:this.labelTexture},e.uniforms.labelDataTextureSize={value:new Vi(this.labelTexture.image.width,this.labelTexture.image.height)},e.uniforms.labelLabelsPerRow={value:this.labelsPerRow},e.fragmentShader=e.fragmentShader.replace("#include <map_fragment>\n diffuseColor.rgb *= vBackgroundColor;\n diffuseColor.a *= vOpacity;",`#include <map_fragment>\n diffuseColor.rgb *= vBackgroundColor;\n diffuseColor.a *= vOpacity;\n if (vLabelId >= 0.0 && vLabelUv.x >= 0.0 && vLabelUv.x <= 1.0) {\n float aspect = max(vAspectRatio, 0.001);\n float visibleLength = vLabelLength;\n float textUnits = 1.0 + max(visibleLength - 1.0, 0.0) * ${Iz.toFixed(2)};\n float maxFontSize = ${.8.toFixed(2)};\n float fontSize = min(maxFontSize, aspect * ${Dz.toFixed(2)} / textUnits);\n bool isTruncated = fontSize < ${.05.toFixed(2)};\n if (isTruncated) visibleLength = min(visibleLength, max(3.0, floor((aspect * ${Dz.toFixed(2)} / ${.05.toFixed(2)} - 1.0) / ${Iz.toFixed(2)}) + 1.0));\n textUnits = 1.0 + max(visibleLength - 1.0, 0.0) * ${Iz.toFixed(2)};\n fontSize = min(maxFontSize, aspect * ${Dz.toFixed(2)} / textUnits);\n float characterSize = fontSize / aspect;\n float characterAdvance = characterSize * ${Iz.toFixed(2)};\n float textWidth = characterSize + characterAdvance * max(visibleLength - 1.0, 0.0);\n float textStart = (1.0 - textWidth) * 0.5;\n float textPosition = vLabelUv.x - textStart;\n if (textPosition >= 0.0 && textPosition < textWidth) {\n float glyphVerticalPosition = (vLabelUv.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 charIndex = floor(charPosition);\n float glyphHorizontalPosition = (textPosition - charIndex * characterAdvance) / max(characterSize, 0.001);\n float labelRow = floor(vLabelId / labelLabelsPerRow);\n float labelColumn = mod(vLabelId, 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 previousCharIndex = charIndex - 1.0;\n float previousGlyphPosition = (textPosition - previousCharIndex * characterAdvance) / max(characterSize, 0.001);\n if (charIndex > 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 * vLabelColor.a;\n diffuseColor.rgb = mix(diffuseColor.rgb, vLabelColor.rgb, glyphAlpha);\n }\n }\n }`))},t.customProgramCacheKey=()=>`three-label-glyph-atlas-${this.isEmpty()?"empty":"labels"}-geometry-color-${e}`,t)}dispose(){this.labelTexture?.dispose(),this.materials.forEach(e=>e.dispose())}}const{orientations:kz,transitions:zz}=(()=>{const e=[[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]],t=[[0,1,2,3,4,5,6,7]],i=[],n=new Map([[t[0].join(""),0]]);for(let r=0;r<t.length;r++){const s=t[r],a=[];for(const i of e){const e=i.map(e=>s[e]),r=e.join("");let o=n.get(r);void 0===o&&(o=t.length,t.push(e),n.set(r,o)),a.push(o)}i.push(a)}return{orientations:t,transitions:i}})();function Gz({useInstancing:e=!0,order:t,data:i,paddingAccessor:n,paddingAbsoluteAccessor:r,simplifyCurves:s}){const a=new Map,o=new Map,l=new Map,c=C(e);i.forEach(e=>{const i=n(e),u=r(e),h=c(e),d=h&&function(e,t,i,n,r,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),c=a?i:Math.round(i);const u=a?8n:8,h=a?0n:0;if(s)for(;o>0&&l%u===h&&c%u===h;)l/=u,c/=u,o--;const d=1/2**(o-1),p=(d-Math.min(r,.5*d))*(1-Math.min(1,n));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+(c>0n?c:0n),m>e&&(m=e),f>=m||m-f>4n)return null}else{const e=8**o;if(!Number.isSafeInteger(l)||!Number.isSafeInteger(c)||!Number.isFinite(e))return null;if(f=Math.max(0,l),m=Math.min(e,f+Math.max(0,c)),f>=m||m-f>4)return null}const g=[];for(let e=f;e<m;e=a?e+1n:e+1)g.push(Hz(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:_}}(t,e.start,e.length,i,u,s);if(!h||!d)return void o.set(e,Vz(t,e,i,u,s));const{points:p,width:f,scale:m}=d,g=function(e){const t=[];let i=e[0];for(let n=1;n<e.length;n++){const r=e[n];for(const e of["x","y","z"]){const n=r[e]-i[e];if(n){t.push("x"===e?n>0?"R":"L":"y"===e?n>0?"U":"D":n>0?"B":"F");break}}i=r}return t.join("")}(p),_=`${g}|${f/m}`;let v=a.get(_);v||(v=Vz(t,e,i,u,s),a.set(_,v));let b=l.get(_);b||(b={geometry:v,origin:p[0],scale:m,instances:[]},l.set(_,b)),b.instances.push({data:e,position:p[0],scale:m})});const u=new Map(Array.from(l.values()).map(e=>[e.instances.map(e=>e.data),e]));return u.forEach(e=>{const t=e.geometry;e.geometry=function(e,t,i){const n=new Zr;Object.entries(e.attributes).forEach(([e,t])=>{n.setAttribute(e,t.clone())}),e.index&&n.setIndex(e.index.clone());e.groups.forEach(e=>n.addGroup(e.start,e.count,e.materialIndex)),n.setDrawRange(e.drawRange.start,e.drawRange.count);const r=n.getAttribute("position");for(let e=0;e<r.count;e++)r.setXYZ(e,(r.getX(e)-t.x)/i,(r.getY(e)-t.y)/i,(r.getZ(e)-t.z)/i);r.needsUpdate=!0,n.computeBoundingBox(),n.computeBoundingSphere(),e.parameters&&(n.parameters={...e.parameters,points:e.parameters.points?.map(e=>e.clone().sub(t).divideScalar(i))});return n}(t,e.origin,e.scale),t.dispose(),delete e.origin,delete e.scale}),{instancedGeometries:u,fallbackGeometries:o}}function Vz(e,t,i,n,r){const s=new ZO(e,t.start,t.length,{padding:i,paddingAbsolute:n,simplifyCurves:r});if(r&&4===s.parameters?.points.length){s.computeBoundingBox();const e=s.boundingBox.clone(),t=new Wi;if(e.getSize(t),t.x!==t.y||t.x!==t.z){const i=new Wi;e.getCenter(i);const n=new ua(t.x,t.y,t.z);n.translate(i.x,i.y,i.z),s.dispose(),s.index=n.index,s.attributes=n.attributes}}return function(e){const t=e.getAttribute("uv");if(!t)return;const i=e.getAttribute("position"),n=e.getIndex(),r=e.parameters?.points,s=new Float32Array(t.count),a=[];if(r?.length>1&&(4!==r.length||36!==n.count)){const e=4*(r.length-1);for(let i=0;i+3<t.count&&i/4<e;i+=4){let e=1/0,n=-1/0,r=1/0,s=-1/0;for(let a=0;a<4;a++)e=Math.min(e,t.getX(i+a)),n=Math.max(n,t.getX(i+a)),r=Math.min(r,t.getY(i+a)),s=Math.max(s,t.getY(i+a));n<=e||s===r||a.push({vertex:i,minU:e,maxU:n,minV:r,maxV:s})}}else for(let e=0;e+3<t.count;e+=4){let i=1/0,n=-1/0,r=1/0,s=-1/0;for(let a=0;a<4;a++)i=Math.min(i,t.getX(e+a)),n=Math.max(n,t.getX(e+a)),r=Math.min(r,t.getY(e+a)),s=Math.max(s,t.getY(e+a));Math.abs(n-i-.25)>.01||s<=r||a.push({vertex:e,minU:i,maxU:n,minV:r,maxV:s})}const o=new Set(a.map(({vertex:e})=>e));if(a.forEach(({vertex:e,minU:n,maxU:a,minV:o,maxV:c},u)=>{if(i&&!l(i,e)){for(let i=0;i<4;i++)t.setX(e+i,-1);return}const h=Math.floor(u/4),d=r?.[h],p=r?.[h+1],f=p?p.x-d.x:0,m=p?p.y-d.y:0,g=p?p.z-d.z:0,_=Math.hypot(f,m,g),v=i&&d&&_?((i.getX(e)-d.x)*f+(i.getY(e)-d.y)*m+(i.getZ(e)-d.z)*g)/_:_*(t.getY(e)-o)/(c-o),b=i&&d&&_?((i.getX(e+1)-d.x)*f+(i.getY(e+1)-d.y)*m+(i.getZ(e+1)-d.z)*g)/_:_*(t.getY(e+1)-o)/(c-o),y=i&&d&&_?((i.getX(e+2)-d.x)*f+(i.getY(e+2)-d.y)*m+(i.getZ(e+2)-d.z)*g)/_:_*(t.getY(e+2)-o)/(c-o),x=i&&d&&_?((i.getX(e+3)-d.x)*f+(i.getY(e+3)-d.y)*m+(i.getZ(e+3)-d.z)*g)/_:_*(t.getY(e+3)-o)/(c-o),S=Math.min(v,b,y,x),T=Math.max(v,b,y,x)-S,M=i?i.getX(e+1)-i.getX(e):0,E=i?i.getY(e+1)-i.getY(e):0,w=i?i.getZ(e+1)-i.getZ(e):0,A=Math.sqrt(M*M+E*E+w*w);if(A>0)for(let t=0;t<4;t++)s[e+t]=T/A;if(T<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,s=((0===i?v:1===i?b:2===i?y:x)-S)/T,o=t.getX(r);t.setXY(r,s,1-(o-n)/(a-n))}}),a.length){for(let e=0;e+3<t.count;e+=4)if(!o.has(e))for(let i=0;i<4;i++)t.setX(e+i,-1)}else c(e,t,s);function l(e,t){const i=Array.from({length:4},(i,n)=>(new Wi).fromBufferAttribute(e,t+n)),n=i.map((e,t)=>i[(t+1)%4].clone().sub(e)),r=1e-4*Math.max(...n.map(e=>e.length())),s=n[0].clone().add(n[2]).length()<=r&&n[1].clone().add(n[3]).length()<=r,a=Math.abs(n[0].dot(n[1]))<=n[0].length()*n[1].length()*1e-4;return s&&a}function c(e,t,i){const n=e.getAttribute("position"),r=e.getAttribute("normal");if(n&&r&&24===n.count)for(let e=0;e+3<n.count;e+=4){const s=r.getX(e),a=r.getY(e),o=r.getZ(e),l=Math.abs(a)>.9||o>.9?1:o<-.9?-1:0,c=Math.abs(a)>.9?0:s>.9?-1:s<-.9?1:0,u=Math.abs(a)>.9?0:1,h=Math.abs(a)>.9?a>0?-1:1:0;let d=1/0,p=-1/0,f=1/0,m=-1/0;for(let t=0;t<4;t++){const i=e+t,r=n.getX(i)*l+n.getZ(i)*c,s=n.getY(i)*u+n.getZ(i)*h;d=Math.min(d,r),p=Math.max(p,r),f=Math.min(f,s),m=Math.max(m,s)}const g=p-d,_=m-f,v=_>g,b=v?f:d,y=v?d:f,x=v?_:g,S=v?g:_;for(let r=0;r<4;r++){const s=e+r,a=n.getX(s)*l+n.getZ(s)*c,o=n.getY(s)*u+n.getZ(s)*h,d=v?o:a,f=v?p-a:(v?a:o)-y;t.setXY(s,(d-b)/x,f/S),i[s]=x/S}}}e.setAttribute("aspectRatio",new kr(s,1)),t.needsUpdate=!0}(s),s}function Hz(e,t){const i="bigint"==typeof e;let n=i?8n**BigInt(t-1):8**(t-1),r=0,s=0,a=0,o=1,l=0;for(let c=0;c<t;c++){const t=i?Number(e/n%8n):Math.floor(e/n)%8,c=kz[l][t],u=o/2;r+=c<4?-u:u,s+=c<2||c>5?u:-u,a+=c%4==1||c%4==2?u:-u,o=u,l=zz[l][t],n=i?n/8n:n/8}return{x:r,y:s,z:a}}const Wz=100,jz=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 ZO(e.order,t,1);return i.computeBoundingSphere(),i.boundingSphere.center.clone().multiplyScalar(Wz)},getRangeBbox:(e,t,i)=>{const n=new ZO(e.order,t,i);n.computeBoundingBox();const r=n.boundingBox.clone();return n.dispose(),r.min.multiplyScalar(Wz),r.max.multiplyScalar(Wz),r},_destructor:function(){this.prevLabelAtlas?.dispose()}},stateInit:()=>({defaultColorScale:Tk(Ek)}),init:function(e,t){(e=>{if(e&&e.children)for(;e.children.length;){const t=e.children[0];e.remove(t),Az(t)}})(e),t.scene=e,t.scene.scale.set(Wz,Wz,Wz);const i=t.instancedG=new Hn;t.scene.add(i),t.instancedDataMapper=new Rz(i,{objBindAttr:"__threeObjHilbert"});const n=new Hn;t.scene.add(n),t.fallbackDataMapper=new Rz(n,{objBindAttr:"__threeObjHilbert"}).onCreateObj(()=>new ws)},update:function(e,t){const i=C(e.padding),n=C(e.paddingAbsolute),r=C(e.color),s=C(e.label),a=C(e.labelColor),o=t=>r?.(t)||e.defaultColorScale(s(t)||""),l=e=>e.some(e=>t.hasOwnProperty(e)),c=l(["data","label","labelColor"]),u=l(["useInstancedMeshes","data","order","padding","paddingAbsolute","simplifyCurves"]),h=c?e.prevLabelAtlas=(e.prevLabelAtlas?.dispose(),new Bz(e.data,s,a)):e.prevLabelAtlas,{instancedGeometries:d,fallbackGeometries:p}=u?e.prevHilbertGeometries=Gz({useInstancing:e.useInstancedMeshes,data:e.data,order:e.order,paddingAccessor:i,paddingAbsoluteAccessor:n,simplifyCurves:e.simplifyCurves}):e.prevHilbertGeometries;e.instancedDataMapper.onCreateObj(e=>{const{geometry:t,instances:i}=d.get(e),n=new Os(t,void 0,e.length),r=n.instanceMatrix.array;return i.forEach(({scale:e,position:t},i)=>{const n=16*i;r[n]=e,r[n+5]=e,r[n+10]=e,r[n+12]=t.x,r[n+13]=t.y,r[n+14]=t.z,r[n+15]=1}),n.instanceMatrix.needsUpdate=!0,n.computeBoundingSphere(),e.forEach((e,t)=>{e.__threeObjHilbert=n,e.__threeObjInstanceId=t}),n}).onUpdateObj((e,t)=>{h.tagGeometry(e.geometry,t,{instanced:!0,backgroundColorAccessor:o,recomputeLabels:u||c});const i=e.geometry.getAttribute("opacity").array.some(e=>e<1);e.material=h.getMaterial(i)}).digest([...d.keys()]),e.fallbackDataMapper.onUpdateObj((e,t)=>{u&&(e.geometry?.dispose(),e.geometry=p.get(t),e.renderOrder=Number(t.length)),h.tagGeometry(e.geometry,[t],{backgroundColorAccessor:o,recomputeLabels:u||c});const i=e.geometry.getAttribute("opacity").array.some(e=>e<1);e.material=h.getMaterial(i)}).digest([...p.keys()])}});var $z=function(e,t=Object,i=!1){class n extends t{constructor(...t){super(...t),this.__kapsuleInstance=new e(...[...i?[this]:[],...t])}}const r=e();return r._destructor?.(),Object.keys(r).forEach(e=>n.prototype[e]=function(...t){const i=this.__kapsuleInstance[e](...t);return i===this.__kapsuleInstance?this:i}),n}(jz,Hn,!0);!function(e,t){void 0===t&&(t={});var i=t.insertAt;if("undefined"!=typeof document){var n=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css","top"===i&&n.firstChild?n.insertBefore(r,n.firstChild):n.appendChild(r),r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}}(".hilbert-scene-container .clickable {\n cursor: pointer;\n}");var Xz=R({props:{width:{default:window.innerWidth,onChange(e,t){t.renderObjs.width(e)}},height:{default:window.innerHeight,onChange(e,t){t.renderObjs.height(e)}},hilbertOrder:{default:3,onChange(e,t){t.hilbert.order(e)}},data:{default:[],onChange(e,t){t.hilbert.data(e),t.renderObjs.pointerRaycasterThrottleMs(e.length>1e4?200:50)}},padding:{default:0,onChange(e,t){t.hilbert.padding(e)}},paddingAbsolute:{default:0,onChange(e,t){t.hilbert.paddingAbsolute(e)}},color:{onChange(e,t){t.hilbert.color(e)}},label:{default:"name",onChange(e,t){t.hilbert.label(e)}},labelColor:{default:()=>"lavender",onChange(e,t){t.hilbert.labelColor(e)}},simplifyCurves:{default:!0,onChange(e,t){t.hilbert.simplifyCurves(e)}},useInstancedMeshes:{default:!1,onChange(e,t){t.hilbert.useInstancedMeshes(e)}},valFormatter:{default:e=>e},tooltipContent:{triggerUpdate:!1},onHover:{triggerUpdate:!1},onClick:{triggerUpdate:!1},onBackgroundClick:{triggerUpdate:!1}},methods:{focusOn:function(e,t,i,n){return setTimeout(()=>{const r=e.hilbert.getRangeBbox(t,i),s={x:[r.min.x,r.max.x],y:[r.min.y,r.max.y],z:[r.min.z,r.max.z]};e.renderObjs.fitToBbox(s,n)}),this},zoomToFit:function(e,t,i){return e.renderObjs.zoomToFit(t,i),this},getPositionAtVal:(e,...t)=>e.hilbert.getPositionAtVal(...t),_animationCycle(e){e.renderObjs.tick(),e.animationFrameRequestId=requestAnimationFrame(this._animationCycle)},cameraPosition:function(e,...t){return t.length?(e.renderObjs.cameraPosition(...t),this):e.renderObjs.cameraPosition()},lights:function(e,...t){return t.length?(e.renderObjs.lights(...t),this):e.renderObjs.lights()},scene:e=>e.renderObjs.scene(),camera:e=>e.renderObjs.camera(),renderer:e=>e.renderObjs.renderer(),controls:e=>e.renderObjs.controls(),hoverOrderComparator:function(e,t){return e.renderObjs.hoverOrderComparator(t&&((e,i,n,r)=>{const[s,a]=[n,r].map(e=>qz(e?.object,e));return!s-!a||t(s,a)||n.distance-r.distance})),this},_destructor:function(e){cancelAnimationFrame(e.animationFrameRequestId),this.data([]),e.hilbert._destructor?.(),e.renderObjs._destructor?.()}},stateInit({controlType:e="orbit",rendererConfig:t}){const i=new $z;return{hilbert:i,renderObjs:LO({controlType:e,rendererConfig:t}).objects([i]).lights([new lo(13421772,Math.PI),new oo(16777215,.6*Math.PI)]),controlType:e}},init:function(e,t){e.innerHTML="",e.style.position="relative";const i=document.createElement("div");i.className="hilbert-scene-container",e.appendChild(i),t.renderObjs(i).tooltipContent((e,i)=>{const n=qz(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 r=qz(e,n);r!==t.hoverD&&(t.onHover?.(r,t.hoverD||null),t.renderObjs.renderer().domElement.classList[r&&t.onClick||!r&&t.onBackgroundClick?"add":"remove"]("clickable"),t.hoverD=r)}).onClick((e,i,n)=>{const r=qz(e,n);r?t.onClick?.(r,i):t.onBackgroundClick?.(i)}),t.renderObjs.camera().near=.001,t.renderObjs.camera().position.z=500,"fly"===t.controlType&&(t.renderObjs.controls().movementSpeed=80),this._animationCycle()}});function qz(e,t){if(!e)return null;const i=function(e){let t=e;for(;t&&!t.hasOwnProperty("__data");)t=t.parent;return t}(e),n=i?.__data||null;return t&&i.isInstancedMesh?n?.[t.instanceId]:n}return Xz});
|