@tomorrowevening/hermes 0.1.27 → 0.1.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- "use strict";var tv=Object.create;var Im=Object.defineProperty;var sv=Object.getOwnPropertyDescriptor;var iv=Object.getOwnPropertyNames;var nv=Object.getPrototypeOf,rv=Object.prototype.hasOwnProperty;var av=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of iv(e))!rv.call(r,i)&&i!==t&&Im(r,i,{get:()=>e[i],enumerable:!(s=sv(e,i))||s.enumerable});return r};var ov=(r,e,t)=>(t=r!=null?tv(nv(r)):{},av(e||!r||!r.__esModule?Im(t,"default",{value:r,enumerable:!0}):t,r));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const fe=require("@tomorrowevening/theatre-core"),X=require("react"),_=require("three"),F=require("react/jsx-runtime"),Io=()=>{},lv=()=>{};function Uo(r){return r.substring(0,1).toUpperCase()+r.substring(1)}function rx(r){const e=JSON.stringify(r);return navigator.clipboard.writeText(e),e}function Tt(){return Math.round(Math.random()*1e6).toString()}function ax(r){return r.r!==void 0&&r.g!==void 0&&r.b!==void 0}function jd(r){const e=Math.round(r.r*255),t=Math.round(r.g*255),s=Math.round(r.b*255),i=l=>{const c=l.toString(16);return c.length===1?"0"+c:c},n=i(e),a=i(t),o=i(s);return"#"+n+a+o}function xh(r,e,t,s){return new(t||(t=Promise))(function(i,n){function a(c){try{l(s.next(c))}catch(u){n(u)}}function o(c){try{l(s.throw(c))}catch(u){n(u)}}function l(c){var u;c.done?i(c.value):(u=c.value,u instanceof t?u:new t(function(h){h(u)})).then(a,o)}l((s=s.apply(r,[])).next())})}const cv=["geforce 320m","geforce 8600","geforce 8600m gt","geforce 8800 gs","geforce 8800 gt","geforce 9400","geforce 9400m g","geforce 9400m","geforce 9600m gt","geforce 9600m","geforce fx go5200","geforce gt 120","geforce gt 130","geforce gt 330m","geforce gtx 285","google swiftshader","intel g41","intel g45","intel gma 4500mhd","intel gma x3100","intel hd 3000","intel q45","legacy","mali-2","mali-3","mali-4","quadro fx 1500","quadro fx 4","quadro fx 5","radeon hd 2400","radeon hd 2600","radeon hd 4670","radeon hd 4850","radeon hd 4870","radeon hd 5670","radeon hd 5750","radeon hd 6290","radeon hd 6300","radeon hd 6310","radeon hd 6320","radeon hd 6490m","radeon hd 6630m","radeon hd 6750m","radeon hd 6770m","radeon hd 6970m","sgx 543","sgx543"];function Um(r){return r=r.toLowerCase().replace(/.*angle ?\((.+)\)(?: on vulkan [0-9.]+)?$/i,"$1").replace(/\s(\d{1,2}gb|direct3d.+$)|\(r\)| \([^)]+\)$/g,"").replace(/(?:vulkan|opengl) \d+\.\d+(?:\.\d+)?(?: \((.*)\))?/,"$1")}const ox=typeof window>"u",fi=(()=>{if(ox)return;const{userAgent:r,platform:e,maxTouchPoints:t}=window.navigator,s=/(iphone|ipod|ipad)/i.test(r),i=e==="iPad"||e==="MacIntel"&&t>0&&!window.MSStream;return{isIpad:i,isMobile:/android/i.test(r)||s||i,isSafari12:/Version\/12.+Safari/.test(r),isFirefox:/Firefox/.test(r)}})();function uv(r,e,t){if(!t)return[e];const s=function(c){const u=`
1
+ "use strict";var Mi=Object.create;var Tt=Object.defineProperty;var Ai=Object.getOwnPropertyDescriptor;var Ri=Object.getOwnPropertyNames;var Di=Object.getPrototypeOf,Pi=Object.prototype.hasOwnProperty;var Ii=(i,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ri(e))!Pi.call(i,n)&&n!==t&&Tt(i,n,{get:()=>e[n],enumerable:!(s=Ai(e,n))||s.enumerable});return i};var Li=(i,e,t)=>(t=i!=null?Mi(Di(i)):{},Ii(e||!i||!i.__esModule?Tt(t,"default",{value:i,enumerable:!0}):t,i));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const P=require("@tomorrowevening/theatre-core"),b=require("react"),d=require("three"),u=require("react/jsx-runtime"),Z=require("three/src/math/MathUtils.js"),Ui=require("three/src/materials/nodes/MeshNormalNodeMaterial.js"),tt=require("three/src/renderers/webgpu/WebGPURenderer.js"),Ni=require("three/examples/jsm/helpers/RectAreaLightHelper.js"),ki=require("three/examples/jsm/controls/OrbitControls.js"),Fi=require("three/src/materials/nodes/NodeMaterial.js"),T=require("three/src/nodes/TSL.js"),Yt=require("three/src/materials/nodes/MeshBasicNodeMaterial.js"),zi=require("three/examples/jsm/controls/TransformControls.js"),Fe=()=>{},Hi=()=>{};function ze(i){return i.substring(0,1).toUpperCase()+i.substring(1)}function Zt(i){const e=JSON.stringify(i);return navigator.clipboard.writeText(e),e}function W(){return Math.round(Math.random()*1e6).toString()}function qt(i){return i.r!==void 0&&i.g!==void 0&&i.b!==void 0}function gt(i){const e=Math.round(i.r*255),t=Math.round(i.g*255),s=Math.round(i.b*255),n=c=>{const l=c.toString(16);return l.length===1?"0"+l:l},a=n(e),r=n(t),o=n(s);return"#"+a+r+o}function it(i,e,t,s){return new(t||(t=Promise))(function(n,a){function r(l){try{c(s.next(l))}catch(h){a(h)}}function o(l){try{c(s.throw(l))}catch(h){a(h)}}function c(l){var h;l.done?n(l.value):(h=l.value,h instanceof t?h:new t(function(p){p(h)})).then(r,o)}c((s=s.apply(i,[])).next())})}const ji=["geforce 320m","geforce 8600","geforce 8600m gt","geforce 8800 gs","geforce 8800 gt","geforce 9400","geforce 9400m g","geforce 9400m","geforce 9600m gt","geforce 9600m","geforce fx go5200","geforce gt 120","geforce gt 130","geforce gt 330m","geforce gtx 285","google swiftshader","intel g41","intel g45","intel gma 4500mhd","intel gma x3100","intel hd 3000","intel q45","legacy","mali-2","mali-3","mali-4","quadro fx 1500","quadro fx 4","quadro fx 5","radeon hd 2400","radeon hd 2600","radeon hd 4670","radeon hd 4850","radeon hd 4870","radeon hd 5670","radeon hd 5750","radeon hd 6290","radeon hd 6300","radeon hd 6310","radeon hd 6320","radeon hd 6490m","radeon hd 6630m","radeon hd 6750m","radeon hd 6770m","radeon hd 6970m","sgx 543","sgx543"];function Mt(i){return i=i.toLowerCase().replace(/.*angle ?\((.+)\)(?: on vulkan [0-9.]+)?$/i,"$1").replace(/\s(\d{1,2}gb|direct3d.+$)|\(r\)| \([^)]+\)$/g,"").replace(/(?:vulkan|opengl) \d+\.\d+(?:\.\d+)?(?: \((.*)\))?/,"$1")}const $t=typeof window>"u",ie=(()=>{if($t)return;const{userAgent:i,platform:e,maxTouchPoints:t}=window.navigator,s=/(iphone|ipod|ipad)/i.test(i),n=e==="iPad"||e==="MacIntel"&&t>0&&!window.MSStream;return{isIpad:n,isMobile:/android/i.test(i)||s||n,isSafari12:/Version\/12.+Safari/.test(i),isFirefox:/Firefox/.test(i)}})();function Bi(i,e,t){if(!t)return[e];const s=function(l){const h=`
2
2
  precision highp float;
3
3
  attribute vec3 aPosition;
4
4
  varying float vvv;
@@ -6,7 +6,7 @@
6
6
  vvv = 0.31622776601683794;
7
7
  gl_Position = vec4(aPosition, 1.0);
8
8
  }
9
- `,h=`
9
+ `,p=`
10
10
  precision highp float;
11
11
  varying float vvv;
12
12
  void main() {
@@ -15,452 +15,15 @@
15
15
  enc -= enc.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);
16
16
  gl_FragColor = enc;
17
17
  }
18
- `,d=c.createShader(35633),p=c.createShader(35632),f=c.createProgram();if(!(p&&d&&f))return;c.shaderSource(d,u),c.shaderSource(p,h),c.compileShader(d),c.compileShader(p),c.attachShader(f,d),c.attachShader(f,p),c.linkProgram(f),c.detachShader(f,d),c.detachShader(f,p),c.deleteShader(d),c.deleteShader(p),c.useProgram(f);const m=c.createBuffer();c.bindBuffer(34962,m),c.bufferData(34962,new Float32Array([-1,-1,0,3,-1,0,-1,3,0]),35044);const x=c.getAttribLocation(f,"aPosition");c.vertexAttribPointer(x,3,5126,!1,0,0),c.enableVertexAttribArray(x),c.clearColor(1,1,1,1),c.clear(16384),c.viewport(0,0,1,1),c.drawArrays(4,0,3);const y=new Uint8Array(4);return c.readPixels(0,0,1,1,6408,5121,y),c.deleteProgram(f),c.deleteBuffer(m),y.join("")}(r),i="801621810",n="8016218135",a="80162181161",o=fi?.isIpad?[["a7",a,12],["a8",n,15],["a8x",n,15],["a9",n,15],["a9x",n,15],["a10",n,15],["a10x",n,15],["a12",i,15],["a12x",i,15],["a12z",i,15],["a14",i,15],["a15",i,15],["m1",i,15],["m2",i,15]]:[["a7",a,12],["a8",n,12],["a9",n,15],["a10",n,15],["a11",i,15],["a12",i,15],["a13",i,15],["a14",i,15],["a15",i,15],["a16",i,15],["a17",i,15]];let l;return s==="80162181255"?l=o.filter(([,,c])=>c>=14):(l=o.filter(([,c])=>c===s),l.length||(l=o)),l.map(([c])=>`apple ${c} gpu`)}class Vm extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}const _h=[],km=[];function hv(r,e){if(r===e)return 0;const t=r;r.length>e.length&&(r=e,e=t);let s=r.length,i=e.length;for(;s>0&&r.charCodeAt(~-s)===e.charCodeAt(~-i);)s--,i--;let n,a=0;for(;a<s&&r.charCodeAt(a)===e.charCodeAt(a);)a++;if(s-=a,i-=a,s===0)return i;let o,l,c=0,u=0,h=0;for(;u<s;)km[u]=r.charCodeAt(a+u),_h[u]=++u;for(;h<i;)for(n=e.charCodeAt(a+h),o=h++,c=h,u=0;u<s;u++)l=n===km[u]?o:o+1,o=_h[u],c=_h[u]=o>c?l>c?c+1:l:l>o?o+1:l;return c}function dv(r){return r!=null}const pv=({mobileTiers:r=[0,15,30,60],desktopTiers:e=[0,15,30,60],override:t={},glContext:s,failIfMajorPerformanceCaveat:i=!1,benchmarksURL:n="https://unpkg.com/detect-gpu@5.0.70/dist/benchmarks"}={})=>xh(void 0,void 0,void 0,function*(){const a={};if(ox)return{tier:0,type:"SSR"};const{isIpad:o=!!fi?.isIpad,isMobile:l=!!fi?.isMobile,screenSize:c=window.screen,loadBenchmarks:u=M=>xh(void 0,void 0,void 0,function*(){const A=yield fetch(`${n}/${M}`).then(C=>C.json());if(parseInt(A.shift().split(".")[0],10)<4)throw new Vm("Detect GPU benchmark data is out of date. Please update to version 4x");return A})}=t;let{renderer:h}=t;const d=(M,A,C,P,B)=>({device:B,fps:P,gpu:C,isMobile:l,tier:M,type:A});let p,f="";if(h)h=Um(h),p=[h];else{const M=s||function(C,P=!1){const B={alpha:!1,antialias:!1,depth:!1,failIfMajorPerformanceCaveat:P,powerPreference:"high-performance",stencil:!1};C&&delete B.powerPreference;const V=window.document.createElement("canvas"),Y=V.getContext("webgl",B)||V.getContext("experimental-webgl",B);return Y??void 0}(fi?.isSafari12,i);if(!M)return d(0,"WEBGL_UNSUPPORTED");const A=fi?.isFirefox?null:M.getExtension("WEBGL_debug_renderer_info");if(h=A?M.getParameter(A.UNMASKED_RENDERER_WEBGL):M.getParameter(M.RENDERER),!h)return d(1,"FALLBACK");f=h,h=Um(h),p=function(C,P,B){return P==="apple gpu"?uv(C,P,B):[P]}(M,h,l)}const m=(yield Promise.all(p.map(function(M){var A;return xh(this,void 0,void 0,function*(){const C=(Fe=>{const Ct=l?["adreno","apple","mali-t","mali","nvidia","powervr","samsung"]:["intel","apple","amd","radeon","nvidia","geforce","adreno"];for(const Ts of Ct)if(Fe.includes(Ts))return Ts})(M);if(!C)return;const P=`${l?"m":"d"}-${C}${o?"-ipad":""}.json`,B=a[P]=(A=a[P])!==null&&A!==void 0?A:u(P);let V;try{V=yield B}catch(Fe){if(Fe instanceof Vm)throw Fe;return}const Y=function(Fe){var Ct;const Ts=(Fe=Fe.replace(/\([^)]+\)/,"")).match(/\d+/)||Fe.match(/(\W|^)([A-Za-z]{1,3})(\W|$)/g);return(Ct=Ts?.join("").replace(/\W|amd/g,""))!==null&&Ct!==void 0?Ct:""}(M);let J=V.filter(([,Fe])=>Fe===Y);J.length||(J=V.filter(([Fe])=>Fe.includes(M)));const K=J.length;if(K===0)return;const te=M.split(/[.,()\[\]/\s]/g).sort().filter((Fe,Ct,Ts)=>Ct===0||Fe!==Ts[Ct-1]).join(" ");let q,[oe,,,,Pe]=K>1?J.map(Fe=>[Fe,hv(te,Fe[2])]).sort(([,Fe],[,Ct])=>Fe-Ct)[0][0]:J[0],ge=Number.MAX_VALUE;const{devicePixelRatio:le}=window,Ue=c.width*le*c.height*le;for(const Fe of Pe){const[Ct,Ts]=Fe,ev=Ct*Ts,Lm=Math.abs(Ue-ev);Lm<ge&&(ge=Lm,q=Fe)}if(!q)return;const[,,He,$t]=q;return[ge,He,oe,$t]})}))).filter(dv).sort(([M=Number.MAX_VALUE,A],[C=Number.MAX_VALUE,P])=>M===C?A-P:M-C);if(!m.length){const M=cv.find(A=>h.includes(A));return M?d(0,"BLOCKLISTED",M):d(1,"FALLBACK",`${h} (${f})`)}const[,x,y,b]=m[0];if(x===-1)return d(0,"BLOCKLISTED",y,x,b);const v=l?r:e;let S=0;for(let M=0;M<v.length;M++)x>=v[M]&&(S=M);return d(S,"BENCHMARK",y,x,b)});function lx(r){let e=0;const t=performance.now();function s(){e++;const i=performance.now();if(i-t>=100){const n=e/((i-t)/1e3),a=Math.round(n/30)*30;r(a)}else requestAnimationFrame(s)}requestAnimationFrame(s)}function cx(r=!1,e=!1){return new Promise(t=>{pv().then(s=>{let i=!1;const n=document.createElement("canvas"),a=/^((?!chrome|android).)*safari/i.test(navigator.userAgent);if(i="transferControlToOffscreen"in n,a){const l=navigator.userAgent.match(/version\/(\d+)/i);i=(l?parseInt(l[1]):0)>=17}const o={dpr:devicePixelRatio,fps:30,width:innerWidth,height:innerHeight,mobile:s.isMobile!==void 0?s.isMobile:!1,supportOffScreenCanvas:i,supportWebGPU:!!navigator.gpu,quality:"Low",dev:r,editor:e};s.tier===3?o.quality="High":s.tier===2&&(o.quality="Medium"),lx(l=>{o.fps=l,t(o)})})})}function _n(r,e,t){return Math.min(e,Math.max(r,t))}function Cc(r,e,t){return(t-r)/(e-r)}function Ma(r,e,t){return r*(1-t)+e*t}function fv(r,e,t,s,i){return Ma(t,s,Cc(r,e,i))}function mv(r,e){const t=r-e;return Math.sqrt(t*t)}function gv(r,e,t,s){return Ma(r,e,1-Math.exp(-t*s))}function As(r,e=1){return Number(r.toFixed(e))}function yv(r,e,t,s){return Math.atan2(s-e,t-r)}function xv(r,e,t,s){return r===e&&t===s}function _v(r,e,t,s){return 1/(3*e*r*r+2*t*r+s)}function bv(r,e,t,s,i){return e*(r*r*r)+t*(r*r)+s*r+i}function Tv(r,e,t,s,i){const n=r*r;return e*(n*r)+t*n+s*r+i}function Sv(r,e,t,s,i){if(r<=0)return 0;if(r>=1)return 1;if(xv(e,t,s,i))return r;const n=0,a=0,o=e,l=t,c=s,u=i,h=1,d=1,p=h-3*c+3*o-n,f=3*c-6*o+3*n,m=3*o-3*n,x=n,y=d-3*u+3*l-a,b=3*u-6*l+3*a,v=3*l-3*a,S=a;let M=r;for(let A=0;A<5;A++){const C=bv(M,p,f,m,x);let P=_v(M,p,f,m);P===1/0&&(P=r),M-=(C-r)*P,M=Math.min(Math.max(M,0),1)}return Tv(M,y,b,v,S)}const ll=r=>Math.round(Math.min(1,Math.max(0,r))*255).toString(16).padStart(2,"0");function vv({r,g:e,b:t,a:s=1}){const i=`#${ll(r)}${ll(e)}${ll(t)}`;return s<1?`${i}${ll(s)}`:i}let Rr;function Mv(){const[r,e]=X.useState(Rr);return X.useEffect(()=>{Rr||import("@tomorrowevening/theatre-studio").then(t=>{Rr=t.default,Rr.initialize(),Rr.ui.hide(),e(Rr)})},[]),r}async function wv(){for(;!document.getElementById("theatrejs-studio-root");)await new Promise(s=>setTimeout(s,100));const r=document.getElementById("theatrejs-studio-root");if(r===null||r.shadowRoot===null)return;const e=r.shadowRoot.getElementById("pointer-root");if(e===null)return;const t=e.children[0];if(t!==null){try{const i=t.children[1].children[1];i.parentElement?.removeChild(i)}catch{}try{const s=t.children[3];s.style.top="0",s.style.right="300px"}catch{}}}function Cv(r,e,t,s){s.sheetObject(r,e,{transform:{position:{x:t.position.x,y:t.position.y,z:t.position.z},rotation:{x:t.rotation.x,y:t.rotation.y,z:t.rotation.z},scale:{x:t.scale.x,y:t.scale.y,z:t.scale.z},visible:t.visible}},i=>{const n=i.transform;t.position.copy(n.position),t.rotation.copy(n.rotation),t.scale.copy(n.scale),t.visible=n.visible})}const Av=["allowOverride","alphaHash","alphaTest","alphaToCoverage","blendAlpha","blendColor","blendDst","blendDstAlpha","blendEquation","blendEquationAlpha","blendSrc","blendSrcAlpha","blending","clipIntersection","clipShadows","clipping","clippingPlanes","colorWrite","combine","defaultAttributeValues","defines","depthFunc","depthTest","depthWrite","dithering","extensions","fog","forceSinglePass","fragmentShader","glslVersion","id","index0AttributeName","index1AttributeName","index2AttributeName","index3AttributeName","index4AttributeName","isMaterial","lights","linewidth","name","needsUpdate","polygonOffset","polygonOffsetFactor","polygonOffsetUnits","precision","premultipliedAlpha","shadowSide","side","stencilFail","stencilFunc","stencilFuncMask","stencilRef","stencilWrite","stencilWriteMask","stencilZFail","stencilZPass","toneMapped","transparent","type","uniformsGroups","uniformsNeedUpdate","userData","uuid","version","vertexColors","vertexShader","visible","wireframe","wireframeLinewidth","wireframeLinecap","wireframeLinejoin"];function zm(r){const e=typeof r;if(r===null||r.isTexture)return"texture";if(e==="boolean")return"boolean";if(e==="number")return"number";if(e==="string")return"string";if(e==="object"){if(r.isColor)return"color";if(r.isVector2)return"vector2";if(r.isVector3)return"vector3";if(r.isVector4)return"vector4";if(r.isMatrix2)return"matrix2";if(r.isMatrix3)return"matrix3";if(r.isMatrix4)return"matrix4";if(r.isEuler)return"euler";if(Array.isArray(r))return"array"}return"object"}function ux(r){const e=[];for(const s in r){const i=Av.find(o=>o===s),n=s.indexOf("_")===0||s.indexOf("is")===0;if(!(i||n))if(s==="uniforms"){const o=r.uniforms;for(const l in o){const c=o[l].value,u=zm(c);u==="array"||u==="object"||e.push({name:`uniforms.${l}.value`,type:u,value:c})}}else{const o=zm(r[s]);e.push({name:s,type:o,value:r[s]})}}return e.filter(s=>s.type!=="array"&&s.type!=="object"&&s.type!=="texture")}function hx(r){const e={},t={nudgeMultiplier:.01};return r.forEach(s=>{let i=s.value;switch(s.type){case"color":i=fe.types.rgba({r:i.r,g:i.g,b:i.b,a:1});break;case"number":i=fe.types.number(i,t);break;case"euler":case"vector3":i={x:fe.types.number(i.x,t),y:fe.types.number(i.y,t),z:fe.types.number(i.z,t)};break;case"vector2":i={x:fe.types.number(i.x,t),y:fe.types.number(i.y,t)};break;case"vector4":i={x:fe.types.number(i.x,t),y:fe.types.number(i.y,t),z:fe.types.number(i.z,t),w:fe.types.number(i.w,t)};break;case"matrix2":i={0:fe.types.number(i.elements[0],t),1:fe.types.number(i.elements[1],t),2:fe.types.number(i.elements[2],t),3:fe.types.number(i.elements[3],t)};break;case"matrix3":i={0:fe.types.number(i.elements[0],t),1:fe.types.number(i.elements[1],t),2:fe.types.number(i.elements[2],t),3:fe.types.number(i.elements[3],t),4:fe.types.number(i.elements[4],t),5:fe.types.number(i.elements[5],t),6:fe.types.number(i.elements[6],t),7:fe.types.number(i.elements[7],t),8:fe.types.number(i.elements[8],t)};break;case"matrix4":i={0:fe.types.number(i.elements[0],t),1:fe.types.number(i.elements[1],t),2:fe.types.number(i.elements[2],t),3:fe.types.number(i.elements[3],t),4:fe.types.number(i.elements[4],t),5:fe.types.number(i.elements[5],t),6:fe.types.number(i.elements[6],t),7:fe.types.number(i.elements[7],t),8:fe.types.number(i.elements[8],t),9:fe.types.number(i.elements[9],t),10:fe.types.number(i.elements[10],t),11:fe.types.number(i.elements[11],t),12:fe.types.number(i.elements[12],t),13:fe.types.number(i.elements[13],t),14:fe.types.number(i.elements[14],t),15:fe.types.number(i.elements[15],t)};break}if(s.name.includes(".")){const n=s.name.split(".");let a=e;for(let o=0;o<n.length-1;o++){const l=n[o];a[l]||(a[l]={}),a=a[l]}a[n[n.length-1]]=i}else e[s.name]=i}),e}function dx(r,e,t){e.forEach(s=>{if(r[s.name]!==void 0)switch(s.type){case"boolean":case"number":r[s.name]=t.material[s.name];break;case"color":case"euler":case"matrix2":case"matrix3":case"matrix4":case"vector2":case"vector3":case"vector4":r[s.name].copy(t.material[s.name]);break}})}function Ev(r,e,t,s){if(!t.isMaterial)return;const i=ux(t),n=hx(i);s.sheetObject(r,e,{material:n},a=>{dx(t,i,a)})}const Cu=new _.BufferGeometry;Cu.setAttribute("position",new _.Float32BufferAttribute([-.5,-.5,0,1.5,-.5,0,-.5,1.5,0],3));Cu.setAttribute("normal",new _.Float32BufferAttribute([0,0,1,0,0,1],3));Cu.setAttribute("uv",new _.Float32BufferAttribute([0,0,2,0,0,2],2));const Nv=new _.OrthographicCamera(-.5,.5,.5,-.5,0,100),qd=r=>{r?.dispose()},Fp=r=>{if(r)if(Array.isArray(r))r.forEach(e=>Fp(e));else{for(const e in r){const t=r[e];t!==null&&t instanceof _.Texture&&qd(t)}if(r.isShaderMaterial===!0){const e=r;for(const t in e.uniforms){const s=e.uniforms[t];s.value!==null&&s.value instanceof _.Texture&&qd(s.value)}}r.dispose()}},Ri=r=>{if(r){for(;r.children.length>0;){const e=r.children[0];e.type==="Audio"?(e.pause(),e.parent&&e.parent.remove(e)):Ri(e)}if(r.parent&&r.parent.remove(r),r.isMesh){const e=r;e.geometry?.dispose(),Fp(e.material)}r.dispose!==void 0&&r.dispose()}};exports.totalThreeObjects=0;const mo=()=>{exports.totalThreeObjects=0},ca=r=>{if(!r)return;let e=r.name.replaceAll(" ","").replaceAll("/",".");if(e.length===0&&(e=`obj_${exports.totalThreeObjects}`,exports.totalThreeObjects++),r.parent!==null&&r.parent.uuid.length>0&&(e=`${r.parent.uuid}.${e}`),r.uuid=e,r.isMesh!==void 0){const t=r;if(Array.isArray(t.material))t.material.forEach((s,i)=>{s.uuid=`${e}.material.${i}`});else{const s=t.material;s.uuid=`${e}.material`}}r.children.forEach(t=>ca(t))};class Hi{static renderer;static canvas;static context=null;static scene=null;static camera=null;static material=null;static inited=!1;static width=100;static height=100;static init(){this.inited||(this.canvas=document.createElement("canvas"),this.canvas.width=this.width,this.canvas.height=this.height,this.context=this.canvas.getContext("2d"),this.inited=!0)}static renderToBlob(e){this.init();const t=e.repeat.clone(),s=e.offset.clone();if(e.repeat.set(1,1),e.offset.set(0,0),this.context!==null){this.context.clearRect(0,0,this.width,this.height);const i=e.image;if(i!=null&&i.width>0){this.canvas.title=e.sourceFile;const n=this.canvas.width/i.width,a=this.renderToCanvas(e);this.context.drawImage(a,0,0,i.width*n,i.height*n)}}return e.repeat.copy(t),e.offset.copy(s),this.canvas.toDataURL("image/png")}static renderToCanvas(e){if(this.material===null){this.camera=new _.OrthographicCamera(-.5,.5,.5,-.5,0,100),this.scene=new _.Scene,this.material=new _.MeshBasicMaterial;const t=new _.BufferGeometry;t.setAttribute("position",new _.Float32BufferAttribute([-.5,-.5,0,1.5,-.5,0,-.5,1.5,0],3)),t.setAttribute("normal",new _.Float32BufferAttribute([0,0,1,0,0,1],3)),t.setAttribute("uv",new _.Float32BufferAttribute([0,0,2,0,0,2],2));const s=new _.Mesh(t,this.material);this.scene.add(s)}if(e.isRenderTargetTexture)this.material.map=e,this.renderer.render(this.scene,this.camera);else{const t=this.renderer.outputColorSpace,s=e.colorSpace;this.renderer.outputColorSpace=_.LinearSRGBColorSpace,e.colorSpace=_.LinearSRGBColorSpace,this.material.map=e,this.renderer.render(this.scene,this.camera),this.renderer.outputColorSpace=t,e.colorSpace=s}return this.renderer.domElement}}function Rv(r){return new Promise(e=>{const t=new _.ObjectLoader;t.parseAsync(r.scene).then(s=>{const i=new _.AnimationMixer(s);if(r.animations.length>0){const a=r.animations.map(l=>_.AnimationClip.parse(l));i.clipAction(a[0]).play(),i.getRoot().animations=r.animations,i.getRoot().mixer=i}const n=[];r.cameras&&r.cameras.length>0&&r.cameras.forEach(a=>{const o=t.parse(a);n.push(o)}),e({animations:r.animations,model:s,mixer:i,cameras:n})})})}const Pv=(r,e,t,s)=>{r.setRenderTarget(s),r.clear(),r.render(e,t)};function px(r,e,t,s){r.applyMatrix4(new _.Matrix4().makeTranslation(e,-t,-s))}function Fv(r){r.computeBoundingBox();const e=r.boundingBox,t=(e.max.x-e.min.x)/2,s=(e.max.y-e.min.y)/2;px(r,t,s,0)}function Bv(r,e,t){r.left=e/-2,r.right=e/2,r.top=t/2,r.bottom=t/-2,r.position.x=e/2,r.position.y=t/-2,r.updateProjectionMatrix()}function Dv(r,e,t){const s=1.7777777777777777,i=e/t;let n=e,a=t;i>s?n=t*s:a=e/s,r.left=n/-2,r.right=n/2,r.top=a/2,r.bottom=a/-2,r.updateProjectionMatrix()}function Ov(){let e="transferControlToOffscreen"in document.createElement("canvas");if(/^((?!chrome|android).)*safari/i.test(navigator.userAgent)){const s=navigator.userAgent.match(/version\/(\d+)/i);e=(s?parseInt(s[1]):0)>=17}return e}function Lv(r,e,t=!0,s=!1){r.renderOrder=-e;const i=r.material;Array.isArray(i)?i.forEach(n=>{n.colorWrite=t,n.depthWrite=s,n.stencilWrite=!0,n.stencilRef=e,n.stencilFunc=_.AlwaysStencilFunc,n.stencilFail=_.ReplaceStencilOp,n.stencilZFail=_.ReplaceStencilOp,n.stencilZPass=_.ReplaceStencilOp}):(i.colorWrite=t,i.depthWrite=s,i.stencilWrite=!0,i.stencilRef=e,i.stencilFunc=_.AlwaysStencilFunc,i.stencilFail=_.ReplaceStencilOp,i.stencilZFail=_.ReplaceStencilOp,i.stencilZPass=_.ReplaceStencilOp)}function Iv(r,e,t=!1){const s=r.material;Array.isArray(s)?s.forEach(i=>{i.stencilWrite=!0,i.stencilRef=e,i.stencilFunc=t?_.NotEqualStencilFunc:_.EqualStencilFunc,i.stencilFail=_.KeepStencilOp,i.stencilZFail=_.KeepStencilOp,i.stencilZPass=_.KeepStencilOp}):(s.stencilWrite=!0,s.stencilRef=e,s.stencilFunc=t?_.NotEqualStencilFunc:_.EqualStencilFunc,s.stencilFail=_.KeepStencilOp,s.stencilZFail=_.KeepStencilOp,s.stencilZPass=_.KeepStencilOp)}function Uv(r){r.blending=_.NormalBlending,r.blendEquation=_.AddEquation,r.blendSrc=_.SrcAlphaFactor,r.blendDst=_.OneMinusSrcAlphaFactor,r.needsUpdate=!0}function Vv(r){r.blending=_.CustomBlending,r.blendEquation=_.AddEquation,r.blendSrc=_.SrcAlphaFactor,r.blendDst=_.OneFactor,r.needsUpdate=!0}function kv(r){r.blending=_.CustomBlending,r.blendEquation=_.AddEquation,r.blendSrc=_.DstColorFactor,r.blendDst=_.OneMinusSrcAlphaFactor,r.needsUpdate=!0}function zv(r){r.blending=_.CustomBlending,r.blendEquation=_.AddEquation,r.blendSrc=_.OneMinusDstColorFactor,r.blendDst=_.OneFactor,r.needsUpdate=!0}let Xd=[];function fx(r,e,t=!0){Hi.renderer=e.renderer;const s=[];s.push({type:"boolean",prop:"Enabled",value:r.enabled});let i=(a,o)=>{console.log("Default Handle Pass:",a,o)};if(r.name==="EffectPass")r.effects.forEach(a=>{a.uniforms.size>0&&a.uniforms.forEach((o,l)=>{if(l==="map")return;const c=`${a.name.replace("Effect","")} ${l}`;if(o.value===null&&t)s.push({prop:l,title:c,type:"image",value:{offset:[0,0],repeat:[1,1],src:""}});else if(o.value.isTexture&&t){const u=o.value,h=Hi.renderToBlob(u);s.push({prop:l,title:c,type:"image",value:{offset:[u.offset.x,u.offset.y],repeat:[u.repeat.x,u.repeat.y],src:h}})}else typeof o.value=="number"?s.push({prop:l,title:c,type:"number",value:o.value,step:.01}):typeof o.value=="string"?s.push({prop:l,title:c,type:"string",value:o.value}):typeof o.value=="boolean"&&s.push({prop:l,title:c,type:"boolean",value:o.value})})}),i=(a,o)=>{r.effects.forEach(l=>{l.uniforms.size>0&&l.uniforms.forEach((c,u)=>{u===a&&(c.value=o)})})};else if(r.name==="ShaderPass"){const a=r.fullscreenMaterial;for(const o in a.uniforms){if(o==="inputBuffer"||o==="map")continue;const l=a.uniforms[o],c=`${a.name.replace("Material","")} ${o}`;if(l.value===null&&t)s.push({title:c,prop:o,type:"image",value:{offset:[0,0],repeat:[1,1],src:""}});else if(l.value.isTexture&&t){const u=l.value,h=Hi.renderToBlob(u);s.push({title:c,prop:o,type:"image",value:{offset:[u.offset.x,u.offset.y],repeat:[u.repeat.x,u.repeat.y],src:h}})}else typeof l.value=="number"?s.push({title:c,prop:o,type:"number",value:l.value,step:.01}):typeof l.value=="string"?s.push({title:c,prop:o,type:"string",value:l.value}):typeof l.value=="boolean"&&s.push({title:c,prop:o,type:"boolean",value:l.value})}i=(o,l)=>{const c=a.uniforms[o];c.value=l}}else return;const n=`${r.name}: ${r.scene.name}`;e.addGroup({title:n,items:s,onUpdate:(a,o)=>{a==="Enabled"?r.enabled=o:i(a,o)}}),Xd.push(n)}function Gv(r,e){r.passes.forEach(t=>{fx(t,e)})}function $v(r){Xd.forEach(e=>{r.removeGroup(e)}),Xd=[]}function Wv(r,e,t,s=1024){return new Promise(i=>{const n=e.aspect,a=e.fov,o=e.rotation.clone(),l=t.outputBuffer;e.aspect=1,e.fov=90,e.updateProjectionMatrix();const c=new _.WebGLRenderTarget(s,s,{format:_.RGBAFormat,depthBuffer:!0,stencilBuffer:!1});t.outputBuffer=c,Pr(r,c,e,"nx",t,s).then(()=>{Pr(r,c,e,"ny",t,s).then(()=>{Pr(r,c,e,"nz",t,s).then(()=>{Pr(r,c,e,"px",t,s).then(()=>{Pr(r,c,e,"py",t,s).then(()=>{Pr(r,c,e,"pz",t,s).then(()=>{e.aspect=n,e.fov=a,e.rotation.copy(o),e.updateMatrixWorld(),e.updateProjectionMatrix(),t.outputBuffer=l,c.dispose(),i()})})})})})})})}function Pr(r,e,t,s,i,n){return new Promise(a=>{const o=Math.PI/2;switch(s){case"nx":t.rotation.set(0,-o,0);break;case"ny":t.rotation.set(-o,0,Math.PI);break;case"nz":t.rotation.set(0,0,0);break;case"px":t.rotation.set(0,o,0);break;case"py":t.rotation.set(o,0,Math.PI);break;case"pz":t.rotation.set(0,Math.PI,0);break}t.updateMatrixWorld(),i.render();const l=new Uint8Array(n*n*4);r.readRenderTargetPixels(e,0,0,n,n,l);const c=document.createElement("canvas");c.width=c.height=n;const u=c.getContext("2d"),h=u.createImageData(n,n);h.data.set(l),u.putImageData(h,0,0);const d=document.createElement("canvas");d.width=d.height=n;const p=d.getContext("2d");p.translate(0,n),p.scale(1,-1),p.drawImage(c,0,0);const f=d.toDataURL("image/png"),m=document.createElement("a");m.href=f,m.download=`${t.name}_${s}.png`,document.body.appendChild(m),m.click(),m.remove(),a()})}const Fr=Bp(["ctrlKey","metaKey","shiftKey","button","pointerId","pointerType","clientX","clientY","pageX","pageY"]),Hv=Bp(["clientX","clientY","deltaX","deltaY","deltaMode"]),jv=Bp(["ctrlKey","metaKey","shiftKey","keyCode"]);function qv(r,e){r.preventDefault(),Hv(r,e)}function Xv(r){r.preventDefault()}function Yv(r,e,t){for(const s of e)t[s]=r[s]}function Bp(r){return function(t,s){const i={type:t.type};Yv(t,r,i),s(i)}}function bh(r,e){const t=[],s={type:r.type,touches:t};for(let i=0;i<r.touches.length;++i){const n=r.touches[i];t.push({pageX:n.pageX,pageY:n.pageY})}e(s)}const Zv={37:!0,38:!0,39:!0,40:!0};function Qv(r,e){const{keyCode:t}=r;Zv[t]&&(r.preventDefault(),jv(r,e))}const Kv={contextmenu:Xv,mousedown:Fr,mousemove:Fr,mouseup:Fr,pointerdown:Fr,pointermove:Fr,pointerup:Fr,touchstart:bh,touchmove:bh,touchend:bh,wheel:qv,keydown:Qv};let Jv=0;class eM{id;worker;constructor(e,t,s){this.id=Jv++,this.worker=t;const i=a=>{this.worker.postMessage({type:"event",id:this.id,data:a})};t.postMessage({type:"makeProxy",id:this.id});for(const[a,o]of Object.entries(s))e.addEventListener(a,l=>{o(l,i)});function n(){i({type:"resize",left:0,top:0,width:innerWidth,height:innerHeight})}window.addEventListener("resize",n),n()}}class mx extends _.EventDispatcher{style={};left=0;top=0;width=0;height=0;ownerDocument=void 0;constructor(){super(),this.ownerDocument=this}get clientWidth(){return this.width}set clientWidth(e){this.width=e}get clientHeight(){return this.height}set clientHeight(e){this.height=e}setPointerCapture(){}releasePointerCapture(){}getBoundingClientRect(){return{x:this.left,y:this.top,left:this.left,top:this.top,width:this.width,height:this.height,right:this.left+this.width,bottom:this.top+this.height,toJSON:()=>({})}}handleEvent(e){if(e.type==="size"){this.left=e.left,this.top=e.top,this.width=e.width,this.height=e.height;return}e.preventDefault=Io,e.stopPropagation=Io,this.dispatchEvent(e)}focus(){}getRootNode(){return this}}class tM{targets={};constructor(){this.handleEvent=this.handleEvent.bind(this)}makeProxy(e){const{id:t}=e,s=new mx;this.targets[t]=s}getProxy(e){return this.targets[e]}handleEvent(e){this.targets[e.id]?.handleEvent(e.data)}}class sM{assets={audio:new Map,image:new Map,json:new Map,model:new Map,video:new Map};components=new Map;settings={dpr:1,fps:30,width:0,height:0,mobile:!1,supportOffScreenCanvas:!1,supportWebGPU:!1,quality:"Low",dev:!1,editor:!1};onUpdateCallback;playing=!1;rafID=-1;dispose(){this.pause(),this.components.forEach(e=>e.dispose()),this.components.clear()}detectSettings(e=!1,t=!1){return new Promise(s=>{cx(e,t).then(i=>{this.settings=i,s()})})}update(){}draw(){}play=()=>{this.playing||(this.playing=!0,this.onUpdate())};pause=()=>{this.playing&&(this.playing=!1,cancelAnimationFrame(this.rafID),this.rafID=-1)};onUpdate=()=>{this.update(),this.isApp&&this.draw(),this.onUpdateCallback&&this.onUpdateCallback(),this.rafID=requestAnimationFrame(this.onUpdate)};addComponent(e,t){this.components.set(e,t)}get debugEnabled(){return this.settings.dev}get isApp(){return!this.editor}set isApp(e){this.editor=!e}get editor(){return this.settings.editor}set editor(e){this.settings.editor=e}}class Dp{name;_debug=!1;_editor=!1;broadcastChannel;constructor(e,t=!1,s=!1){this.name=e,this._debug=t,this._editor=s,t&&(this.broadcastChannel=new BroadcastChannel(e),this.broadcastChannel.addEventListener("message",this.messageHandler.bind(this)))}dispose(){this.broadcastChannel?.removeEventListener("message",this.messageHandler.bind(this)),this.broadcastChannel?.close()}get debug(){return this._debug}get editor(){return this._editor}send(e){if(this.editor&&e.target==="app"||!this.editor&&e.target==="editor")try{this.broadcastChannel?.postMessage(e)}catch(s){console.log("Hermes - Error sending message:"),console.log(s),console.log(e)}}messageHandler(e){const t=e.data;t.target==="app"?this.handleApp(t):this.handleEditor(t)}handleApp(e){}handleEditor(e){}}function iM(r,e,t,s,i){const n=1-r;return n*n*n*e+3*n*n*r*t+3*n*r*r*s+r*r*r*i}function nM(r,e,t){if(r.type!=="bezier"||r.handles.length!==4)throw new Error("Invalid keyframe data for Bézier interpolation.");const[s,i]=r.handles,n=(t-r.position)/(e.position-r.position);return iM(n,r.value,r.value+s,e.value+i,e.value)}class rM extends Dp{project;sheets=new Map;sheetObjects=new Map;sheetObjectCBs=new Map;sheetObjectUnsubscribe=new Map;activeSheet;studio=void 0;constructor(e=!1,t=!1){super("RemoteTheatre",e,t)}dispose(){this.project=void 0,this.sheets=new Map,this.sheetObjects=new Map,this.sheetObjectCBs=new Map,this.sheetObjectUnsubscribe=new Map}loadProject(e,t){return this.project=fe.getProject(e,{state:t}),new Promise((s,i)=>{this.project?.ready.then(()=>{if(t){const n=t.sheetsById;for(const a in n)this.sheet(a)}s()}).catch(()=>i())})}getSheetInstance(e,t){return t!==void 0?`${e}-${t}`:e}sheet(e,t){if(this.project===void 0){console.error("Theatre Project hasn't been created yet.");return}const s=this.getSheetInstance(e,t);let i=this.sheets.get(s);return i!==void 0||(i=this.project?.sheet(e,t),this.sheets.set(s,i)),i}playSheet(e,t,s){return new Promise(i=>{this.sheet(e,s)?.sequence.play(t).then(n=>i(n)),this.send({event:"playSheet",target:"editor",data:{sheet:e,instance:s,value:t}})})}pauseSheet(e,t){this.sheet(e,t)?.sequence.pause(),this.send({event:"pauseSheet",target:"editor",data:{sheet:e,instance:t}})}clearSheetObjects(e){this.sheetObjects.forEach((t,s)=>{s.search(`${e}_`)>-1&&this.unsubscribe(t)})}sheetObject(e,t,s,i,n){if(this.project===void 0){console.error("Theatre Project hasn't been created yet.");return}const a=this.sheet(e,n);if(a===void 0)return;const l=`${this.getSheetInstance(e,n)}_${t}`;let c=this.sheetObjects.get(l),u=s;c!==void 0&&(u={...s,...c.value}),c=a.object(t,u,{reconfigure:!0}),this.sheetObjects.set(l,c),this.sheetObjectCBs.set(l,i!==void 0?i:Io);function h(p,f,m){if(typeof m=="object")if(ax(m))p[f]={r:m.r,g:m.g,b:m.b,a:m.a};else for(const x in m){const y=m[x];typeof y=="object"&&h(m,x,y)}}const d=c.onValuesChange(p=>{const f=this.sheetObjectCBs.get(l);if(this.editor){for(const m in p){const x=p[m];typeof x=="object"&&h(p,m,x)}this.send({event:"updateSheetObject",target:"app",data:{sheet:e,sheetObject:l,values:p}}),f&&f(p)}else f&&f(p)});return this.sheetObjectUnsubscribe.set(l,d),c}getSheetObjectKeyframes(e,t,s){const i=this.sheet(e);if(i===void 0)return[];const n=`${e}_${t}`,a=this.sheetObjects.get(n);return a===void 0?[]:i.sequence.__experimental_getKeyframes(a.props[s])}getSheetObjectVectors(e,t){const s=this.sheet(e);if(s===void 0)return[];const i=`${e}_${t}`,n=this.sheetObjects.get(i);if(n===void 0)return[];const a=[],o=s.sequence.__experimental_getKeyframes(n.props.x),l=s.sequence.__experimental_getKeyframes(n.props.y),c=s.sequence.__experimental_getKeyframes(n.props.z),u=new Set;return o.forEach(d=>u.add(d.position)),l.forEach(d=>u.add(d.position)),c.forEach(d=>u.add(d.position)),Array.from(u).sort((d,p)=>d-p).forEach(d=>{const p=(f,m)=>{const x=f.find((v,S)=>v.position<=m&&(f[S+1]?.position||1/0)>m),y=f.find(v=>v.position>m);if(!x)return y?.value||0;if(!y||x.position===m)return x.value;if(x.type==="bezier")return nM(x,y,m);const b=(m-x.position)/(y.position-x.position);return x.value+b*(y.value-x.value)};a.push({position:d,x:p(o,d),y:p(l,d),z:p(c,d)})}),a}update(e){}unsubscribe(e){if(this.project===void 0){console.error("Theatre Project hasn't been created yet.");return}const t=e.address.sheetId,s=e.address.objectKey;this.sheets.get(t)?.detachObject(s);const n=`${t}_${s}`,a=this.sheetObjectUnsubscribe.get(n);a!==void 0&&(this.sheetObjects.delete(n),this.sheetObjectCBs.delete(n),this.sheetObjectUnsubscribe.delete(n),a())}handleApp(e){let t;switch(e.event){case"setSheet":t=this.sheets.get(e.data.sheet),t!==void 0?this.studio?.setSelection([t]):console.log(`Hermes - Can't set Sheet: ${e.data.sheet}`,t);break;case"setSheetObject":t=this.sheetObjects.get(`${e.data.sheet}_${e.data.key}`),t!==void 0?this.studio?.setSelection([t]):console.log(`Hermes - Can't set Sheet Object: ${e.data.sheet}, ${e.data.key}: ${e.data.sheet}_${e.data.key}`,t);break;case"updateSheetObject":t=this.sheets.get(e.data.sheet),t!==void 0&&t.sequence.pause(),t=this.sheetObjectCBs.get(e.data.sheetObject),t!==void 0?t(e.data.values):console.log(`Hermes - Can't update Sheet Object: ${e.data.sheetObject}, ${e.data.sheet}`,t);break;case"updateTimeline":t=this.sheets.get(e.data.sheet),t!==void 0?t.sequence.position=e.data.position:console.log(`Hermes - Can't update sheet position: ${e.data.sheet}, ${e.data.position}`);break}}handleEditor(e){switch(e.event){case"playSheet":this.sheet(e.data.sheet,e.data.instance)?.sequence.play(e.data.value);break;case"pauseSheet":this.sheet(e.data.sheet,e.data.instance)?.sequence.pause();break}}getSheetNames(){const e=[];return this.sheets.forEach((t,s)=>{e.push(s)}),e}handleEditorApp(){if(this.editor){this.studio?.ui.restore(),this.studio?.onSelectionChange(i=>{i.length<1||i.forEach(n=>{let a=n.address.sheetId,o="setSheet",l={};switch(n.type){case"Theatre_Sheet_PublicAPI":o="setSheet",l={sheet:n.address.sheetId},this.activeSheet=this.sheets.get(n.address.sheetId);break;case"Theatre_SheetObject_PublicAPI":o="setSheetObject",a+=`_${n.address.objectKey}`,l={id:a,sheet:n.address.sheetId,key:n.address.objectKey},this.activeSheet=this.sheets.get(n.address.sheetId);break}this.send({event:o,target:"app",data:l})})});let e=-1;const t=()=>{if(this.activeSheet!==void 0&&e!==this.activeSheet.sequence.position){e=this.activeSheet.sequence.position;const i=this.activeSheet;this.send({event:"updateTimeline",target:"app",data:{position:e,sheet:i.address.sheetId}})}},s=()=>{t(),requestAnimationFrame(s)};t(),s()}else this.studio?.ui.hide()}}function aM(r){if(r.name==="cameras")return"camera";if(r.name==="interactive")return"interactive";if(r.name==="lights")return"light";if(r.name==="ui")return"ui";if(r.name==="utils")return"utils";const e=r.type;return e.search("Helper")>-1?"icon_utils":e.search("Camera")>-1?"camera":e.search("Light")>-1?"light":"obj3D"}function yn(r){const e={name:r.name,type:r.type,uuid:r.uuid,children:[]};return r.children.forEach(t=>{e.children.push(yn(t))}),e}function oM(r){const e={};for(const t in r){const s=r[t].value;e[t]={value:s},s===null?e[t].value={src:"",offset:[0,0],repeat:[1,1]}:s!==void 0&&s.isTexture&&(e[t].value={src:s.image.src,offset:[s.offset.x,s.offset.y],repeat:[s.repeat.x,s.repeat.y]})}return e}function lM(r){switch(r){case"blendSrcAlpha":case"blendDstAlpha":case"blendEquationAlpha":case"clippingPlanes":case"shadowSide":case"precision":return!0}return!1}function Br(r){const e={};for(const t in r){if(t.substring(0,1)==="_"||t.substring(0,2)==="is"||lM(t))continue;const s=typeof r[t],i=r[t];switch(s){case"boolean":case"number":case"string":e[t]=i;break;case"object":i!==null?(e[t]=i,i.isTexture?e[t]={src:Hi.renderToBlob(i),offset:[i.offset.x,i.offset.y],repeat:[i.repeat.x,i.repeat.y]}:t==="uniforms"&&(e[t]=oM(e[t]))):t==="glslVersion"?e[t]="":e[t]={src:"",offset:[0,0],repeat:[1,1]};break}}return r.anisotropy!==void 0&&(e.anisotropy=r.anisotropy),r.clearcoat!==void 0&&(e.clearcoat=r.clearcoat),r.iridescence!==void 0&&(e.iridescence=r.iridescence),r.dispersion!==void 0&&(e.dispersion=r.dispersion),r.sheen!==void 0&&(e.sheen=r.sheen),r.transmission!==void 0&&(e.transmission=r.transmission),r.transmission!==void 0&&(e.transmission=r.transmission),e}function Th(r){r.updateMatrix();const e={name:r.name,type:r.type,uuid:r.uuid,visible:r.visible,matrix:r.matrix.elements,animations:[],material:void 0,perspectiveCameraInfo:void 0,orthographicCameraInfo:void 0,lightInfo:void 0,children:[]};r.animations.forEach(s=>{e.animations.push({name:s.name,duration:s.duration,blendMode:s.blendMode})});const t=r.type.toLowerCase();if(t.search("mesh")>-1){const s=r;if(Array.isArray(s.material)){const i=[];s.material.forEach(n=>{i.push(Br(n))}),e.material=i}else e.material=Br(s.material)}else if(t.search("points")>-1){const s=r;if(Array.isArray(s.material)){const i=[];s.material.forEach(n=>{i.push(Br(n))}),e.material=i}else e.material=Br(s.material)}else if(t.search("line")>-1){const s=r;if(Array.isArray(s.material)){const i=[];s.material.forEach(n=>{i.push(Br(n))}),e.material=i}else e.material=Br(s.material)}else t.search("camera")>-1?r.type==="PerspectiveCamera"?e.perspectiveCameraInfo={fov:r.fov,zoom:r.zoom,near:r.near,far:r.far,focus:r.focus,aspect:r.aspect,filmGauge:r.filmGauge,filmOffset:r.filmOffset}:r.type==="OrthographicCamera"&&(e.orthographicCameraInfo={zoom:r.zoom,near:r.near,far:r.far,left:r.left,right:r.right,top:r.top,bottom:r.bottom}):t.search("light")>-1&&(e.lightInfo={color:r.color,intensity:r.intensity,decay:r.decay,distance:r.distance,angle:r.angle,penumbra:r.penumbra,groundColor:r.groundColor,width:r.width,height:r.height});return e}function cM(r,e){const t=e.split(".");switch(t.length){case 1:return r[t[0]];case 2:return r[t[0]][t[1]];case 3:return r[t[0]][t[1]][t[2]];case 4:return r[t[0]][t[1]][t[2]][t[3]];case 5:return r[t[0]][t[1]][t[2]][t[3]][t[4]];case 6:return r[t[0]][t[1]][t[2]][t[3]][t[4]][t[5]]}}function uM(r,e){for(const t in e)r[t]=e[t]}function ut(r,e,t){if(r===void 0){console.log(`Hermes - Can't set props: ${e}`,t);return}const s=e.split("."),i=s.length;if(typeof t!="object")switch(i){case 1:r[s[0]]=t;break;case 2:r[s[0]][s[1]]=t;break;case 3:r[s[0]][s[1]][s[2]]=t;break;case 4:r[s[0]][s[1]][s[2]][s[3]]=t;break;case 5:r[s[0]][s[1]][s[2]][s[3]][s[4]]=t;break}else{let a;switch(i){case 1:a=r[s[0]];break;case 2:a=r[s[0]][s[1]];break;case 3:a=r[s[0]][s[1]][s[2]];break;case 4:a=r[s[0]][s[1]][s[2]][s[3]];break;case 5:a=r[s[0]][s[1]][s[2]][s[3]][s[4]];break}a!=null?uM(a,t):console.log(`Hermes - Can't set props because target isn't found: ${e}`,t)}}function gx(r){return new Promise((e,t)=>{const s=new Image;s.onload=()=>{const i=new _.Texture(s);i.wrapS=_.RepeatWrapping,i.wrapT=_.RepeatWrapping,i.needsUpdate=!0,e(i)},s.onerror=t,s.src=r})}var me=(r=>(r.CUSTOM="ToolEvents::custom",r.SELECT_DROPDOWN="ToolEvents::selectDropdown",r.DRAG_UPDATE="ToolEvents::dragUpdate",r.ADD_SCENE="ToolEvents::addScene",r.REFRESH_SCENE="ToolEvents::refreshScene",r.REMOVE_SCENE="ToolEvents::removeScene",r.SET_SCENE="ToolEvents::setScene",r.SET_OBJECT="ToolEvents::setObject",r.CLEAR_OBJECT="ToolEvents::clearObject",r.ADD_CAMERA="ToolEvents::addCamera",r.REMOVE_CAMERA="ToolEvents::removeCamera",r.ADD_GROUP="ToolEvents::addGroup",r.REMOVE_GROUP="ToolEvents::removeGroup",r.ADD_SPLINE="ToolEvents::addSpline",r.ADD_RENDERER="ToolEvents::addRenderer",r.UPDATE_RENDERER="ToolEvents::updateRenderer",r))(me||{});class hM extends Dp{name;canvas=null;inputElement=null;scene=void 0;scenes=new Map;renderer=void 0;renderTargets=new Map;renderTargetsResize=new Map;groups=new Map;_listeners={};constructor(e,t=!1,s=!1){super("RemoteThree",t,s),this.name=e}dispose(){this.scenes.forEach(e=>{Ri(e)}),this.scenes.clear(),this.scene&&Ri(this.scene),this.renderTargets.forEach(e=>{e.dispose()}),this.renderTargets.clear(),this.renderer?.dispose()}addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const s=this._listeners;s[e]===void 0&&(s[e]=[]),s[e].indexOf(t)===-1&&s[e].push(t)}hasEventListener(e,t){const s=this._listeners;return s===void 0?!1:s[e]!==void 0&&s[e].indexOf(t)!==-1}removeEventListener(e,t){const s=this._listeners;if(s===void 0)return;const i=s[e];if(i!==void 0){const n=i.indexOf(t);n!==-1&&i.splice(n,1)}}dispatchEvent(e){const t=this._listeners;if(t===void 0)return;const s=t[e.type];if(s!==void 0){const i={...e,target:this},n=s.slice(0);for(let a=0,o=n.length;a<o;a++)n[a].call(this,i)}}getObjectByUUID(e){const t=e.split(".")[0],s=this.scenes.get(t);if(s!==void 0)return s.getObjectByProperty("uuid",e)}getObject(e){if(!this.debug)return;this.renderer!==void 0&&(Hi.renderer=this.renderer);const t=this.getObjectByUUID(e);t&&this.setObject(t)}setObject(e){this.renderer!==void 0&&(Hi.renderer=this.renderer);const t=Th(e);this.dispatchEvent({type:"ToolEvents::setObject",value:t})}requestMethod(e,t,s,i){const n=this.getObjectByUUID(e);if(n)try{i!==void 0?cM(n,i)[t](s):n[t](s)}catch(a){console.log("Hermes - Error requesting method:",e,t,s),console.log(a)}}updateObject(e,t,s){this.send({event:"updateObject",target:"app",data:{uuid:e,key:t,value:s}})}createTexture(e,t,s){this.send({event:"createTexture",target:"app",data:{uuid:e,key:t,value:s}})}onUpdateObject(e,t,s){const i=this.getObjectByUUID(e);i&&ut(i,t,s)}onCreateTexture(e,t,s){const i=this.getObjectByUUID(e);if(i){const n=a=>{const o=t.split(".");switch(o.length){case 1:i[o[0]]=a;break;case 2:i[o[0]][o[1]]=a;break;case 3:i[o[0]][o[1]][o[2]]=a;break;case 4:i[o[0]][o[1]][o[2]][o[3]]=a;break;case 5:i[o[0]][o[1]][o[2]][o[3]][o[4]]=a;break}i.material.needsUpdate=!0};s.src.length>0?gx(s.src).then(a=>{a.offset.set(s.offset[0],s.offset[1]),a.repeat.set(s.repeat[0],s.repeat[1]),n(a)}):n(null)}}addGroup(e){this.groups.get(e.title)===void 0&&(this.groups.set(e.title,{title:e.title,onUpdate:e.onUpdate}),this.send({event:"addGroup",target:"editor",data:JSON.stringify(e)}))}removeGroup(e){this.groups.get(e)!==void 0&&(this.groups.delete(e),this.send({event:"removeGroup",target:"editor",data:e}))}updateGroup(e,t,s){this.send({event:"updateGroup",target:"app",data:JSON.stringify({group:e,prop:t,value:s})})}addSplineCurve(e){setTimeout(()=>{this.send({event:"addSpline",target:"editor",data:JSON.stringify(e.toJSON())})},1)}addSplineObject(e){setTimeout(()=>{this.send({event:"addSpline",target:"editor",data:JSON.stringify(e)})},1)}setRenderer(e,t=null){if(this.renderer=e,this.canvas=e.domElement,this.inputElement=t!==null?t:this.canvas,!this.debug)return;const s=`#${e.getClearColor(new _.Color).getHexString()}`;this.send({event:"addRenderer",target:"editor",data:{autoClear:e.autoClear,autoClearColor:e.autoClearColor,autoClearDepth:e.autoClearDepth,autoClearStencil:e.autoClearStencil,outputColorSpace:e.outputColorSpace,localClippingEnabled:e.localClippingEnabled,clearColor:s,clearAlpha:e.getClearAlpha(),colorManagement:_.ColorManagement.enabled,toneMapping:e.toneMapping,toneMappingExposure:e.toneMappingExposure,type:e.isWebGLRenderer?"WebGLRenderer":"WebGPURenderer"}})}updateRenderer(e){this.send({event:"updateRenderer",target:"app",data:e})}addScene(e){if(e===void 0||(this.scenes.set(e.name,e),!this.debug))return;mo(),ca(e);const t=yn(e);this.send({event:"addScene",target:"editor",data:t})}refreshScene(e){if(!this.debug)return;const t=this.scenes.get(e);if(t!==void 0){const s=yn(t);this.send({event:"refreshScene",target:"app",data:s})}}removeScene(e){if(e===void 0||(this.scenes.delete(e.name),!this.debug))return;const t=yn(e);this.send({event:"removeScene",target:"editor",data:t})}removeAllScenes(){this.scenes.forEach(e=>this.removeScene(e))}getScene(e){let t=null;return this.scene!==void 0&&this.scene.uuid.search(e)>-1?this.scene:(this.scenes.forEach((s,i)=>{e.search(i)>-1&&(t=s)}),t)}setScene(e){if(e===void 0||(this.scene=e,!this.debug))return;this.renderer!==void 0&&(Hi.renderer=this.renderer),mo(),ca(e);const t=yn(e);this.send({event:"setScene",target:"editor",data:t})}requestSize(){this.send({event:"requestSize",target:"app"})}requestRenderer(){this.send({event:"requestRenderer",target:"app"})}requestScene(){this.send({event:"requestScene",target:"app"})}addCamera(e){if(!this.debug)return;const t=Th(e);this.send({event:"addCamera",target:"editor",data:t})}removeCamera(e){if(!this.debug)return;const t=Th(e);this.send({event:"removeCamera",target:"editor",data:t})}handleApp(e){switch(e.event){case"refreshScene":this.send({event:"refreshScene",target:"editor",data:yn(this.scenes.get(e.data.name))});break;case"updateRenderer":this.renderer&&(this.renderer.autoClearColor=e.data.autoClearColor,this.renderer.outputColorSpace=e.data.outputColorSpace,this.renderer.localClippingEnabled=e.data.localClippingEnabled,this.renderer.setClearColor(e.data.clearColor,e.data.clearAlpha),this.renderer.toneMapping=e.data.toneMapping,this.renderer.toneMappingExposure=e.data.toneMappingExposure,_.ColorManagement.enabled=e.data.colorManagement);break;case"requestRenderer":if(this.renderer!==void 0){const t=`#${this.renderer.getClearColor(new _.Color).getHexString()}`;this.send({event:"addRenderer",target:"editor",data:{autoClear:this.renderer.autoClear,autoClearColor:this.renderer.autoClearColor,autoClearDepth:this.renderer.autoClearDepth,autoClearStencil:this.renderer.autoClearStencil,outputColorSpace:this.renderer.outputColorSpace,localClippingEnabled:this.renderer.localClippingEnabled,clearColor:t,clearAlpha:this.renderer.getClearAlpha(),colorManagement:_.ColorManagement.enabled,toneMapping:this.renderer.toneMapping,toneMappingExposure:this.renderer.toneMappingExposure,type:this.renderer.isWebGLRenderer?"WebGLRenderer":"WebGPURenderer"}})}break;case"requestScene":this.scenes.forEach(t=>{mo(),ca(t),this.send({event:"addScene",target:"editor",data:yn(t)})}),this.scene!==void 0&&(this.renderer!==void 0&&(Hi.renderer=this.renderer),mo(),ca(this.scene),this.send({event:"setScene",target:"editor",data:yn(this.scene)}));break}if(e.event==="updateGroup"){const t=JSON.parse(e.data);this.groups.get(t.group)?.onUpdate(t.prop,t.value)}}handleEditor(e){switch(e.event){case"addScene":this.dispatchEvent({type:"ToolEvents::addScene",value:e.data});break;case"refreshScene":this.dispatchEvent({type:"ToolEvents::refreshScene",value:e.data});break;case"removeScene":this.dispatchEvent({type:"ToolEvents::removeScene",value:e.data});break;case"setScene":this.dispatchEvent({type:"ToolEvents::setScene",value:e.data});break;case"addCamera":this.dispatchEvent({type:"ToolEvents::addCamera",value:e.data});break;case"removeCamera":this.dispatchEvent({type:"ToolEvents::removeCamera",value:e.data});break;case"addGroup":this.dispatchEvent({type:"ToolEvents::addGroup",value:e.data});break;case"removeGroup":this.dispatchEvent({type:"ToolEvents::removeGroup",value:e.data});break;case"addSpline":this.dispatchEvent({type:"ToolEvents::addSpline",value:e.data});break;case"addRenderer":this.dispatchEvent({type:"ToolEvents::addRenderer",value:e.data})}}messageHandler(e){const t=e.data;if(t.event==="updateObject"){this.onUpdateObject(t.data.uuid,t.data.key,t.data.value);return}else if(t.event==="createTexture"){this.onCreateTexture(t.data.uuid,t.data.key,t.data.value);return}else if(t.event==="requestSize"){t.target==="app"?this.send({event:"requestSize",target:"editor",data:{width:this.width,height:this.height}}):this.scenes.forEach(s=>{s.resize!==void 0&&s.resize(t.data.width,t.data.height)});return}t.target==="app"?this.handleApp(t):this.handleEditor(t)}addRT(e,t=!0,s){const i=new _.WebGLRenderTarget(32,32,s);i.texture.name=e,this.renderTargets.set(e,i),this.renderTargetsResize.set(e,t)}removeRT(e){this.renderTargets.delete(e),this.renderTargetsResize.delete(e)}resize(e,t){const s=this.dpr;this.renderTargets.forEach((n,a)=>{this.renderTargetsResize.get(a)&&n.setSize(e*s,t*s)});const i=!(this.renderer?.domElement instanceof OffscreenCanvas);this.renderer?.setSize(e,t,i)}set dpr(e){this.renderer?.setPixelRatio(_n(1,2,e))}get dpr(){return this.renderer!==void 0?this.renderer?.getPixelRatio():1}get width(){return this.renderer!==void 0?this.renderer.domElement.width/this.dpr:0}get height(){return this.renderer!==void 0?this.renderer.domElement.height/this.dpr:0}}function Op(r){return r.title.search("<")>-1?F.jsx("button",{className:"svg",dangerouslySetInnerHTML:{__html:r.title}}):F.jsx("button",{children:r.title})}const dM=F.jsxs("svg",{className:"closeIcon",width:"14",height:"14",fill:"none",stroke:"#666666",strokeMiterlimit:"10",children:[F.jsx("circle",{cx:"7",cy:"7",r:"6"}),F.jsx("line",{x1:"4",y1:"4",x2:"10",y2:"10"}),F.jsx("line",{x1:"4",y1:"10",x2:"10",y2:"4"})]}),pM=F.jsx("svg",{className:"dragIcon",width:"14",height:"14",fill:"#666666",stroke:"none",children:F.jsx("path",{d:`M10.43,4H3.57C3.26,4,3,4.22,3,4.5v1C3,5.78,3.26,6,3.57,6h6.86C10.74,6,11,5.78,11,5.5v-1\r
18
+ `,m=l.createShader(35633),g=l.createShader(35632),y=l.createProgram();if(!(g&&m&&y))return;l.shaderSource(m,h),l.shaderSource(g,p),l.compileShader(m),l.compileShader(g),l.attachShader(y,m),l.attachShader(y,g),l.linkProgram(y),l.detachShader(y,m),l.detachShader(y,g),l.deleteShader(m),l.deleteShader(g),l.useProgram(y);const _=l.createBuffer();l.bindBuffer(34962,_),l.bufferData(34962,new Float32Array([-1,-1,0,3,-1,0,-1,3,0]),35044);const E=l.getAttribLocation(y,"aPosition");l.vertexAttribPointer(E,3,5126,!1,0,0),l.enableVertexAttribArray(E),l.clearColor(1,1,1,1),l.clear(16384),l.viewport(0,0,1,1),l.drawArrays(4,0,3);const v=new Uint8Array(4);return l.readPixels(0,0,1,1,6408,5121,v),l.deleteProgram(y),l.deleteBuffer(_),v.join("")}(i),n="801621810",a="8016218135",r="80162181161",o=ie?.isIpad?[["a7",r,12],["a8",a,15],["a8x",a,15],["a9",a,15],["a9x",a,15],["a10",a,15],["a10x",a,15],["a12",n,15],["a12x",n,15],["a12z",n,15],["a14",n,15],["a15",n,15],["m1",n,15],["m2",n,15]]:[["a7",r,12],["a8",a,12],["a9",a,15],["a10",a,15],["a11",n,15],["a12",n,15],["a13",n,15],["a14",n,15],["a15",n,15],["a16",n,15],["a17",n,15]];let c;return s==="80162181255"?c=o.filter(([,,l])=>l>=14):(c=o.filter(([,l])=>l===s),c.length||(c=o)),c.map(([l])=>`apple ${l} gpu`)}class At extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}const st=[],Rt=[];function Vi(i,e){if(i===e)return 0;const t=i;i.length>e.length&&(i=e,e=t);let s=i.length,n=e.length;for(;s>0&&i.charCodeAt(~-s)===e.charCodeAt(~-n);)s--,n--;let a,r=0;for(;r<s&&i.charCodeAt(r)===e.charCodeAt(r);)r++;if(s-=r,n-=r,s===0)return n;let o,c,l=0,h=0,p=0;for(;h<s;)Rt[h]=i.charCodeAt(r+h),st[h]=++h;for(;p<n;)for(a=e.charCodeAt(r+p),o=p++,l=p,h=0;h<s;h++)c=a===Rt[h]?o:o+1,o=st[h],l=st[h]=o>l?c>l?l+1:c:c>o?o+1:c;return l}function Gi(i){return i!=null}const Wi=({mobileTiers:i=[0,15,30,60],desktopTiers:e=[0,15,30,60],override:t={},glContext:s,failIfMajorPerformanceCaveat:n=!1,benchmarksURL:a="https://unpkg.com/detect-gpu@5.0.70/dist/benchmarks"}={})=>it(void 0,void 0,void 0,function*(){const r={};if($t)return{tier:0,type:"SSR"};const{isIpad:o=!!ie?.isIpad,isMobile:c=!!ie?.isMobile,screenSize:l=window.screen,loadBenchmarks:h=S=>it(void 0,void 0,void 0,function*(){const w=yield fetch(`${a}/${S}`).then(M=>M.json());if(parseInt(w.shift().split(".")[0],10)<4)throw new At("Detect GPU benchmark data is out of date. Please update to version 4x");return w})}=t;let{renderer:p}=t;const m=(S,w,M,L,A)=>({device:A,fps:L,gpu:M,isMobile:c,tier:S,type:w});let g,y="";if(p)p=Mt(p),g=[p];else{const S=s||function(M,L=!1){const A={alpha:!1,antialias:!1,depth:!1,failIfMajorPerformanceCaveat:L,powerPreference:"high-performance",stencil:!1};M&&delete A.powerPreference;const F=window.document.createElement("canvas"),Q=F.getContext("webgl",A)||F.getContext("experimental-webgl",A);return Q??void 0}(ie?.isSafari12,n);if(!S)return m(0,"WEBGL_UNSUPPORTED");const w=ie?.isFirefox?null:S.getExtension("WEBGL_debug_renderer_info");if(p=w?S.getParameter(w.UNMASKED_RENDERER_WEBGL):S.getParameter(S.RENDERER),!p)return m(1,"FALLBACK");y=p,p=Mt(p),g=function(M,L,A){return L==="apple gpu"?Bi(M,L,A):[L]}(S,p,c)}const _=(yield Promise.all(g.map(function(S){var w;return it(this,void 0,void 0,function*(){const M=(j=>{const q=c?["adreno","apple","mali-t","mali","nvidia","powervr","samsung"]:["intel","apple","amd","radeon","nvidia","geforce","adreno"];for(const ae of q)if(j.includes(ae))return ae})(S);if(!M)return;const L=`${c?"m":"d"}-${M}${o?"-ipad":""}.json`,A=r[L]=(w=r[L])!==null&&w!==void 0?w:h(L);let F;try{F=yield A}catch(j){if(j instanceof At)throw j;return}const Q=function(j){var q;const ae=(j=j.replace(/\([^)]+\)/,"")).match(/\d+/)||j.match(/(\W|^)([A-Za-z]{1,3})(\W|$)/g);return(q=ae?.join("").replace(/\W|amd/g,""))!==null&&q!==void 0?q:""}(S);let re=F.filter(([,j])=>j===Q);re.length||(re=F.filter(([j])=>j.includes(S)));const de=re.length;if(de===0)return;const ve=S.split(/[.,()\[\]/\s]/g).sort().filter((j,q,ae)=>q===0||j!==ae[q-1]).join(" ");let ue,[Ei,,,,Si]=de>1?re.map(j=>[j,Vi(ve,j[2])]).sort(([,j],[,q])=>j-q)[0][0]:re[0],et=Number.MAX_VALUE;const{devicePixelRatio:Ot}=window,xi=l.width*Ot*l.height*Ot;for(const j of Si){const[q,ae]=j,Ti=q*ae,wt=Math.abs(xi-Ti);wt<et&&(et=wt,ue=j)}if(!ue)return;const[,,Oi,wi]=ue;return[et,Oi,Ei,wi]})}))).filter(Gi).sort(([S=Number.MAX_VALUE,w],[M=Number.MAX_VALUE,L])=>S===M?w-L:S-M);if(!_.length){const S=ji.find(w=>p.includes(w));return S?m(0,"BLOCKLISTED",S):m(1,"FALLBACK",`${p} (${y})`)}const[,E,v,C]=_[0];if(E===-1)return m(0,"BLOCKLISTED",v,E,C);const x=c?i:e;let O=0;for(let S=0;S<x.length;S++)E>=x[S]&&(O=S);return m(O,"BENCHMARK",v,E,C)});function Kt(i){let e=0;const t=performance.now();function s(){e++;const n=performance.now();if(n-t>=100){const a=e/((n-t)/1e3),r=Math.round(a/30)*30;i(r)}else requestAnimationFrame(s)}requestAnimationFrame(s)}function Xt(i=!1,e=!1){return new Promise(t=>{Wi().then(s=>{let n=!1;const a=document.createElement("canvas"),r=/^((?!chrome|android).)*safari/i.test(navigator.userAgent);if(n="transferControlToOffscreen"in a,r){const c=navigator.userAgent.match(/version\/(\d+)/i);n=(c?parseInt(c[1]):0)>=17}const o={dpr:devicePixelRatio,fps:30,width:innerWidth,height:innerHeight,mobile:s.isMobile!==void 0?s.isMobile:!1,supportOffScreenCanvas:n,supportWebGPU:!!navigator.gpu,quality:"Low",dev:i,editor:e};s.tier===3?o.quality="High":s.tier===2&&(o.quality="Medium"),Kt(c=>{o.fps=c,t(o)})})})}function he(i,e,t){return Math.min(e,Math.max(i,t))}function $e(i,e,t){return(t-i)/(e-i)}function Me(i,e,t){return i*(1-t)+e*t}function Yi(i,e,t,s,n){return Me(t,s,$e(i,e,n))}function Zi(i,e){const t=i-e;return Math.sqrt(t*t)}function qi(i,e,t,s){return Me(i,e,1-Math.exp(-t*s))}function K(i,e=1){return Number(i.toFixed(e))}function $i(i,e,t,s){return Math.atan2(s-e,t-i)}function Ki(i,e,t,s){return i===e&&t===s}function Xi(i,e,t,s){return 1/(3*e*i*i+2*t*i+s)}function Qi(i,e,t,s,n){return e*(i*i*i)+t*(i*i)+s*i+n}function Ji(i,e,t,s,n){const a=i*i;return e*(a*i)+t*a+s*i+n}function es(i,e,t,s,n){if(i<=0)return 0;if(i>=1)return 1;if(Ki(e,t,s,n))return i;const a=0,r=0,o=e,c=t,l=s,h=n,p=1,m=1,g=p-3*l+3*o-a,y=3*l-6*o+3*a,_=3*o-3*a,E=a,v=m-3*h+3*c-r,C=3*h-6*c+3*r,x=3*c-3*r,O=r;let S=i;for(let w=0;w<5;w++){const M=Qi(S,g,y,_,E);let L=Xi(S,g,y,_);L===1/0&&(L=i),S-=(M-i)*L,S=Math.min(Math.max(S,0),1)}return Ji(S,v,C,x,O)}const He=i=>Math.round(Math.min(1,Math.max(0,i))*255).toString(16).padStart(2,"0");function ts({r:i,g:e,b:t,a:s=1}){const n=`#${He(i)}${He(e)}${He(t)}`;return s<1?`${n}${He(s)}`:n}let _e;function is(){const[i,e]=b.useState(_e);return b.useEffect(()=>{_e||import("@tomorrowevening/theatre-studio").then(t=>{_e=t.default,_e.initialize(),_e.ui.hide(),e(_e)})},[]),i}async function ss(){for(;!document.getElementById("theatrejs-studio-root");)await new Promise(s=>setTimeout(s,100));const i=document.getElementById("theatrejs-studio-root");if(i===null||i.shadowRoot===null)return;const e=i.shadowRoot.getElementById("pointer-root");if(e===null)return;const t=e.children[0];if(t!==null){try{const n=t.children[1].children[1];n.parentElement?.removeChild(n)}catch{}try{const s=t.children[3];s.style.top="0",s.style.right="300px"}catch{}}}function ns(i,e,t,s){s.sheetObject(i,e,{transform:{position:{x:t.position.x,y:t.position.y,z:t.position.z},rotation:{x:t.rotation.x,y:t.rotation.y,z:t.rotation.z},scale:{x:t.scale.x,y:t.scale.y,z:t.scale.z},visible:t.visible}},n=>{const a=n.transform;t.position.copy(a.position),t.rotation.copy(a.rotation),t.scale.copy(a.scale),t.visible=a.visible})}const rs=["allowOverride","alphaHash","alphaTest","alphaToCoverage","blendAlpha","blendColor","blendDst","blendDstAlpha","blendEquation","blendEquationAlpha","blendSrc","blendSrcAlpha","blending","clipIntersection","clipShadows","clipping","clippingPlanes","colorWrite","combine","defaultAttributeValues","defines","depthFunc","depthTest","depthWrite","dithering","extensions","fog","forceSinglePass","fragmentShader","glslVersion","id","index0AttributeName","index1AttributeName","index2AttributeName","index3AttributeName","index4AttributeName","isMaterial","lights","linewidth","name","needsUpdate","polygonOffset","polygonOffsetFactor","polygonOffsetUnits","precision","premultipliedAlpha","shadowSide","side","stencilFail","stencilFunc","stencilFuncMask","stencilRef","stencilWrite","stencilWriteMask","stencilZFail","stencilZPass","toneMapped","transparent","type","uniformsGroups","uniformsNeedUpdate","userData","uuid","version","vertexColors","vertexShader","visible","wireframe","wireframeLinewidth","wireframeLinecap","wireframeLinejoin"];function Dt(i){const e=typeof i;if(i===null||i.isTexture)return"texture";if(e==="boolean")return"boolean";if(e==="number")return"number";if(e==="string")return"string";if(e==="object"){if(i.isColor)return"color";if(i.isVector2)return"vector2";if(i.isVector3)return"vector3";if(i.isVector4)return"vector4";if(i.isMatrix2)return"matrix2";if(i.isMatrix3)return"matrix3";if(i.isMatrix4)return"matrix4";if(i.isEuler)return"euler";if(Array.isArray(i))return"array"}return"object"}function Qt(i){const e=[];for(const s in i){const n=rs.find(o=>o===s),a=s.indexOf("_")===0||s.indexOf("is")===0;if(!(n||a))if(s==="uniforms"){const o=i.uniforms;for(const c in o){const l=o[c].value,h=Dt(l);h==="array"||h==="object"||e.push({name:`uniforms.${c}.value`,type:h,value:l})}}else{const o=Dt(i[s]);e.push({name:s,type:o,value:i[s]})}}return e.filter(s=>s.type!=="array"&&s.type!=="object"&&s.type!=="texture")}function Jt(i){const e={},t={nudgeMultiplier:.01};return i.forEach(s=>{let n=s.value;switch(s.type){case"color":n=P.types.rgba({r:n.r,g:n.g,b:n.b,a:1});break;case"number":n=P.types.number(n,t);break;case"euler":case"vector3":n={x:P.types.number(n.x,t),y:P.types.number(n.y,t),z:P.types.number(n.z,t)};break;case"vector2":n={x:P.types.number(n.x,t),y:P.types.number(n.y,t)};break;case"vector4":n={x:P.types.number(n.x,t),y:P.types.number(n.y,t),z:P.types.number(n.z,t),w:P.types.number(n.w,t)};break;case"matrix2":n={0:P.types.number(n.elements[0],t),1:P.types.number(n.elements[1],t),2:P.types.number(n.elements[2],t),3:P.types.number(n.elements[3],t)};break;case"matrix3":n={0:P.types.number(n.elements[0],t),1:P.types.number(n.elements[1],t),2:P.types.number(n.elements[2],t),3:P.types.number(n.elements[3],t),4:P.types.number(n.elements[4],t),5:P.types.number(n.elements[5],t),6:P.types.number(n.elements[6],t),7:P.types.number(n.elements[7],t),8:P.types.number(n.elements[8],t)};break;case"matrix4":n={0:P.types.number(n.elements[0],t),1:P.types.number(n.elements[1],t),2:P.types.number(n.elements[2],t),3:P.types.number(n.elements[3],t),4:P.types.number(n.elements[4],t),5:P.types.number(n.elements[5],t),6:P.types.number(n.elements[6],t),7:P.types.number(n.elements[7],t),8:P.types.number(n.elements[8],t),9:P.types.number(n.elements[9],t),10:P.types.number(n.elements[10],t),11:P.types.number(n.elements[11],t),12:P.types.number(n.elements[12],t),13:P.types.number(n.elements[13],t),14:P.types.number(n.elements[14],t),15:P.types.number(n.elements[15],t)};break}if(s.name.includes(".")){const a=s.name.split(".");let r=e;for(let o=0;o<a.length-1;o++){const c=a[o];r[c]||(r[c]={}),r=r[c]}r[a[a.length-1]]=n}else e[s.name]=n}),e}function ei(i,e,t){e.forEach(s=>{if(i[s.name]!==void 0)switch(s.type){case"boolean":case"number":i[s.name]=t.material[s.name];break;case"color":case"euler":case"matrix2":case"matrix3":case"matrix4":case"vector2":case"vector3":case"vector4":i[s.name].copy(t.material[s.name]);break}})}function as(i,e,t,s){if(!t.isMaterial)return;const n=Qt(t),a=Jt(n);s.sheetObject(i,e,{material:a},r=>{ei(t,n,r)})}const Xe=new d.BufferGeometry;Xe.setAttribute("position",new d.Float32BufferAttribute([-.5,-.5,0,1.5,-.5,0,-.5,1.5,0],3));Xe.setAttribute("normal",new d.Float32BufferAttribute([0,0,1,0,0,1],3));Xe.setAttribute("uv",new d.Float32BufferAttribute([0,0,2,0,0,2],2));const os=new d.OrthographicCamera(-.5,.5,.5,-.5,0,100),vt=i=>{i?.dispose()},yt=i=>{if(i)if(Array.isArray(i))i.forEach(e=>yt(e));else{for(const e in i){const t=i[e];t!==null&&t instanceof d.Texture&&vt(t)}if(i.isShaderMaterial===!0){const e=i;for(const t in e.uniforms){const s=e.uniforms[t];s.value!==null&&s.value instanceof d.Texture&&vt(s.value)}}i.dispose()}},ne=i=>{if(i){for(;i.children.length>0;){const e=i.children[0];e.type==="Audio"?(e.pause(),e.parent&&e.parent.remove(e)):ne(e)}if(i.parent&&i.parent.remove(i),i.isMesh){const e=i;e.geometry?.dispose(),yt(e.material)}i.dispose!==void 0&&i.dispose()}};exports.totalThreeObjects=0;const Ue=()=>{exports.totalThreeObjects=0},we=i=>{if(!i)return;let e=i.name.replaceAll(" ","").replaceAll("/",".");if(e.length===0&&(e=`obj_${exports.totalThreeObjects}`,exports.totalThreeObjects++),i.parent!==null&&i.parent.uuid.length>0&&(e=`${i.parent.uuid}.${e}`),i.uuid=e,i.isMesh!==void 0){const t=i;if(Array.isArray(t.material))t.material.forEach((s,n)=>{s.uuid=`${e}.material.${n}`});else{const s=t.material;s.uuid=`${e}.material`}}i.children.forEach(t=>we(t))};class oe{static renderer;static canvas;static context=null;static scene=null;static camera=null;static material=null;static inited=!1;static width=100;static height=100;static init(){this.inited||(this.canvas=document.createElement("canvas"),this.canvas.width=this.width,this.canvas.height=this.height,this.context=this.canvas.getContext("2d"),this.inited=!0)}static renderToBlob(e){this.init();const t=e.repeat.clone(),s=e.offset.clone();if(e.repeat.set(1,1),e.offset.set(0,0),this.context!==null){this.context.clearRect(0,0,this.width,this.height);const n=e.image;if(n!=null&&n.width>0){this.canvas.title=e.sourceFile;const a=this.canvas.width/n.width,r=this.renderToCanvas(e);this.context.drawImage(r,0,0,n.width*a,n.height*a)}}return e.repeat.copy(t),e.offset.copy(s),this.canvas.toDataURL("image/png")}static renderToCanvas(e){if(this.material===null){this.camera=new d.OrthographicCamera(-.5,.5,.5,-.5,0,100),this.scene=new d.Scene,this.material=new d.MeshBasicMaterial;const t=new d.BufferGeometry;t.setAttribute("position",new d.Float32BufferAttribute([-.5,-.5,0,1.5,-.5,0,-.5,1.5,0],3)),t.setAttribute("normal",new d.Float32BufferAttribute([0,0,1,0,0,1],3)),t.setAttribute("uv",new d.Float32BufferAttribute([0,0,2,0,0,2],2));const s=new d.Mesh(t,this.material);this.scene.add(s)}if(e.isRenderTargetTexture)this.material.map=e,this.renderer.render(this.scene,this.camera);else{const t=this.renderer.outputColorSpace,s=e.colorSpace;this.renderer.outputColorSpace=d.LinearSRGBColorSpace,e.colorSpace=d.LinearSRGBColorSpace,this.material.map=e,this.renderer.render(this.scene,this.camera),this.renderer.outputColorSpace=t,e.colorSpace=s}return this.renderer.domElement}}function ls(i){return new Promise(e=>{const t=new d.ObjectLoader;t.parseAsync(i.scene).then(s=>{const n=new d.AnimationMixer(s);if(i.animations.length>0){const r=i.animations.map(c=>d.AnimationClip.parse(c));n.clipAction(r[0]).play(),n.getRoot().animations=i.animations,n.getRoot().mixer=n}const a=[];i.cameras&&i.cameras.length>0&&i.cameras.forEach(r=>{const o=t.parse(r);a.push(o)}),e({animations:i.animations,model:s,mixer:n,cameras:a})})})}const cs=(i,e,t,s)=>{i.setRenderTarget(s),i.clear(),i.render(e,t)};function ti(i,e,t,s){i.applyMatrix4(new d.Matrix4().makeTranslation(e,-t,-s))}function hs(i){i.computeBoundingBox();const e=i.boundingBox,t=(e.max.x-e.min.x)/2,s=(e.max.y-e.min.y)/2;ti(i,t,s,0)}function ds(i,e,t){i.left=e/-2,i.right=e/2,i.top=t/2,i.bottom=t/-2,i.position.x=e/2,i.position.y=t/-2,i.updateProjectionMatrix()}function us(i,e,t){const s=1.7777777777777777,n=e/t;let a=e,r=t;n>s?a=t*s:r=e/s,i.left=a/-2,i.right=a/2,i.top=r/2,i.bottom=r/-2,i.updateProjectionMatrix()}function ps(){let e="transferControlToOffscreen"in document.createElement("canvas");if(/^((?!chrome|android).)*safari/i.test(navigator.userAgent)){const s=navigator.userAgent.match(/version\/(\d+)/i);e=(s?parseInt(s[1]):0)>=17}return e}function ms(i,e,t=!0,s=!1){i.renderOrder=-e;const n=i.material;Array.isArray(n)?n.forEach(a=>{a.colorWrite=t,a.depthWrite=s,a.stencilWrite=!0,a.stencilRef=e,a.stencilFunc=d.AlwaysStencilFunc,a.stencilFail=d.ReplaceStencilOp,a.stencilZFail=d.ReplaceStencilOp,a.stencilZPass=d.ReplaceStencilOp}):(n.colorWrite=t,n.depthWrite=s,n.stencilWrite=!0,n.stencilRef=e,n.stencilFunc=d.AlwaysStencilFunc,n.stencilFail=d.ReplaceStencilOp,n.stencilZFail=d.ReplaceStencilOp,n.stencilZPass=d.ReplaceStencilOp)}function fs(i,e,t=!1){const s=i.material;Array.isArray(s)?s.forEach(n=>{n.stencilWrite=!0,n.stencilRef=e,n.stencilFunc=t?d.NotEqualStencilFunc:d.EqualStencilFunc,n.stencilFail=d.KeepStencilOp,n.stencilZFail=d.KeepStencilOp,n.stencilZPass=d.KeepStencilOp}):(s.stencilWrite=!0,s.stencilRef=e,s.stencilFunc=t?d.NotEqualStencilFunc:d.EqualStencilFunc,s.stencilFail=d.KeepStencilOp,s.stencilZFail=d.KeepStencilOp,s.stencilZPass=d.KeepStencilOp)}function gs(i){i.blending=d.NormalBlending,i.blendEquation=d.AddEquation,i.blendSrc=d.SrcAlphaFactor,i.blendDst=d.OneMinusSrcAlphaFactor,i.needsUpdate=!0}function vs(i){i.blending=d.CustomBlending,i.blendEquation=d.AddEquation,i.blendSrc=d.SrcAlphaFactor,i.blendDst=d.OneFactor,i.needsUpdate=!0}function _s(i){i.blending=d.CustomBlending,i.blendEquation=d.AddEquation,i.blendSrc=d.DstColorFactor,i.blendDst=d.OneMinusSrcAlphaFactor,i.needsUpdate=!0}function Cs(i){i.blending=d.CustomBlending,i.blendEquation=d.AddEquation,i.blendSrc=d.OneMinusDstColorFactor,i.blendDst=d.OneFactor,i.needsUpdate=!0}let _t=[];function ii(i,e,t=!0){oe.renderer=e.renderer;const s=[];s.push({type:"boolean",prop:"Enabled",value:i.enabled});let n=(r,o)=>{console.log("Default Handle Pass:",r,o)};if(i.name==="EffectPass")i.effects.forEach(r=>{r.uniforms.size>0&&r.uniforms.forEach((o,c)=>{if(c==="map")return;const l=`${r.name.replace("Effect","")} ${c}`;if(o.value===null&&t)s.push({prop:c,title:l,type:"image",value:{offset:[0,0],repeat:[1,1],src:""}});else if(o.value.isTexture&&t){const h=o.value,p=oe.renderToBlob(h);s.push({prop:c,title:l,type:"image",value:{offset:[h.offset.x,h.offset.y],repeat:[h.repeat.x,h.repeat.y],src:p}})}else typeof o.value=="number"?s.push({prop:c,title:l,type:"number",value:o.value,step:.01}):typeof o.value=="string"?s.push({prop:c,title:l,type:"string",value:o.value}):typeof o.value=="boolean"&&s.push({prop:c,title:l,type:"boolean",value:o.value})})}),n=(r,o)=>{i.effects.forEach(c=>{c.uniforms.size>0&&c.uniforms.forEach((l,h)=>{h===r&&(l.value=o)})})};else if(i.name==="ShaderPass"){const r=i.fullscreenMaterial;for(const o in r.uniforms){if(o==="inputBuffer"||o==="map")continue;const c=r.uniforms[o],l=`${r.name.replace("Material","")} ${o}`;if(c.value===null&&t)s.push({title:l,prop:o,type:"image",value:{offset:[0,0],repeat:[1,1],src:""}});else if(c.value.isTexture&&t){const h=c.value,p=oe.renderToBlob(h);s.push({title:l,prop:o,type:"image",value:{offset:[h.offset.x,h.offset.y],repeat:[h.repeat.x,h.repeat.y],src:p}})}else typeof c.value=="number"?s.push({title:l,prop:o,type:"number",value:c.value,step:.01}):typeof c.value=="string"?s.push({title:l,prop:o,type:"string",value:c.value}):typeof c.value=="boolean"&&s.push({title:l,prop:o,type:"boolean",value:c.value})}n=(o,c)=>{const l=r.uniforms[o];l.value=c}}else return;const a=`${i.name}: ${i.scene.name}`;e.addGroup({title:a,items:s,onUpdate:(r,o)=>{r==="Enabled"?i.enabled=o:n(r,o)}}),_t.push(a)}function ys(i,e){i.passes.forEach(t=>{ii(t,e)})}function bs(i){_t.forEach(e=>{i.removeGroup(e)}),_t=[]}function Es(i,e,t,s=1024){return new Promise(n=>{const a=e.aspect,r=e.fov,o=e.rotation.clone(),c=t.outputBuffer;e.aspect=1,e.fov=90,e.updateProjectionMatrix();const l=new d.WebGLRenderTarget(s,s,{format:d.RGBAFormat,depthBuffer:!0,stencilBuffer:!1});t.outputBuffer=l,Ce(i,l,e,"nx",t,s).then(()=>{Ce(i,l,e,"ny",t,s).then(()=>{Ce(i,l,e,"nz",t,s).then(()=>{Ce(i,l,e,"px",t,s).then(()=>{Ce(i,l,e,"py",t,s).then(()=>{Ce(i,l,e,"pz",t,s).then(()=>{e.aspect=a,e.fov=r,e.rotation.copy(o),e.updateMatrixWorld(),e.updateProjectionMatrix(),t.outputBuffer=c,l.dispose(),n()})})})})})})})}function Ce(i,e,t,s,n,a){return new Promise(r=>{const o=Math.PI/2;switch(s){case"nx":t.rotation.set(0,-o,0);break;case"ny":t.rotation.set(-o,0,Math.PI);break;case"nz":t.rotation.set(0,0,0);break;case"px":t.rotation.set(0,o,0);break;case"py":t.rotation.set(o,0,Math.PI);break;case"pz":t.rotation.set(0,Math.PI,0);break}t.updateMatrixWorld(),n.render();const c=new Uint8Array(a*a*4);i.readRenderTargetPixels(e,0,0,a,a,c);const l=document.createElement("canvas");l.width=l.height=a;const h=l.getContext("2d"),p=h.createImageData(a,a);p.data.set(c),h.putImageData(p,0,0);const m=document.createElement("canvas");m.width=m.height=a;const g=m.getContext("2d");g.translate(0,a),g.scale(1,-1),g.drawImage(l,0,0);const y=m.toDataURL("image/png"),_=document.createElement("a");_.href=y,_.download=`${t.name}_${s}.png`,document.body.appendChild(_),_.click(),_.remove(),r()})}const ye=bt(["ctrlKey","metaKey","shiftKey","button","pointerId","pointerType","clientX","clientY","pageX","pageY"]),Ss=bt(["clientX","clientY","deltaX","deltaY","deltaMode"]),xs=bt(["ctrlKey","metaKey","shiftKey","keyCode"]);function Os(i,e){i.preventDefault(),Ss(i,e)}function ws(i){i.preventDefault()}function Ts(i,e,t){for(const s of e)t[s]=i[s]}function bt(i){return function(t,s){const n={type:t.type};Ts(t,i,n),s(n)}}function nt(i,e){const t=[],s={type:i.type,touches:t};for(let n=0;n<i.touches.length;++n){const a=i.touches[n];t.push({pageX:a.pageX,pageY:a.pageY})}e(s)}const Ms={37:!0,38:!0,39:!0,40:!0};function As(i,e){const{keyCode:t}=i;Ms[t]&&(i.preventDefault(),xs(i,e))}const Rs={contextmenu:ws,mousedown:ye,mousemove:ye,mouseup:ye,pointerdown:ye,pointermove:ye,pointerup:ye,touchstart:nt,touchmove:nt,touchend:nt,wheel:Os,keydown:As};let Ds=0;class Ps{id;worker;constructor(e,t,s){this.id=Ds++,this.worker=t;const n=r=>{this.worker.postMessage({type:"event",id:this.id,data:r})};t.postMessage({type:"makeProxy",id:this.id});for(const[r,o]of Object.entries(s))e.addEventListener(r,c=>{o(c,n)});function a(){n({type:"resize",left:0,top:0,width:innerWidth,height:innerHeight})}window.addEventListener("resize",a),a()}}class si extends d.EventDispatcher{style={};left=0;top=0;width=0;height=0;ownerDocument=void 0;constructor(){super(),this.ownerDocument=this}get clientWidth(){return this.width}set clientWidth(e){this.width=e}get clientHeight(){return this.height}set clientHeight(e){this.height=e}setPointerCapture(){}releasePointerCapture(){}getBoundingClientRect(){return{x:this.left,y:this.top,left:this.left,top:this.top,width:this.width,height:this.height,right:this.left+this.width,bottom:this.top+this.height,toJSON:()=>({})}}handleEvent(e){if(e.type==="size"){this.left=e.left,this.top=e.top,this.width=e.width,this.height=e.height;return}e.preventDefault=Fe,e.stopPropagation=Fe,this.dispatchEvent(e)}focus(){}getRootNode(){return this}}class Is{targets={};constructor(){this.handleEvent=this.handleEvent.bind(this)}makeProxy(e){const{id:t}=e,s=new si;this.targets[t]=s}getProxy(e){return this.targets[e]}handleEvent(e){this.targets[e.id]?.handleEvent(e.data)}}class Ls{assets={audio:new Map,image:new Map,json:new Map,model:new Map,video:new Map};components=new Map;settings={dpr:1,fps:30,width:0,height:0,mobile:!1,supportOffScreenCanvas:!1,supportWebGPU:!1,quality:"Low",dev:!1,editor:!1};onUpdateCallback;playing=!1;rafID=-1;dispose(){this.pause(),this.components.forEach(e=>e.dispose()),this.components.clear()}detectSettings(e=!1,t=!1){return new Promise(s=>{Xt(e,t).then(n=>{this.settings=n,s()})})}update(){}draw(){}play=()=>{this.playing||(this.playing=!0,this.onUpdate())};pause=()=>{this.playing&&(this.playing=!1,cancelAnimationFrame(this.rafID),this.rafID=-1)};onUpdate=()=>{this.update(),this.isApp&&this.draw(),this.onUpdateCallback&&this.onUpdateCallback(),this.rafID=requestAnimationFrame(this.onUpdate)};addComponent(e,t){this.components.set(e,t)}get debugEnabled(){return this.settings.dev}get isApp(){return!this.editor}set isApp(e){this.editor=!e}get editor(){return this.settings.editor}set editor(e){this.settings.editor=e}}class Et{name;_debug=!1;_editor=!1;broadcastChannel;constructor(e,t=!1,s=!1){this.name=e,this._debug=t,this._editor=s,t&&(this.broadcastChannel=new BroadcastChannel(e),this.broadcastChannel.addEventListener("message",this.messageHandler.bind(this)))}dispose(){this.broadcastChannel?.removeEventListener("message",this.messageHandler.bind(this)),this.broadcastChannel?.close()}get debug(){return this._debug}get editor(){return this._editor}send(e){if(this.editor&&e.target==="app"||!this.editor&&e.target==="editor")try{this.broadcastChannel?.postMessage(e)}catch(s){console.log("Hermes - Error sending message:"),console.log(s),console.log(e)}}messageHandler(e){const t=e.data;t.target==="app"?this.handleApp(t):this.handleEditor(t)}handleApp(e){}handleEditor(e){}}function Us(i,e,t,s,n){const a=1-i;return a*a*a*e+3*a*a*i*t+3*a*i*i*s+i*i*i*n}function Ns(i,e,t){if(i.type!=="bezier"||i.handles.length!==4)throw new Error("Invalid keyframe data for Bézier interpolation.");const[s,n]=i.handles,a=(t-i.position)/(e.position-i.position);return Us(a,i.value,i.value+s,e.value+n,e.value)}class ks extends Et{project;sheets=new Map;sheetObjects=new Map;sheetObjectCBs=new Map;sheetObjectUnsubscribe=new Map;activeSheet;studio=void 0;constructor(e=!1,t=!1){super("RemoteTheatre",e,t)}dispose(){this.project=void 0,this.sheets=new Map,this.sheetObjects=new Map,this.sheetObjectCBs=new Map,this.sheetObjectUnsubscribe=new Map}loadProject(e,t){return this.project=P.getProject(e,{state:t}),new Promise((s,n)=>{this.project?.ready.then(()=>{if(t){const a=t.sheetsById;for(const r in a)this.sheet(r)}s()}).catch(()=>n())})}getSheetInstance(e,t){return t!==void 0?`${e}-${t}`:e}sheet(e,t){if(this.project===void 0){console.error("Theatre Project hasn't been created yet.");return}const s=this.getSheetInstance(e,t);let n=this.sheets.get(s);return n!==void 0||(n=this.project?.sheet(e,t),this.sheets.set(s,n)),n}playSheet(e,t,s){return new Promise(n=>{this.sheet(e,s)?.sequence.play(t).then(a=>n(a)),this.send({event:"playSheet",target:"editor",data:{sheet:e,instance:s,value:t}})})}pauseSheet(e,t){this.sheet(e,t)?.sequence.pause(),this.send({event:"pauseSheet",target:"editor",data:{sheet:e,instance:t}})}clearSheetObjects(e){this.sheetObjects.forEach((t,s)=>{s.search(`${e}_`)>-1&&this.unsubscribe(t)})}sheetObject(e,t,s,n,a){if(this.project===void 0){console.error("Theatre Project hasn't been created yet.");return}const r=this.sheet(e,a);if(r===void 0)return;const c=`${this.getSheetInstance(e,a)}_${t}`;let l=this.sheetObjects.get(c),h=s;l!==void 0&&(h={...s,...l.value}),l=r.object(t,h,{reconfigure:!0}),this.sheetObjects.set(c,l),this.sheetObjectCBs.set(c,n!==void 0?n:Fe);function p(g,y,_){if(typeof _=="object")if(qt(_))g[y]={r:_.r,g:_.g,b:_.b,a:_.a};else for(const E in _){const v=_[E];typeof v=="object"&&p(_,E,v)}}const m=l.onValuesChange(g=>{const y=this.sheetObjectCBs.get(c);if(this.editor){for(const _ in g){const E=g[_];typeof E=="object"&&p(g,_,E)}this.send({event:"updateSheetObject",target:"app",data:{sheet:e,sheetObject:c,values:g}}),y&&y(g)}else y&&y(g)});return this.sheetObjectUnsubscribe.set(c,m),l}getSheetObjectKeyframes(e,t,s){const n=this.sheet(e);if(n===void 0)return[];const a=`${e}_${t}`,r=this.sheetObjects.get(a);return r===void 0?[]:n.sequence.__experimental_getKeyframes(r.props[s])}getSheetObjectVectors(e,t){const s=this.sheet(e);if(s===void 0)return[];const n=`${e}_${t}`,a=this.sheetObjects.get(n);if(a===void 0)return[];const r=[],o=s.sequence.__experimental_getKeyframes(a.props.x),c=s.sequence.__experimental_getKeyframes(a.props.y),l=s.sequence.__experimental_getKeyframes(a.props.z),h=new Set;return o.forEach(m=>h.add(m.position)),c.forEach(m=>h.add(m.position)),l.forEach(m=>h.add(m.position)),Array.from(h).sort((m,g)=>m-g).forEach(m=>{const g=(y,_)=>{const E=y.find((x,O)=>x.position<=_&&(y[O+1]?.position||1/0)>_),v=y.find(x=>x.position>_);if(!E)return v?.value||0;if(!v||E.position===_)return E.value;if(E.type==="bezier")return Ns(E,v,_);const C=(_-E.position)/(v.position-E.position);return E.value+C*(v.value-E.value)};r.push({position:m,x:g(o,m),y:g(c,m),z:g(l,m)})}),r}update(e){}unsubscribe(e){if(this.project===void 0){console.error("Theatre Project hasn't been created yet.");return}const t=e.address.sheetId,s=e.address.objectKey;this.sheets.get(t)?.detachObject(s);const a=`${t}_${s}`,r=this.sheetObjectUnsubscribe.get(a);r!==void 0&&(this.sheetObjects.delete(a),this.sheetObjectCBs.delete(a),this.sheetObjectUnsubscribe.delete(a),r())}handleApp(e){let t;switch(e.event){case"setSheet":t=this.sheets.get(e.data.sheet),t!==void 0?this.studio?.setSelection([t]):console.log(`Hermes - Can't set Sheet: ${e.data.sheet}`,t);break;case"setSheetObject":t=this.sheetObjects.get(`${e.data.sheet}_${e.data.key}`),t!==void 0?this.studio?.setSelection([t]):console.log(`Hermes - Can't set Sheet Object: ${e.data.sheet}, ${e.data.key}: ${e.data.sheet}_${e.data.key}`,t);break;case"updateSheetObject":t=this.sheets.get(e.data.sheet),t!==void 0&&t.sequence.pause(),t=this.sheetObjectCBs.get(e.data.sheetObject),t!==void 0?t(e.data.values):console.log(`Hermes - Can't update Sheet Object: ${e.data.sheetObject}, ${e.data.sheet}`,t);break;case"updateTimeline":t=this.sheets.get(e.data.sheet),t!==void 0?t.sequence.position=e.data.position:console.log(`Hermes - Can't update sheet position: ${e.data.sheet}, ${e.data.position}`);break}}handleEditor(e){switch(e.event){case"playSheet":this.sheet(e.data.sheet,e.data.instance)?.sequence.play(e.data.value);break;case"pauseSheet":this.sheet(e.data.sheet,e.data.instance)?.sequence.pause();break}}getSheetNames(){const e=[];return this.sheets.forEach((t,s)=>{e.push(s)}),e}handleEditorApp(){if(this.editor){this.studio?.ui.restore(),this.studio?.onSelectionChange(n=>{n.length<1||n.forEach(a=>{let r=a.address.sheetId,o="setSheet",c={};switch(a.type){case"Theatre_Sheet_PublicAPI":o="setSheet",c={sheet:a.address.sheetId},this.activeSheet=this.sheets.get(a.address.sheetId);break;case"Theatre_SheetObject_PublicAPI":o="setSheetObject",r+=`_${a.address.objectKey}`,c={id:r,sheet:a.address.sheetId,key:a.address.objectKey},this.activeSheet=this.sheets.get(a.address.sheetId);break}this.send({event:o,target:"app",data:c})})});let e=-1;const t=()=>{if(this.activeSheet!==void 0&&e!==this.activeSheet.sequence.position){e=this.activeSheet.sequence.position;const n=this.activeSheet;this.send({event:"updateTimeline",target:"app",data:{position:e,sheet:n.address.sheetId}})}},s=()=>{t(),requestAnimationFrame(s)};t(),s()}else this.studio?.ui.hide()}}function Fs(i){if(i.name==="cameras")return"camera";if(i.name==="interactive")return"interactive";if(i.name==="lights")return"light";if(i.name==="ui")return"ui";if(i.name==="utils")return"utils";const e=i.type;return e.search("Helper")>-1?"icon_utils":e.search("Camera")>-1?"camera":e.search("Light")>-1?"light":"obj3D"}function le(i){const e={name:i.name,type:i.type,uuid:i.uuid,children:[]};return i.children.forEach(t=>{e.children.push(le(t))}),e}function zs(i){const e={};for(const t in i){const s=i[t].value;e[t]={value:s},s===null?e[t].value={src:"",offset:[0,0],repeat:[1,1]}:s!==void 0&&s.isTexture&&(e[t].value={src:s.image.src,offset:[s.offset.x,s.offset.y],repeat:[s.repeat.x,s.repeat.y]})}return e}function Hs(i){switch(i){case"blendSrcAlpha":case"blendDstAlpha":case"blendEquationAlpha":case"clippingPlanes":case"shadowSide":case"precision":return!0}return!1}function be(i){const e={};for(const t in i){if(t.substring(0,1)==="_"||t.substring(0,2)==="is"||Hs(t))continue;const s=typeof i[t],n=i[t];switch(s){case"boolean":case"number":case"string":e[t]=n;break;case"object":n!==null?(e[t]=n,n.isTexture?e[t]={src:oe.renderToBlob(n),offset:[n.offset.x,n.offset.y],repeat:[n.repeat.x,n.repeat.y]}:t==="uniforms"&&(e[t]=zs(e[t]))):t==="glslVersion"?e[t]="":e[t]={src:"",offset:[0,0],repeat:[1,1]};break}}return i.anisotropy!==void 0&&(e.anisotropy=i.anisotropy),i.clearcoat!==void 0&&(e.clearcoat=i.clearcoat),i.iridescence!==void 0&&(e.iridescence=i.iridescence),i.dispersion!==void 0&&(e.dispersion=i.dispersion),i.sheen!==void 0&&(e.sheen=i.sheen),i.transmission!==void 0&&(e.transmission=i.transmission),i.transmission!==void 0&&(e.transmission=i.transmission),e}function rt(i){i.updateMatrix();const e={name:i.name,type:i.type,uuid:i.uuid,visible:i.visible,matrix:i.matrix.elements,animations:[],material:void 0,perspectiveCameraInfo:void 0,orthographicCameraInfo:void 0,lightInfo:void 0,children:[]};i.animations.forEach(s=>{e.animations.push({name:s.name,duration:s.duration,blendMode:s.blendMode})});const t=i.type.toLowerCase();if(t.search("mesh")>-1){const s=i;if(Array.isArray(s.material)){const n=[];s.material.forEach(a=>{n.push(be(a))}),e.material=n}else e.material=be(s.material)}else if(t.search("points")>-1){const s=i;if(Array.isArray(s.material)){const n=[];s.material.forEach(a=>{n.push(be(a))}),e.material=n}else e.material=be(s.material)}else if(t.search("line")>-1){const s=i;if(Array.isArray(s.material)){const n=[];s.material.forEach(a=>{n.push(be(a))}),e.material=n}else e.material=be(s.material)}else t.search("camera")>-1?i.type==="PerspectiveCamera"?e.perspectiveCameraInfo={fov:i.fov,zoom:i.zoom,near:i.near,far:i.far,focus:i.focus,aspect:i.aspect,filmGauge:i.filmGauge,filmOffset:i.filmOffset}:i.type==="OrthographicCamera"&&(e.orthographicCameraInfo={zoom:i.zoom,near:i.near,far:i.far,left:i.left,right:i.right,top:i.top,bottom:i.bottom}):t.search("light")>-1&&(e.lightInfo={color:i.color,intensity:i.intensity,decay:i.decay,distance:i.distance,angle:i.angle,penumbra:i.penumbra,groundColor:i.groundColor,width:i.width,height:i.height});return e}function js(i,e){const t=e.split(".");switch(t.length){case 1:return i[t[0]];case 2:return i[t[0]][t[1]];case 3:return i[t[0]][t[1]][t[2]];case 4:return i[t[0]][t[1]][t[2]][t[3]];case 5:return i[t[0]][t[1]][t[2]][t[3]][t[4]];case 6:return i[t[0]][t[1]][t[2]][t[3]][t[4]][t[5]]}}function Bs(i,e){for(const t in e)i[t]=e[t]}function B(i,e,t){if(i===void 0){console.log(`Hermes - Can't set props: ${e}`,t);return}const s=e.split("."),n=s.length;if(typeof t!="object")switch(n){case 1:i[s[0]]=t;break;case 2:i[s[0]][s[1]]=t;break;case 3:i[s[0]][s[1]][s[2]]=t;break;case 4:i[s[0]][s[1]][s[2]][s[3]]=t;break;case 5:i[s[0]][s[1]][s[2]][s[3]][s[4]]=t;break}else{let r;switch(n){case 1:r=i[s[0]];break;case 2:r=i[s[0]][s[1]];break;case 3:r=i[s[0]][s[1]][s[2]];break;case 4:r=i[s[0]][s[1]][s[2]][s[3]];break;case 5:r=i[s[0]][s[1]][s[2]][s[3]][s[4]];break}r!=null?Bs(r,t):console.log(`Hermes - Can't set props because target isn't found: ${e}`,t)}}function ni(i){return new Promise((e,t)=>{const s=new Image;s.onload=()=>{const n=new d.Texture(s);n.wrapS=d.RepeatWrapping,n.wrapT=d.RepeatWrapping,n.needsUpdate=!0,e(n)},s.onerror=t,s.src=i})}var I=(i=>(i.CUSTOM="ToolEvents::custom",i.SELECT_DROPDOWN="ToolEvents::selectDropdown",i.DRAG_UPDATE="ToolEvents::dragUpdate",i.ADD_SCENE="ToolEvents::addScene",i.REFRESH_SCENE="ToolEvents::refreshScene",i.REMOVE_SCENE="ToolEvents::removeScene",i.SET_SCENE="ToolEvents::setScene",i.SET_OBJECT="ToolEvents::setObject",i.CLEAR_OBJECT="ToolEvents::clearObject",i.ADD_CAMERA="ToolEvents::addCamera",i.REMOVE_CAMERA="ToolEvents::removeCamera",i.ADD_GROUP="ToolEvents::addGroup",i.REMOVE_GROUP="ToolEvents::removeGroup",i.ADD_SPLINE="ToolEvents::addSpline",i.ADD_RENDERER="ToolEvents::addRenderer",i.UPDATE_RENDERER="ToolEvents::updateRenderer",i))(I||{});class Vs extends Et{name;canvas=null;inputElement=null;scene=void 0;scenes=new Map;renderer=void 0;renderTargets=new Map;renderTargetsResize=new Map;groups=new Map;_listeners={};constructor(e,t=!1,s=!1){super("RemoteThree",t,s),this.name=e}dispose(){this.scenes.forEach(e=>{ne(e)}),this.scenes.clear(),this.scene&&ne(this.scene),this.renderTargets.forEach(e=>{e.dispose()}),this.renderTargets.clear(),this.renderer?.dispose()}addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const s=this._listeners;s[e]===void 0&&(s[e]=[]),s[e].indexOf(t)===-1&&s[e].push(t)}hasEventListener(e,t){const s=this._listeners;return s===void 0?!1:s[e]!==void 0&&s[e].indexOf(t)!==-1}removeEventListener(e,t){const s=this._listeners;if(s===void 0)return;const n=s[e];if(n!==void 0){const a=n.indexOf(t);a!==-1&&n.splice(a,1)}}dispatchEvent(e){const t=this._listeners;if(t===void 0)return;const s=t[e.type];if(s!==void 0){const n={...e,target:this},a=s.slice(0);for(let r=0,o=a.length;r<o;r++)a[r].call(this,n)}}getObjectByUUID(e){const t=e.split(".")[0],s=this.scenes.get(t);if(s!==void 0)return s.getObjectByProperty("uuid",e)}getObject(e){if(!this.debug)return;this.renderer!==void 0&&(oe.renderer=this.renderer);const t=this.getObjectByUUID(e);t&&this.setObject(t)}setObject(e){this.renderer!==void 0&&(oe.renderer=this.renderer);const t=rt(e);this.dispatchEvent({type:"ToolEvents::setObject",value:t})}requestMethod(e,t,s,n){const a=this.getObjectByUUID(e);if(a)try{n!==void 0?js(a,n)[t](s):a[t](s)}catch(r){console.log("Hermes - Error requesting method:",e,t,s),console.log(r)}}updateObject(e,t,s){this.send({event:"updateObject",target:"app",data:{uuid:e,key:t,value:s}})}createTexture(e,t,s){this.send({event:"createTexture",target:"app",data:{uuid:e,key:t,value:s}})}onUpdateObject(e,t,s){const n=this.getObjectByUUID(e);n&&B(n,t,s)}onCreateTexture(e,t,s){const n=this.getObjectByUUID(e);if(n){const a=r=>{const o=t.split(".");switch(o.length){case 1:n[o[0]]=r;break;case 2:n[o[0]][o[1]]=r;break;case 3:n[o[0]][o[1]][o[2]]=r;break;case 4:n[o[0]][o[1]][o[2]][o[3]]=r;break;case 5:n[o[0]][o[1]][o[2]][o[3]][o[4]]=r;break}n.material.needsUpdate=!0};s.src.length>0?ni(s.src).then(r=>{r.offset.set(s.offset[0],s.offset[1]),r.repeat.set(s.repeat[0],s.repeat[1]),a(r)}):a(null)}}addGroup(e){this.groups.get(e.title)===void 0&&(this.groups.set(e.title,{title:e.title,onUpdate:e.onUpdate}),this.send({event:"addGroup",target:"editor",data:JSON.stringify(e)}))}removeGroup(e){this.groups.get(e)!==void 0&&(this.groups.delete(e),this.send({event:"removeGroup",target:"editor",data:e}))}updateGroup(e,t,s){this.send({event:"updateGroup",target:"app",data:JSON.stringify({group:e,prop:t,value:s})})}addSplineCurve(e){setTimeout(()=>{this.send({event:"addSpline",target:"editor",data:JSON.stringify(e.toJSON())})},1)}addSplineObject(e){setTimeout(()=>{this.send({event:"addSpline",target:"editor",data:JSON.stringify(e)})},1)}setRenderer(e,t=null){if(this.renderer=e,this.canvas=e.domElement,this.inputElement=t!==null?t:this.canvas,!this.debug)return;const s=`#${e.getClearColor(new d.Color).getHexString()}`;this.send({event:"addRenderer",target:"editor",data:{autoClear:e.autoClear,autoClearColor:e.autoClearColor,autoClearDepth:e.autoClearDepth,autoClearStencil:e.autoClearStencil,outputColorSpace:e.outputColorSpace,localClippingEnabled:e.localClippingEnabled,clearColor:s,clearAlpha:e.getClearAlpha(),colorManagement:d.ColorManagement.enabled,toneMapping:e.toneMapping,toneMappingExposure:e.toneMappingExposure,type:e.isWebGLRenderer?"WebGLRenderer":"WebGPURenderer"}})}updateRenderer(e){this.send({event:"updateRenderer",target:"app",data:e})}addScene(e){if(e===void 0||(this.scenes.set(e.name,e),!this.debug))return;Ue(),we(e);const t=le(e);this.send({event:"addScene",target:"editor",data:t})}refreshScene(e){if(!this.debug)return;const t=this.scenes.get(e);if(t!==void 0){const s=le(t);this.send({event:"refreshScene",target:"app",data:s})}}removeScene(e){if(e===void 0||(this.scenes.delete(e.name),!this.debug))return;const t=le(e);this.send({event:"removeScene",target:"editor",data:t})}removeAllScenes(){this.scenes.forEach(e=>this.removeScene(e))}getScene(e){let t=null;return this.scene!==void 0&&this.scene.uuid.search(e)>-1?this.scene:(this.scenes.forEach((s,n)=>{e.search(n)>-1&&(t=s)}),t)}setScene(e){if(e===void 0||(this.scene=e,!this.debug))return;this.renderer!==void 0&&(oe.renderer=this.renderer),Ue(),we(e);const t=le(e);this.send({event:"setScene",target:"editor",data:t})}requestSize(){this.send({event:"requestSize",target:"app"})}requestRenderer(){this.send({event:"requestRenderer",target:"app"})}requestScene(){this.send({event:"requestScene",target:"app"})}addCamera(e){if(!this.debug)return;const t=rt(e);this.send({event:"addCamera",target:"editor",data:t})}removeCamera(e){if(!this.debug)return;const t=rt(e);this.send({event:"removeCamera",target:"editor",data:t})}handleApp(e){switch(e.event){case"refreshScene":this.send({event:"refreshScene",target:"editor",data:le(this.scenes.get(e.data.name))});break;case"updateRenderer":this.renderer&&(this.renderer.autoClearColor=e.data.autoClearColor,this.renderer.outputColorSpace=e.data.outputColorSpace,this.renderer.localClippingEnabled=e.data.localClippingEnabled,this.renderer.setClearColor(e.data.clearColor,e.data.clearAlpha),this.renderer.toneMapping=e.data.toneMapping,this.renderer.toneMappingExposure=e.data.toneMappingExposure,d.ColorManagement.enabled=e.data.colorManagement);break;case"requestRenderer":if(this.renderer!==void 0){const t=`#${this.renderer.getClearColor(new d.Color).getHexString()}`;this.send({event:"addRenderer",target:"editor",data:{autoClear:this.renderer.autoClear,autoClearColor:this.renderer.autoClearColor,autoClearDepth:this.renderer.autoClearDepth,autoClearStencil:this.renderer.autoClearStencil,outputColorSpace:this.renderer.outputColorSpace,localClippingEnabled:this.renderer.localClippingEnabled,clearColor:t,clearAlpha:this.renderer.getClearAlpha(),colorManagement:d.ColorManagement.enabled,toneMapping:this.renderer.toneMapping,toneMappingExposure:this.renderer.toneMappingExposure,type:this.renderer.isWebGLRenderer?"WebGLRenderer":"WebGPURenderer"}})}break;case"requestScene":this.scenes.forEach(t=>{Ue(),we(t),this.send({event:"addScene",target:"editor",data:le(t)})}),this.scene!==void 0&&(this.renderer!==void 0&&(oe.renderer=this.renderer),Ue(),we(this.scene),this.send({event:"setScene",target:"editor",data:le(this.scene)}));break}if(e.event==="updateGroup"){const t=JSON.parse(e.data);this.groups.get(t.group)?.onUpdate(t.prop,t.value)}}handleEditor(e){switch(e.event){case"addScene":this.dispatchEvent({type:"ToolEvents::addScene",value:e.data});break;case"refreshScene":this.dispatchEvent({type:"ToolEvents::refreshScene",value:e.data});break;case"removeScene":this.dispatchEvent({type:"ToolEvents::removeScene",value:e.data});break;case"setScene":this.dispatchEvent({type:"ToolEvents::setScene",value:e.data});break;case"addCamera":this.dispatchEvent({type:"ToolEvents::addCamera",value:e.data});break;case"removeCamera":this.dispatchEvent({type:"ToolEvents::removeCamera",value:e.data});break;case"addGroup":this.dispatchEvent({type:"ToolEvents::addGroup",value:e.data});break;case"removeGroup":this.dispatchEvent({type:"ToolEvents::removeGroup",value:e.data});break;case"addSpline":this.dispatchEvent({type:"ToolEvents::addSpline",value:e.data});break;case"addRenderer":this.dispatchEvent({type:"ToolEvents::addRenderer",value:e.data})}}messageHandler(e){const t=e.data;if(t.event==="updateObject"){this.onUpdateObject(t.data.uuid,t.data.key,t.data.value);return}else if(t.event==="createTexture"){this.onCreateTexture(t.data.uuid,t.data.key,t.data.value);return}else if(t.event==="requestSize"){t.target==="app"?this.send({event:"requestSize",target:"editor",data:{width:this.width,height:this.height}}):this.scenes.forEach(s=>{s.resize!==void 0&&s.resize(t.data.width,t.data.height)});return}t.target==="app"?this.handleApp(t):this.handleEditor(t)}addRT(e,t=!0,s){const n=new d.WebGLRenderTarget(32,32,s);n.texture.name=e,this.renderTargets.set(e,n),this.renderTargetsResize.set(e,t)}removeRT(e){this.renderTargets.delete(e),this.renderTargetsResize.delete(e)}resize(e,t){const s=this.dpr;this.renderTargets.forEach((a,r)=>{this.renderTargetsResize.get(r)&&a.setSize(e*s,t*s)});const n=!(this.renderer?.domElement instanceof OffscreenCanvas);this.renderer?.setSize(e,t,n)}set dpr(e){this.renderer?.setPixelRatio(he(1,2,e))}get dpr(){return this.renderer!==void 0?this.renderer?.getPixelRatio():1}get width(){return this.renderer!==void 0?this.renderer.domElement.width/this.dpr:0}get height(){return this.renderer!==void 0?this.renderer.domElement.height/this.dpr:0}}function St(i){return i.title.search("<")>-1?u.jsx("button",{className:"svg",dangerouslySetInnerHTML:{__html:i.title}}):u.jsx("button",{children:i.title})}const Gs=u.jsxs("svg",{className:"closeIcon",width:"14",height:"14",fill:"none",stroke:"#666666",strokeMiterlimit:"10",children:[u.jsx("circle",{cx:"7",cy:"7",r:"6"}),u.jsx("line",{x1:"4",y1:"4",x2:"10",y2:"10"}),u.jsx("line",{x1:"4",y1:"10",x2:"10",y2:"4"})]}),Ws=u.jsx("svg",{className:"dragIcon",width:"14",height:"14",fill:"#666666",stroke:"none",children:u.jsx("path",{d:`M10.43,4H3.57C3.26,4,3,4.22,3,4.5v1C3,5.78,3.26,6,3.57,6h6.86C10.74,6,11,5.78,11,5.5v-1\r
19
19
  C11,4.22,10.74,4,10.43,4z M10.43,8H3.57C3.26,8,3,8.22,3,8.5v1C3,9.78,3.26,10,3.57,10h6.86C10.74,10,11,9.78,11,9.5v-1\r
20
- C11,8.22,10.74,8,10.43,8z`})});function yx(r){return F.jsx("li",{className:`reorder-item ${r.draggingIndex===r.index?"dragging":""}`,draggable:!0,onDragStart:()=>r.onDragStart(r.index),onDragOver:e=>{e.preventDefault(),r.onDragOver(r.index)},onDragEnd:r.onDragEnd,children:F.jsxs("div",{children:[pM,F.jsx("span",{children:r.title}),F.jsx("button",{className:"closeIcon",onClick:()=>r.onDelete(r.index),children:dM})]})})}function xx(r){const[e,t]=X.useState(!1),[s,i]=X.useState(r.options),[n,a]=X.useState(null),o=p=>{r.onDragComplete(p),i(p)},l=p=>{const f=[...s];f.splice(p,1),o(f)},c=p=>{a(p)},u=p=>{if(n===p||n===null)return;const f=[...s],m=f.splice(n,1)[0];f.splice(p,0,m),a(p),i(f)},h=()=>{r.onDragComplete(s),a(null)};let d="dropdown draggable";return r.subdropdown&&(d+=" subdropdown"),F.jsxs("div",{className:d,onMouseEnter:()=>t(!0),onMouseLeave:()=>t(!1),children:[F.jsx(Op,{title:r.title}),F.jsx("ul",{className:"reorder-list",style:{display:e?"block":"none"},children:s.map((p,f)=>F.jsx(yx,{title:p,index:f,draggingIndex:n,onDelete:l,onDragStart:c,onDragOver:u,onDragEnd:h},p))})]})}function _x(r){const[e,t]=X.useState(!1),s=[];r.options.map((n,a)=>{r.onSelect!==void 0&&(n.onSelect=r.onSelect),s.push(F.jsx(bx,{option:n},a))});let i="dropdown";return r.subdropdown&&(i+=" subdropdown"),F.jsxs("div",{className:i,onMouseEnter:()=>t(!0),onMouseLeave:()=>t(!1),children:[F.jsx(Op,{title:r.title}),F.jsx("ul",{style:{visibility:e?"visible":"hidden"},children:s})]})}function bx(r){const{option:e}=r,[t,s]=X.useState("");let i;switch(e.type){case"draggable":i=F.jsx(xx,{title:e.title,options:e.value,onDragComplete:n=>{e.onDragComplete!==void 0&&e.onDragComplete(n)},subdropdown:!0});break;case"dropdown":i=F.jsx(_x,{title:e.title,options:e.value,onSelect:e.onSelect,subdropdown:!0});break;case"option":i=F.jsx("button",{onClick:()=>{e.onSelect!==void 0&&e.onSelect(e.value),e.selectable&&(t!==e.title?s(e.title):s(""))},children:e.title});break}return F.jsx("li",{className:t===e.title?"selected":"",children:i},Tt())}function fa(r){const[e,t]=X.useState(r.open!==void 0?r.open:!1),[s,i]=X.useState(r.visible!==void 0?r.visible:!1),n=!e||r.children===void 0,a=()=>{r.three.dispatchEvent({type:me.REMOVE_SCENE,value:r.scene})};return F.jsxs("div",{className:`accordion ${n?"hide":""}`,children:[F.jsxs("button",{className:"toggle",onClick:()=>{const o=!e;r.onToggle!==void 0&&r.onToggle(o),t(o)},children:[F.jsx("p",{className:`status ${e?"open":""}`,children:"Toggle"}),F.jsx("p",{className:"label",children:Uo(r.label)})]}),r.onRefresh?F.jsxs(F.Fragment,{children:[F.jsx("button",{className:"visibility",style:{opacity:s?1:.25},onClick:()=>{const l=r.three.getScene(r.scene.uuid);if(l){const c=!l.visible;l.visible=c,i(c)}}}),F.jsx("button",{className:"refresh",onClick:r.onRefresh}),F.jsx("button",{className:"remove",onClick:a})]}):null,r.button,F.jsx("div",{className:e?"open":"",children:F.jsx("div",{children:r.children})},Math.random())]})}function Lp(r){if(r.child===void 0)return console.log("Hermes - No child attached"),null;const e=X.useRef(null),[t,s]=X.useState(!1),i=r.child.children.length>0,n=[];return r.child.children.length>0&&r.child.children.map((a,o)=>{n.push(F.jsx(Lp,{child:a,three:r.three},o))}),X.useEffect(()=>{if(r.child){const a=r.child.uuid.split(".")[0],o=r.three.getScene(a);if(o!==null)try{const l=o.getObjectByProperty("uuid",r.child.uuid);l!==void 0?e.current.style.opacity=l.visible?"1":"0.25":console.log(`Hermes - Can't find child: ${r.child.uuid}`)}catch(l){console.log("Error looking for child:",l),console.log(r.child),console.log(r.three.scenes),console.log(o)}else console.log(`Hermes (ChildObject) - Can't find Scene: ${a} with child UUID: ${r.child.uuid}`,r.three.scenes,r.three.scene,o)}},[t]),F.jsxs("div",{className:"childObject",children:[F.jsxs("div",{className:"child",children:[i?F.jsx("button",{className:"status",style:{backgroundPositionX:t?"-14px":"2px"},onClick:()=>{s(!t)}}):null,F.jsx("button",{className:"name",style:{left:i?"20px":"5px"},onClick:()=>{r.child!==void 0?(r.three.getObject(r.child.uuid),!t&&i&&s(!0)):console.log("Hermes - No child attached...")},children:r.child.name.length>0?`${r.child.name} (${r.child.type})`:`${r.child.type}::${r.child.uuid}`}),F.jsx("button",{className:"visibility",ref:e,onClick:()=>{if(r.child){const a=r.three.getScene(r.child.uuid);if(a!==null){const o=a.getObjectByProperty("uuid",r.child.uuid);if(o!==void 0){const l="visible",c=!o.visible;e.current.style.opacity=c?"1":"0.25",r.three.updateObject(r.child.uuid,l,c),ut(o,l,c)}else console.log(`Hermes - Couldn't find object: ${r.child.uuid}`,a)}else console.log(`Hermes - Couldn't find object in scene: ${r.child.uuid}, ${r.child.name}`)}}}),F.jsx("div",{className:`icon ${aM(r.child)}`})]}),F.jsx("div",{className:t?"open":"",children:F.jsx("div",{className:"container",children:n})})]},Math.random())}function gc(r){const e=[];return r.child?.children.map((t,s)=>{e.push(F.jsx(Lp,{child:t,scene:r.scene,three:r.three},s))}),F.jsx("div",{className:`scene ${r.class!==void 0?r.class:""}`,children:e})}function go(r){const[e,t]=X.useState(r.defaultValue);return X.useEffect(()=>{let s=!1,i=-1,n=0,a=r.defaultValue,o=!1;const l=p=>{o=p.ctrlKey},c=p=>{s=!0,n=Number(r.input.current?.value),i=p.clientX,document.addEventListener("mouseup",h,!1),document.addEventListener("mousemove",u,!1),document.addEventListener("contextmenu",h,!1)},u=p=>{if(!s)return;const f=r.step!==void 0?r.step:1,m=(p.clientX-i)*f*(o?10:1);a=Number((n+m).toFixed(4)),r.min!==void 0&&(a=Math.max(a,r.min)),r.max!==void 0&&(a=Math.min(a,r.max)),r.onChange!==void 0&&r.onChange(a),t(a)},h=()=>{s=!1,document.removeEventListener("mouseup",h),document.removeEventListener("mousemove",u),document.removeEventListener("contextmenu",h)},d=p=>{const f=Number(p.target.value);r.onChange!==void 0&&r.onChange(f),t(f)};return r.label.current?.addEventListener("mousedown",c,!1),r.sliderRef!==void 0&&r.sliderRef.current?.addEventListener("input",d),document.addEventListener("keydown",l,!1),document.addEventListener("keyup",l,!1),()=>{r.label.current?.removeEventListener("mousedown",c),r.sliderRef!==void 0&&r.sliderRef.current?.removeEventListener("input",d),document.removeEventListener("mouseup",h),document.removeEventListener("mousemove",u),document.removeEventListener("contextmenu",h),document.removeEventListener("keydown",l),document.addEventListener("keyup",l,!1)}},[]),e}function yr(r){const e=X.useRef(null),t=X.useRef(null),[s,i]=X.useState(r.value);return go({label:r.labelRef,input:e,sliderRef:t,defaultValue:s,min:r.min,max:r.max,step:r.step,onChange:n=>{i(n),r.onChange!==void 0&&r.onChange(r.prop,n)}}),F.jsxs(F.Fragment,{children:[r.type==="number"&&F.jsx("input",{alt:r.alt,className:r.className,ref:e,type:"number",value:s,min:r.min,max:r.max,step:r.step,disabled:r.disabled,name:Tt(),onChange:n=>{if(i(n.target.value),n.target.value.length===0)return;const a=Number(n.target.value);isNaN(a)||r.onChange!==void 0&&r.onChange(r.prop,a)}}),r.type==="range"&&F.jsxs(F.Fragment,{children:[F.jsx("input",{type:"text",value:s.toString(),disabled:r.disabled,ref:e,className:"min",name:Tt(),onChange:n=>{if(n.target.value.length===0)return;const a=Number(n.target.value);isNaN(a)||(i(a),r.onChange!==void 0&&r.onChange(r.prop,a))}}),F.jsx("input",{disabled:r.disabled,type:"range",value:s,min:r.min,max:r.max,step:r.step,ref:t,name:Tt(),onChange:Io})]})]})}function fM(r){const e=X.useRef(null),t=X.useRef(null),s=X.useRef(null),i=X.useRef(null),n=X.useRef(null),a=X.useRef(null),o=X.useRef(null),l=X.useRef(null),c=X.useRef(null),u=X.useRef(null),[h,d]=X.useState(r.value.x),[p,f]=X.useState(r.value.y),[m,x]=X.useState({min:Math.min(r.min,Math.min(r.value.x,r.value.y)),max:Math.max(r.max,Math.max(r.value.x,r.value.y))}),[y,b]=X.useState(!1);go({label:o,input:e,defaultValue:h,min:m.min,max:m.max,step:.01,onChange:B=>{d(B),r.onChange({target:{value:{x:B,y:p}}})}}),go({label:l,input:t,defaultValue:p,min:m.min,max:m.max,step:.01,onChange:B=>{f(B),r.onChange({target:{value:{x:h,y:B}}})}}),go({label:c,input:s,defaultValue:m.min,min:m.min-1,max:m.max+1,step:.01,onChange:B=>{x({min:B,max:m.max})}}),go({label:u,input:i,defaultValue:m.max,min:m.min-1,max:m.max+1,step:.01,onChange:B=>{x({min:m.min,max:B})}});function v(){y||(window.addEventListener("mousemove",M),window.addEventListener("mouseup",S),b(!0))}function S(){window.removeEventListener("mousemove",M),window.removeEventListener("mouseup",S),b(!1)}function M(B){const V=n.current.getBoundingClientRect(),Y=_n(0,99,B.clientX-V.left)/99,J=1-_n(0,99,B.clientY-V.top)/99,K=As(Ma(m.min,m.max,Y),3),te=As(Ma(m.min,m.max,J),3);r.onChange({target:{value:{x:K,y:te}}}),d(K),f(te)}function A(){const B=Number(s.current.value);x({min:B,max:m.max}),h<B&&d(_n(B,m.max,h)),p<B&&f(_n(B,m.max,p))}function C(){const B=Number(i.current.value);x({min:m.min,max:B}),h>B&&d(_n(m.min,B,h)),p>B&&f(_n(m.min,B,p))}X.useEffect(()=>{a.current.style.left=`${Cc(m.min,m.max,h)*100}%`,a.current.style.top=`${(1-Cc(m.min,m.max,p))*100}%`},[m,h,p]);const P=r.step!==void 0?r.step:.01;return F.jsxs("div",{className:"vector2",children:[F.jsxs("div",{className:"fields",children:[F.jsxs("div",{children:[F.jsx("span",{ref:o,children:"X"}),F.jsx("input",{ref:e,type:"number",value:h,min:m.min,max:m.max,step:P,name:Tt(),onChange:B=>{if(d(B.target.value),B.target.value.length===0)return;const V=Number(B.target.value);isNaN(V)||(r.onChange({target:{value:{x:V,y:p}}}),V<m.min&&x({min:V,max:m.max}))}})]}),F.jsxs("div",{children:[F.jsx("span",{ref:l,children:"Y"}),F.jsx("input",{ref:t,type:"number",value:p,min:m.min,max:m.max,step:P,name:Tt(),onChange:B=>{if(f(B.target.value),B.target.value.length===0)return;const V=Number(B.target.value);isNaN(V)||(r.onChange({target:{value:{x:h,y:V}}}),V>m.max&&x({min:m.min,max:V}))}})]}),F.jsxs("div",{children:[F.jsx("span",{ref:c,children:"Min"}),F.jsx("input",{ref:s,type:"number",value:m.min,step:P,name:Tt(),onChange:A})]}),F.jsxs("div",{children:[F.jsx("span",{ref:u,children:"Max"}),F.jsx("input",{ref:i,type:"number",value:m.max,step:P,name:Tt(),onChange:C})]})]}),F.jsxs("div",{className:"input",ref:n,onMouseDown:v,onMouseUp:S,children:[F.jsx("div",{className:"x"}),F.jsx("div",{className:"y"}),F.jsx("div",{className:"pt",ref:a})]})]})}const mM=Math.PI/180,gM=180/Math.PI;function Dr(r,e,t,s,i){return s+(r-e)*(i-s)/(t-e)}function Sh(r,e,t){return(1-t)*r+t*e}function Yd(r){return r*mM}function yM(r){return r*gM}function Gm(r){const e=r.value.x!==void 0&&r.value.y!==void 0&&r.value.z!==void 0,t=r.value.isEuler!==void 0,s=r.value.elements!==void 0,i=r.step!==void 0?r.step:.01,n=[];if(t){const a=X.useMemo(()=>r.value,[]);["_x","_y","_z"].forEach(l=>{const c=X.useRef(null);n.push(F.jsxs("div",{children:[F.jsx("span",{ref:c,children:l.substring(1).toUpperCase()}),F.jsx(yr,{value:yM(a[l]),type:"number",prop:l,step:.1,labelRef:c,onChange:(u,h)=>{a[u]=Yd(h),r.onChange({target:{value:a}})}})]},l))})}else if(e){const a=X.useMemo(()=>r.value,[]),o=(c,u)=>{a[c]=u,r.onChange({target:{value:a}})};["x","y","z"].forEach(c=>{const u=X.useRef(null);n.push(F.jsxs("div",{children:[F.jsx("label",{ref:u,children:c.toUpperCase()}),F.jsx(yr,{value:a[c],type:"number",prop:c,step:i,labelRef:u,onChange:o})]},c))})}else if(s){const a=X.useMemo(()=>r.value,[]),o=(l,c)=>{const u=Number(l);a.elements[u]=c,r.onChange({target:{value:a}})};for(let l=0;l<9;l++){const c=X.useRef(null);n.push(F.jsxs("div",{children:[F.jsx("label",{ref:c,children:l+1}),F.jsx(yr,{value:a.elements[l],type:"number",prop:l.toString(),step:i,labelRef:c,onChange:o})]},l.toString()))}}return F.jsx("div",{className:"grid3",children:n},Math.random().toString())}function xM(r){const e=r.value.x!==void 0,t=r.step!==void 0?r.step:.01,s=[];if(e){const i=X.useMemo(()=>r.value,[]),n=(o,l)=>{i[o]=l,r.onChange({target:{value:i}})};["x","y","z","w"].forEach(o=>{const l=X.useRef(null);s.push(F.jsxs("div",{children:[F.jsx("label",{ref:l,children:o.toUpperCase()}),F.jsx(yr,{value:i[o],type:"number",prop:o,step:t,labelRef:l,onChange:n})]},o))})}else{const i=X.useMemo(()=>r.value,[]),n=(a,o)=>{const l=Number(a);i.elements[l]=o,r.onChange({target:{value:i}})};for(let a=0;a<16;a++){const o=X.useRef(null);s.push(F.jsxs("div",{children:[F.jsx("span",{ref:o,children:a+1}),F.jsx(yr,{value:i.elements[a],type:"number",prop:a.toString(),step:t,labelRef:o,onChange:n})]},a.toString()))}}return F.jsx("div",{className:"grid4",children:s})}function _M(r){return!(r==="defaultAttributeValues"||r==="forceSinglePass"||r==="linecap"||r==="linejoin"||r==="linewidth"||r==="normalMapType"||r==="precision"||r==="shadowSide"||r==="uniformsGroups"||r==="uniformsNeedUpdate"||r==="userData"||r==="version"||r==="wireframeLinecap"||r==="wireframeLinejoin"||r==="wireframeLinewidth"||r.slice(0,4)==="clip"||r.slice(0,7)==="polygon"||r.slice(0,7)==="stencil"||r.slice(0,2)==="is")}function bM(r){switch(r){case"Alpha Map":return"alphaMap";case"Anisotropy Map":return"anisotropyMap";case"AO Map":return"aoMap";case"Bump Map":return"bumpMap";case"Clearcoat Map":return"clearcoatMap";case"Clearcoat Normal Map":return"clearcoatNormalMap";case"Clearcoat Roughness Map":return"clearcoatRoughnessMap";case"Displacement Map":return"displacementMap";case"Emissive Map":return"emissiveMap";case"Gradient Map":return"gradientMap";case"Iridescence Map":return"iridescenceMap";case"Iridescence Thickness Map":return"iridescenceThicknessMap";case"Map":return"map";case"Matcap":return"matcap";case"Normal Map":return"normalMap";case"Roughness Map":return"roughnessMap";case"Sheen Color Map":return"sheenColorMap";case"Sheen Roughness Map":return"sheenRoughnessMap";case"Specular Color Map":return"specularColorMap";case"Specular Map Intensity":return"specularIntensityMap";case"Thickness Map":return"thicknessMap";case"Transmission Map":return"transmissionMap"}return r}function Au(r){switch(r){case"alphaHash":return"Alpha Hash";case"alphaMap":return"Alpha Map";case"alphaToCoverage":return"Alpha To Coverage";case"anisotropy":return"Anisotropy";case"anisotropyMap":return"Anisotropy Map";case"anisotropyRotation":return"Anisotropy Rotation";case"aoMap":return"AO Map";case"aoMapIntensity":return"AO Map Intensity";case"attenuationColor":return"Attenuation Color";case"attenuationDistance":return"Attenuation Distance";case"blendAlpha":return"Blend Alpha";case"blendColor":return"Blend Color";case"blendDst":return"Blend Dst";case"blendDstAlpha":return"Blend Dst Alha";case"blendEquation":return"Blend Equation";case"blendEquationAlpha":return"Blend Equation Alpha";case"blending":return"Blending";case"blendSrc":return"Blend Src";case"blendSrcAlpha":return"Blend Src Alpha";case"bumpMap":return"Bump Map";case"bumpScale":return"Bump Scale";case"clearcoat":return"Clearcoat";case"clearcoatMap":return"Clearcoat Map";case"clearcoatNormalMap":return"Clearcoat Normal Map";case"clearcoatNormalScale":return"Clearcoat Normal Scale";case"clearcoatRoughness":return"Clearcoat Roughness";case"clearcoatRoughnessMap":return"Clearcoat Roughness Map";case"color":return"Color";case"colorWrite":return"Color Write";case"defines":return"Defines";case"depthFunc":return"Depth Func";case"depthTest":return"Depth Test";case"depthWrite":return"Depth Write";case"dispersion":return"Dispersion";case"displacementBias":return"Displacement Bias";case"displacementMap":return"Displacement Map";case"displacementScale":return"Displacement Scale";case"dithering":return"Dithering";case"emissive":return"Emissive";case"emissiveMap":return"Emissive Map";case"emissiveIntensity":return"Emissive Intensity";case"envMap":return"Environment Map";case"envMapIntensity":return"Environment Map Intensity";case"envMapRotation":return"Environment Map Rotation";case"extensions":return"Extensions";case"flatShading":return"Flat Shading";case"fragmentShader":return"Fragment Shader";case"fog":return"Fog";case"glslVersion":return"GLSL Version";case"gradientMap":return"Gradient Map";case"ior":return"IOR";case"iridescence":return"Iridescence";case"iridescenceIOR":return"Iridescence IOR";case"iridescenceMap":return"Iridescence Map";case"iridescenceThicknessMap":return"Iridescence Thickness Map";case"iridescenceThicknessRange":return"Iridescence Thickness Range";case"lights":return"Lights";case"lightMap":return"Light Map";case"lightMapIntensity":return"Light Map Intensity";case"map":return"Map";case"matcap":return"Matcap";case"metalness":return"Metalness";case"metalnessMap":return"Metalness Map";case"name":return"Name";case"normalMap":return"Normal Map";case"normalScale":return"Normal Scale";case"premultipliedAlpha":return"Premultiplied Alpha";case"opacity":return"Opacity";case"reflectivity":return"Reflectivity";case"refractionRatio":return"Refraction Ratio";case"roughness":return"Roughness";case"roughnessMap":return"Roughness Map";case"sheen":return"Sheen";case"sheenColor":return"Sheen Color";case"sheenColorMap":return"Sheen Color Map";case"sheenRoughness":return"Sheen Roughness";case"sheenRoughnessMap":return"Sheen Roughness Map";case"shininess":return"Shininess";case"side":return"Side";case"size":return"Size";case"sizeAttenuation":return"Size Attenuation";case"specular":return"Specular";case"specularColor":return"Specular Color";case"specularColorMap":return"Specular Color Map";case"specularIntensity":return"Specular Intensity";case"specularIntensityMap":return"Specular Map Intensity";case"thickness":return"Thickness";case"thicknessMap":return"Thickness Map";case"toneMapped":return"Tone Mapped";case"transmission":return"Transmission";case"transmissionMap":return"Transmission Map";case"transparent":return"Transparent";case"type":return"Type";case"uuid":return"UUID";case"uniforms":return"Uniforms";case"vertexColors":return"Vertex Colors";case"vertexShader":return"Vertex Shader";case"visible":return"Visible";case"wireframe":return"Wireframe"}return r}function Tx(r){const e=r.toLowerCase();return e.search("intensity")>-1||e==="anisotropyrotation"||e==="blendalpha"||e==="bumpscale"||e==="clearcoatroughness"||e==="displacementbias"||e==="displacementscale"||e==="metalness"||e==="opacity"||e==="reflectivity"||e==="refractionratio"||e==="roughness"||e==="sheenroughness"}function TM(){const r=document.createElement("input");return r.type="file",new Promise((e,t)=>{r.addEventListener("change",function(){if(r.files===null)t();else{const s=r.files[0],i=new FileReader;i.onload=function(n){e(n.target.result)},i.readAsDataURL(s)}}),r.click()})}const SM=[{title:"Front",value:_.FrontSide},{title:"Back",value:_.BackSide},{title:"Double",value:_.DoubleSide}],vM=[{title:"No Blending",value:_.NoBlending},{title:"Normal",value:_.NormalBlending},{title:"Additive",value:_.AdditiveBlending},{title:"Subtractive",value:_.SubtractiveBlending},{title:"Multiply",value:_.MultiplyBlending},{title:"Custom",value:_.CustomBlending}],MM=[{title:"Add",value:_.AddEquation},{title:"Subtract",value:_.SubtractEquation},{title:"Reverse Subtract",value:_.ReverseSubtractEquation},{title:"Min",value:_.MinEquation},{title:"Max",value:_.MaxEquation}],wM=[{title:"Zero",value:_.ZeroFactor},{title:"One",value:_.OneFactor},{title:"Src Color",value:_.SrcColorFactor},{title:"One Minus Src Color",value:_.OneMinusSrcColorFactor},{title:"Src Alpha",value:_.SrcAlphaFactor},{title:"One Minus Src Alpha",value:_.OneMinusSrcAlphaFactor},{title:"Dst Alpha",value:_.DstAlphaFactor},{title:"One Minus Dst Alpha",value:_.OneMinusDstAlphaFactor},{title:"Dst Color",value:_.DstColorFactor},{title:"One Minus Dst Color",value:_.OneMinusDstColorFactor},{title:"Src Alpha Saturate",value:_.SrcAlphaSaturateFactor},{title:"Constant Color",value:_.ConstantColorFactor},{title:"One Minus Constant Color",value:_.OneMinusConstantColorFactor},{title:"Constant Alpha",value:_.ConstantAlphaFactor},{title:"One Minus Constant Alpha",value:_.OneMinusConstantAlphaFactor}],CM=[{title:"Zero",value:_.ZeroFactor},{title:"One",value:_.OneFactor},{title:"Src Color",value:_.SrcColorFactor},{title:"One Minus Src Color",value:_.OneMinusSrcColorFactor},{title:"Src Alpha",value:_.SrcAlphaFactor},{title:"One Minus Src Alpha",value:_.OneMinusSrcAlphaFactor},{title:"Dst Alpha",value:_.DstAlphaFactor},{title:"One Minus Dst Alpha",value:_.OneMinusDstAlphaFactor},{title:"Dst Color",value:_.DstColorFactor},{title:"One Minus Dst Color",value:_.OneMinusDstColorFactor},{title:"Constant Color",value:_.ConstantColorFactor},{title:"One Minus Constant Color",value:_.OneMinusConstantColorFactor},{title:"Constant Alpha",value:_.ConstantAlphaFactor},{title:"One Minus Constant Alpha",value:_.OneMinusConstantAlphaFactor}];function Ga(r,e){r.needsUpdate=!0,r.type="option",r.options=e}function AM(r,e,t,s){return{type:"boolean",title:Au(r),prop:r,value:e,needsUpdate:!0,onChange:(i,n)=>{s.updateObject(t.uuid,`material.${r}`,n),s.updateObject(t.uuid,"material.needsUpdate",!0);const a=s.getScene(t.uuid);if(a!==null){const o=a.getObjectByProperty("uuid",t.uuid);ut(o,`material.${r}`,n)}}}}function EM(r,e,t,s){const i={type:"number",title:Au(r),prop:r,value:e,min:void 0,max:void 0,step:.01,needsUpdate:!0,onChange:(n,a)=>{s.updateObject(t.uuid,`material.${r}`,a),s.updateObject(t.uuid,"material.needsUpdate",!0);const o=s.getScene(t.uuid);if(o!==null){const l=o.getObjectByProperty("uuid",t.uuid);ut(l,`material.${r}`,a)}}};switch(r){case"blending":Ga(i,vM);break;case"blendDst":Ga(i,CM);break;case"blendEquation":Ga(i,MM);break;case"blendSrc":Ga(i,wM);break;case"side":Ga(i,SM);break}return Tx(r)&&(i.value=Number(e),i.type="range",i.min=Math.min(0,i.value),i.max=Math.max(1,i.value),i.step=.01),i}function NM(r,e,t,s){const i={type:"string",title:Au(r),prop:r,value:e,needsUpdate:!0,onChange:(a,o)=>{s.updateObject(t.uuid,`material.${r}`,o),s.updateObject(t.uuid,"material.needsUpdate",!0);const l=s.getScene(t.uuid);if(l!==null){const c=l.getObjectByProperty("uuid",t.uuid);ut(c,`material.${r}`,o)}},onKeyDown:a=>{}};return(r==="vertexShader"||r==="fragmentShader")&&(i.type="field",i.disabled=!1,i.latest=i.value,i.onChange=(a,o)=>{i.latest=o,s.updateObject(t.uuid,`material.${r}`,o);const l=s.getScene(t.uuid);if(l!==null){const c=l.getObjectByProperty("uuid",t.uuid);ut(c,`material.${r}`,o)}},i.onKeyDown=a=>{if(a.key==="Enter"&&(a.altKey||a.metaKey)){s.updateObject(t.uuid,"material.needsUpdate",!0);const o=s.getScene(t.uuid);if(o!==null){const l=o.getObjectByProperty("uuid",t.uuid);ut(l,"material.needsUpdate",!0)}}}),i}function RM(r){return r.x!==void 0&&r.y!==void 0&&r.z===void 0}function PM(r){return r.x!==void 0&&r.y!==void 0&&r.z!==void 0&&r.w===void 0}function FM(r){return r.x!==void 0&&r.y!==void 0&&r.z!==void 0&&r.w!==void 0}function Zd(r){r.sort((e,t)=>e.title<t.title?-1:e.title>t.title?1:0)}function yo(r,e,t,s,i="",n=!1){const a=Au(r).split(".")[0].replaceAll("[","").replaceAll("]",""),o=i.length>0?`${i}.${r}`:r,l=typeof e;if(l==="boolean"||l==="string")return{title:a,prop:o,type:l,value:e,disabled:n,onChange:(c,u)=>{s.updateObject(t.uuid,`material.${o}`,u);const h=s.getScene(t.uuid);if(h!==null){const d=h.getObjectByProperty("uuid",t.uuid);ut(d,`material.${o}`,u)}}};if(l==="number"){const c={title:a,prop:o,type:"number",value:e,step:.01,disabled:n,onChange:(u,h)=>{s.updateObject(t.uuid,`material.${o}`,h);const d=s.getScene(t.uuid);if(d!==null){const p=d.getObjectByProperty("uuid",t.uuid);ut(p,`material.${o}`,h)}}};return Tx(a)&&(c.type="range",c.min=0,c.max=1),c}else{if(e.isColor)return{title:a,prop:o,type:"color",value:e,disabled:n,onChange:(c,u)=>{const h=new _.Color(u);s.updateObject(t.uuid,`material.${o}`,h);const d=s.getScene(t.uuid);if(d!==null){const p=d.getObjectByProperty("uuid",t.uuid);ut(p,`material.${o}`,h)}}};if(Array.isArray(e)){const c=[];for(const u in e){const h=e[u],d=`[${u.toString()}]`;if(h.value!==void 0){const p=yo(`${d}.value`,h.value,t,s,o,n);p!==void 0&&c.push(p)}else{const p=yo(d,h,t,s,o,n);p!==void 0&&c.push(p)}}if(c.length>0)return Zd(c),{title:a,items:c}}else{if(RM(e))return{title:a,prop:o,type:"vector2",value:e,disabled:n,onChange:(c,u)=>{s.updateObject(t.uuid,`material.${o}`,u);const h=s.getScene(t.uuid);if(h!==null){const d=h.getObjectByProperty("uuid",t.uuid);ut(d,`material.${o}`,u)}}};if(PM(e))return{title:a,prop:o,type:"grid3",value:e,disabled:n,onChange:(c,u)=>{s.updateObject(t.uuid,`material.${o}`,u);const h=s.getScene(t.uuid);if(h!==null){const d=h.getObjectByProperty("uuid",t.uuid);ut(d,`material.${o}`,u)}}};if(FM(e))return{title:a,prop:o,type:"grid4",value:e,disabled:n,onChange:(c,u)=>{s.updateObject(t.uuid,`material.${o}`,u);const h=s.getScene(t.uuid);if(h!==null){const d=h.getObjectByProperty("uuid",t.uuid);ut(d,`material.${o}`,u)}}};if(e.isEuler)return{title:a,prop:o,type:"euler",value:e,disabled:n,onChange:(c,u)=>{s.updateObject(t.uuid,`material.${o}`,u);const h=s.getScene(t.uuid);if(h!==null){const d=h.getObjectByProperty("uuid",t.uuid);ut(d,`material.${o}`,u)}}};if(e.src!==void 0)return{title:a,type:"image",value:e,disabled:n,onChange:(c,u)=>{const h=bM(r),d=i.length>0?`${i}.${h}`:h;s.createTexture(t.uuid,`material.${d}`,u);const p=s.getScene(t.uuid);if(p!==null){const f=p.getObjectByProperty("uuid",t.uuid);if(f!==void 0){const m=x=>{const y=f.material,b=d.split(".");switch(b.length){case 1:y[b[0]]=x;break;case 2:y[b[0]][b[1]]=x;break;case 3:y[b[0]][b[1]][b[2]]=x;break;case 4:y[b[0]][b[1]][b[2]][b[3]]=x;break;case 5:y[b[0]][b[1]][b[2]][b[3]][b[4]]=x;break}y.needsUpdate=!0};u.src.length>0?gx(u.src).then(x=>{x.offset.set(u.offset[0],u.offset[1]),x.repeat.set(u.repeat[0],u.repeat[1]),m(x)}):m(null)}}}};if(e.elements!==void 0)return{title:a,prop:o,type:e.elements.length>9?"grid4":"grid3",value:e,disabled:n,onChange:(c,u)=>{s.updateObject(t.uuid,`material.${o}`,u);const h=s.getScene(t.uuid);if(h!==null){const d=h.getObjectByProperty("uuid",t.uuid);ut(d,`material.${o}`,u)}}};{const c=[],u=r==="defines"||r==="extensions";try{for(const h in e){const d=e[h];if(d!==void 0)if(d.value!==void 0){const p=yo(`${h}.value`,d.value,t,s,o,u);p!==void 0&&c.push(p)}else{const p=yo(h,d,t,s,o,u);p!==void 0&&c.push(p)}}}catch{console.log("Hermes - Issue cycling through material object:",r,e)}if(c.length>0)return Zd(c),{title:a,items:c}}}}}function $m(r,e,t){const s=[];for(const i in r){if(!_M(i)||i.search("Node")>-1)continue;const n=typeof r[i],a=r[i];if(n==="boolean")s.push(AM(i,a,e,t));else if(n==="number")s.push(EM(i,a,e,t));else if(n==="string")s.push(NM(i,a,e,t));else if(n==="object"){const o=yo(i,a,e,t);o!==void 0&&s.push(o)}else a!==void 0&&console.log("Hermes - Other Material Prop Type:",i,n,a)}return Zd(s),s.push({title:"Update Material",type:"button",onChange:()=>{t.updateObject(e.uuid,"material.needsUpdate",!0);const i=t.getScene(e.uuid);if(i!==null){const n=i.getObjectByProperty("uuid",e.uuid);ut(n,"material.needsUpdate",!0)}}}),s}function BM(r,e){function t(){return`${e.name}_material`}const s=localStorage.getItem(t()),i=s!==null?s==="open":!1;function n(o){localStorage.setItem(t(),o?"open":"closed")}const a=r.material;if(Array.isArray(a)){const o=[],l=a.length;for(let c=0;c<l;c++)o.push(F.jsx(Os,{three:e,title:`Material ${c}`,items:$m(a[c],r,e)},`Material ${c}`));return F.jsx(F.Fragment,{children:o})}else return F.jsx(Os,{three:e,title:"Material",items:$m(a,r,e),expanded:i,onToggle:o=>{n(o)}})}const Wm="data:image/gif;base64,R0lGODlhDgFkAIAAAP///wAAACH/C1hNUCBEYXRhWE1QPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgOS4xLWMwMDIgNzkuZGJhM2RhM2I1LCAyMDIzLzEyLzE1LTEwOjQyOjM3ICAgICAgICAiPiA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPiA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtbG5zOnhtcE1NPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvbW0vIiB4bWxuczpzdFJlZj0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL3NUeXBlL1Jlc291cmNlUmVmIyIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgMjUuNiAoTWFjaW50b3NoKSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDoyMDk3M0NEODAxQjQxMUVGODVGNENDMkUyMUExNDk1NSIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDoyMDk3M0NEOTAxQjQxMUVGODVGNENDMkUyMUExNDk1NSI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOkE4ODc3Qzg5MDFCMzExRUY4NUY0Q0MyRTIxQTE0OTU1IiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOkE4ODc3QzhBMDFCMzExRUY4NUY0Q0MyRTIxQTE0OTU1Ii8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+Af/+/fz7+vn49/b19PPy8fDv7u3s6+rp6Ofm5eTj4uHg397d3Nva2djX1tXU09LR0M/OzczLysnIx8bFxMPCwcC/vr28u7q5uLe2tbSzsrGwr66trKuqqainpqWko6KhoJ+enZybmpmYl5aVlJOSkZCPjo2Mi4qJiIeGhYSDgoGAf359fHt6eXh3dnV0c3JxcG9ubWxramloZ2ZlZGNiYWBfXl1cW1pZWFdWVVRTUlFQT05NTEtKSUhHRkVEQ0JBQD8+PTw7Ojk4NzY1NDMyMTAvLi0sKyopKCcmJSQjIiEgHx4dHBsaGRgXFhUUExIREA8ODQwLCgkIBwYFBAMCAQAAIfkEAAAAAAAsAAAAAA4BZAAAAv+Mj6nL7Q+jnLTai7PevPsPhuJIluaJpurKtu4Lx/JM1/aN5/rO9/4PDAqHxKLxiEwql8ym8wmNSqfUqvWKzWq33K73Cw6Lx+Sy+YxOq9fstvsNj8vn9Lr9js/r9/y+/w8YKDhIWGh4iJiouMjY6PgIGSk5SVlpeYmZqTkJAGDQ+dnpuekmGgAKejpKuiZqmprKqoZKGyrbOlqrejub6xvLGyw8TFzcprurGuvqybxq7ETbrItsCz0l7Zpc+6p9/cS967w9/S2FTF0u/mzehK4Oqz3eTl9vf4+fr7/P3+//DzCgwIEECxo8iDChwoUMGzp8CDGixIkUK1q8iDGjxo0XHDt6/AgypMiRJEuaPIkypcqVLFt+KwAAOw==";function DM(r){const e=r.step!==void 0?r.step:.01,t=X.useRef(null),s=X.useRef(null),i=X.useRef(null),n=X.useRef(null),a=X.useRef(null),[o]=X.useState(r.value),[l,c]=X.useState(r.value.offset[0]),[u,h]=X.useState(r.value.offset[1]),[d,p]=X.useState(r.value.repeat[0]),[f,m]=X.useState(r.value.repeat[1]);function x(b,v,S,M,A){if(r.onChange!==void 0){const C=r.prop!==void 0?r.prop:r.title;r.onChange(C,{src:b,offset:[v,S],repeat:[M,A]})}}function y(b){const v=t.current.src,S=b.target.value;switch(b.target){case s.current:c(S),x(v,S,u,d,f);break;case i.current:h(S),x(v,l,S,d,f);break;case n.current:p(S),x(v,l,u,S,f);break;case a.current:m(S),x(v,l,u,d,S);break}}return F.jsxs("div",{className:"imageField",children:[F.jsx("img",{alt:r.title,ref:t,onClick:()=>{TM().then(b=>{t.current.src=b,x(b,l,u,d,f)})},src:o.src.length>0?o.src:Wm}),F.jsxs("div",{className:"fields",children:[F.jsxs("div",{children:[F.jsx("span",{children:"Offset:"}),F.jsx("input",{ref:s,type:"number",value:l,step:e,name:Tt(),onChange:y}),F.jsx("input",{ref:i,type:"number",value:u,step:e,name:Tt(),onChange:y})]}),F.jsxs("div",{children:[F.jsx("span",{children:"Repeat:"}),F.jsx("input",{ref:n,type:"number",value:d,step:e,name:Tt(),onChange:y}),F.jsx("input",{ref:a,type:"number",value:f,step:e,name:Tt(),onChange:y})]}),F.jsx("button",{onClick:()=>{x("",l,u,d,f),t.current.src=Wm},children:"Clear"})]})]})}function yc(r){let e=r.value;e!==void 0&&(e.isColor!==void 0?e=jd(r.value):r.type==="color"&&(e=jd(new _.Color().setStyle(r.value,_.LinearSRGBColorSpace))));const[t,s]=X.useState(e),i=X.useRef(null),n=c=>{let u=c.target.value;if(r.type==="boolean")u=c.target.checked;else if(r.type==="option"&&(typeof r.value=="number"?u=Number(u):typeof r.value=="boolean"?u=!!u:typeof r.value=="object"&&(u=JSON.parse(u)),r.options!==void 0)){const h=r.options.length;for(let d=0;d<h&&r.options[d].value!==u;d++);}s(u),r.onChange!==void 0&&r.onChange(r.prop!==void 0?r.prop:r.title,u)},a={};r.disabled&&(a.opacity=.8);const o=r.type==="field"||r.type==="string"&&(t.length>100||t.search(`
21
- `)>-1),l=o||r.type==="image"||r.type==="vector2";return F.jsxs("div",{className:`field ${l?"block":""}`,style:a,children:[r.type!=="button"&&F.jsx("span",{ref:i,children:Uo(r.title)},"fieldLabel"),r.type==="string"&&!o&&F.jsx("input",{type:"text",disabled:r.disabled,onChange:n,value:t,name:Tt()}),(r.type==="field"||r.type==="string"&&o)&&F.jsx("textarea",{cols:50,rows:10,disabled:r.disabled!==void 0?r.disabled:!0,onChange:n,onKeyDown:c=>{r.onKeyDown!==void 0&&r.onKeyDown(c)},value:t,name:Tt()}),r.type==="boolean"&&F.jsx("input",{type:"checkbox",disabled:r.disabled,onChange:n,checked:t,name:Tt()}),r.type==="number"&&F.jsx(yr,{value:t,type:r.type,prop:r.prop!==void 0?r.prop:r.title,min:r.min,max:r.max,step:r.step,disabled:r.disabled,labelRef:i,onChange:r.onChange}),r.type==="range"&&F.jsx(yr,{value:t,type:r.type,prop:r.prop!==void 0?r.prop:r.title,min:r.min,max:r.max,step:r.step,disabled:r.disabled,labelRef:i,onChange:r.onChange}),r.type==="color"&&F.jsxs(F.Fragment,{children:[F.jsx("input",{type:"text",value:t.toString(),onChange:n,disabled:r.disabled,className:"color",name:Tt()}),F.jsx("input",{type:"color",value:t,onChange:n,disabled:r.disabled,name:Tt()})]}),r.type==="button"&&F.jsx("button",{disabled:r.disabled,onClick:()=>{r.onChange!==void 0&&r.onChange(r.prop!==void 0?r.prop:r.title,!0)},children:r.title}),r.type==="image"&&F.jsx(DM,{title:r.title,prop:r.prop,value:r.value,onChange:r.onChange}),r.type==="option"&&F.jsx(F.Fragment,{children:F.jsx("select",{onChange:n,disabled:r.disabled,defaultValue:r.value,name:Tt(),children:r.options?.map((c,u)=>F.jsx("option",{value:c.value,children:Uo(c.title)},u))})}),r.type==="vector2"&&F.jsx(fM,{step:r.step,value:t,min:0,max:1,onChange:n}),r.type==="grid3"&&F.jsx(Gm,{step:r.step,value:t,onChange:n}),r.type==="grid4"&&F.jsx(xM,{step:r.step,value:t,onChange:n}),r.type==="euler"&&F.jsx(Gm,{step:r.step,value:t,onChange:n})]})}function OM(r){return"items"in r}class Os extends X.Component{subgroupNames=[];subgroupElements=[];valueOverrides=new Map;three;constructor(e){super(e),this.three=e.three,this.state={lastUpdated:Date.now()}}addGroup(e){const t=[];e.items.forEach(n=>{t.push({type:n.type,prop:n.prop,title:n.title!==void 0?n.title:n.prop,value:n.value,min:n.min,max:n.max,step:n.step,options:n.options,disabled:n.disabled,onChange:(a,o)=>{e.onUpdate(a,o)}})});const s=X.createRef(),i=F.jsx(Os,{three:this.props.three,ref:s,title:e.title,expanded:e.expanded,items:t},Math.random());return this.subgroupNames.push(e.title),this.subgroupElements.push(i),this.setState({lastUpdated:Date.now()}),s}removeGroup(e){const t=this.subgroupNames.length;for(let s=0;s<t;s++){const i=this.subgroupNames[s];if(e===i){this.subgroupNames.splice(s,1),this.subgroupElements.splice(s,1),this.setState({lastUpdated:Date.now()});return}}}setField(e,t){this.valueOverrides.set(e,t),this.setState({lastUpdated:Date.now()})}render(){const e=[];return this.props.items.forEach(t=>{if(OM(t))e.push(F.jsx(Os,{three:this.props.three,title:Uo(t.title),items:t.items},Math.random()));else{const s=this.valueOverrides.get(t.title),i=s!==void 0?s:t.value;e.push(F.jsx(yc,{title:t.title,prop:t.prop,value:i,type:t.type,min:t.min,max:t.max,step:t.step,disabled:t.disabled,options:t.options,onChange:(n,a)=>{t.onChange!==void 0&&(this.valueOverrides.delete(t.title),t.onChange(n,a))},onKeyDown:n=>{t.onKeyDown!==void 0&&t.onKeyDown(n)}},Math.random()))}}),this.subgroupElements.forEach(t=>e.push(t)),F.jsx(fa,{three:this.props.three,label:this.props.title,open:this.props.expanded===!0,onToggle:t=>{this.props.onToggle&&this.props?.onToggle(t)},children:e})}}class Ce extends X.Component{static instance;static groups=[];static groupsRefs=[];static groupTitles=[];static three;constructor(e){super(e),this.state={lastUpdate:Date.now()},Ce.instance=this,Ce.three=e.three,e.three.addEventListener(me.ADD_GROUP,this.addGroup),e.three.addEventListener(me.REMOVE_GROUP,this.removeGroup)}componentWillUnmount(){this.props.three.removeEventListener(me.ADD_GROUP,this.addGroup),this.props.three.removeEventListener(me.REMOVE_GROUP,this.removeGroup)}render(){return F.jsx("div",{className:"customGroups",children:Ce.groups},this.state.lastUpdate)}addGroup=e=>{const t=JSON.parse(e.value),s=[];t.items.forEach(i=>{s.push({type:i.type,prop:i.prop,title:i.title!==void 0?i.title:i.prop,value:i.value,min:i.min,max:i.max,step:i.step,options:i.options,disabled:i.disabled,onChange:(n,a)=>{this.props.three.updateGroup(t.title,n,a)}})}),Ce.groups.push(F.jsx(Os,{three:this.props.three,title:t.title,items:s},Math.random())),Ce.groupTitles.push(t.title),this.setState({lastUpdate:Date.now()})};removeGroup=e=>{const t=e.value,s=Ce.groupTitles.length;for(let i=0;i<s;i++)if(t===Ce.groupTitles[i]){Ce.groups.splice(i,1),Ce.groupTitles.splice(i,1),this.setState({lastUpdate:Date.now()});return}};static addEditorGroup(e){const t=Ce.groupTitles.length;for(let a=0;a<t;a++)if(Ce.groupTitles[a]===e.title)return Ce.groupsRefs[a];const s=[];e.items.forEach(a=>{s.push({type:a.type,prop:a.prop,title:a.title!==void 0?a.title:a.prop,value:a.value,min:a.min,max:a.max,step:a.step,options:a.options,disabled:a.disabled,onChange:(o,l)=>{e.onUpdate(o,l)}})}),e.subgroups&&e.subgroups.length>0&&e.subgroups.forEach(a=>{const o=[];a.items.forEach(l=>{o.push({type:l.type,prop:l.prop,title:l.title!==void 0?l.title:l.prop,value:l.value,min:l.min,max:l.max,step:l.step,options:l.options,disabled:l.disabled,onChange:(c,u)=>{a.onUpdate(c,u)}})}),s.push({three:Ce.three,title:a.title,expanded:a.expanded,items:o})});const i=X.createRef(),n=F.jsx(Os,{three:Ce.three,ref:i,title:e.title,expanded:e.expanded,items:s},Math.random());return Ce.groups.push(n),Ce.groupsRefs.push(i),Ce.groupTitles.push(e.title),setTimeout(()=>{Ce.instance.setState({lastUpdate:Date.now()})},0),i}static removeEditorGroup(e){const t=Ce.groupTitles.length;for(let s=0;s<t;s++)if(e===Ce.groupTitles[s]){Ce.groups.splice(s,1),Ce.groupTitles.splice(s,1),Ce.instance.setState({lastUpdate:Date.now()});return}}static removeAllGroups(){for(let e=Ce.groupTitles.length;e>0;e--)Ce.groups.splice(e,1),Ce.groupTitles.splice(e,1);Ce.instance.setState({lastUpdate:Date.now()})}}function Hm(r){switch(r){case"fov":return"FOV";case"zoom":return"Zoom";case"near":return"Near";case"far":return"Far";case"focus":return"Focus";case"aspect":return"Aspect";case"filmGauge":return"Film Gauge";case"filmOffset":return"Film Offset";case"left":return"Left";case"right":return"Right";case"top":return"Top";case"bottom":return"Bottom"}return r}function LM(r,e){function t(){return`${e.name}_camera`}const s=localStorage.getItem(t()),i=s!==null?s==="open":!1;function n(o){localStorage.setItem(t(),o?"open":"closed")}const a=[];if(r.perspectiveCameraInfo!==void 0)for(const o in r.perspectiveCameraInfo)a.push({title:Hm(o),prop:o,type:"number",step:.01,value:r.perspectiveCameraInfo[o],onChange:(l,c)=>{e.updateObject(r.uuid,l,c),e.requestMethod(r.uuid,"updateProjectionMatrix");const u=e.getScene(r.uuid);if(u!==null){const h=u.getObjectByProperty("uuid",r.uuid);h!==void 0&&(ut(h,l,c),h.updateProjectionMatrix())}}});else if(r.orthographicCameraInfo!==void 0)for(const o in r.orthographicCameraInfo)a.push({title:Hm(o),prop:o,type:"number",step:.01,value:r.orthographicCameraInfo[o],onChange:(l,c)=>{e.updateObject(r.uuid,l,c),e.requestMethod(r.uuid,"updateProjectionMatrix");const u=e.getScene(r.uuid);if(u!==null){const h=u.getObjectByProperty("uuid",r.uuid);h!==void 0&&(ut(h,l,c),h.updateProjectionMatrix())}}});return F.jsx(Os,{three:e,title:"Camera",items:a,expanded:i,onToggle:o=>{n(o)}})}/**
22
- * @license
23
- * Copyright 2010-2026 Three.js Authors
24
- * SPDX-License-Identifier: MIT
25
- */const Zo="183",IM=0,UM=1,VM=2,kM=0,Sx=1,zM=2,vo=3,Si=0,Rt=1,qi=2,Xi=0,Es=1,ua=2,ha=3,da=4,ma=5,Ip=6,Ns=100,vx=101,Mx=102,GM=103,$M=104,bn=200,wx=201,Cx=202,Ax=203,Vo=204,ko=205,Ex=206,Nx=207,Rx=208,Px=209,Fx=210,Ac=0,Ec=1,Nc=2,wa=3,Rc=4,Pc=5,Fc=6,Bc=7,Eu=0,WM=1,HM=2,dr=0,jM=1,qM=2,XM=3,YM=4,ZM=6,QM=7,Up=300,Ca=301,Dc=302,Vp=303,kp=304,Qd=306,Aa=1e3,xi=1001,Ea=1002,at=1003,Bx=1004,zo=1005,Gt=1006,Kd=1007,Pn=1008,KM=1008,Ut=1009,ga=1010,ya=1011,pr=1012,Lt=1013,rt=1014,es=1015,Et=1016,Dx=1017,Ox=1018,Fn=1020,zp=35902,Gp=35899,Lx=1021,Nu=1022,ms=1023,Qs=1026,Yi=1027,Ru=1028,Pu=1029,_i=1030,Fu=1031,JM=1032,Bu=1033,Mo=33776,wo=33777,Co=33778,Ao=33779,Jd=35840,ep=35841,tp=35842,sp=35843,Oc=36196,Lc=37492,Ic=37496,Uc=37488,Vc=37489,Go=37490,kc=37491,zc=37808,Gc=37809,$c=37810,Wc=37811,Hc=37812,jc=37813,qc=37814,Xc=37815,Yc=37816,Zc=37817,Qc=37818,Kc=37819,Jc=37820,eu=37821,tu=36492,ew=36494,tw=36495,su=36283,iu=36284,$o=36285,nu=36286,Zi=0,sw=1,In="",ds="srgb",ru="srgb-linear",au="linear",ce="srgb",vh="",Ix="rg",iw="ga",nw=0,lr=7680,rw=7681,aw=7682,ow=7683,lw=34055,cw=34056,uw=5386,hw=512,dw=513,pw=514,fw=515,mw=516,gw=517,yw=518,ip=519,Ux=512,$p=513,Vx=514,Du=515,kx=516,zx=517,Ou=518,Gx=519,Na=35044,Wo=35048,gs=2e3,Ls=2001,bi={COMPUTE:"compute",RENDER:"render"},Bn={TEXTURE_COMPARE:"depthTextureCompare"};function xw(r){for(let e=r.length-1;e>=0;--e)if(r[e]>=65535)return!0;return!1}function ou(r){return ArrayBuffer.isView(r)&&!(r instanceof DataView)}function np(r){return document.createElementNS("http://www.w3.org/1999/xhtml",r)}function _w(){const r=np("canvas");return r.style.display="block",r}const jm={};function rp(...r){const e="THREE."+r.shift();console.log(e,...r)}function $x(r){const e=r[0];if(typeof e=="string"&&e.startsWith("TSL:")){const t=r[1];t&&t.isStackTrace?r[0]+=" "+t.getLocation():r[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return r}function W(...r){r=$x(r);const e="THREE."+r.shift();{const t=r[0];t&&t.isStackTrace?console.warn(t.getError(e)):console.warn(e,...r)}}function $(...r){r=$x(r);const e="THREE."+r.shift();{const t=r[0];t&&t.isStackTrace?console.error(t.getError(e)):console.error(e,...r)}}function Le(...r){const e=r.join(" ");e in jm||(jm[e]=!0,W(...r))}const Wx={[Ac]:Ec,[Nc]:Fc,[Rc]:Bc,[wa]:Pc,[Ec]:Ac,[Fc]:Nc,[Bc]:Rc,[Pc]:wa};let Gn=class{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const s=this._listeners;s[e]===void 0&&(s[e]=[]),s[e].indexOf(t)===-1&&s[e].push(t)}hasEventListener(e,t){const s=this._listeners;return s===void 0?!1:s[e]!==void 0&&s[e].indexOf(t)!==-1}removeEventListener(e,t){const s=this._listeners;if(s===void 0)return;const i=s[e];if(i!==void 0){const n=i.indexOf(t);n!==-1&&i.splice(n,1)}}dispatchEvent(e){const t=this._listeners;if(t===void 0)return;const s=t[e.type];if(s!==void 0){e.target=this;const i=s.slice(0);for(let n=0,a=i.length;n<a;n++)i[n].call(this,e);e.target=null}}};const Ft=["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 qm=1234567;const Eo=Math.PI/180,Ra=180/Math.PI;function Qi(){const r=Math.random()*4294967295|0,e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,s=Math.random()*4294967295|0;return(Ft[r&255]+Ft[r>>8&255]+Ft[r>>16&255]+Ft[r>>24&255]+"-"+Ft[e&255]+Ft[e>>8&255]+"-"+Ft[e>>16&15|64]+Ft[e>>24&255]+"-"+Ft[t&63|128]+Ft[t>>8&255]+"-"+Ft[t>>16&255]+Ft[t>>24&255]+Ft[s&255]+Ft[s>>8&255]+Ft[s>>16&255]+Ft[s>>24&255]).toLowerCase()}function be(r,e,t){return Math.max(e,Math.min(t,r))}function Wp(r,e){return(r%e+e)%e}function bw(r,e,t,s,i){return s+(r-e)*(i-s)/(t-e)}function Tw(r,e,t){return r!==e?(t-r)/(e-r):0}function No(r,e,t){return(1-t)*r+t*e}function Sw(r,e,t,s){return No(r,e,1-Math.exp(-t*s))}function vw(r,e=1){return e-Math.abs(Wp(r,e*2)-e)}function Mw(r,e,t){return r<=e?0:r>=t?1:(r=(r-e)/(t-e),r*r*(3-2*r))}function ww(r,e,t){return r<=e?0:r>=t?1:(r=(r-e)/(t-e),r*r*r*(r*(r*6-15)+10))}function Cw(r,e){return r+Math.floor(Math.random()*(e-r+1))}function Aw(r,e){return r+Math.random()*(e-r)}function Ew(r){return r*(.5-Math.random())}function Nw(r){r!==void 0&&(qm=r);let e=qm+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}function Rw(r){return r*Eo}function Pw(r){return r*Ra}function Fw(r){return(r&r-1)===0&&r!==0}function Bw(r){return Math.pow(2,Math.ceil(Math.log(r)/Math.LN2))}function Dw(r){return Math.pow(2,Math.floor(Math.log(r)/Math.LN2))}function Ow(r,e,t,s,i){const n=Math.cos,a=Math.sin,o=n(t/2),l=a(t/2),c=n((e+s)/2),u=a((e+s)/2),h=n((e-s)/2),d=a((e-s)/2),p=n((s-e)/2),f=a((s-e)/2);switch(i){case"XYX":r.set(o*u,l*h,l*d,o*c);break;case"YZY":r.set(l*d,o*u,l*h,o*c);break;case"ZXZ":r.set(l*h,l*d,o*u,o*c);break;case"XZX":r.set(o*u,l*f,l*p,o*c);break;case"YXY":r.set(l*p,o*u,l*f,o*c);break;case"ZYZ":r.set(l*f,l*p,o*u,o*c);break;default:W("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+i)}}function qt(r,e){switch(e.constructor){case Float32Array:return r;case Uint32Array:return r/4294967295;case Uint16Array:return r/65535;case Uint8Array:return r/255;case Int32Array:return Math.max(r/2147483647,-1);case Int16Array:return Math.max(r/32767,-1);case Int8Array:return Math.max(r/127,-1);default:throw new Error("Invalid component type.")}}function de(r,e){switch(e.constructor){case Float32Array:return r;case Uint32Array:return Math.round(r*4294967295);case Uint16Array:return Math.round(r*65535);case Uint8Array:return Math.round(r*255);case Int32Array:return Math.round(r*2147483647);case Int16Array:return Math.round(r*32767);case Int8Array:return Math.round(r*127);default:throw new Error("Invalid component type.")}}const Hx={DEG2RAD:Eo,RAD2DEG:Ra,generateUUID:Qi,clamp:be,euclideanModulo:Wp,mapLinear:bw,inverseLerp:Tw,lerp:No,damp:Sw,pingpong:vw,smoothstep:Mw,smootherstep:ww,randInt:Cw,randFloat:Aw,randFloatSpread:Ew,seededRandom:Nw,degToRad:Rw,radToDeg:Pw,isPowerOfTwo:Fw,ceilPowerOfTwo:Bw,floorPowerOfTwo:Dw,setQuaternionFromProperEuler:Ow,normalize:de,denormalize:qt};class xe{constructor(e=0,t=0){xe.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,s=this.y,i=e.elements;return this.x=i[0]*t+i[3]*s+i[6],this.y=i[1]*t+i[4]*s+i[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=be(this.x,e.x,t.x),this.y=be(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=be(this.x,e,t),this.y=be(this.y,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(be(s,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(t===0)return Math.PI/2;const s=this.dot(e)/t;return Math.acos(be(s,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,s=this.y-e.y;return t*t+s*s}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,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,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 s=Math.cos(t),i=Math.sin(t),n=this.x-e.x,a=this.y-e.y;return this.x=n*s-a*i+e.x,this.y=n*i+a*s+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class vr{constructor(e=0,t=0,s=0,i=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=s,this._w=i}static slerpFlat(e,t,s,i,n,a,o){let l=s[i+0],c=s[i+1],u=s[i+2],h=s[i+3],d=n[a+0],p=n[a+1],f=n[a+2],m=n[a+3];if(h!==m||l!==d||c!==p||u!==f){let x=l*d+c*p+u*f+h*m;x<0&&(d=-d,p=-p,f=-f,m=-m,x=-x);let y=1-o;if(x<.9995){const b=Math.acos(x),v=Math.sin(b);y=Math.sin(y*b)/v,o=Math.sin(o*b)/v,l=l*y+d*o,c=c*y+p*o,u=u*y+f*o,h=h*y+m*o}else{l=l*y+d*o,c=c*y+p*o,u=u*y+f*o,h=h*y+m*o;const b=1/Math.sqrt(l*l+c*c+u*u+h*h);l*=b,c*=b,u*=b,h*=b}}e[t]=l,e[t+1]=c,e[t+2]=u,e[t+3]=h}static multiplyQuaternionsFlat(e,t,s,i,n,a){const o=s[i],l=s[i+1],c=s[i+2],u=s[i+3],h=n[a],d=n[a+1],p=n[a+2],f=n[a+3];return e[t]=o*f+u*h+l*p-c*d,e[t+1]=l*f+u*d+c*h-o*p,e[t+2]=c*f+u*p+o*d-l*h,e[t+3]=u*f-o*h-l*d-c*p,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,s,i){return this._x=e,this._y=t,this._z=s,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const s=e._x,i=e._y,n=e._z,a=e._order,o=Math.cos,l=Math.sin,c=o(s/2),u=o(i/2),h=o(n/2),d=l(s/2),p=l(i/2),f=l(n/2);switch(a){case"XYZ":this._x=d*u*h+c*p*f,this._y=c*p*h-d*u*f,this._z=c*u*f+d*p*h,this._w=c*u*h-d*p*f;break;case"YXZ":this._x=d*u*h+c*p*f,this._y=c*p*h-d*u*f,this._z=c*u*f-d*p*h,this._w=c*u*h+d*p*f;break;case"ZXY":this._x=d*u*h-c*p*f,this._y=c*p*h+d*u*f,this._z=c*u*f+d*p*h,this._w=c*u*h-d*p*f;break;case"ZYX":this._x=d*u*h-c*p*f,this._y=c*p*h+d*u*f,this._z=c*u*f-d*p*h,this._w=c*u*h+d*p*f;break;case"YZX":this._x=d*u*h+c*p*f,this._y=c*p*h+d*u*f,this._z=c*u*f-d*p*h,this._w=c*u*h-d*p*f;break;case"XZY":this._x=d*u*h-c*p*f,this._y=c*p*h-d*u*f,this._z=c*u*f+d*p*h,this._w=c*u*h+d*p*f;break;default:W("Quaternion: .setFromEuler() encountered an unknown order: "+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const s=t/2,i=Math.sin(s);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(s),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,s=t[0],i=t[4],n=t[8],a=t[1],o=t[5],l=t[9],c=t[2],u=t[6],h=t[10],d=s+o+h;if(d>0){const p=.5/Math.sqrt(d+1);this._w=.25/p,this._x=(u-l)*p,this._y=(n-c)*p,this._z=(a-i)*p}else if(s>o&&s>h){const p=2*Math.sqrt(1+s-o-h);this._w=(u-l)/p,this._x=.25*p,this._y=(i+a)/p,this._z=(n+c)/p}else if(o>h){const p=2*Math.sqrt(1+o-s-h);this._w=(n-c)/p,this._x=(i+a)/p,this._y=.25*p,this._z=(l+u)/p}else{const p=2*Math.sqrt(1+h-s-o);this._w=(a-i)/p,this._x=(n+c)/p,this._y=(l+u)/p,this._z=.25*p}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let s=e.dot(t)+1;return s<1e-8?(s=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=s):(this._x=0,this._y=-e.z,this._z=e.y,this._w=s)):(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=s),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(be(this.dot(e),-1,1)))}rotateTowards(e,t){const s=this.angleTo(e);if(s===0)return this;const i=Math.min(1,t/s);return this.slerp(e,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(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 s=e._x,i=e._y,n=e._z,a=e._w,o=t._x,l=t._y,c=t._z,u=t._w;return this._x=s*u+a*o+i*c-n*l,this._y=i*u+a*l+n*o-s*c,this._z=n*u+a*c+s*l-i*o,this._w=a*u-s*o-i*l-n*c,this._onChangeCallback(),this}slerp(e,t){let s=e._x,i=e._y,n=e._z,a=e._w,o=this.dot(e);o<0&&(s=-s,i=-i,n=-n,a=-a,o=-o);let l=1-t;if(o<.9995){const c=Math.acos(o),u=Math.sin(c);l=Math.sin(l*c)/u,t=Math.sin(t*c)/u,this._x=this._x*l+s*t,this._y=this._y*l+i*t,this._z=this._z*l+n*t,this._w=this._w*l+a*t,this._onChangeCallback()}else this._x=this._x*l+s*t,this._y=this._y*l+i*t,this._z=this._z*l+n*t,this._w=this._w*l+a*t,this.normalize();return this}slerpQuaternions(e,t,s){return this.copy(e).slerp(t,s)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),s=Math.random(),i=Math.sqrt(1-s),n=Math.sqrt(s);return this.set(i*Math.sin(e),i*Math.cos(e),n*Math.sin(t),n*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class D{constructor(e=0,t=0,s=0){D.prototype.isVector3=!0,this.x=e,this.y=t,this.z=s}set(e,t,s){return s===void 0&&(s=this.z),this.x=e,this.y=t,this.z=s,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(Xm.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Xm.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,s=this.y,i=this.z,n=e.elements;return this.x=n[0]*t+n[3]*s+n[6]*i,this.y=n[1]*t+n[4]*s+n[7]*i,this.z=n[2]*t+n[5]*s+n[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,s=this.y,i=this.z,n=e.elements,a=1/(n[3]*t+n[7]*s+n[11]*i+n[15]);return this.x=(n[0]*t+n[4]*s+n[8]*i+n[12])*a,this.y=(n[1]*t+n[5]*s+n[9]*i+n[13])*a,this.z=(n[2]*t+n[6]*s+n[10]*i+n[14])*a,this}applyQuaternion(e){const t=this.x,s=this.y,i=this.z,n=e.x,a=e.y,o=e.z,l=e.w,c=2*(a*i-o*s),u=2*(o*t-n*i),h=2*(n*s-a*t);return this.x=t+l*c+a*h-o*u,this.y=s+l*u+o*c-n*h,this.z=i+l*h+n*u-a*c,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,s=this.y,i=this.z,n=e.elements;return this.x=n[0]*t+n[4]*s+n[8]*i,this.y=n[1]*t+n[5]*s+n[9]*i,this.z=n[2]*t+n[6]*s+n[10]*i,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=be(this.x,e.x,t.x),this.y=be(this.y,e.y,t.y),this.z=be(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=be(this.x,e,t),this.y=be(this.y,e,t),this.z=be(this.z,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(be(s,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,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,this.z=e.z+(t.z-e.z)*s,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const s=e.x,i=e.y,n=e.z,a=t.x,o=t.y,l=t.z;return this.x=i*l-n*o,this.y=n*a-s*l,this.z=s*o-i*a,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const s=e.dot(this)/t;return this.copy(e).multiplyScalar(s)}projectOnPlane(e){return Mh.copy(this).projectOnVector(e),this.sub(Mh)}reflect(e){return this.sub(Mh.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const s=this.dot(e)/t;return Math.acos(be(s,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,s=this.y-e.y,i=this.z-e.z;return t*t+s*s+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,s){const i=Math.sin(t)*e;return this.x=i*Math.sin(s),this.y=Math.cos(t)*e,this.z=i*Math.cos(s),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,s){return this.x=e*Math.sin(t),this.y=s,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(),s=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=s,this.z=i,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}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=Math.random()*2-1,s=Math.sqrt(1-t*t);return this.x=s*Math.cos(e),this.y=t,this.z=s*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const Mh=new D,Xm=new vr;class as{constructor(e,t,s,i,n,a,o,l,c){as.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,s,i,n,a,o,l,c)}set(e,t,s,i,n,a,o,l,c){const u=this.elements;return u[0]=e,u[1]=i,u[2]=o,u[3]=t,u[4]=n,u[5]=l,u[6]=s,u[7]=a,u[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,s=e.elements;return t[0]=s[0],t[1]=s[1],t[2]=s[2],t[3]=s[3],t[4]=s[4],t[5]=s[5],t[6]=s[6],t[7]=s[7],t[8]=s[8],this}extractBasis(e,t,s){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),s.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 s=e.elements,i=t.elements,n=this.elements,a=s[0],o=s[3],l=s[6],c=s[1],u=s[4],h=s[7],d=s[2],p=s[5],f=s[8],m=i[0],x=i[3],y=i[6],b=i[1],v=i[4],S=i[7],M=i[2],A=i[5],C=i[8];return n[0]=a*m+o*b+l*M,n[3]=a*x+o*v+l*A,n[6]=a*y+o*S+l*C,n[1]=c*m+u*b+h*M,n[4]=c*x+u*v+h*A,n[7]=c*y+u*S+h*C,n[2]=d*m+p*b+f*M,n[5]=d*x+p*v+f*A,n[8]=d*y+p*S+f*C,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],s=e[1],i=e[2],n=e[3],a=e[4],o=e[5],l=e[6],c=e[7],u=e[8];return t*a*u-t*o*c-s*n*u+s*o*l+i*n*c-i*a*l}invert(){const e=this.elements,t=e[0],s=e[1],i=e[2],n=e[3],a=e[4],o=e[5],l=e[6],c=e[7],u=e[8],h=u*a-o*c,d=o*l-u*n,p=c*n-a*l,f=t*h+s*d+i*p;if(f===0)return this.set(0,0,0,0,0,0,0,0,0);const m=1/f;return e[0]=h*m,e[1]=(i*c-u*s)*m,e[2]=(o*s-i*a)*m,e[3]=d*m,e[4]=(u*t-i*l)*m,e[5]=(i*n-o*t)*m,e[6]=p*m,e[7]=(s*l-c*t)*m,e[8]=(a*t-s*n)*m,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,s,i,n,a,o){const l=Math.cos(n),c=Math.sin(n);return this.set(s*l,s*c,-s*(l*a+c*o)+a+e,-i*c,i*l,-i*(-c*a+l*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(wh.makeScale(e,t)),this}rotate(e){return this.premultiply(wh.makeRotation(-e)),this}translate(e,t){return this.premultiply(wh.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),s=Math.sin(e);return this.set(t,-s,0,s,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,s=e.elements;for(let i=0;i<9;i++)if(t[i]!==s[i])return!1;return!0}fromArray(e,t=0){for(let s=0;s<9;s++)this.elements[s]=e[s+t];return this}toArray(e=[],t=0){const s=this.elements;return e[t]=s[0],e[t+1]=s[1],e[t+2]=s[2],e[t+3]=s[3],e[t+4]=s[4],e[t+5]=s[5],e[t+6]=s[6],e[t+7]=s[7],e[t+8]=s[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const wh=new as,Ym=new as().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),Zm=new as().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Lw(){const r={enabled:!0,workingColorSpace:ru,spaces:{},convert:function(i,n,a){return this.enabled===!1||n===a||!n||!a||(this.spaces[n].transfer===ce&&(i.r=Ki(i.r),i.g=Ki(i.g),i.b=Ki(i.b)),this.spaces[n].primaries!==this.spaces[a].primaries&&(i.applyMatrix3(this.spaces[n].toXYZ),i.applyMatrix3(this.spaces[a].fromXYZ)),this.spaces[a].transfer===ce&&(i.r=xa(i.r),i.g=xa(i.g),i.b=xa(i.b))),i},workingToColorSpace:function(i,n){return this.convert(i,this.workingColorSpace,n)},colorSpaceToWorking:function(i,n){return this.convert(i,n,this.workingColorSpace)},getPrimaries:function(i){return this.spaces[i].primaries},getTransfer:function(i){return i===In?au:this.spaces[i].transfer},getToneMappingMode:function(i){return this.spaces[i].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(i,n=this.workingColorSpace){return i.fromArray(this.spaces[n].luminanceCoefficients)},define:function(i){Object.assign(this.spaces,i)},_getMatrix:function(i,n,a){return i.copy(this.spaces[n].toXYZ).multiply(this.spaces[a].fromXYZ)},_getDrawingBufferColorSpace:function(i){return this.spaces[i].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(i=this.workingColorSpace){return this.spaces[i].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(i,n){return Le("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),r.workingToColorSpace(i,n)},toWorkingColorSpace:function(i,n){return Le("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),r.colorSpaceToWorking(i,n)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],s=[.3127,.329];return r.define({[ru]:{primaries:e,whitePoint:s,transfer:au,toXYZ:Ym,fromXYZ:Zm,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:ds},outputColorSpaceConfig:{drawingBufferColorSpace:ds}},[ds]:{primaries:e,whitePoint:s,transfer:ce,toXYZ:Ym,fromXYZ:Zm,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:ds}}}),r}const Ae=Lw();function Ki(r){return r<.04045?r*.0773993808:Math.pow(r*.9478672986+.0521327014,2.4)}function xa(r){return r<.0031308?r*12.92:1.055*Math.pow(r,.41666)-.055}let Or;class Iw{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let s;if(e instanceof HTMLCanvasElement)s=e;else{Or===void 0&&(Or=np("canvas")),Or.width=e.width,Or.height=e.height;const i=Or.getContext("2d");e instanceof ImageData?i.putImageData(e,0,0):i.drawImage(e,0,0,e.width,e.height),s=Or}return s.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=np("canvas");t.width=e.width,t.height=e.height;const s=t.getContext("2d");s.drawImage(e,0,0,e.width,e.height);const i=s.getImageData(0,0,e.width,e.height),n=i.data;for(let a=0;a<n.length;a++)n[a]=Ki(n[a]/255)*255;return s.putImageData(i,0,0),t}else if(e.data){const t=e.data.slice(0);for(let s=0;s<t.length;s++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[s]=Math.floor(Ki(t[s]/255)*255):t[s]=Ki(t[s]);return{data:t,width:e.width,height:e.height}}else return W("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let Uw=0;class Hp{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:Uw++}),this.uuid=Qi(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){const t=this.data;return typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):typeof VideoFrame<"u"&&t instanceof VideoFrame?e.set(t.displayHeight,t.displayWidth,0):t!==null?e.set(t.width,t.height,t.depth||0):e.set(0,0,0),e}set needsUpdate(e){e===!0&&this.version++}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];const s={uuid:this.uuid,url:""},i=this.data;if(i!==null){let n;if(Array.isArray(i)){n=[];for(let a=0,o=i.length;a<o;a++)i[a].isDataTexture?n.push(Ch(i[a].image)):n.push(Ch(i[a]))}else n=Ch(i);s.url=n}return t||(e.images[this.uuid]=s),s}}function Ch(r){return typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&r instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&r instanceof ImageBitmap?Iw.getDataURL(r):r.data?{data:Array.from(r.data),width:r.width,height:r.height,type:r.data.constructor.name}:(W("Texture: Unable to serialize Texture."),{})}let Vw=0;const Ah=new D;class kt extends Gn{constructor(e=kt.DEFAULT_IMAGE,t=kt.DEFAULT_MAPPING,s=xi,i=xi,n=Gt,a=Pn,o=ms,l=Ut,c=kt.DEFAULT_ANISOTROPY,u=In){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:Vw++}),this.uuid=Qi(),this.name="",this.source=new Hp(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=s,this.wrapT=i,this.magFilter=n,this.minFilter=a,this.anisotropy=c,this.format=o,this.internalFormat=null,this.type=l,this.offset=new xe(0,0),this.repeat=new xe(1,1),this.center=new xe(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new as,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=u,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(e&&e.depth&&e.depth>1),this.pmremVersion=0}get width(){return this.source.getSize(Ah).x}get height(){return this.source.getSize(Ah).y}get depth(){return this.source.getSize(Ah).z}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const t in e){const s=e[t];if(s===void 0){W(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const i=this[t];if(i===void 0){W(`Texture.setValues(): property '${t}' does not exist.`);continue}i&&s&&i.isVector2&&s.isVector2||i&&s&&i.isVector3&&s.isVector3||i&&s&&i.isMatrix3&&s.isMatrix3?i.copy(s):this[t]=s}}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const s={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(s.userData=this.userData),t||(e.textures[this.uuid]=s),s}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==Up)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case Aa:e.x=e.x-Math.floor(e.x);break;case xi:e.x=e.x<0?0:1;break;case Ea:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case Aa:e.y=e.y-Math.floor(e.y);break;case xi:e.y=e.y<0?0:1;break;case Ea:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}kt.DEFAULT_IMAGE=null;kt.DEFAULT_MAPPING=Up;kt.DEFAULT_ANISOTROPY=1;class Ee{constructor(e=0,t=0,s=0,i=1){Ee.prototype.isVector4=!0,this.x=e,this.y=t,this.z=s,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,s,i){return this.x=e,this.y=t,this.z=s,this.w=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?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,s=this.y,i=this.z,n=this.w,a=e.elements;return this.x=a[0]*t+a[4]*s+a[8]*i+a[12]*n,this.y=a[1]*t+a[5]*s+a[9]*i+a[13]*n,this.z=a[2]*t+a[6]*s+a[10]*i+a[14]*n,this.w=a[3]*t+a[7]*s+a[11]*i+a[15]*n,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,s,i,n;const l=e.elements,c=l[0],u=l[4],h=l[8],d=l[1],p=l[5],f=l[9],m=l[2],x=l[6],y=l[10];if(Math.abs(u-d)<.01&&Math.abs(h-m)<.01&&Math.abs(f-x)<.01){if(Math.abs(u+d)<.1&&Math.abs(h+m)<.1&&Math.abs(f+x)<.1&&Math.abs(c+p+y-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const v=(c+1)/2,S=(p+1)/2,M=(y+1)/2,A=(u+d)/4,C=(h+m)/4,P=(f+x)/4;return v>S&&v>M?v<.01?(s=0,i=.707106781,n=.707106781):(s=Math.sqrt(v),i=A/s,n=C/s):S>M?S<.01?(s=.707106781,i=0,n=.707106781):(i=Math.sqrt(S),s=A/i,n=P/i):M<.01?(s=.707106781,i=.707106781,n=0):(n=Math.sqrt(M),s=C/n,i=P/n),this.set(s,i,n,t),this}let b=Math.sqrt((x-f)*(x-f)+(h-m)*(h-m)+(d-u)*(d-u));return Math.abs(b)<.001&&(b=1),this.x=(x-f)/b,this.y=(h-m)/b,this.z=(d-u)/b,this.w=Math.acos((c+p+y-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=be(this.x,e.x,t.x),this.y=be(this.y,e.y,t.y),this.z=be(this.z,e.z,t.z),this.w=be(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=be(this.x,e,t),this.y=be(this.y,e,t),this.z=be(this.z,e,t),this.w=be(this.w,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(be(s,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,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,this.z=e.z+(t.z-e.z)*s,this.w=e.w+(t.w-e.w)*s,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 nn extends Gn{constructor(e=1,t=1,s={}){super(),s=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Gt,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},s),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=s.depth,this.scissor=new Ee(0,0,e,t),this.scissorTest=!1,this.viewport=new Ee(0,0,e,t),this.textures=[];const i={width:e,height:t,depth:s.depth},n=new kt(i),a=s.count;for(let o=0;o<a;o++)this.textures[o]=n.clone(),this.textures[o].isRenderTargetTexture=!0,this.textures[o].renderTarget=this;this._setTextureOptions(s),this.depthBuffer=s.depthBuffer,this.stencilBuffer=s.stencilBuffer,this.resolveDepthBuffer=s.resolveDepthBuffer,this.resolveStencilBuffer=s.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=s.depthTexture,this.samples=s.samples,this.multiview=s.multiview}_setTextureOptions(e={}){const t={minFilter:Gt,generateMipmaps:!1,flipY:!1,internalFormat:null};e.mapping!==void 0&&(t.mapping=e.mapping),e.wrapS!==void 0&&(t.wrapS=e.wrapS),e.wrapT!==void 0&&(t.wrapT=e.wrapT),e.wrapR!==void 0&&(t.wrapR=e.wrapR),e.magFilter!==void 0&&(t.magFilter=e.magFilter),e.minFilter!==void 0&&(t.minFilter=e.minFilter),e.format!==void 0&&(t.format=e.format),e.type!==void 0&&(t.type=e.type),e.anisotropy!==void 0&&(t.anisotropy=e.anisotropy),e.colorSpace!==void 0&&(t.colorSpace=e.colorSpace),e.flipY!==void 0&&(t.flipY=e.flipY),e.generateMipmaps!==void 0&&(t.generateMipmaps=e.generateMipmaps),e.internalFormat!==void 0&&(t.internalFormat=e.internalFormat);for(let s=0;s<this.textures.length;s++)this.textures[s].setValues(t)}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&(this._depthTexture.renderTarget=null),e!==null&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,s=1){if(this.width!==e||this.height!==t||this.depth!==s){this.width=e,this.height=t,this.depth=s;for(let i=0,n=this.textures.length;i<n;i++)this.textures[i].image.width=e,this.textures[i].image.height=t,this.textures[i].image.depth=s,this.textures[i].isData3DTexture!==!0&&(this.textures[i].isArrayTexture=this.textures[i].image.depth>1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,s=e.textures.length;t<s;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 Hp(i)}return this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,e.depthTexture!==null&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}}class kw extends kt{constructor(e=null,t=1,s=1,i=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:s,depth:i},this.magFilter=at,this.minFilter=at,this.wrapR=xi,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class ve{constructor(e,t,s,i,n,a,o,l,c,u,h,d,p,f,m,x){ve.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,s,i,n,a,o,l,c,u,h,d,p,f,m,x)}set(e,t,s,i,n,a,o,l,c,u,h,d,p,f,m,x){const y=this.elements;return y[0]=e,y[4]=t,y[8]=s,y[12]=i,y[1]=n,y[5]=a,y[9]=o,y[13]=l,y[2]=c,y[6]=u,y[10]=h,y[14]=d,y[3]=p,y[7]=f,y[11]=m,y[15]=x,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 ve().fromArray(this.elements)}copy(e){const t=this.elements,s=e.elements;return t[0]=s[0],t[1]=s[1],t[2]=s[2],t[3]=s[3],t[4]=s[4],t[5]=s[5],t[6]=s[6],t[7]=s[7],t[8]=s[8],t[9]=s[9],t[10]=s[10],t[11]=s[11],t[12]=s[12],t[13]=s[13],t[14]=s[14],t[15]=s[15],this}copyPosition(e){const t=this.elements,s=e.elements;return t[12]=s[12],t[13]=s[13],t[14]=s[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,s){return this.determinant()===0?(e.set(1,0,0),t.set(0,1,0),s.set(0,0,1),this):(e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),s.setFromMatrixColumn(this,2),this)}makeBasis(e,t,s){return this.set(e.x,t.x,s.x,0,e.y,t.y,s.y,0,e.z,t.z,s.z,0,0,0,0,1),this}extractRotation(e){if(e.determinant()===0)return this.identity();const t=this.elements,s=e.elements,i=1/Lr.setFromMatrixColumn(e,0).length(),n=1/Lr.setFromMatrixColumn(e,1).length(),a=1/Lr.setFromMatrixColumn(e,2).length();return t[0]=s[0]*i,t[1]=s[1]*i,t[2]=s[2]*i,t[3]=0,t[4]=s[4]*n,t[5]=s[5]*n,t[6]=s[6]*n,t[7]=0,t[8]=s[8]*a,t[9]=s[9]*a,t[10]=s[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,s=e.x,i=e.y,n=e.z,a=Math.cos(s),o=Math.sin(s),l=Math.cos(i),c=Math.sin(i),u=Math.cos(n),h=Math.sin(n);if(e.order==="XYZ"){const d=a*u,p=a*h,f=o*u,m=o*h;t[0]=l*u,t[4]=-l*h,t[8]=c,t[1]=p+f*c,t[5]=d-m*c,t[9]=-o*l,t[2]=m-d*c,t[6]=f+p*c,t[10]=a*l}else if(e.order==="YXZ"){const d=l*u,p=l*h,f=c*u,m=c*h;t[0]=d+m*o,t[4]=f*o-p,t[8]=a*c,t[1]=a*h,t[5]=a*u,t[9]=-o,t[2]=p*o-f,t[6]=m+d*o,t[10]=a*l}else if(e.order==="ZXY"){const d=l*u,p=l*h,f=c*u,m=c*h;t[0]=d-m*o,t[4]=-a*h,t[8]=f+p*o,t[1]=p+f*o,t[5]=a*u,t[9]=m-d*o,t[2]=-a*c,t[6]=o,t[10]=a*l}else if(e.order==="ZYX"){const d=a*u,p=a*h,f=o*u,m=o*h;t[0]=l*u,t[4]=f*c-p,t[8]=d*c+m,t[1]=l*h,t[5]=m*c+d,t[9]=p*c-f,t[2]=-c,t[6]=o*l,t[10]=a*l}else if(e.order==="YZX"){const d=a*l,p=a*c,f=o*l,m=o*c;t[0]=l*u,t[4]=m-d*h,t[8]=f*h+p,t[1]=h,t[5]=a*u,t[9]=-o*u,t[2]=-c*u,t[6]=p*h+f,t[10]=d-m*h}else if(e.order==="XZY"){const d=a*l,p=a*c,f=o*l,m=o*c;t[0]=l*u,t[4]=-h,t[8]=c*u,t[1]=d*h+m,t[5]=a*u,t[9]=p*h-f,t[2]=f*h-p,t[6]=o*u,t[10]=m*h+d}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(zw,e,Gw)}lookAt(e,t,s){const i=this.elements;return os.subVectors(e,t),os.lengthSq()===0&&(os.z=1),os.normalize(),on.crossVectors(s,os),on.lengthSq()===0&&(Math.abs(s.z)===1?os.x+=1e-4:os.z+=1e-4,os.normalize(),on.crossVectors(s,os)),on.normalize(),cl.crossVectors(os,on),i[0]=on.x,i[4]=cl.x,i[8]=os.x,i[1]=on.y,i[5]=cl.y,i[9]=os.y,i[2]=on.z,i[6]=cl.z,i[10]=os.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const s=e.elements,i=t.elements,n=this.elements,a=s[0],o=s[4],l=s[8],c=s[12],u=s[1],h=s[5],d=s[9],p=s[13],f=s[2],m=s[6],x=s[10],y=s[14],b=s[3],v=s[7],S=s[11],M=s[15],A=i[0],C=i[4],P=i[8],B=i[12],V=i[1],Y=i[5],J=i[9],K=i[13],te=i[2],q=i[6],oe=i[10],Pe=i[14],ge=i[3],le=i[7],Ue=i[11],He=i[15];return n[0]=a*A+o*V+l*te+c*ge,n[4]=a*C+o*Y+l*q+c*le,n[8]=a*P+o*J+l*oe+c*Ue,n[12]=a*B+o*K+l*Pe+c*He,n[1]=u*A+h*V+d*te+p*ge,n[5]=u*C+h*Y+d*q+p*le,n[9]=u*P+h*J+d*oe+p*Ue,n[13]=u*B+h*K+d*Pe+p*He,n[2]=f*A+m*V+x*te+y*ge,n[6]=f*C+m*Y+x*q+y*le,n[10]=f*P+m*J+x*oe+y*Ue,n[14]=f*B+m*K+x*Pe+y*He,n[3]=b*A+v*V+S*te+M*ge,n[7]=b*C+v*Y+S*q+M*le,n[11]=b*P+v*J+S*oe+M*Ue,n[15]=b*B+v*K+S*Pe+M*He,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],s=e[4],i=e[8],n=e[12],a=e[1],o=e[5],l=e[9],c=e[13],u=e[2],h=e[6],d=e[10],p=e[14],f=e[3],m=e[7],x=e[11],y=e[15],b=l*p-c*d,v=o*p-c*h,S=o*d-l*h,M=a*p-c*u,A=a*d-l*u,C=a*h-o*u;return t*(m*b-x*v+y*S)-s*(f*b-x*M+y*A)+i*(f*v-m*M+y*C)-n*(f*S-m*A+x*C)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,s){const i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=t,i[14]=s),this}invert(){const e=this.elements,t=e[0],s=e[1],i=e[2],n=e[3],a=e[4],o=e[5],l=e[6],c=e[7],u=e[8],h=e[9],d=e[10],p=e[11],f=e[12],m=e[13],x=e[14],y=e[15],b=t*o-s*a,v=t*l-i*a,S=t*c-n*a,M=s*l-i*o,A=s*c-n*o,C=i*c-n*l,P=u*m-h*f,B=u*x-d*f,V=u*y-p*f,Y=h*x-d*m,J=h*y-p*m,K=d*y-p*x,te=b*K-v*J+S*Y+M*V-A*B+C*P;if(te===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const q=1/te;return e[0]=(o*K-l*J+c*Y)*q,e[1]=(i*J-s*K-n*Y)*q,e[2]=(m*C-x*A+y*M)*q,e[3]=(d*A-h*C-p*M)*q,e[4]=(l*V-a*K-c*B)*q,e[5]=(t*K-i*V+n*B)*q,e[6]=(x*S-f*C-y*v)*q,e[7]=(u*C-d*S+p*v)*q,e[8]=(a*J-o*V+c*P)*q,e[9]=(s*V-t*J-n*P)*q,e[10]=(f*A-m*S+y*b)*q,e[11]=(h*S-u*A-p*b)*q,e[12]=(o*B-a*Y-l*P)*q,e[13]=(t*Y-s*B+i*P)*q,e[14]=(m*v-f*M-x*b)*q,e[15]=(u*M-h*v+d*b)*q,this}scale(e){const t=this.elements,s=e.x,i=e.y,n=e.z;return t[0]*=s,t[4]*=i,t[8]*=n,t[1]*=s,t[5]*=i,t[9]*=n,t[2]*=s,t[6]*=i,t[10]*=n,t[3]*=s,t[7]*=i,t[11]*=n,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],s=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,s,i))}makeTranslation(e,t,s){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,s,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),s=Math.sin(e);return this.set(1,0,0,0,0,t,-s,0,0,s,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,0,s,0,0,1,0,0,-s,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,-s,0,0,s,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const s=Math.cos(t),i=Math.sin(t),n=1-s,a=e.x,o=e.y,l=e.z,c=n*a,u=n*o;return this.set(c*a+s,c*o-i*l,c*l+i*o,0,c*o+i*l,u*o+s,u*l-i*a,0,c*l-i*o,u*l+i*a,n*l*l+s,0,0,0,0,1),this}makeScale(e,t,s){return this.set(e,0,0,0,0,t,0,0,0,0,s,0,0,0,0,1),this}makeShear(e,t,s,i,n,a){return this.set(1,s,n,0,e,1,a,0,t,i,1,0,0,0,0,1),this}compose(e,t,s){const i=this.elements,n=t._x,a=t._y,o=t._z,l=t._w,c=n+n,u=a+a,h=o+o,d=n*c,p=n*u,f=n*h,m=a*u,x=a*h,y=o*h,b=l*c,v=l*u,S=l*h,M=s.x,A=s.y,C=s.z;return i[0]=(1-(m+y))*M,i[1]=(p+S)*M,i[2]=(f-v)*M,i[3]=0,i[4]=(p-S)*A,i[5]=(1-(d+y))*A,i[6]=(x+b)*A,i[7]=0,i[8]=(f+v)*C,i[9]=(x-b)*C,i[10]=(1-(d+m))*C,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,s){const i=this.elements;e.x=i[12],e.y=i[13],e.z=i[14];const n=this.determinant();if(n===0)return s.set(1,1,1),t.identity(),this;let a=Lr.set(i[0],i[1],i[2]).length();const o=Lr.set(i[4],i[5],i[6]).length(),l=Lr.set(i[8],i[9],i[10]).length();n<0&&(a=-a),$s.copy(this);const c=1/a,u=1/o,h=1/l;return $s.elements[0]*=c,$s.elements[1]*=c,$s.elements[2]*=c,$s.elements[4]*=u,$s.elements[5]*=u,$s.elements[6]*=u,$s.elements[8]*=h,$s.elements[9]*=h,$s.elements[10]*=h,t.setFromRotationMatrix($s),s.x=a,s.y=o,s.z=l,this}makePerspective(e,t,s,i,n,a,o=gs,l=!1){const c=this.elements,u=2*n/(t-e),h=2*n/(s-i),d=(t+e)/(t-e),p=(s+i)/(s-i);let f,m;if(l)f=n/(a-n),m=a*n/(a-n);else if(o===gs)f=-(a+n)/(a-n),m=-2*a*n/(a-n);else if(o===Ls)f=-a/(a-n),m=-a*n/(a-n);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return c[0]=u,c[4]=0,c[8]=d,c[12]=0,c[1]=0,c[5]=h,c[9]=p,c[13]=0,c[2]=0,c[6]=0,c[10]=f,c[14]=m,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,s,i,n,a,o=gs,l=!1){const c=this.elements,u=2/(t-e),h=2/(s-i),d=-(t+e)/(t-e),p=-(s+i)/(s-i);let f,m;if(l)f=1/(a-n),m=a/(a-n);else if(o===gs)f=-2/(a-n),m=-(a+n)/(a-n);else if(o===Ls)f=-1/(a-n),m=-n/(a-n);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return c[0]=u,c[4]=0,c[8]=0,c[12]=d,c[1]=0,c[5]=h,c[9]=0,c[13]=p,c[2]=0,c[6]=0,c[10]=f,c[14]=m,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){const t=this.elements,s=e.elements;for(let i=0;i<16;i++)if(t[i]!==s[i])return!1;return!0}fromArray(e,t=0){for(let s=0;s<16;s++)this.elements[s]=e[s+t];return this}toArray(e=[],t=0){const s=this.elements;return e[t]=s[0],e[t+1]=s[1],e[t+2]=s[2],e[t+3]=s[3],e[t+4]=s[4],e[t+5]=s[5],e[t+6]=s[6],e[t+7]=s[7],e[t+8]=s[8],e[t+9]=s[9],e[t+10]=s[10],e[t+11]=s[11],e[t+12]=s[12],e[t+13]=s[13],e[t+14]=s[14],e[t+15]=s[15],e}}const Lr=new D,$s=new ve,zw=new D(0,0,0),Gw=new D(1,1,1),on=new D,cl=new D,os=new D,Qm=new ve,Km=new vr;class Is{constructor(e=0,t=0,s=0,i=Is.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=s,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,s,i=this._order){return this._x=e,this._y=t,this._z=s,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,s=!0){const i=e.elements,n=i[0],a=i[4],o=i[8],l=i[1],c=i[5],u=i[9],h=i[2],d=i[6],p=i[10];switch(t){case"XYZ":this._y=Math.asin(be(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-u,p),this._z=Math.atan2(-a,n)):(this._x=Math.atan2(d,c),this._z=0);break;case"YXZ":this._x=Math.asin(-be(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(o,p),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-h,n),this._z=0);break;case"ZXY":this._x=Math.asin(be(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-h,p),this._z=Math.atan2(-a,c)):(this._y=0,this._z=Math.atan2(l,n));break;case"ZYX":this._y=Math.asin(-be(h,-1,1)),Math.abs(h)<.9999999?(this._x=Math.atan2(d,p),this._z=Math.atan2(l,n)):(this._x=0,this._z=Math.atan2(-a,c));break;case"YZX":this._z=Math.asin(be(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-u,c),this._y=Math.atan2(-h,n)):(this._x=0,this._y=Math.atan2(o,p));break;case"XZY":this._z=Math.asin(-be(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(d,c),this._y=Math.atan2(o,n)):(this._x=Math.atan2(-u,p),this._y=0);break;default:W("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,s===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,s){return Qm.makeRotationFromQuaternion(e),this.setFromRotationMatrix(Qm,t,s)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return Km.setFromEuler(this),this.setFromQuaternion(Km,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],e[3]!==void 0&&(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}}Is.DEFAULT_ORDER="XYZ";class $w{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return(this.mask&(1<<e|0))!==0}}let Ww=0;const Jm=new D,Ir=new vr,Oi=new ve,ul=new D,$a=new D,Hw=new D,jw=new vr,eg=new D(1,0,0),tg=new D(0,1,0),sg=new D(0,0,1),ig={type:"added"},qw={type:"removed"},Ur={type:"childadded",child:null},Eh={type:"childremoved",child:null};class gt extends Gn{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:Ww++}),this.uuid=Qi(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=gt.DEFAULT_UP.clone();const e=new D,t=new Is,s=new vr,i=new D(1,1,1);function n(){s.setFromEuler(t,!1)}function a(){t.setFromQuaternion(s,void 0,!1)}t._onChange(n),s._onChange(a),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:s},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new ve},normalMatrix:{value:new as}}),this.matrix=new ve,this.matrixWorld=new ve,this.matrixAutoUpdate=gt.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=gt.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new $w,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.static=!1,this.userData={},this.pivot=null}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return Ir.setFromAxisAngle(e,t),this.quaternion.multiply(Ir),this}rotateOnWorldAxis(e,t){return Ir.setFromAxisAngle(e,t),this.quaternion.premultiply(Ir),this}rotateX(e){return this.rotateOnAxis(eg,e)}rotateY(e){return this.rotateOnAxis(tg,e)}rotateZ(e){return this.rotateOnAxis(sg,e)}translateOnAxis(e,t){return Jm.copy(e).applyQuaternion(this.quaternion),this.position.add(Jm.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(eg,e)}translateY(e){return this.translateOnAxis(tg,e)}translateZ(e){return this.translateOnAxis(sg,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(Oi.copy(this.matrixWorld).invert())}lookAt(e,t,s){e.isVector3?ul.copy(e):ul.set(e,t,s);const i=this.parent;this.updateWorldMatrix(!0,!1),$a.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Oi.lookAt($a,ul,this.up):Oi.lookAt(ul,$a,this.up),this.quaternion.setFromRotationMatrix(Oi),i&&(Oi.extractRotation(i.matrixWorld),Ir.setFromRotationMatrix(Oi),this.quaternion.premultiply(Ir.invert()))}add(e){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return e===this?($("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(ig),Ur.child=e,this.dispatchEvent(Ur),Ur.child=null):$("Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let s=0;s<arguments.length;s++)this.remove(arguments[s]);return this}const t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(qw),Eh.child=e,this.dispatchEvent(Eh),Eh.child=null),this}removeFromParent(){const e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),Oi.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),Oi.multiply(e.parent.matrixWorld)),e.applyMatrix4(Oi),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(ig),Ur.child=e,this.dispatchEvent(Ur),Ur.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 s=0,i=this.children.length;s<i;s++){const a=this.children[s].getObjectByProperty(e,t);if(a!==void 0)return a}}getObjectsByProperty(e,t,s=[]){this[e]===t&&s.push(this);const i=this.children;for(let n=0,a=i.length;n<a;n++)i[n].getObjectsByProperty(e,t,s);return s}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose($a,e,Hw),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose($a,jw,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);const t=this.children;for(let s=0,i=t.length;s<i;s++)t[s].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);const t=this.children;for(let s=0,i=t.length;s<i;s++)t[s].traverseVisible(e)}traverseAncestors(e){const t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale);const e=this.pivot;if(e!==null){const t=e.x,s=e.y,i=e.z,n=this.matrix.elements;n[12]+=t-n[0]*t-n[4]*s-n[8]*i,n[13]+=s-n[1]*t-n[5]*s-n[9]*i,n[14]+=i-n[2]*t-n[6]*s-n[10]*i}this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);const t=this.children;for(let s=0,i=t.length;s<i;s++)t[s].updateMatrixWorld(e)}updateWorldMatrix(e,t){const s=this.parent;if(e===!0&&s!==null&&s.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),t===!0){const i=this.children;for(let n=0,a=i.length;n<a;n++)i[n].updateWorldMatrix(!1,!0)}}toJSON(e){const t=e===void 0||typeof e=="string",s={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},s.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});const i={};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.castShadow===!0&&(i.castShadow=!0),this.receiveShadow===!0&&(i.receiveShadow=!0),this.visible===!1&&(i.visible=!1),this.frustumCulled===!1&&(i.frustumCulled=!1),this.renderOrder!==0&&(i.renderOrder=this.renderOrder),this.static!==!1&&(i.static=this.static),Object.keys(this.userData).length>0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),this.pivot!==null&&(i.pivot=this.pivot.toArray()),this.matrixAutoUpdate===!1&&(i.matrixAutoUpdate=!1),this.morphTargetDictionary!==void 0&&(i.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(i.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.geometryInfo=this._geometryInfo.map(o=>({...o,boundingBox:o.boundingBox?o.boundingBox.toJSON():void 0,boundingSphere:o.boundingSphere?o.boundingSphere.toJSON():void 0})),i.instanceInfo=this._instanceInfo.map(o=>({...o})),i.availableInstanceIds=this._availableInstanceIds.slice(),i.availableGeometryIds=this._availableGeometryIds.slice(),i.nextIndexStart=this._nextIndexStart,i.nextVertexStart=this._nextVertexStart,i.geometryCount=this._geometryCount,i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.matricesTexture=this._matricesTexture.toJSON(e),i.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(i.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(i.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(i.boundingBox=this.boundingBox.toJSON()));function n(o,l){return o[l.uuid]===void 0&&(o[l.uuid]=l.toJSON(e)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=n(e.geometries,this.geometry);const o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){const l=o.shapes;if(Array.isArray(l))for(let c=0,u=l.length;c<u;c++){const h=l[c];n(e.shapes,h)}else n(e.shapes,l)}}if(this.isSkinnedMesh&&(i.bindMode=this.bindMode,i.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(n(e.skeletons,this.skeleton),i.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const o=[];for(let l=0,c=this.material.length;l<c;l++)o.push(n(e.materials,this.material[l]));i.material=o}else i.material=n(e.materials,this.material);if(this.children.length>0){i.children=[];for(let o=0;o<this.children.length;o++)i.children.push(this.children[o].toJSON(e).object)}if(this.animations.length>0){i.animations=[];for(let o=0;o<this.animations.length;o++){const l=this.animations[o];i.animations.push(n(e.animations,l))}}if(t){const o=a(e.geometries),l=a(e.materials),c=a(e.textures),u=a(e.images),h=a(e.shapes),d=a(e.skeletons),p=a(e.animations),f=a(e.nodes);o.length>0&&(s.geometries=o),l.length>0&&(s.materials=l),c.length>0&&(s.textures=c),u.length>0&&(s.images=u),h.length>0&&(s.shapes=h),d.length>0&&(s.skeletons=d),p.length>0&&(s.animations=p),f.length>0&&(s.nodes=f)}return s.object=i,s;function a(o){const l=[];for(const c in o){const u=o[c];delete u.metadata,l.push(u)}return l}}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),e.pivot!==null&&(this.pivot=e.pivot.clone()),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.static=e.static,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let s=0;s<e.children.length;s++){const i=e.children[s];this.add(i.clone())}return this}}gt.DEFAULT_UP=new D(0,1,0);gt.DEFAULT_MATRIX_AUTO_UPDATE=!0;gt.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;class hl extends gt{constructor(){super(),this.isGroup=!0,this.type="Group"}}const Xw={type:"move"};class Yw{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new hl,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new hl,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new D,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new D),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new hl,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new D,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new D),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const s of e.hand.values())this._getHandJoint(t,s)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,s){let i=null,n=null,a=null;const o=this._targetRay,l=this._grip,c=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(c&&e.hand){a=!0;for(const m of e.hand.values()){const x=t.getJointPose(m,s),y=this._getHandJoint(c,m);x!==null&&(y.matrix.fromArray(x.transform.matrix),y.matrix.decompose(y.position,y.rotation,y.scale),y.matrixWorldNeedsUpdate=!0,y.jointRadius=x.radius),y.visible=x!==null}const u=c.joints["index-finger-tip"],h=c.joints["thumb-tip"],d=u.position.distanceTo(h.position),p=.02,f=.005;c.inputState.pinching&&d>p+f?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!c.inputState.pinching&&d<=p-f&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(n=t.getPose(e.gripSpace,s),n!==null&&(l.matrix.fromArray(n.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,n.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(n.linearVelocity)):l.hasLinearVelocity=!1,n.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(n.angularVelocity)):l.hasAngularVelocity=!1));o!==null&&(i=t.getPose(e.targetRaySpace,s),i===null&&n!==null&&(i=n),i!==null&&(o.matrix.fromArray(i.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,i.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(i.linearVelocity)):o.hasLinearVelocity=!1,i.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(i.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(Xw)))}return o!==null&&(o.visible=i!==null),l!==null&&(l.visible=n!==null),c!==null&&(c.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const s=new hl;s.matrixAutoUpdate=!1,s.visible=!1,e.joints[t.jointName]=s,e.add(s)}return e.joints[t.jointName]}}const jx={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},ln={h:0,s:0,l:0},dl={h:0,s:0,l:0};function Nh(r,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?r+(e-r)*6*t:t<1/2?e:t<2/3?r+(e-r)*6*(2/3-t):r}class Ne{constructor(e,t,s){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,s)}set(e,t,s){if(t===void 0&&s===void 0){const i=e;i&&i.isColor?this.copy(i):typeof i=="number"?this.setHex(i):typeof i=="string"&&this.setStyle(i)}else this.setRGB(e,t,s);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=ds){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,Ae.colorSpaceToWorking(this,t),this}setRGB(e,t,s,i=Ae.workingColorSpace){return this.r=e,this.g=t,this.b=s,Ae.colorSpaceToWorking(this,i),this}setHSL(e,t,s,i=Ae.workingColorSpace){if(e=Wp(e,1),t=be(t,0,1),s=be(s,0,1),t===0)this.r=this.g=this.b=s;else{const n=s<=.5?s*(1+t):s+t-s*t,a=2*s-n;this.r=Nh(a,n,e+1/3),this.g=Nh(a,n,e),this.b=Nh(a,n,e-1/3)}return Ae.colorSpaceToWorking(this,i),this}setStyle(e,t=ds){function s(n){n!==void 0&&parseFloat(n)<1&&W("Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let n;const a=i[1],o=i[2];switch(a){case"rgb":case"rgba":if(n=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return s(n[4]),this.setRGB(Math.min(255,parseInt(n[1],10))/255,Math.min(255,parseInt(n[2],10))/255,Math.min(255,parseInt(n[3],10))/255,t);if(n=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return s(n[4]),this.setRGB(Math.min(100,parseInt(n[1],10))/100,Math.min(100,parseInt(n[2],10))/100,Math.min(100,parseInt(n[3],10))/100,t);break;case"hsl":case"hsla":if(n=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return s(n[4]),this.setHSL(parseFloat(n[1])/360,parseFloat(n[2])/100,parseFloat(n[3])/100,t);break;default:W("Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const n=i[1],a=n.length;if(a===3)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,t);if(a===6)return this.setHex(parseInt(n,16),t);W("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=ds){const s=jx[e.toLowerCase()];return s!==void 0?this.setHex(s,t):W("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=Ki(e.r),this.g=Ki(e.g),this.b=Ki(e.b),this}copyLinearToSRGB(e){return this.r=xa(e.r),this.g=xa(e.g),this.b=xa(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=ds){return Ae.workingToColorSpace(Bt.copy(this),e),Math.round(be(Bt.r*255,0,255))*65536+Math.round(be(Bt.g*255,0,255))*256+Math.round(be(Bt.b*255,0,255))}getHexString(e=ds){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Ae.workingColorSpace){Ae.workingToColorSpace(Bt.copy(this),t);const s=Bt.r,i=Bt.g,n=Bt.b,a=Math.max(s,i,n),o=Math.min(s,i,n);let l,c;const u=(o+a)/2;if(o===a)l=0,c=0;else{const h=a-o;switch(c=u<=.5?h/(a+o):h/(2-a-o),a){case s:l=(i-n)/h+(i<n?6:0);break;case i:l=(n-s)/h+2;break;case n:l=(s-i)/h+4;break}l/=6}return e.h=l,e.s=c,e.l=u,e}getRGB(e,t=Ae.workingColorSpace){return Ae.workingToColorSpace(Bt.copy(this),t),e.r=Bt.r,e.g=Bt.g,e.b=Bt.b,e}getStyle(e=ds){Ae.workingToColorSpace(Bt.copy(this),e);const t=Bt.r,s=Bt.g,i=Bt.b;return e!==ds?`color(${e} ${t.toFixed(3)} ${s.toFixed(3)} ${i.toFixed(3)})`:`rgb(${Math.round(t*255)},${Math.round(s*255)},${Math.round(i*255)})`}offsetHSL(e,t,s){return this.getHSL(ln),this.setHSL(ln.h+e,ln.s+t,ln.l+s)}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,s){return this.r=e.r+(t.r-e.r)*s,this.g=e.g+(t.g-e.g)*s,this.b=e.b+(t.b-e.b)*s,this}lerpHSL(e,t){this.getHSL(ln),e.getHSL(dl);const s=No(ln.h,dl.h,t),i=No(ln.s,dl.s,t),n=No(ln.l,dl.l,t);return this.setHSL(s,i,n),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const t=this.r,s=this.g,i=this.b,n=e.elements;return this.r=n[0]*t+n[3]*s+n[6]*i,this.g=n[1]*t+n[4]*s+n[7]*i,this.b=n[2]*t+n[5]*s+n[8]*i,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const Bt=new Ne;Ne.NAMES=jx;class qx extends gt{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 Is,this.environmentIntensity=1,this.environmentRotation=new Is,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}const Ws=new D,Li=new D,Rh=new D,Ii=new D,Vr=new D,kr=new D,ng=new D,Ph=new D,Fh=new D,Bh=new D,Dh=new Ee,Oh=new Ee,Lh=new Ee;class Ys{constructor(e=new D,t=new D,s=new D){this.a=e,this.b=t,this.c=s}static getNormal(e,t,s,i){i.subVectors(s,t),Ws.subVectors(e,t),i.cross(Ws);const n=i.lengthSq();return n>0?i.multiplyScalar(1/Math.sqrt(n)):i.set(0,0,0)}static getBarycoord(e,t,s,i,n){Ws.subVectors(i,t),Li.subVectors(s,t),Rh.subVectors(e,t);const a=Ws.dot(Ws),o=Ws.dot(Li),l=Ws.dot(Rh),c=Li.dot(Li),u=Li.dot(Rh),h=a*c-o*o;if(h===0)return n.set(0,0,0),null;const d=1/h,p=(c*l-o*u)*d,f=(a*u-o*l)*d;return n.set(1-p-f,f,p)}static containsPoint(e,t,s,i){return this.getBarycoord(e,t,s,i,Ii)===null?!1:Ii.x>=0&&Ii.y>=0&&Ii.x+Ii.y<=1}static getInterpolation(e,t,s,i,n,a,o,l){return this.getBarycoord(e,t,s,i,Ii)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(n,Ii.x),l.addScaledVector(a,Ii.y),l.addScaledVector(o,Ii.z),l)}static getInterpolatedAttribute(e,t,s,i,n,a){return Dh.setScalar(0),Oh.setScalar(0),Lh.setScalar(0),Dh.fromBufferAttribute(e,t),Oh.fromBufferAttribute(e,s),Lh.fromBufferAttribute(e,i),a.setScalar(0),a.addScaledVector(Dh,n.x),a.addScaledVector(Oh,n.y),a.addScaledVector(Lh,n.z),a}static isFrontFacing(e,t,s,i){return Ws.subVectors(s,t),Li.subVectors(e,t),Ws.cross(Li).dot(i)<0}set(e,t,s){return this.a.copy(e),this.b.copy(t),this.c.copy(s),this}setFromPointsAndIndices(e,t,s,i){return this.a.copy(e[t]),this.b.copy(e[s]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,s,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,s),this.c.fromBufferAttribute(e,i),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Ws.subVectors(this.c,this.b),Li.subVectors(this.a,this.b),Ws.cross(Li).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Ys.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Ys.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,s,i,n){return Ys.getInterpolation(e,this.a,this.b,this.c,t,s,i,n)}containsPoint(e){return Ys.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Ys.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const s=this.a,i=this.b,n=this.c;let a,o;Vr.subVectors(i,s),kr.subVectors(n,s),Ph.subVectors(e,s);const l=Vr.dot(Ph),c=kr.dot(Ph);if(l<=0&&c<=0)return t.copy(s);Fh.subVectors(e,i);const u=Vr.dot(Fh),h=kr.dot(Fh);if(u>=0&&h<=u)return t.copy(i);const d=l*h-u*c;if(d<=0&&l>=0&&u<=0)return a=l/(l-u),t.copy(s).addScaledVector(Vr,a);Bh.subVectors(e,n);const p=Vr.dot(Bh),f=kr.dot(Bh);if(f>=0&&p<=f)return t.copy(n);const m=p*c-l*f;if(m<=0&&c>=0&&f<=0)return o=c/(c-f),t.copy(s).addScaledVector(kr,o);const x=u*f-p*h;if(x<=0&&h-u>=0&&p-f>=0)return ng.subVectors(n,i),o=(h-u)/(h-u+(p-f)),t.copy(i).addScaledVector(ng,o);const y=1/(x+m+d);return a=m*y,o=d*y,t.copy(s).addScaledVector(Vr,a).addScaledVector(kr,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}class Qo{constructor(e=new D(1/0,1/0,1/0),t=new D(-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,s=e.length;t<s;t+=3)this.expandByPoint(Hs.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,s=e.count;t<s;t++)this.expandByPoint(Hs.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,s=e.length;t<s;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){const s=Hs.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(s),this.max.copy(e).add(s),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 s=e.geometry;if(s!==void 0){const n=s.getAttribute("position");if(t===!0&&n!==void 0&&e.isInstancedMesh!==!0)for(let a=0,o=n.count;a<o;a++)e.isMesh===!0?e.getVertexPosition(a,Hs):Hs.fromBufferAttribute(n,a),Hs.applyMatrix4(e.matrixWorld),this.expandByPoint(Hs);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),pl.copy(e.boundingBox)):(s.boundingBox===null&&s.computeBoundingBox(),pl.copy(s.boundingBox)),pl.applyMatrix4(e.matrixWorld),this.union(pl)}const i=e.children;for(let n=0,a=i.length;n<a;n++)this.expandByObject(i[n],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,Hs),Hs.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,s;return e.normal.x>0?(t=e.normal.x*this.min.x,s=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,s=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,s+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,s+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,s+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,s+=e.normal.z*this.min.z),t<=-e.constant&&s>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Wa),fl.subVectors(this.max,Wa),zr.subVectors(e.a,Wa),Gr.subVectors(e.b,Wa),$r.subVectors(e.c,Wa),cn.subVectors(Gr,zr),un.subVectors($r,Gr),Yn.subVectors(zr,$r);let t=[0,-cn.z,cn.y,0,-un.z,un.y,0,-Yn.z,Yn.y,cn.z,0,-cn.x,un.z,0,-un.x,Yn.z,0,-Yn.x,-cn.y,cn.x,0,-un.y,un.x,0,-Yn.y,Yn.x,0];return!Ih(t,zr,Gr,$r,fl)||(t=[1,0,0,0,1,0,0,0,1],!Ih(t,zr,Gr,$r,fl))?!1:(ml.crossVectors(cn,un),t=[ml.x,ml.y,ml.z],Ih(t,zr,Gr,$r,fl))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Hs).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Hs).length()*.5),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()?this:(Ui[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Ui[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Ui[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Ui[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Ui[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Ui[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Ui[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Ui[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Ui),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}}const Ui=[new D,new D,new D,new D,new D,new D,new D,new D],Hs=new D,pl=new Qo,zr=new D,Gr=new D,$r=new D,cn=new D,un=new D,Yn=new D,Wa=new D,fl=new D,ml=new D,Zn=new D;function Ih(r,e,t,s,i){for(let n=0,a=r.length-3;n<=a;n+=3){Zn.fromArray(r,n);const o=i.x*Math.abs(Zn.x)+i.y*Math.abs(Zn.y)+i.z*Math.abs(Zn.z),l=e.dot(Zn),c=t.dot(Zn),u=s.dot(Zn);if(Math.max(-Math.max(l,c,u),Math.min(l,c,u))>o)return!1}return!0}const $i=Zw();function Zw(){const r=new ArrayBuffer(4),e=new Float32Array(r),t=new Uint32Array(r),s=new Uint32Array(512),i=new Uint32Array(512);for(let l=0;l<256;++l){const c=l-127;c<-27?(s[l]=0,s[l|256]=32768,i[l]=24,i[l|256]=24):c<-14?(s[l]=1024>>-c-14,s[l|256]=1024>>-c-14|32768,i[l]=-c-1,i[l|256]=-c-1):c<=15?(s[l]=c+15<<10,s[l|256]=c+15<<10|32768,i[l]=13,i[l|256]=13):c<128?(s[l]=31744,s[l|256]=64512,i[l]=24,i[l|256]=24):(s[l]=31744,s[l|256]=64512,i[l]=13,i[l|256]=13)}const n=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let l=1;l<1024;++l){let c=l<<13,u=0;for(;(c&8388608)===0;)c<<=1,u-=8388608;c&=-8388609,u+=947912704,n[l]=c|u}for(let l=1024;l<2048;++l)n[l]=939524096+(l-1024<<13);for(let l=1;l<31;++l)a[l]=l<<23;a[31]=1199570944,a[32]=2147483648;for(let l=33;l<63;++l)a[l]=2147483648+(l-32<<23);a[63]=3347054592;for(let l=1;l<64;++l)l!==32&&(o[l]=1024);return{floatView:e,uint32View:t,baseTable:s,shiftTable:i,mantissaTable:n,exponentTable:a,offsetTable:o}}function ls(r){Math.abs(r)>65504&&W("DataUtils.toHalfFloat(): Value out of range."),r=be(r,-65504,65504),$i.floatView[0]=r;const e=$i.uint32View[0],t=e>>23&511;return $i.baseTable[t]+((e&8388607)>>$i.shiftTable[t])}function gl(r){const e=r>>10;return $i.uint32View[0]=$i.mantissaTable[$i.offsetTable[e]+(r&1023)]+$i.exponentTable[e],$i.floatView[0]}const pt=new D,yl=new xe;let Qw=0;class ys{constructor(e,t,s=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:Qw++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=s,this.usage=Na,this.updateRanges=[],this.gpuType=es,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,s){e*=this.itemSize,s*=t.itemSize;for(let i=0,n=this.itemSize;i<n;i++)this.array[e+i]=t.array[s+i];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,s=this.count;t<s;t++)yl.fromBufferAttribute(this,t),yl.applyMatrix3(e),this.setXY(t,yl.x,yl.y);else if(this.itemSize===3)for(let t=0,s=this.count;t<s;t++)pt.fromBufferAttribute(this,t),pt.applyMatrix3(e),this.setXYZ(t,pt.x,pt.y,pt.z);return this}applyMatrix4(e){for(let t=0,s=this.count;t<s;t++)pt.fromBufferAttribute(this,t),pt.applyMatrix4(e),this.setXYZ(t,pt.x,pt.y,pt.z);return this}applyNormalMatrix(e){for(let t=0,s=this.count;t<s;t++)pt.fromBufferAttribute(this,t),pt.applyNormalMatrix(e),this.setXYZ(t,pt.x,pt.y,pt.z);return this}transformDirection(e){for(let t=0,s=this.count;t<s;t++)pt.fromBufferAttribute(this,t),pt.transformDirection(e),this.setXYZ(t,pt.x,pt.y,pt.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let s=this.array[e*this.itemSize+t];return this.normalized&&(s=qt(s,this.array)),s}setComponent(e,t,s){return this.normalized&&(s=de(s,this.array)),this.array[e*this.itemSize+t]=s,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=qt(t,this.array)),t}setX(e,t){return this.normalized&&(t=de(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=qt(t,this.array)),t}setY(e,t){return this.normalized&&(t=de(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=qt(t,this.array)),t}setZ(e,t){return this.normalized&&(t=de(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=qt(t,this.array)),t}setW(e,t){return this.normalized&&(t=de(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,s){return e*=this.itemSize,this.normalized&&(t=de(t,this.array),s=de(s,this.array)),this.array[e+0]=t,this.array[e+1]=s,this}setXYZ(e,t,s,i){return e*=this.itemSize,this.normalized&&(t=de(t,this.array),s=de(s,this.array),i=de(i,this.array)),this.array[e+0]=t,this.array[e+1]=s,this.array[e+2]=i,this}setXYZW(e,t,s,i,n){return e*=this.itemSize,this.normalized&&(t=de(t,this.array),s=de(s,this.array),i=de(i,this.array),n=de(n,this.array)),this.array[e+0]=t,this.array[e+1]=s,this.array[e+2]=i,this.array[e+3]=n,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(e.name=this.name),this.usage!==Na&&(e.usage=this.usage),e}}class Xx extends ys{constructor(e,t,s){super(new Uint16Array(e),t,s)}}class Yx extends ys{constructor(e,t,s){super(new Uint32Array(e),t,s)}}class Zx extends ys{constructor(e,t,s){super(new Uint16Array(e),t,s),this.isFloat16BufferAttribute=!0}getX(e){let t=gl(this.array[e*this.itemSize]);return this.normalized&&(t=qt(t,this.array)),t}setX(e,t){return this.normalized&&(t=de(t,this.array)),this.array[e*this.itemSize]=ls(t),this}getY(e){let t=gl(this.array[e*this.itemSize+1]);return this.normalized&&(t=qt(t,this.array)),t}setY(e,t){return this.normalized&&(t=de(t,this.array)),this.array[e*this.itemSize+1]=ls(t),this}getZ(e){let t=gl(this.array[e*this.itemSize+2]);return this.normalized&&(t=qt(t,this.array)),t}setZ(e,t){return this.normalized&&(t=de(t,this.array)),this.array[e*this.itemSize+2]=ls(t),this}getW(e){let t=gl(this.array[e*this.itemSize+3]);return this.normalized&&(t=qt(t,this.array)),t}setW(e,t){return this.normalized&&(t=de(t,this.array)),this.array[e*this.itemSize+3]=ls(t),this}setXY(e,t,s){return e*=this.itemSize,this.normalized&&(t=de(t,this.array),s=de(s,this.array)),this.array[e+0]=ls(t),this.array[e+1]=ls(s),this}setXYZ(e,t,s,i){return e*=this.itemSize,this.normalized&&(t=de(t,this.array),s=de(s,this.array),i=de(i,this.array)),this.array[e+0]=ls(t),this.array[e+1]=ls(s),this.array[e+2]=ls(i),this}setXYZW(e,t,s,i,n){return e*=this.itemSize,this.normalized&&(t=de(t,this.array),s=de(s,this.array),i=de(i,this.array),n=de(n,this.array)),this.array[e+0]=ls(t),this.array[e+1]=ls(s),this.array[e+2]=ls(i),this.array[e+3]=ls(n),this}}class Yt extends ys{constructor(e,t,s){super(new Float32Array(e),t,s)}}const Kw=new Qo,Ha=new D,Uh=new D;class Lu{constructor(e=new D,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 s=this.center;t!==void 0?s.copy(t):Kw.setFromPoints(e).getCenter(s);let i=0;for(let n=0,a=e.length;n<a;n++)i=Math.max(i,s.distanceToSquared(e[n]));return this.radius=Math.sqrt(i),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){const t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){const s=this.center.distanceToSquared(e);return t.copy(e),s>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;Ha.subVectors(e,this.center);const t=Ha.lengthSq();if(t>this.radius*this.radius){const s=Math.sqrt(t),i=(s-this.radius)*.5;this.center.addScaledVector(Ha,i/s),this.radius+=i}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(Uh.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Ha.copy(e.center).add(Uh)),this.expandByPoint(Ha.copy(e.center).sub(Uh))),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 Jw=0;const Ss=new ve,Vh=new gt,Wr=new D,cs=new Qo,ja=new Qo,vt=new D;class Bi extends Gn{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:Jw++}),this.uuid=Qi(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(xw(e)?Yx:Xx)(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 this.attributes[e]!==void 0}addGroup(e,t,s=0){this.groups.push({start:e,count:t,materialIndex:s})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);const s=this.attributes.normal;if(s!==void 0){const n=new as().getNormalMatrix(e);s.applyNormalMatrix(n),s.needsUpdate=!0}const i=this.attributes.tangent;return i!==void 0&&(i.transformDirection(e),i.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return Ss.makeRotationFromQuaternion(e),this.applyMatrix4(Ss),this}rotateX(e){return Ss.makeRotationX(e),this.applyMatrix4(Ss),this}rotateY(e){return Ss.makeRotationY(e),this.applyMatrix4(Ss),this}rotateZ(e){return Ss.makeRotationZ(e),this.applyMatrix4(Ss),this}translate(e,t,s){return Ss.makeTranslation(e,t,s),this.applyMatrix4(Ss),this}scale(e,t,s){return Ss.makeScale(e,t,s),this.applyMatrix4(Ss),this}lookAt(e){return Vh.lookAt(e),Vh.updateMatrix(),this.applyMatrix4(Vh.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Wr).negate(),this.translate(Wr.x,Wr.y,Wr.z),this}setFromPoints(e){const t=this.getAttribute("position");if(t===void 0){const s=[];for(let i=0,n=e.length;i<n;i++){const a=e[i];s.push(a.x,a.y,a.z||0)}this.setAttribute("position",new Yt(s,3))}else{const s=Math.min(e.length,t.count);for(let i=0;i<s;i++){const n=e[i];t.setXYZ(i,n.x,n.y,n.z||0)}e.length>t.count&&W("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Qo);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){$("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new D(-1/0,-1/0,-1/0),new D(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let s=0,i=t.length;s<i;s++){const n=t[s];cs.setFromBufferAttribute(n),this.morphTargetsRelative?(vt.addVectors(this.boundingBox.min,cs.min),this.boundingBox.expandByPoint(vt),vt.addVectors(this.boundingBox.max,cs.max),this.boundingBox.expandByPoint(vt)):(this.boundingBox.expandByPoint(cs.min),this.boundingBox.expandByPoint(cs.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&$('BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new Lu);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){$("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new D,1/0);return}if(e){const s=this.boundingSphere.center;if(cs.setFromBufferAttribute(e),t)for(let n=0,a=t.length;n<a;n++){const o=t[n];ja.setFromBufferAttribute(o),this.morphTargetsRelative?(vt.addVectors(cs.min,ja.min),cs.expandByPoint(vt),vt.addVectors(cs.max,ja.max),cs.expandByPoint(vt)):(cs.expandByPoint(ja.min),cs.expandByPoint(ja.max))}cs.getCenter(s);let i=0;for(let n=0,a=e.count;n<a;n++)vt.fromBufferAttribute(e,n),i=Math.max(i,s.distanceToSquared(vt));if(t)for(let n=0,a=t.length;n<a;n++){const o=t[n],l=this.morphTargetsRelative;for(let c=0,u=o.count;c<u;c++)vt.fromBufferAttribute(o,c),l&&(Wr.fromBufferAttribute(e,c),vt.add(Wr)),i=Math.max(i,s.distanceToSquared(vt))}this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius)&&$('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(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){$("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const s=t.position,i=t.normal,n=t.uv;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new ys(new Float32Array(4*s.count),4));const a=this.getAttribute("tangent"),o=[],l=[];for(let P=0;P<s.count;P++)o[P]=new D,l[P]=new D;const c=new D,u=new D,h=new D,d=new xe,p=new xe,f=new xe,m=new D,x=new D;function y(P,B,V){c.fromBufferAttribute(s,P),u.fromBufferAttribute(s,B),h.fromBufferAttribute(s,V),d.fromBufferAttribute(n,P),p.fromBufferAttribute(n,B),f.fromBufferAttribute(n,V),u.sub(c),h.sub(c),p.sub(d),f.sub(d);const Y=1/(p.x*f.y-f.x*p.y);isFinite(Y)&&(m.copy(u).multiplyScalar(f.y).addScaledVector(h,-p.y).multiplyScalar(Y),x.copy(h).multiplyScalar(p.x).addScaledVector(u,-f.x).multiplyScalar(Y),o[P].add(m),o[B].add(m),o[V].add(m),l[P].add(x),l[B].add(x),l[V].add(x))}let b=this.groups;b.length===0&&(b=[{start:0,count:e.count}]);for(let P=0,B=b.length;P<B;++P){const V=b[P],Y=V.start,J=V.count;for(let K=Y,te=Y+J;K<te;K+=3)y(e.getX(K+0),e.getX(K+1),e.getX(K+2))}const v=new D,S=new D,M=new D,A=new D;function C(P){M.fromBufferAttribute(i,P),A.copy(M);const B=o[P];v.copy(B),v.sub(M.multiplyScalar(M.dot(B))).normalize(),S.crossVectors(A,B);const Y=S.dot(l[P])<0?-1:1;a.setXYZW(P,v.x,v.y,v.z,Y)}for(let P=0,B=b.length;P<B;++P){const V=b[P],Y=V.start,J=V.count;for(let K=Y,te=Y+J;K<te;K+=3)C(e.getX(K+0)),C(e.getX(K+1)),C(e.getX(K+2))}}computeVertexNormals(){const e=this.index,t=this.getAttribute("position");if(t!==void 0){let s=this.getAttribute("normal");if(s===void 0)s=new ys(new Float32Array(t.count*3),3),this.setAttribute("normal",s);else for(let d=0,p=s.count;d<p;d++)s.setXYZ(d,0,0,0);const i=new D,n=new D,a=new D,o=new D,l=new D,c=new D,u=new D,h=new D;if(e)for(let d=0,p=e.count;d<p;d+=3){const f=e.getX(d+0),m=e.getX(d+1),x=e.getX(d+2);i.fromBufferAttribute(t,f),n.fromBufferAttribute(t,m),a.fromBufferAttribute(t,x),u.subVectors(a,n),h.subVectors(i,n),u.cross(h),o.fromBufferAttribute(s,f),l.fromBufferAttribute(s,m),c.fromBufferAttribute(s,x),o.add(u),l.add(u),c.add(u),s.setXYZ(f,o.x,o.y,o.z),s.setXYZ(m,l.x,l.y,l.z),s.setXYZ(x,c.x,c.y,c.z)}else for(let d=0,p=t.count;d<p;d+=3)i.fromBufferAttribute(t,d+0),n.fromBufferAttribute(t,d+1),a.fromBufferAttribute(t,d+2),u.subVectors(a,n),h.subVectors(i,n),u.cross(h),s.setXYZ(d+0,u.x,u.y,u.z),s.setXYZ(d+1,u.x,u.y,u.z),s.setXYZ(d+2,u.x,u.y,u.z);this.normalizeNormals(),s.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,s=e.count;t<s;t++)vt.fromBufferAttribute(e,t),vt.normalize(),e.setXYZ(t,vt.x,vt.y,vt.z)}toNonIndexed(){function e(o,l){const c=o.array,u=o.itemSize,h=o.normalized,d=new c.constructor(l.length*u);let p=0,f=0;for(let m=0,x=l.length;m<x;m++){o.isInterleavedBufferAttribute?p=l[m]*o.data.stride+o.offset:p=l[m]*u;for(let y=0;y<u;y++)d[f++]=c[p++]}return new ys(d,u,h)}if(this.index===null)return W("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new Bi,s=this.index.array,i=this.attributes;for(const o in i){const l=i[o],c=e(l,s);t.setAttribute(o,c)}const n=this.morphAttributes;for(const o in n){const l=[],c=n[o];for(let u=0,h=c.length;u<h;u++){const d=c[u],p=e(d,s);l.push(p)}t.morphAttributes[o]=l}t.morphTargetsRelative=this.morphTargetsRelative;const a=this.groups;for(let o=0,l=a.length;o<l;o++){const c=a[o];t.addGroup(c.start,c.count,c.materialIndex)}return t}toJSON(){const e={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.type,this.name!==""&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0){const l=this.parameters;for(const c in l)l[c]!==void 0&&(e[c]=l[c]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const s=this.attributes;for(const l in s){const c=s[l];e.data.attributes[l]=c.toJSON(e.data)}const i={};let n=!1;for(const l in this.morphAttributes){const c=this.morphAttributes[l],u=[];for(let h=0,d=c.length;h<d;h++){const p=c[h];u.push(p.toJSON(e.data))}u.length>0&&(i[l]=u,n=!0)}n&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));const o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.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 s=e.index;s!==null&&this.setIndex(s.clone());const i=e.attributes;for(const c in i){const u=i[c];this.setAttribute(c,u.clone(t))}const n=e.morphAttributes;for(const c in n){const u=[],h=n[c];for(let d=0,p=h.length;d<p;d++)u.push(h[d].clone(t));this.morphAttributes[c]=u}this.morphTargetsRelative=e.morphTargetsRelative;const a=e.groups;for(let c=0,u=a.length;c<u;c++){const h=a[c];this.addGroup(h.start,h.count,h.materialIndex)}const o=e.boundingBox;o!==null&&(this.boundingBox=o.clone());const l=e.boundingSphere;return l!==null&&(this.boundingSphere=l.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}class Qx{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e!==void 0?e.length/t:0,this.usage=Na,this.updateRanges=[],this.version=0,this.uuid=Qi()}onUploadCallback(){}set needsUpdate(e){e===!0&&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,s){e*=this.stride,s*=t.stride;for(let i=0,n=this.stride;i<n;i++)this.array[e+i]=t.array[s+i];return this}set(e,t=0){return this.array.set(e,t),this}clone(e){e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=Qi()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);const t=new this.array.constructor(e.arrayBuffers[this.array.buffer._uuid]),s=new this.constructor(t,this.stride);return s.setUsage(this.usage),s}onUpload(e){return this.onUploadCallback=e,this}toJSON(e){return e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=Qi()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer))),{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}}const Wt=new D;class jp{constructor(e,t,s,i=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=e,this.itemSize=t,this.offset=s,this.normalized=i}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(e){this.data.needsUpdate=e}applyMatrix4(e){for(let t=0,s=this.data.count;t<s;t++)Wt.fromBufferAttribute(this,t),Wt.applyMatrix4(e),this.setXYZ(t,Wt.x,Wt.y,Wt.z);return this}applyNormalMatrix(e){for(let t=0,s=this.count;t<s;t++)Wt.fromBufferAttribute(this,t),Wt.applyNormalMatrix(e),this.setXYZ(t,Wt.x,Wt.y,Wt.z);return this}transformDirection(e){for(let t=0,s=this.count;t<s;t++)Wt.fromBufferAttribute(this,t),Wt.transformDirection(e),this.setXYZ(t,Wt.x,Wt.y,Wt.z);return this}getComponent(e,t){let s=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(s=qt(s,this.array)),s}setComponent(e,t,s){return this.normalized&&(s=de(s,this.array)),this.data.array[e*this.data.stride+this.offset+t]=s,this}setX(e,t){return this.normalized&&(t=de(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=de(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=de(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=de(t,this.array)),this.data.array[e*this.data.stride+this.offset+3]=t,this}getX(e){let t=this.data.array[e*this.data.stride+this.offset];return this.normalized&&(t=qt(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=qt(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=qt(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=qt(t,this.array)),t}setXY(e,t,s){return e=e*this.data.stride+this.offset,this.normalized&&(t=de(t,this.array),s=de(s,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=s,this}setXYZ(e,t,s,i){return e=e*this.data.stride+this.offset,this.normalized&&(t=de(t,this.array),s=de(s,this.array),i=de(i,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=s,this.data.array[e+2]=i,this}setXYZW(e,t,s,i,n){return e=e*this.data.stride+this.offset,this.normalized&&(t=de(t,this.array),s=de(s,this.array),i=de(i,this.array),n=de(n,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=s,this.data.array[e+2]=i,this.data.array[e+3]=n,this}clone(e){if(e===void 0){rp("InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");const t=[];for(let s=0;s<this.count;s++){const i=s*this.data.stride+this.offset;for(let n=0;n<this.itemSize;n++)t.push(this.data.array[i+n])}return new ys(new this.array.constructor(t),this.itemSize,this.normalized)}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.clone(e)),new jp(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(e===void 0){rp("InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");const t=[];for(let s=0;s<this.count;s++){const i=s*this.data.stride+this.offset;for(let n=0;n<this.itemSize;n++)t.push(this.data.array[i+n])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:t,normalized:this.normalized}}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.toJSON(e)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}}let eC=0;class _s extends Gn{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:eC++}),this.uuid=Qi(),this.name="",this.type="Material",this.blending=Es,this.side=Si,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=Vo,this.blendDst=ko,this.blendEquation=Ns,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Ne(0,0,0),this.blendAlpha=0,this.depthFunc=wa,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=ip,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=lr,this.stencilZFail=lr,this.stencilZPass=lr,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(e!==void 0)for(const t in e){const s=e[t];if(s===void 0){W(`Material: parameter '${t}' has value of undefined.`);continue}const i=this[t];if(i===void 0){W(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}i&&i.isColor?i.set(s):i&&i.isVector3&&s&&s.isVector3?i.copy(s):this[t]=s}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const s={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};s.uuid=this.uuid,s.type=this.type,this.name!==""&&(s.name=this.name),this.color&&this.color.isColor&&(s.color=this.color.getHex()),this.roughness!==void 0&&(s.roughness=this.roughness),this.metalness!==void 0&&(s.metalness=this.metalness),this.sheen!==void 0&&(s.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(s.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(s.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(s.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(s.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(s.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(s.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(s.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(s.shininess=this.shininess),this.clearcoat!==void 0&&(s.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(s.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(s.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(s.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(s.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,s.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(s.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(s.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(s.dispersion=this.dispersion),this.iridescence!==void 0&&(s.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(s.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(s.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(s.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(s.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(s.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(s.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(s.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(s.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(s.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(s.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(s.lightMap=this.lightMap.toJSON(e).uuid,s.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(s.aoMap=this.aoMap.toJSON(e).uuid,s.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(s.bumpMap=this.bumpMap.toJSON(e).uuid,s.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(s.normalMap=this.normalMap.toJSON(e).uuid,s.normalMapType=this.normalMapType,s.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(s.displacementMap=this.displacementMap.toJSON(e).uuid,s.displacementScale=this.displacementScale,s.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(s.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(s.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(s.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(s.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(s.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(s.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(s.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(s.combine=this.combine)),this.envMapRotation!==void 0&&(s.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(s.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(s.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(s.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(s.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(s.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(s.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(s.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(s.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(s.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(s.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(s.size=this.size),this.shadowSide!==null&&(s.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(s.sizeAttenuation=this.sizeAttenuation),this.blending!==Es&&(s.blending=this.blending),this.side!==Si&&(s.side=this.side),this.vertexColors===!0&&(s.vertexColors=!0),this.opacity<1&&(s.opacity=this.opacity),this.transparent===!0&&(s.transparent=!0),this.blendSrc!==Vo&&(s.blendSrc=this.blendSrc),this.blendDst!==ko&&(s.blendDst=this.blendDst),this.blendEquation!==Ns&&(s.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(s.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(s.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(s.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(s.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(s.blendAlpha=this.blendAlpha),this.depthFunc!==wa&&(s.depthFunc=this.depthFunc),this.depthTest===!1&&(s.depthTest=this.depthTest),this.depthWrite===!1&&(s.depthWrite=this.depthWrite),this.colorWrite===!1&&(s.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(s.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==ip&&(s.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(s.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(s.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==lr&&(s.stencilFail=this.stencilFail),this.stencilZFail!==lr&&(s.stencilZFail=this.stencilZFail),this.stencilZPass!==lr&&(s.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(s.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(s.rotation=this.rotation),this.polygonOffset===!0&&(s.polygonOffset=!0),this.polygonOffsetFactor!==0&&(s.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(s.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(s.linewidth=this.linewidth),this.dashSize!==void 0&&(s.dashSize=this.dashSize),this.gapSize!==void 0&&(s.gapSize=this.gapSize),this.scale!==void 0&&(s.scale=this.scale),this.dithering===!0&&(s.dithering=!0),this.alphaTest>0&&(s.alphaTest=this.alphaTest),this.alphaHash===!0&&(s.alphaHash=!0),this.alphaToCoverage===!0&&(s.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(s.premultipliedAlpha=!0),this.forceSinglePass===!0&&(s.forceSinglePass=!0),this.allowOverride===!1&&(s.allowOverride=!1),this.wireframe===!0&&(s.wireframe=!0),this.wireframeLinewidth>1&&(s.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(s.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(s.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(s.flatShading=!0),this.visible===!1&&(s.visible=!1),this.toneMapped===!1&&(s.toneMapped=!1),this.fog===!1&&(s.fog=!1),Object.keys(this.userData).length>0&&(s.userData=this.userData);function i(n){const a=[];for(const o in n){const l=n[o];delete l.metadata,a.push(l)}return a}if(t){const n=i(e.textures),a=i(e.images);n.length>0&&(s.textures=n),a.length>0&&(s.images=a)}return s}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 s=null;if(t!==null){const i=t.length;s=new Array(i);for(let n=0;n!==i;++n)s[n]=t[n].clone()}return this.clippingPlanes=s,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){e===!0&&this.version++}}class tC extends _s{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new Ne(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 Vi=new D,kh=new D,xl=new D,hn=new D,zh=new D,_l=new D,Gh=new D;class sC{constructor(e=new D,t=new D(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,Vi)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const s=t.dot(this.direction);return s<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,s)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=Vi.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Vi.copy(this.origin).addScaledVector(this.direction,t),Vi.distanceToSquared(e))}distanceSqToSegment(e,t,s,i){kh.copy(e).add(t).multiplyScalar(.5),xl.copy(t).sub(e).normalize(),hn.copy(this.origin).sub(kh);const n=e.distanceTo(t)*.5,a=-this.direction.dot(xl),o=hn.dot(this.direction),l=-hn.dot(xl),c=hn.lengthSq(),u=Math.abs(1-a*a);let h,d,p,f;if(u>0)if(h=a*l-o,d=a*o-l,f=n*u,h>=0)if(d>=-f)if(d<=f){const m=1/u;h*=m,d*=m,p=h*(h+a*d+2*o)+d*(a*h+d+2*l)+c}else d=n,h=Math.max(0,-(a*d+o)),p=-h*h+d*(d+2*l)+c;else d=-n,h=Math.max(0,-(a*d+o)),p=-h*h+d*(d+2*l)+c;else d<=-f?(h=Math.max(0,-(-a*n+o)),d=h>0?-n:Math.min(Math.max(-n,-l),n),p=-h*h+d*(d+2*l)+c):d<=f?(h=0,d=Math.min(Math.max(-n,-l),n),p=d*(d+2*l)+c):(h=Math.max(0,-(a*n+o)),d=h>0?n:Math.min(Math.max(-n,-l),n),p=-h*h+d*(d+2*l)+c);else d=a>0?-n:n,h=Math.max(0,-(a*d+o)),p=-h*h+d*(d+2*l)+c;return s&&s.copy(this.origin).addScaledVector(this.direction,h),i&&i.copy(kh).addScaledVector(xl,d),p}intersectSphere(e,t){Vi.subVectors(e.center,this.origin);const s=Vi.dot(this.direction),i=Vi.dot(Vi)-s*s,n=e.radius*e.radius;if(i>n)return null;const a=Math.sqrt(n-i),o=s-a,l=s+a;return l<0?null:o<0?this.at(l,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const s=-(this.origin.dot(e.normal)+e.constant)/t;return s>=0?s:null}intersectPlane(e,t){const s=this.distanceToPlane(e);return s===null?null:this.at(s,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let s,i,n,a,o,l;const c=1/this.direction.x,u=1/this.direction.y,h=1/this.direction.z,d=this.origin;return c>=0?(s=(e.min.x-d.x)*c,i=(e.max.x-d.x)*c):(s=(e.max.x-d.x)*c,i=(e.min.x-d.x)*c),u>=0?(n=(e.min.y-d.y)*u,a=(e.max.y-d.y)*u):(n=(e.max.y-d.y)*u,a=(e.min.y-d.y)*u),s>a||n>i||((n>s||isNaN(s))&&(s=n),(a<i||isNaN(i))&&(i=a),h>=0?(o=(e.min.z-d.z)*h,l=(e.max.z-d.z)*h):(o=(e.max.z-d.z)*h,l=(e.min.z-d.z)*h),s>l||o>i)||((o>s||s!==s)&&(s=o),(l<i||i!==i)&&(i=l),i<0)?null:this.at(s>=0?s:i,t)}intersectsBox(e){return this.intersectBox(e,Vi)!==null}intersectTriangle(e,t,s,i,n){zh.subVectors(t,e),_l.subVectors(s,e),Gh.crossVectors(zh,_l);let a=this.direction.dot(Gh),o;if(a>0){if(i)return null;o=1}else if(a<0)o=-1,a=-a;else return null;hn.subVectors(this.origin,e);const l=o*this.direction.dot(_l.crossVectors(hn,_l));if(l<0)return null;const c=o*this.direction.dot(zh.cross(hn));if(c<0||l+c>a)return null;const u=-o*hn.dot(Gh);return u<0?null:this.at(u/a,n)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class vn extends _s{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Ne(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 Is,this.combine=Eu,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 rg=new ve,Qn=new sC,bl=new Lu,ag=new D,Tl=new D,Sl=new D,vl=new D,$h=new D,Ml=new D,og=new D,wl=new D;class Un extends gt{constructor(e=new Bi,t=new vn){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),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){const t=this.geometry.morphAttributes,s=Object.keys(t);if(s.length>0){const i=t[s[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let n=0,a=i.length;n<a;n++){const o=i[n].name||String(n);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=n}}}}getVertexPosition(e,t){const s=this.geometry,i=s.attributes.position,n=s.morphAttributes.position,a=s.morphTargetsRelative;t.fromBufferAttribute(i,e);const o=this.morphTargetInfluences;if(n&&o){Ml.set(0,0,0);for(let l=0,c=n.length;l<c;l++){const u=o[l],h=n[l];u!==0&&($h.fromBufferAttribute(h,e),a?Ml.addScaledVector($h,u):Ml.addScaledVector($h.sub(t),u))}t.add(Ml)}return t}raycast(e,t){const s=this.geometry,i=this.material,n=this.matrixWorld;i!==void 0&&(s.boundingSphere===null&&s.computeBoundingSphere(),bl.copy(s.boundingSphere),bl.applyMatrix4(n),Qn.copy(e.ray).recast(e.near),!(bl.containsPoint(Qn.origin)===!1&&(Qn.intersectSphere(bl,ag)===null||Qn.origin.distanceToSquared(ag)>(e.far-e.near)**2))&&(rg.copy(n).invert(),Qn.copy(e.ray).applyMatrix4(rg),!(s.boundingBox!==null&&Qn.intersectsBox(s.boundingBox)===!1)&&this._computeIntersections(e,t,Qn)))}_computeIntersections(e,t,s){let i;const n=this.geometry,a=this.material,o=n.index,l=n.attributes.position,c=n.attributes.uv,u=n.attributes.uv1,h=n.attributes.normal,d=n.groups,p=n.drawRange;if(o!==null)if(Array.isArray(a))for(let f=0,m=d.length;f<m;f++){const x=d[f],y=a[x.materialIndex],b=Math.max(x.start,p.start),v=Math.min(o.count,Math.min(x.start+x.count,p.start+p.count));for(let S=b,M=v;S<M;S+=3){const A=o.getX(S),C=o.getX(S+1),P=o.getX(S+2);i=Cl(this,y,e,s,c,u,h,A,C,P),i&&(i.faceIndex=Math.floor(S/3),i.face.materialIndex=x.materialIndex,t.push(i))}}else{const f=Math.max(0,p.start),m=Math.min(o.count,p.start+p.count);for(let x=f,y=m;x<y;x+=3){const b=o.getX(x),v=o.getX(x+1),S=o.getX(x+2);i=Cl(this,a,e,s,c,u,h,b,v,S),i&&(i.faceIndex=Math.floor(x/3),t.push(i))}}else if(l!==void 0)if(Array.isArray(a))for(let f=0,m=d.length;f<m;f++){const x=d[f],y=a[x.materialIndex],b=Math.max(x.start,p.start),v=Math.min(l.count,Math.min(x.start+x.count,p.start+p.count));for(let S=b,M=v;S<M;S+=3){const A=S,C=S+1,P=S+2;i=Cl(this,y,e,s,c,u,h,A,C,P),i&&(i.faceIndex=Math.floor(S/3),i.face.materialIndex=x.materialIndex,t.push(i))}}else{const f=Math.max(0,p.start),m=Math.min(l.count,p.start+p.count);for(let x=f,y=m;x<y;x+=3){const b=x,v=x+1,S=x+2;i=Cl(this,a,e,s,c,u,h,b,v,S),i&&(i.faceIndex=Math.floor(x/3),t.push(i))}}}}function iC(r,e,t,s,i,n,a,o){let l;if(e.side===Rt?l=s.intersectTriangle(a,n,i,!0,o):l=s.intersectTriangle(i,n,a,e.side===Si,o),l===null)return null;wl.copy(o),wl.applyMatrix4(r.matrixWorld);const c=t.ray.origin.distanceTo(wl);return c<t.near||c>t.far?null:{distance:c,point:wl.clone(),object:r}}function Cl(r,e,t,s,i,n,a,o,l,c){r.getVertexPosition(o,Tl),r.getVertexPosition(l,Sl),r.getVertexPosition(c,vl);const u=iC(r,e,t,s,Tl,Sl,vl,og);if(u){const h=new D;Ys.getBarycoord(og,Tl,Sl,vl,h),i&&(u.uv=Ys.getInterpolatedAttribute(i,o,l,c,h,new xe)),n&&(u.uv1=Ys.getInterpolatedAttribute(n,o,l,c,h,new xe)),a&&(u.normal=Ys.getInterpolatedAttribute(a,o,l,c,h,new D),u.normal.dot(s.direction)>0&&u.normal.multiplyScalar(-1));const d={a:o,b:l,c,normal:new D,materialIndex:0};Ys.getNormal(Tl,Sl,vl,d.normal),u.face=d,u.barycoord=h}return u}class Kx extends kt{constructor(e=null,t=1,s=1,i,n,a,o,l,c=at,u=at,h,d){super(null,a,o,l,c,u,i,n,h,d),this.isDataTexture=!0,this.image={data:e,width:t,height:s},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class _a extends ys{constructor(e,t,s,i=1){super(e,t,s),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=i}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}toJSON(){const e=super.toJSON();return e.meshPerAttribute=this.meshPerAttribute,e.isInstancedBufferAttribute=!0,e}}const Wh=new D,nC=new D,rC=new as;class Tn{constructor(e=new D(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,s,i){return this.normal.set(e,t,s),this.constant=i,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,s){const i=Wh.subVectors(s,t).cross(nC.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(i,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){const s=e.delta(Wh),i=this.normal.dot(s);if(i===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;const n=-(e.start.dot(this.normal)+this.constant)/i;return n<0||n>1?null:t.copy(e.start).addScaledVector(s,n)}intersectsLine(e){const t=this.distanceToPoint(e.start),s=this.distanceToPoint(e.end);return t<0&&s>0||s<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 s=t||rC.getNormalMatrix(e),i=this.coplanarPoint(Wh).applyMatrix4(e),n=this.normal.applyMatrix3(s).normalize();return this.constant=-i.dot(n),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const Kn=new Lu,aC=new xe(.5,.5),Al=new D;class qp{constructor(e=new Tn,t=new Tn,s=new Tn,i=new Tn,n=new Tn,a=new Tn){this.planes=[e,t,s,i,n,a]}set(e,t,s,i,n,a){const o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(s),o[3].copy(i),o[4].copy(n),o[5].copy(a),this}copy(e){const t=this.planes;for(let s=0;s<6;s++)t[s].copy(e.planes[s]);return this}setFromProjectionMatrix(e,t=gs,s=!1){const i=this.planes,n=e.elements,a=n[0],o=n[1],l=n[2],c=n[3],u=n[4],h=n[5],d=n[6],p=n[7],f=n[8],m=n[9],x=n[10],y=n[11],b=n[12],v=n[13],S=n[14],M=n[15];if(i[0].setComponents(c-a,p-u,y-f,M-b).normalize(),i[1].setComponents(c+a,p+u,y+f,M+b).normalize(),i[2].setComponents(c+o,p+h,y+m,M+v).normalize(),i[3].setComponents(c-o,p-h,y-m,M-v).normalize(),s)i[4].setComponents(l,d,x,S).normalize(),i[5].setComponents(c-l,p-d,y-x,M-S).normalize();else if(i[4].setComponents(c-l,p-d,y-x,M-S).normalize(),t===gs)i[5].setComponents(c+l,p+d,y+x,M+S).normalize();else if(t===Ls)i[5].setComponents(l,d,x,S).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),Kn.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),Kn.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Kn)}intersectsSprite(e){Kn.center.set(0,0,0);const t=aC.distanceTo(e.center);return Kn.radius=.7071067811865476+t,Kn.applyMatrix4(e.matrixWorld),this.intersectsSphere(Kn)}intersectsSphere(e){const t=this.planes,s=e.center,i=-e.radius;for(let n=0;n<6;n++)if(t[n].distanceToPoint(s)<i)return!1;return!0}intersectsBox(e){const t=this.planes;for(let s=0;s<6;s++){const i=t[s];if(Al.x=i.normal.x>0?e.max.x:e.min.x,Al.y=i.normal.y>0?e.max.y:e.min.y,Al.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(Al)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let s=0;s<6;s++)if(t[s].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}const si=new ve,ii=new qp;class Xp{constructor(){this.coordinateSystem=gs}intersectsObject(e,t){if(!t.isArrayCamera||t.cameras.length===0)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(si.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),ii.setFromProjectionMatrix(si,i.coordinateSystem,i.reversedDepth),ii.intersectsObject(e))return!0}return!1}intersectsSprite(e,t){if(!t||!t.cameras||t.cameras.length===0)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(si.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),ii.setFromProjectionMatrix(si,i.coordinateSystem,i.reversedDepth),ii.intersectsSprite(e))return!0}return!1}intersectsSphere(e,t){if(!t||!t.cameras||t.cameras.length===0)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(si.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),ii.setFromProjectionMatrix(si,i.coordinateSystem,i.reversedDepth),ii.intersectsSphere(e))return!0}return!1}intersectsBox(e,t){if(!t||!t.cameras||t.cameras.length===0)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(si.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),ii.setFromProjectionMatrix(si,i.coordinateSystem,i.reversedDepth),ii.intersectsBox(e))return!0}return!1}containsPoint(e,t){if(!t||!t.cameras||t.cameras.length===0)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(si.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),ii.setFromProjectionMatrix(si,i.coordinateSystem,i.reversedDepth),ii.containsPoint(e))return!0}return!1}clone(){return new Xp}}class Jx extends _s{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new Ne(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}}class oC extends _s{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new Ne(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 Yp extends kt{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=at,this.minFilter=at,this.generateMipmaps=!1,this.needsUpdate=!0}}class Iu extends kt{constructor(e=[],t=Ca,s,i,n,a,o,l,c,u){super(e,t,s,i,n,a,o,l,c,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class Bs extends kt{constructor(e,t,s=rt,i,n,a,o=at,l=at,c,u=Qs,h=1){if(u!==Qs&&u!==Yi)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const d={width:e,height:t,depth:h};super(d,i,n,a,o,l,u,s,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new Hp(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}}class lC extends Bs{constructor(e,t=rt,s=Ca,i,n,a=at,o=at,l,c=Qs){const u={width:e,height:e,depth:1},h=[u,u,u,u,u,u];super(e,e,t,s,i,n,a,o,l,c),this.image=h,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}}class Uu extends Bi{constructor(e=1,t=1,s=1,i=1,n=1,a=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:s,widthSegments:i,heightSegments:n,depthSegments:a};const o=this;i=Math.floor(i),n=Math.floor(n),a=Math.floor(a);const l=[],c=[],u=[],h=[];let d=0,p=0;f("z","y","x",-1,-1,s,t,e,a,n,0),f("z","y","x",1,-1,s,t,-e,a,n,1),f("x","z","y",1,1,e,s,t,i,a,2),f("x","z","y",1,-1,e,s,-t,i,a,3),f("x","y","z",1,-1,e,t,s,i,n,4),f("x","y","z",-1,-1,e,t,-s,i,n,5),this.setIndex(l),this.setAttribute("position",new Yt(c,3)),this.setAttribute("normal",new Yt(u,3)),this.setAttribute("uv",new Yt(h,2));function f(m,x,y,b,v,S,M,A,C,P,B){const V=S/C,Y=M/P,J=S/2,K=M/2,te=A/2,q=C+1,oe=P+1;let Pe=0,ge=0;const le=new D;for(let Ue=0;Ue<oe;Ue++){const He=Ue*Y-K;for(let $t=0;$t<q;$t++){const Fe=$t*V-J;le[m]=Fe*b,le[x]=He*v,le[y]=te,c.push(le.x,le.y,le.z),le[m]=0,le[x]=0,le[y]=A>0?1:-1,u.push(le.x,le.y,le.z),h.push($t/C),h.push(1-Ue/P),Pe+=1}}for(let Ue=0;Ue<P;Ue++)for(let He=0;He<C;He++){const $t=d+He+q*Ue,Fe=d+He+q*(Ue+1),Ct=d+(He+1)+q*(Ue+1),Ts=d+(He+1)+q*Ue;l.push($t,Fe,Ts),l.push(Fe,Ct,Ts),ge+=6}o.addGroup(p,ge,B),p+=ge,d+=Pe}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Uu(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}class Zp extends Bi{constructor(e=1,t=1,s=1,i=32,n=1,a=!1,o=0,l=Math.PI*2){super(),this.type="CylinderGeometry",this.parameters={radiusTop:e,radiusBottom:t,height:s,radialSegments:i,heightSegments:n,openEnded:a,thetaStart:o,thetaLength:l};const c=this;i=Math.floor(i),n=Math.floor(n);const u=[],h=[],d=[],p=[];let f=0;const m=[],x=s/2;let y=0;b(),a===!1&&(e>0&&v(!0),t>0&&v(!1)),this.setIndex(u),this.setAttribute("position",new Yt(h,3)),this.setAttribute("normal",new Yt(d,3)),this.setAttribute("uv",new Yt(p,2));function b(){const S=new D,M=new D;let A=0;const C=(t-e)/s;for(let P=0;P<=n;P++){const B=[],V=P/n,Y=V*(t-e)+e;for(let J=0;J<=i;J++){const K=J/i,te=K*l+o,q=Math.sin(te),oe=Math.cos(te);M.x=Y*q,M.y=-V*s+x,M.z=Y*oe,h.push(M.x,M.y,M.z),S.set(q,C,oe).normalize(),d.push(S.x,S.y,S.z),p.push(K,1-V),B.push(f++)}m.push(B)}for(let P=0;P<i;P++)for(let B=0;B<n;B++){const V=m[B][P],Y=m[B+1][P],J=m[B+1][P+1],K=m[B][P+1];(e>0||B!==0)&&(u.push(V,Y,K),A+=3),(t>0||B!==n-1)&&(u.push(Y,J,K),A+=3)}c.addGroup(y,A,0),y+=A}function v(S){const M=f,A=new xe,C=new D;let P=0;const B=S===!0?e:t,V=S===!0?1:-1;for(let J=1;J<=i;J++)h.push(0,x*V,0),d.push(0,V,0),p.push(.5,.5),f++;const Y=f;for(let J=0;J<=i;J++){const te=J/i*l+o,q=Math.cos(te),oe=Math.sin(te);C.x=B*oe,C.y=x*V,C.z=B*q,h.push(C.x,C.y,C.z),d.push(0,V,0),A.x=q*.5+.5,A.y=oe*.5*V+.5,p.push(A.x,A.y),f++}for(let J=0;J<i;J++){const K=M+J,te=Y+J;S===!0?u.push(te,te+1,K):u.push(te+1,te,K),P+=3}c.addGroup(y,P,S===!0?1:2),y+=P}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Zp(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class Qp extends Bi{constructor(e=1,t=1,s=1,i=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:s,heightSegments:i};const n=e/2,a=t/2,o=Math.floor(s),l=Math.floor(i),c=o+1,u=l+1,h=e/o,d=t/l,p=[],f=[],m=[],x=[];for(let y=0;y<u;y++){const b=y*d-a;for(let v=0;v<c;v++){const S=v*h-n;f.push(S,-b,0),m.push(0,0,1),x.push(v/o),x.push(1-y/l)}}for(let y=0;y<l;y++)for(let b=0;b<o;b++){const v=b+c*y,S=b+c*(y+1),M=b+1+c*(y+1),A=b+1+c*y;p.push(v,S,A),p.push(S,M,A)}this.setIndex(p),this.setAttribute("position",new Yt(f,3)),this.setAttribute("normal",new Yt(m,3)),this.setAttribute("uv",new Yt(x,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Qp(e.width,e.height,e.widthSegments,e.heightSegments)}}class Kp extends Bi{constructor(e=1,t=32,s=16,i=0,n=Math.PI*2,a=0,o=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:e,widthSegments:t,heightSegments:s,phiStart:i,phiLength:n,thetaStart:a,thetaLength:o},t=Math.max(3,Math.floor(t)),s=Math.max(2,Math.floor(s));const l=Math.min(a+o,Math.PI);let c=0;const u=[],h=new D,d=new D,p=[],f=[],m=[],x=[];for(let y=0;y<=s;y++){const b=[],v=y/s;let S=0;y===0&&a===0?S=.5/t:y===s&&l===Math.PI&&(S=-.5/t);for(let M=0;M<=t;M++){const A=M/t;h.x=-e*Math.cos(i+A*n)*Math.sin(a+v*o),h.y=e*Math.cos(a+v*o),h.z=e*Math.sin(i+A*n)*Math.sin(a+v*o),f.push(h.x,h.y,h.z),d.copy(h).normalize(),m.push(d.x,d.y,d.z),x.push(A+S,1-v),b.push(c++)}u.push(b)}for(let y=0;y<s;y++)for(let b=0;b<t;b++){const v=u[y][b+1],S=u[y][b],M=u[y+1][b],A=u[y+1][b+1];(y!==0||a>0)&&p.push(v,S,A),(y!==s-1||l<Math.PI)&&p.push(S,M,A)}this.setIndex(p),this.setAttribute("position",new Yt(f,3)),this.setAttribute("normal",new Yt(m,3)),this.setAttribute("uv",new Yt(x,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Kp(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}class cC extends _s{constructor(e){super(),this.isShadowMaterial=!0,this.type="ShadowMaterial",this.color=new Ne(0),this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.fog=e.fog,this}}class e0 extends _s{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new Ne(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 Ne(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Zi,this.normalScale=new xe(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 Is,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 uC extends e0{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 xe(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return be(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(t){this.ior=(1+.4*t)/(1-.4*t)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new Ne(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 Ne(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new Ne(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}}class hC extends _s{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new Ne(16777215),this.specular=new Ne(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Ne(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Zi,this.normalScale=new xe(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Is,this.combine=Eu,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 dC extends _s{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new Ne(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Ne(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Zi,this.normalScale=new xe(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 pC extends _s{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Zi,this.normalScale=new xe(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 fC extends _s{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new Ne(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Ne(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Zi,this.normalScale=new xe(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Is,this.combine=Eu,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 mC extends _s{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new Ne(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Zi,this.normalScale=new xe(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 gC extends Jx{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}}class Mr extends gt{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new Ne(e),this.intensity=t}dispose(){this.dispatchEvent({type:"dispose"})}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){const t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,t}}class yC extends Mr{constructor(e,t,s){super(e,s),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(gt.DEFAULT_UP),this.updateMatrix(),this.groundColor=new Ne(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 Hh=new ve,lg=new D,cg=new D;class Jp{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 xe(512,512),this.mapType=Ut,this.map=null,this.mapPass=null,this.matrix=new ve,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new qp,this._frameExtents=new xe(1,1),this._viewportCount=1,this._viewports=[new Ee(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const t=this.camera,s=this.matrix;lg.setFromMatrixPosition(e.matrixWorld),t.position.copy(lg),cg.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(cg),t.updateMatrixWorld(),Hh.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Hh,t.coordinateSystem,t.reversedDepth),t.coordinateSystem===Ls||t.reversedDepth?s.set(.5,0,0,.5,0,.5,0,.5,0,0,1,0,0,0,0,1):s.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),s.multiply(Hh)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.intensity=e.intensity,this.bias=e.bias,this.radius=e.radius,this.autoUpdate=e.autoUpdate,this.needsUpdate=e.needsUpdate,this.normalBias=e.normalBias,this.blurSamples=e.blurSamples,this.mapSize.copy(e.mapSize),this.biasNode=e.biasNode,this}clone(){return new this.constructor().copy(this)}toJSON(){const e={};return this.intensity!==1&&(e.intensity=this.intensity),this.bias!==0&&(e.bias=this.bias),this.normalBias!==0&&(e.normalBias=this.normalBias),this.radius!==1&&(e.radius=this.radius),(this.mapSize.x!==512||this.mapSize.y!==512)&&(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}}const El=new D,Nl=new vr,ni=new D;class t0 extends gt{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new ve,this.projectionMatrix=new ve,this.projectionMatrixInverse=new ve,this.coordinateSystem=gs,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(El,Nl,ni),ni.x===1&&ni.y===1&&ni.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(El,Nl,ni.set(1,1,1)).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorld.decompose(El,Nl,ni),ni.x===1&&ni.y===1&&ni.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(El,Nl,ni.set(1,1,1)).invert()}clone(){return new this.constructor().copy(this)}}const dn=new D,ug=new xe,hg=new xe;class fs extends t0{constructor(e=50,t=1,s=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=s,this.far=i,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=Ra*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(Eo*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return Ra*2*Math.atan(Math.tan(Eo*.5*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,s){dn.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(dn.x,dn.y).multiplyScalar(-e/dn.z),dn.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),s.set(dn.x,dn.y).multiplyScalar(-e/dn.z)}getViewSize(e,t){return this.getViewBounds(e,ug,hg),t.subVectors(hg,ug)}setViewOffset(e,t,s,i,n,a){this.aspect=e/t,this.view===null&&(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=s,this.view.offsetY=i,this.view.width=n,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(Eo*.5*this.fov)/this.zoom,s=2*t,i=this.aspect*s,n=-.5*i;const a=this.view;if(this.view!==null&&this.view.enabled){const l=a.fullWidth,c=a.fullHeight;n+=a.offsetX*i/l,t-=a.offsetY*s/c,i*=a.width/l,s*=a.height/c}const o=this.filmOffset;o!==0&&(n+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(n,n+i,t,t-s,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,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}class xC extends Jp{constructor(){super(new fs(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(e){const t=this.camera,s=Ra*2*e.angle*this.focus,i=this.mapSize.width/this.mapSize.height*this.aspect,n=e.distance||t.far;(s!==t.fov||i!==t.aspect||n!==t.far)&&(t.fov=s,t.aspect=i,t.far=n,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this}}class ef extends Mr{constructor(e,t,s=0,i=Math.PI/3,n=0,a=2){super(e,t),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(gt.DEFAULT_UP),this.updateMatrix(),this.target=new gt,this.distance=s,this.angle=i,this.penumbra=n,this.decay=a,this.map=null,this.shadow=new xC}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 _C extends Jp{constructor(){super(new fs(90,1,.5,500)),this.isPointLightShadow=!0}}class bC extends Mr{constructor(e,t,s=0,i=2){super(e,t),this.isPointLight=!0,this.type="PointLight",this.distance=s,this.decay=i,this.shadow=new _C}get power(){return this.intensity*4*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 tf extends t0{constructor(e=-1,t=1,s=1,i=-1,n=.1,a=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=s,this.bottom=i,this.near=n,this.far=a,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=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,s,i,n,a){this.view===null&&(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=s,this.view.offsetY=i,this.view.width=n,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),s=(this.right+this.left)/2,i=(this.top+this.bottom)/2;let n=s-e,a=s+e,o=i+t,l=i-t;if(this.view!==null&&this.view.enabled){const c=(this.right-this.left)/this.view.fullWidth/this.zoom,u=(this.top-this.bottom)/this.view.fullHeight/this.zoom;n+=c*this.view.offsetX,a=n+c*this.view.width,o-=u*this.view.offsetY,l=o-u*this.view.height}this.projectionMatrix.makeOrthographic(n,a,o,l,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,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}}class TC extends Jp{constructor(){super(new tf(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class SC extends Mr{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(gt.DEFAULT_UP),this.updateMatrix(),this.target=new gt,this.shadow=new TC}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 vC extends Mr{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}}class MC extends Mr{constructor(e,t,s=10,i=10){super(e,t),this.isRectAreaLight=!0,this.type="RectAreaLight",this.width=s,this.height=i}get power(){return this.intensity*this.width*this.height*Math.PI}set power(e){this.intensity=e/(this.width*this.height*Math.PI)}copy(e){return super.copy(e),this.width=e.width,this.height=e.height,this}toJSON(e){const t=super.toJSON(e);return t.object.width=this.width,t.object.height=this.height,t}}class wC{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let e=0;e<9;e++)this.coefficients.push(new D)}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 s=e.x,i=e.y,n=e.z,a=this.coefficients;return t.copy(a[0]).multiplyScalar(.282095),t.addScaledVector(a[1],.488603*i),t.addScaledVector(a[2],.488603*n),t.addScaledVector(a[3],.488603*s),t.addScaledVector(a[4],1.092548*(s*i)),t.addScaledVector(a[5],1.092548*(i*n)),t.addScaledVector(a[6],.315392*(3*n*n-1)),t.addScaledVector(a[7],1.092548*(s*n)),t.addScaledVector(a[8],.546274*(s*s-i*i)),t}getIrradianceAt(e,t){const s=e.x,i=e.y,n=e.z,a=this.coefficients;return t.copy(a[0]).multiplyScalar(.886227),t.addScaledVector(a[1],2*.511664*i),t.addScaledVector(a[2],2*.511664*n),t.addScaledVector(a[3],2*.511664*s),t.addScaledVector(a[4],2*.429043*s*i),t.addScaledVector(a[5],2*.429043*i*n),t.addScaledVector(a[6],.743125*n*n-.247708),t.addScaledVector(a[7],2*.429043*s*n),t.addScaledVector(a[8],.429043*(s*s-i*i)),t}add(e){for(let t=0;t<9;t++)this.coefficients[t].add(e.coefficients[t]);return this}addScaledSH(e,t){for(let s=0;s<9;s++)this.coefficients[s].addScaledVector(e.coefficients[s],t);return this}scale(e){for(let t=0;t<9;t++)this.coefficients[t].multiplyScalar(e);return this}lerp(e,t){for(let s=0;s<9;s++)this.coefficients[s].lerp(e.coefficients[s],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 s=this.coefficients;for(let i=0;i<9;i++)s[i].fromArray(e,t+i*3);return this}toArray(e=[],t=0){const s=this.coefficients;for(let i=0;i<9;i++)s[i].toArray(e,t+i*3);return e}static getBasisAt(e,t){const s=e.x,i=e.y,n=e.z;t[0]=.282095,t[1]=.488603*i,t[2]=.488603*n,t[3]=.488603*s,t[4]=1.092548*s*i,t[5]=1.092548*i*n,t[6]=.315392*(3*n*n-1),t[7]=1.092548*s*n,t[8]=.546274*(s*s-i*i)}}class CC extends Mr{constructor(e=new wC,t=1){super(void 0,t),this.isLightProbe=!0,this.sh=e}copy(e){return super.copy(e),this.sh.copy(e.sh),this}toJSON(e){const t=super.toJSON(e);return t.object.sh=this.sh.toArray(),t}}const Hr=-90,jr=1;class AC extends gt{constructor(e,t,s){super(),this.type="CubeCamera",this.renderTarget=s,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new fs(Hr,jr,e,t);i.layers=this.layers,this.add(i);const n=new fs(Hr,jr,e,t);n.layers=this.layers,this.add(n);const a=new fs(Hr,jr,e,t);a.layers=this.layers,this.add(a);const o=new fs(Hr,jr,e,t);o.layers=this.layers,this.add(o);const l=new fs(Hr,jr,e,t);l.layers=this.layers,this.add(l);const c=new fs(Hr,jr,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[s,i,n,a,o,l]=t;for(const c of t)this.remove(c);if(e===gs)s.up.set(0,1,0),s.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),n.up.set(0,0,-1),n.lookAt(0,1,0),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),l.up.set(0,1,0),l.lookAt(0,0,-1);else if(e===Ls)s.up.set(0,-1,0),s.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),n.up.set(0,0,1),n.lookAt(0,1,0),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),l.up.set(0,-1,0),l.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const c of t)this.add(c),c.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:s,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[n,a,o,l,c,u]=this.children,h=e.getRenderTarget(),d=e.getActiveCubeFace(),p=e.getActiveMipmapLevel(),f=e.xr.enabled;e.xr.enabled=!1;const m=s.texture.generateMipmaps;s.texture.generateMipmaps=!1;let x=!1;e.isWebGLRenderer===!0?x=e.state.buffers.depth.getReversed():x=e.reversedDepthBuffer,e.setRenderTarget(s,0,i),x&&e.autoClear===!1&&e.clearDepth(),e.render(t,n),e.setRenderTarget(s,1,i),x&&e.autoClear===!1&&e.clearDepth(),e.render(t,a),e.setRenderTarget(s,2,i),x&&e.autoClear===!1&&e.clearDepth(),e.render(t,o),e.setRenderTarget(s,3,i),x&&e.autoClear===!1&&e.clearDepth(),e.render(t,l),e.setRenderTarget(s,4,i),x&&e.autoClear===!1&&e.clearDepth(),e.render(t,c),s.texture.generateMipmaps=m,e.setRenderTarget(s,5,i),x&&e.autoClear===!1&&e.clearDepth(),e.render(t,u),e.setRenderTarget(h,d,p),e.xr.enabled=f,s.texture.needsPMREMUpdate=!0}}class EC extends fs{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class NC extends Qx{constructor(e,t,s=1){super(e,t),this.isInstancedInterleavedBuffer=!0,this.meshPerAttribute=s}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}clone(e){const t=super.clone(e);return t.meshPerAttribute=this.meshPerAttribute,t}toJSON(e){const t=super.toJSON(e);return t.isInstancedInterleavedBuffer=!0,t.meshPerAttribute=this.meshPerAttribute,t}}class Vu{constructor(e,t,s,i){Vu.prototype.isMatrix2=!0,this.elements=[1,0,0,1],e!==void 0&&this.set(e,t,s,i)}identity(){return this.set(1,0,0,1),this}fromArray(e,t=0){for(let s=0;s<4;s++)this.elements[s]=e[s+t];return this}set(e,t,s,i){const n=this.elements;return n[0]=e,n[2]=t,n[1]=s,n[3]=i,this}}function RC(r,e,t,s){const i=PC(s);switch(t){case Lx:return r*e;case Ru:return r*e/i.components*i.byteLength;case Pu:return r*e/i.components*i.byteLength;case _i:return r*e*2/i.components*i.byteLength;case Fu:return r*e*2/i.components*i.byteLength;case Nu:return r*e*3/i.components*i.byteLength;case ms:return r*e*4/i.components*i.byteLength;case Bu:return r*e*4/i.components*i.byteLength;case Mo:case wo:return Math.floor((r+3)/4)*Math.floor((e+3)/4)*8;case Co:case Ao:return Math.floor((r+3)/4)*Math.floor((e+3)/4)*16;case ep:case sp:return Math.max(r,16)*Math.max(e,8)/4;case Jd:case tp:return Math.max(r,8)*Math.max(e,8)/2;case Oc:case Lc:case Uc:case Vc:return Math.floor((r+3)/4)*Math.floor((e+3)/4)*8;case Ic:case Go:case kc:return Math.floor((r+3)/4)*Math.floor((e+3)/4)*16;case zc:return Math.floor((r+3)/4)*Math.floor((e+3)/4)*16;case Gc:return Math.floor((r+4)/5)*Math.floor((e+3)/4)*16;case $c:return Math.floor((r+4)/5)*Math.floor((e+4)/5)*16;case Wc:return Math.floor((r+5)/6)*Math.floor((e+4)/5)*16;case Hc:return Math.floor((r+5)/6)*Math.floor((e+5)/6)*16;case jc:return Math.floor((r+7)/8)*Math.floor((e+4)/5)*16;case qc:return Math.floor((r+7)/8)*Math.floor((e+5)/6)*16;case Xc:return Math.floor((r+7)/8)*Math.floor((e+7)/8)*16;case Yc:return Math.floor((r+9)/10)*Math.floor((e+4)/5)*16;case Zc:return Math.floor((r+9)/10)*Math.floor((e+5)/6)*16;case Qc:return Math.floor((r+9)/10)*Math.floor((e+7)/8)*16;case Kc:return Math.floor((r+9)/10)*Math.floor((e+9)/10)*16;case Jc:return Math.floor((r+11)/12)*Math.floor((e+9)/10)*16;case eu:return Math.floor((r+11)/12)*Math.floor((e+11)/12)*16;case tu:case ew:case tw:return Math.ceil(r/4)*Math.ceil(e/4)*16;case su:case iu:return Math.ceil(r/4)*Math.ceil(e/4)*8;case $o:case nu:return Math.ceil(r/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${t} format.`)}function PC(r){switch(r){case Ut:case ga:return{byteLength:1,components:1};case pr:case ya:case Et:return{byteLength:2,components:1};case Dx:case Ox:return{byteLength:2,components:4};case rt:case Lt:case es:return{byteLength:4,components:1};case zp:case Gp:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${r}.`)}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:Zo}}));typeof window<"u"&&(window.__THREE__?W("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=Zo);/**
26
- * @license
27
- * Copyright 2010-2026 Three.js Authors
28
- * SPDX-License-Identifier: MIT
29
- */const FC=["alphaMap","alphaTest","anisotropy","anisotropyMap","anisotropyRotation","aoMap","aoMapIntensity","attenuationColor","attenuationDistance","bumpMap","clearcoat","clearcoatMap","clearcoatNormalMap","clearcoatNormalScale","clearcoatRoughness","color","dispersion","displacementMap","emissive","emissiveIntensity","emissiveMap","envMap","envMapIntensity","gradientMap","ior","iridescence","iridescenceIOR","iridescenceMap","iridescenceThicknessMap","lightMap","lightMapIntensity","map","matcap","metalness","metalnessMap","normalMap","normalScale","opacity","roughness","roughnessMap","sheen","sheenColor","sheenColorMap","sheenRoughnessMap","shininess","specular","specularColor","specularColorMap","specularIntensity","specularIntensityMap","specularMap","thickness","transmission","transmissionMap"],jh=new WeakMap;class BC{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=e.object.isSkinnedMesh===!0,this.refreshUniforms=FC,this.renderId=0}firstInitialization(e){return this.renderObjects.has(e)===!1?(this.getRenderObjectData(e),!0):!1}needsVelocity(e){const t=e.getMRT();return t!==null&&t.has("velocity")}getRenderObjectData(e){let t=this.renderObjects.get(e);if(t===void 0){const{geometry:s,material:i,object:n}=e;if(t={material:this.getMaterialData(i),geometry:{id:s.id,attributes:this.getAttributesData(s.attributes),indexId:s.index?s.index.id:null,indexVersion:s.index?s.index.version:null,drawRange:{start:s.drawRange.start,count:s.drawRange.count}},worldMatrix:n.matrixWorld.clone()},n.center&&(t.center=n.center.clone()),n.morphTargetInfluences&&(t.morphTargetInfluences=n.morphTargetInfluences.slice()),e.bundle!==null&&(t.version=e.bundle.version),t.material.transmission>0){const{width:a,height:o}=e.context;t.bufferWidth=a,t.bufferHeight=o}t.lights=this.getLightsData(e.lightsNode.getLights()),this.renderObjects.set(e,t)}return t}getAttributesData(e){const t={};for(const s in e){const i=e[s];t[s]={id:i.id,version:i.version}}return t}containsNode(e){const t=e.material;for(const s in t)if(t[s]&&t[s].isNode)return!0;return!!(e.context.modelViewMatrix||e.context.modelNormalViewMatrix||e.context.getAO||e.context.getShadow)}getMaterialData(e){const t={};for(const s of this.refreshUniforms){const i=e[s];i!=null&&(typeof i=="object"&&i.clone!==void 0?i.isTexture===!0?t[s]={id:i.id,version:i.version}:t[s]=i.clone():t[s]=i)}return t}equals(e,t){const{object:s,material:i,geometry:n}=e,a=this.getRenderObjectData(e);if(a.worldMatrix.equals(s.matrixWorld)!==!0)return a.worldMatrix.copy(s.matrixWorld),!1;const o=a.material;for(const b in o){const v=o[b],S=i[b];if(v.equals!==void 0){if(v.equals(S)===!1)return v.copy(S),!1}else if(S.isTexture===!0){if(v.id!==S.id||v.version!==S.version)return v.id=S.id,v.version=S.version,!1}else if(v!==S)return o[b]=S,!1}if(o.transmission>0){const{width:b,height:v}=e.context;if(a.bufferWidth!==b||a.bufferHeight!==v)return a.bufferWidth=b,a.bufferHeight=v,!1}const l=a.geometry,c=n.attributes,u=l.attributes,h=Object.keys(u),d=Object.keys(c);if(l.id!==n.id)return l.id=n.id,!1;if(h.length!==d.length)return a.geometry.attributes=this.getAttributesData(c),!1;for(const b of h){const v=u[b],S=c[b];if(S===void 0)return delete u[b],!1;if(v.id!==S.id||v.version!==S.version)return v.id=S.id,v.version=S.version,!1}const p=n.index,f=l.indexId,m=l.indexVersion,x=p?p.id:null,y=p?p.version:null;if(f!==x||m!==y)return l.indexId=x,l.indexVersion=y,!1;if(l.drawRange.start!==n.drawRange.start||l.drawRange.count!==n.drawRange.count)return l.drawRange.start=n.drawRange.start,l.drawRange.count=n.drawRange.count,!1;if(a.morphTargetInfluences){let b=!1;for(let v=0;v<a.morphTargetInfluences.length;v++)a.morphTargetInfluences[v]!==s.morphTargetInfluences[v]&&(a.morphTargetInfluences[v]=s.morphTargetInfluences[v],b=!0);if(b)return!1}if(a.lights){for(let b=0;b<t.length;b++)if(a.lights[b].map!==t[b].map)return!1}return a.center&&a.center.equals(s.center)===!1?(a.center.copy(s.center),!0):(e.bundle!==null&&(a.version=e.bundle.version),!0)}getLightsData(e){const t=[];for(const s of e)s.isSpotLight===!0&&s.map!==null&&t.push({map:s.map.version});return t}getLights(e,t){if(jh.has(e)){const i=jh.get(e);if(i.renderId===t)return i.lightsData}const s=this.getLightsData(e.getLights());return jh.set(e,{renderId:t,lightsData:s}),s}needsRefresh(e,t){if(this.hasNode||this.hasAnimation||this.firstInitialization(e)||this.needsVelocity(t.renderer))return!0;const{renderId:s}=t;if(this.renderId!==s)return this.renderId=s,!0;const i=e.object.static===!0,n=e.bundle!==null&&e.bundle.static===!0&&this.getRenderObjectData(e).version===e.bundle.version;if(i||n)return!1;const a=this.getLights(e.lightsNode,s);return this.equals(e,a)!==!0}}const DC=[/^StackTrace\.js$/,/^TSLCore\.js$/,/^.*Node\.js$/,/^three\.webgpu.*\.js$/];function OC(r){const e=/(?:at\s+(.+?)\s+\()?(?:(.+?)@)?([^@\s()]+):(\d+):(\d+)/;return r.split(`
30
- `).map(t=>{const s=t.match(e);if(!s)return null;const i=s[1]||s[2]||"",n=s[3].split("?")[0],a=parseInt(s[4],10),o=parseInt(s[5],10),l=n.split("/").pop();return{fn:i,file:l,line:a,column:o}}).filter(t=>t&&!DC.some(s=>s.test(t.file)))}class ct{constructor(e=null){this.isStackTrace=!0,this.stack=OC(e||new Error().stack)}getLocation(){if(this.stack.length===0)return"[Unknown location]";const e=this.stack[0],t=e.fn;return`${t?`"${t}()" at `:""}"${e.file}:${e.line}"`}getError(e){if(this.stack.length===0)return e;const t=this.stack.map(s=>{const i=`${s.file}:${s.line}:${s.column}`;return s.fn?` at ${s.fn} (${i})`:` at ${i}`}).join(`
31
- `);return`${e}
32
- ${t}`}}function sf(r,e=0){let t=3735928559^e,s=1103547991^e;if(r instanceof Array)for(let i=0,n;i<r.length;i++)n=r[i],t=Math.imul(t^n,2654435761),s=Math.imul(s^n,1597334677);else for(let i=0,n;i<r.length;i++)n=r.charCodeAt(i),t=Math.imul(t^n,2654435761),s=Math.imul(s^n,1597334677);return t=Math.imul(t^t>>>16,2246822507),t^=Math.imul(s^s>>>13,3266489909),s=Math.imul(s^s>>>16,2246822507),s^=Math.imul(t^t>>>13,3266489909),4294967296*(2097151&s)+(t>>>0)}const Ia=r=>sf(r),Ko=r=>sf(r),Ro=(...r)=>sf(r),LC=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),dg=new WeakMap;function s0(r){return LC.get(r)}function lu(r){if(/[iu]?vec\d/.test(r))return r.startsWith("ivec")?Int32Array:r.startsWith("uvec")?Uint32Array:Float32Array;if(/mat\d/.test(r)||/float/.test(r))return Float32Array;if(/uint/.test(r))return Uint32Array;if(/int/.test(r))return Int32Array;throw new Error(`THREE.NodeUtils: Unsupported type: ${r}`)}function i0(r){if(/float|int|uint/.test(r))return 1;if(/vec2/.test(r))return 2;if(/vec3/.test(r))return 3;if(/vec4/.test(r)||/mat2/.test(r))return 4;if(/mat3/.test(r))return 9;if(/mat4/.test(r))return 16;$(`TSL: Unsupported type: ${r}`,new ct)}function IC(r){if(/float|int|uint/.test(r))return 1;if(/vec2/.test(r))return 2;if(/vec3/.test(r))return 3;if(/vec4/.test(r)||/mat2/.test(r))return 4;if(/mat3/.test(r))return 12;if(/mat4/.test(r))return 16;$(`TSL: Unsupported type: ${r}`,new ct)}function UC(r){if(/float|int|uint/.test(r))return 4;if(/vec2/.test(r))return 8;if(/vec3/.test(r)||/vec4/.test(r))return 16;if(/mat2/.test(r))return 8;if(/mat3/.test(r)||/mat4/.test(r))return 16;$(`TSL: Unsupported type: ${r}`,new ct)}function Nn(r){if(r==null)return null;const e=typeof r;return r.isNode===!0?"node":e==="number"?"float":e==="boolean"?"bool":e==="string"?"string":e==="function"?"shader":r.isVector2===!0?"vec2":r.isVector3===!0?"vec3":r.isVector4===!0?"vec4":r.isMatrix2===!0?"mat2":r.isMatrix3===!0?"mat3":r.isMatrix4===!0?"mat4":r.isColor===!0?"color":r instanceof ArrayBuffer?"ArrayBuffer":null}function nf(r,...e){const t=r?r.slice(-4):void 0;return e.length===1&&(t==="vec2"?e=[e[0],e[0]]:t==="vec3"?e=[e[0],e[0],e[0]]:t==="vec4"&&(e=[e[0],e[0],e[0],e[0]])),r==="color"?new Ne(...e):t==="vec2"?new xe(...e):t==="vec3"?new D(...e):t==="vec4"?new Ee(...e):t==="mat2"?new Vu(...e):t==="mat3"?new as(...e):t==="mat4"?new ve(...e):r==="bool"?e[0]||!1:r==="float"||r==="int"||r==="uint"?e[0]||0:r==="string"?e[0]||"":r==="ArrayBuffer"?kC(e[0]):null}function n0(r){let e=dg.get(r);return e===void 0&&(e={},dg.set(r,e)),e}function VC(r){let e="";const t=new Uint8Array(r);for(let s=0;s<t.length;s++)e+=String.fromCharCode(t[s]);return btoa(e)}function kC(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0)).buffer}const xo={VERTEX:"vertex",FRAGMENT:"fragment"},re={NONE:"none",FRAME:"frame",RENDER:"render",OBJECT:"object"},zC={BOOLEAN:"bool",INTEGER:"int",FLOAT:"float",VECTOR2:"vec2",VECTOR3:"vec3",VECTOR4:"vec4",MATRIX2:"mat2",MATRIX3:"mat3",MATRIX4:"mat4"},Nt={READ_ONLY:"readOnly",WRITE_ONLY:"writeOnly",READ_WRITE:"readWrite"},r0=["fragment","vertex"],ap=["setup","analyze","generate"],op=[...r0,"compute"],wr=["x","y","z","w"],GC={analyze:"setup",generate:"analyze"};let $C=0;class Q extends Gn{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=re.NONE,this.updateBeforeType=re.NONE,this.updateAfterType=re.NONE,this.uuid=Hx.generateUUID(),this.version=0,this.name="",this.global=!1,this.parents=!1,this.isNode=!0,this._beforeNodes=null,this._cacheKey=null,this._cacheKeyVersion=0,Object.defineProperty(this,"id",{value:$C++}),this.stackTrace=null,Q.captureStackTrace===!0&&(this.stackTrace=new ct)}set needsUpdate(e){e===!0&&this.version++}get type(){return this.constructor.type}onUpdate(e,t){return this.updateType=t,this.update=e.bind(this),this}onFrameUpdate(e){return this.onUpdate(e,re.FRAME)}onRenderUpdate(e){return this.onUpdate(e,re.RENDER)}onObjectUpdate(e){return this.onUpdate(e,re.OBJECT)}onReference(e){return this.updateReference=e.bind(this),this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(const{childNode:e}of this._getChildren())yield e}dispose(){this.dispatchEvent({type:"dispose"})}traverse(e){e(this);for(const t of this.getChildren())t.traverse(e)}_getChildren(e=new Set){const t=[];e.add(this);for(const s of Object.getOwnPropertyNames(this)){const i=this[s];if(!(s.startsWith("_")===!0||e.has(i))){if(Array.isArray(i)===!0)for(let n=0;n<i.length;n++){const a=i[n];a&&a.isNode===!0&&t.push({property:s,index:n,childNode:a})}else if(i&&i.isNode===!0)t.push({property:s,childNode:i});else if(i&&Object.getPrototypeOf(i)===Object.prototype)for(const n in i){if(n.startsWith("_")===!0)continue;const a=i[n];a&&a.isNode===!0&&t.push({property:s,index:n,childNode:a})}}}return t}getCacheKey(e=!1,t=null){if(e=e||this.version!==this._cacheKeyVersion,e===!0||this._cacheKey===null){t===null&&(t=new Set);const s=[];for(const{property:i,childNode:n}of this._getChildren(t))s.push(Ia(i.slice(0,-4)),n.getCacheKey(e,t));this._cacheKey=Ro(Ko(s),this.customCacheKey()),this._cacheKeyVersion=this.version}return this._cacheKey}customCacheKey(){return this.id}getScope(){return this}getHash(){return this.uuid}getUpdateType(){return this.updateType}getUpdateBeforeType(){return this.updateBeforeType}getUpdateAfterType(){return this.updateAfterType}getElementType(e){const t=this.getNodeType(e);return e.getElementType(t)}getMemberType(){return"void"}getNodeType(e){const t=e.getNodeProperties(this);return t.outputNode?t.outputNode.getNodeType(e):this.nodeType}getShared(e){const t=this.getHash(e);return e.getNodeFromHash(t)||this}getArrayCount(){return null}setup(e){const t=e.getNodeProperties(this);let s=0;for(const i of this.getChildren())t["node"+s++]=i;return t.outputNode||null}analyze(e,t=null){const s=e.increaseUsage(this);if(this.parents===!0){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(s===1){const i=e.getNodeProperties(this);for(const n of Object.values(i))n&&n.isNode===!0&&n.build(e,this)}}generate(e,t){const{outputNode:s}=e.getNodeProperties(this);if(s&&s.isNode===!0)return s.build(e,t)}updateBefore(){W("Abstract function.")}updateAfter(){W("Abstract function.")}update(){W("Abstract function.")}before(e){return this._beforeNodes===null&&(this._beforeNodes=[]),this._beforeNodes.push(e),this}build(e,t=null){const s=this.getShared(e);if(this!==s)return s.build(e,t);if(this._beforeNodes!==null){const l=this._beforeNodes;this._beforeNodes=null;for(const c of l)c.build(e,t);this._beforeNodes=l}const i=e.getDataFromNode(this);i.buildStages=i.buildStages||{},i.buildStages[e.buildStage]=!0;const n=GC[e.buildStage];if(n&&i.buildStages[n]!==!0){const l=e.getBuildStage();e.setBuildStage(n),this.build(e),e.setBuildStage(l)}e.addChain(this);let a=null;const o=e.getBuildStage();if(o==="setup"){e.addNode(this),this.updateReference(e);const l=e.getNodeProperties(this);if(l.initialized!==!0){l.initialized=!0,l.outputNode=this.setup(e)||l.outputNode||null;for(const c of Object.values(l))if(c&&c.isNode===!0){if(c.parents===!0){const u=e.getNodeProperties(c);u.parents=u.parents||[],u.parents.push(this)}c.build(e)}e.addSequentialNode(this)}a=l.outputNode}else if(o==="analyze")this.analyze(e,t);else if(o==="generate"){if(this.generate.length<2){const c=this.getNodeType(e),u=e.getDataFromNode(this);a=u.snippet,a===void 0?u.generated===void 0?(u.generated=!0,a=this.generate(e)||"",u.snippet=a):(W("Node: Recursion detected.",this),a="/* Recursion detected. */"):u.flowCodes!==void 0&&e.context.nodeBlock!==void 0&&e.addFlowCodeHierarchy(this,e.context.nodeBlock),a=e.format(a,c,t)}else a=this.generate(e,t)||"";a===""&&t!==null&&t!=="void"&&t!=="OutputType"&&($(`TSL: Invalid generated code, expected a "${t}".`),a=e.generateConst(t))}return e.removeChain(this),a}getSerializeChildren(){return this._getChildren()}serialize(e){const t=this.getSerializeChildren(),s={};for(const{property:i,index:n,childNode:a}of t)n!==void 0?(s[i]===void 0&&(s[i]=Number.isInteger(n)?[]:{}),s[i][n]=a.toJSON(e.meta).uuid):s[i]=a.toJSON(e.meta).uuid;Object.keys(s).length>0&&(e.inputNodes=s)}deserialize(e){if(e.inputNodes!==void 0){const t=e.meta.nodes;for(const s in e.inputNodes)if(Array.isArray(e.inputNodes[s])){const i=[];for(const n of e.inputNodes[s])i.push(t[n]);this[s]=i}else if(typeof e.inputNodes[s]=="object"){const i={};for(const n in e.inputNodes[s]){const a=e.inputNodes[s][n];i[n]=t[a]}this[s]=i}else{const i=e.inputNodes[s];this[s]=t[i]}}}toJSON(e){const{uuid:t,type:s}=this,i=e===void 0||typeof e=="string";i&&(e={textures:{},images:{},nodes:{}});let n=e.nodes[t];n===void 0&&(n={uuid:t,type:s,meta:e,metadata:{version:4.7,type:"Node",generator:"Node.toJSON"}},i!==!0&&(e.nodes[n.uuid]=n),this.serialize(n),delete n.meta);function a(o){const l=[];for(const c in o){const u=o[c];delete u.metadata,l.push(u)}return l}if(i){const o=a(e.textures),l=a(e.images),c=a(e.nodes);o.length>0&&(n.textures=o),l.length>0&&(n.images=l),c.length>0&&(n.nodes=c)}return n}}Q.captureStackTrace=!1;class Cr extends Q{static get type(){return"ArrayElementNode"}constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}getNodeType(e){return this.node.getElementType(e)}getMemberType(e,t){return this.node.getMemberType(e,t)}generate(e){const t=this.indexNode.getNodeType(e),s=this.node.build(e),i=this.indexNode.build(e,!e.isVector(t)&&e.isInteger(t)?t:"uint");return`${s}[ ${i} ]`}}class a0 extends Q{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}getNodeType(e){const t=this.node.getNodeType(e);let s=null;for(const i of this.convertTo.split("|"))(s===null||e.getTypeLength(t)===e.getTypeLength(i))&&(s=i);return s}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){const s=this.node,i=this.getNodeType(e),n=s.build(e,i);return e.format(n,i,t)}}class ot extends Q{static get type(){return"TempNode"}constructor(e=null){super(e),this.isTempNode=!0}hasDependencies(e){return e.getDataFromNode(this).usageCount>1}build(e,t){if(e.getBuildStage()==="generate"){const i=e.getVectorType(this.getNodeType(e,t)),n=e.getDataFromNode(this);if(n.propertyName!==void 0)return e.format(n.propertyName,i,t);if(i!=="void"&&t!=="void"&&this.hasDependencies(e)){const a=super.build(e,i),o=e.getVarFromNode(this,null,i),l=e.getPropertyName(o);return e.addLineFlowCode(`${l} = ${a}`,this),n.snippet=a,n.propertyName=l,e.format(n.propertyName,i,t)}}return super.build(e,t)}}class WC extends ot{static get type(){return"JoinNode"}constructor(e=[],t=null){super(t),this.nodes=e}getNodeType(e){return this.nodeType!==null?e.getVectorType(this.nodeType):e.getTypeFromLength(this.nodes.reduce((t,s)=>t+e.getTypeLength(s.getNodeType(e)),0))}generate(e,t){const s=this.getNodeType(e),i=e.getTypeLength(s),n=this.nodes,a=e.getComponentType(s),o=[];let l=0;for(const u of n){if(l>=i){$(`TSL: Length of parameters exceeds maximum length of function '${s}()' type.`,this.stackTrace);break}let h=u.getNodeType(e),d=e.getTypeLength(h),p;if(l+d>i&&($(`TSL: Length of '${s}()' data exceeds maximum length of output type.`,this.stackTrace),d=i-l,h=e.getTypeFromLength(d)),l+=d,p=u.build(e,h),e.getComponentType(h)!==a){const m=e.getTypeFromLength(d,a);p=e.format(p,h,m)}o.push(p)}const c=`${e.getType(s)}( ${o.join(", ")} )`;return e.format(c,s,t)}}const HC=wr.join("");class o0 extends Q{static get type(){return"SplitNode"}constructor(e,t="x"){super(),this.node=e,this.components=t,this.isSplitNode=!0}getVectorLength(){let e=this.components.length;for(const t of this.components)e=Math.max(wr.indexOf(t)+1,e);return e}getComponentType(e){return e.getComponentType(this.node.getNodeType(e))}getNodeType(e){return e.getTypeFromLength(this.components.length,this.getComponentType(e))}getScope(){return this.node.getScope()}generate(e,t){const s=this.node,i=e.getTypeLength(s.getNodeType(e));let n=null;if(i>1){let a=null;this.getVectorLength()>=i&&(a=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const l=s.build(e,a);this.components.length===i&&this.components===HC.slice(0,this.components.length)?n=e.format(l,a,t):n=e.format(`${l}.${this.components}`,this.getNodeType(e),t)}else n=s.build(e,t);return n}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}class jC extends ot{static get type(){return"SetNode"}constructor(e,t,s){super(),this.sourceNode=e,this.components=t,this.targetNode=s}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:s,targetNode:i}=this,n=this.getNodeType(e),a=e.getComponentType(i.getNodeType(e)),o=e.getTypeFromLength(s.length,a),l=i.build(e,o),c=t.build(e,n),u=e.getTypeLength(n),h=[];for(let d=0;d<u;d++){const p=wr[d];p===s[0]?(h.push(l),d+=s.length-1):h.push(c+"."+p)}return`${e.getType(n)}( ${h.join(", ")} )`}}class qC extends ot{static get type(){return"FlipNode"}constructor(e,t){super(),this.sourceNode=e,this.components=t}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{components:t,sourceNode:s}=this,i=this.getNodeType(e),n=s.build(e),a=e.getVarFromNode(this),o=e.getPropertyName(a);e.addLineFlowCode(o+" = "+n,this);const l=e.getTypeLength(i),c=[];let u=0;for(let h=0;h<l;h++){const d=wr[h];d===t[u]?(c.push("1.0 - "+(o+"."+d)),u++):c.push(o+"."+d)}return`${e.getType(i)}( ${c.join(", ")} )`}}class rf extends Q{static get type(){return"InputNode"}constructor(e,t=null){super(t),this.isInputNode=!0,this.value=e,this.precision=null}getNodeType(){return this.nodeType===null?Nn(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=Nn(this.value),e.nodeType=this.nodeType,e.valueType==="ArrayBuffer"&&(e.value=VC(e.value)),e.precision=this.precision}deserialize(e){super.deserialize(e),this.nodeType=e.nodeType,this.value=Array.isArray(e.value)?nf(e.valueType,...e.value):e.value,this.precision=e.precision||null,this.value&&this.value.fromArray&&(this.value=this.value.fromArray(e.value))}generate(){W("Abstract function.")}}const pg=/float|u?int/;class zs extends rf{static get type(){return"ConstNode"}constructor(e,t=null){super(e,t),this.isConstNode=!0}generateConst(e){return e.generateConst(this.getNodeType(e),this.value)}generate(e,t){const s=this.getNodeType(e);return pg.test(s)&&pg.test(t)?e.generateConst(t,this.value):e.format(this.generateConst(e),s,t)}}class XC extends Q{static get type(){return"MemberNode"}constructor(e,t){super(),this.structNode=e,this.property=t,this.isMemberNode=!0}hasMember(e){return this.structNode.isMemberNode&&this.structNode.hasMember(e)===!1?!1:this.structNode.getMemberType(e,this.property)!=="void"}getNodeType(e){return this.hasMember(e)===!1?"float":this.structNode.getMemberType(e,this.property)}getMemberType(e,t){if(this.hasMember(e)===!1)return"float";const s=this.getNodeType(e);return e.getStructTypeNode(s).getMemberType(e,t)}generate(e){if(this.hasMember(e)===!1){W(`TSL: Member "${this.property}" does not exist in struct.`,this.stackTrace);const s=this.getNodeType(e);return e.generateConst(s)}return this.structNode.build(e)+"."+this.property}}let Vn=null;const lp=new Map;function I(r,e){if(lp.has(r)){W(`TSL: Redefinition of method chaining '${r}'.`);return}if(typeof e!="function")throw new Error(`THREE.TSL: Node element ${r} is not a function`);lp.set(r,e),r!=="assign"&&(Q.prototype[r]=function(...t){return this.isStackNode?this.addToStack(e(...t)):e(this,...t)},Q.prototype[r+"Assign"]=function(...t){return this.isStackNode?this.assign(t[0],e(...t)):this.assign(e(this,...t))})}const YC=r=>r.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"),fg=r=>YC(r).split("").sort().join("");Q.prototype.assign=function(...r){if(this.isStackNode!==!0)return Vn!==null?Vn.assign(this,...r):$("TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().",new ct),this;{const e=lp.get("assign");return this.addToStack(e(...r))}};Q.prototype.toVarIntent=function(){return this};Q.prototype.get=function(r){return new XC(this,r)};const Po={};function Rl(r,e,t){Po[r]=Po[e]=Po[t]={get(){this._cache=this._cache||{};let a=this._cache[r];return a===void 0&&(a=new o0(this,r),this._cache[r]=a),a},set(a){this[r].assign(Z(a))}};const s=r.toUpperCase(),i=e.toUpperCase(),n=t.toUpperCase();Q.prototype["set"+s]=Q.prototype["set"+i]=Q.prototype["set"+n]=function(a){const o=fg(r);return new jC(this,o,Z(a))},Q.prototype["flip"+s]=Q.prototype["flip"+i]=Q.prototype["flip"+n]=function(){const a=fg(r);return new qC(this,a)}}const ri=["x","y","z","w"],ai=["r","g","b","a"],oi=["s","t","p","q"];for(let r=0;r<4;r++){let e=ri[r],t=ai[r],s=oi[r];Rl(e,t,s);for(let i=0;i<4;i++){e=ri[r]+ri[i],t=ai[r]+ai[i],s=oi[r]+oi[i],Rl(e,t,s);for(let n=0;n<4;n++){e=ri[r]+ri[i]+ri[n],t=ai[r]+ai[i]+ai[n],s=oi[r]+oi[i]+oi[n],Rl(e,t,s);for(let a=0;a<4;a++)e=ri[r]+ri[i]+ri[n]+ri[a],t=ai[r]+ai[i]+ai[n]+ai[a],s=oi[r]+oi[i]+oi[n]+oi[a],Rl(e,t,s)}}}for(let r=0;r<32;r++)Po[r]={get(){this._cache=this._cache||{};let e=this._cache[r];return e===void 0&&(e=new Cr(this,new zs(r,"uint")),this._cache[r]=e),e},set(e){this[r].assign(Z(e))}};Object.defineProperties(Q.prototype,Po);const mg=new WeakMap,ZC=function(r,e=null){const t=Nn(r);return t==="node"?r:e===null&&(t==="float"||t==="boolean")||t&&t!=="shader"&&t!=="string"?Z(cp(r,e)):t==="shader"?r.isFn?r:R(r):r},QC=function(r,e=null){for(const t in r)r[t]=Z(r[t],e);return r},KC=function(r,e=null){const t=r.length;for(let s=0;s<t;s++)r[s]=Z(r[s],e);return r},l0=function(r,e=null,t=null,s=null){function i(u){return s!==null?(u=Z(Object.assign(u,s)),s.intent===!0&&(u=u.toVarIntent())):u=Z(u),u}let n,a=e,o,l;function c(u){let h;return a?h=/[a-z]/i.test(a)?a+"()":a:h=r.type,o!==void 0&&u.length<o?($(`TSL: "${h}" parameter length is less than minimum required.`,new ct),u.concat(new Array(o-u.length).fill(0))):l!==void 0&&u.length>l?($(`TSL: "${h}" parameter length exceeds limit.`,new ct),u.slice(0,l)):u}return e===null?n=(...u)=>i(new r(...xr(c(u)))):t!==null?(t=Z(t),n=(...u)=>i(new r(e,...xr(c(u)),t))):n=(...u)=>i(new r(e,...xr(c(u)))),n.setParameterLength=(...u)=>(u.length===1?o=l=u[0]:u.length===2&&([o,l]=u),n),n.setName=u=>(a=u,n),n},JC=function(r,...e){return new r(...xr(e))};class eA extends Q{constructor(e,t){super(),this.shaderNode=e,this.rawInputs=t,this.isShaderCallNodeInternal=!0}getNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}getElementType(e){return this.getOutputNode(e).getElementType(e)}getMemberType(e,t){return this.getOutputNode(e).getMemberType(e,t)}call(e){const{shaderNode:t,rawInputs:s}=this,i=e.getNodeProperties(t),n=e.getClosestSubBuild(t.subBuilds)||"",a=n||"default";if(i[a])return i[a];const o=e.subBuildFn,l=e.fnCall;e.subBuildFn=n,e.fnCall=this;let c=null;if(t.layout){let u=mg.get(e.constructor);u===void 0&&(u=new WeakMap,mg.set(e.constructor,u));let h=u.get(t);h===void 0&&(h=Z(e.buildFunctionNode(t)),u.set(t,h)),e.addInclude(h);const d=s?tA(s):null;c=Z(h.call(d))}else{const u=new Proxy(e,{get:(m,x,y)=>{let b;return Symbol.iterator===x?b=function*(){yield void 0}:b=Reflect.get(m,x,y),b}}),h=s?sA(s):null,d=Array.isArray(s)?s.length>0:s!==null,p=t.jsFunc,f=d||p.length>1?p(h,u):p(u);c=Z(f)}return e.subBuildFn=o,e.fnCall=l,t.once&&(i[a]=c),c}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}getOutputNode(e){const t=e.getNodeProperties(this),s=e.getSubBuildOutput(this);return t[s]=t[s]||this.setupOutput(e),t[s].subBuild=e.getClosestSubBuild(this),t[s]}build(e,t=null){let s=null;const i=e.getBuildStage(),n=e.getNodeProperties(this),a=e.getSubBuildOutput(this),o=this.getOutputNode(e),l=e.fnCall;if(e.fnCall=this,i==="setup"){const c=e.getSubBuildProperty("initialized",this);if(n[c]!==!0&&(n[c]=!0,n[a]=this.getOutputNode(e),n[a].build(e),this.shaderNode.subBuilds))for(const u of e.chaining){const h=e.getDataFromNode(u,"any");h.subBuilds=h.subBuilds||new Set;for(const d of this.shaderNode.subBuilds)h.subBuilds.add(d)}s=n[a]}else i==="analyze"?o.build(e,t):i==="generate"&&(s=o.build(e,t)||"");return e.fnCall=l,s}}function tA(r){let e;return Gu(r),r[0]&&(r[0].isNode||Object.getPrototypeOf(r[0])!==Object.prototype)?e=[...r]:e=r[0],e}function sA(r){let e=0;return Gu(r),new Proxy(r,{get:(t,s,i)=>{let n;if(s==="length")return n=r.length,n;if(Symbol.iterator===s)n=function*(){for(const a of r)yield Z(a)};else{if(r.length>0)if(Object.getPrototypeOf(r[0])===Object.prototype){const a=r[0];a[s]===void 0?n=a[e++]:n=Reflect.get(a,s,i)}else r[0]instanceof Q&&(r[s]===void 0?n=r[e++]:n=Reflect.get(r,s,i));else n=Reflect.get(t,s,i);n=Z(n)}return n}})}class iA extends Q{constructor(e,t){super(t),this.jsFunc=e,this.layout=null,this.global=!0,this.once=!1}setLayout(e){return this.layout=e,this}getLayout(){return this.layout}call(e=null){return new eA(this,e)}setup(){return this.call()}}const nA=[!1,!0],rA=[0,1,2,3],aA=[-1,-2],c0=[.5,1.5,1/3,1e-6,1e6,Math.PI,Math.PI*2,1/Math.PI,2/Math.PI,1/(Math.PI*2),Math.PI/2],af=new Map;for(const r of nA)af.set(r,new zs(r));const of=new Map;for(const r of rA)of.set(r,new zs(r,"uint"));const lf=new Map([...of].map(r=>new zs(r.value,"int")));for(const r of aA)lf.set(r,new zs(r,"int"));const ku=new Map([...lf].map(r=>new zs(r.value)));for(const r of c0)ku.set(r,new zs(r));for(const r of c0)ku.set(-r,new zs(-r));const zu={bool:af,uint:of,ints:lf,float:ku},gg=new Map([...af,...ku]),cp=(r,e)=>gg.has(r)?gg.get(r):r.isNode===!0?r:new zs(r,e),yt=function(r,e=null){return(...t)=>{for(const i of t)if(i===void 0)return $(`TSL: Invalid parameter for the type "${r}".`,new ct),new zs(0,r);if((t.length===0||!["bool","float","int","uint"].includes(r)&&t.every(i=>{const n=typeof i;return n!=="object"&&n!=="function"}))&&(t=[nf(r,...t)]),t.length===1&&e!==null&&e.has(t[0]))return _o(e.get(t[0]));if(t.length===1){const i=cp(t[0],r);return i.nodeType===r?_o(i):_o(new a0(i,r))}const s=t.map(i=>cp(i));return _o(new WC(s,r))}},Ho=r=>typeof r=="object"&&r!==null?r.value:r,u0=r=>r!=null?r.nodeType||r.convertTo||(typeof r=="string"?r:null):null;function pa(r,e){return new iA(r,e)}const Z=(r,e=null)=>ZC(r,e),_o=(r,e=null)=>Z(r,e).toVarIntent(),Gu=(r,e=null)=>new QC(r,e),xr=(r,e=null)=>new KC(r,e),ue=(r,e=null,t=null,s=null)=>new l0(r,e,t,s),H=(r,...e)=>new JC(r,...e),G=(r,e=null,t=null,s={})=>new l0(r,e,t,{...s,intent:!0});let oA=0;class lA extends Q{constructor(e,t=null){super();let s=null;t!==null&&(typeof t=="object"?s=t.return:(typeof t=="string"?s=t:$("TSL: Invalid layout type.",new ct),t=null)),this.shaderNode=new pa(e,s),t!==null&&this.setLayout(t),this.isFn=!0}setLayout(e){const t=this.shaderNode.nodeType;if(typeof e.inputs!="object"){const s={name:"fn"+oA++,type:t,inputs:[]};for(const i in e)i!=="return"&&s.inputs.push({name:i,type:e[i]});e=s}return this.shaderNode.setLayout(e),this}getNodeType(e){return this.shaderNode.getNodeType(e)||"float"}call(...e){const t=this.shaderNode.call(e);return this.shaderNode.nodeType==="void"&&t.toStack(),t.toVarIntent()}once(e=null){return this.shaderNode.once=!0,this.shaderNode.subBuilds=e,this}generate(e){const t=this.getNodeType(e);return $('TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".',this.stackTrace),e.generateConst(t)}}function R(r,e=null){const t=new lA(r,e);return new Proxy(()=>{},{apply(s,i,n){return t.call(...n)},get(s,i,n){return Reflect.get(t,i,n)},set(s,i,n,a){return Reflect.set(t,i,n,a)}})}const jo=r=>{Vn=r},cf=()=>Vn,ne=(...r)=>Vn.If(...r),cA=(...r)=>Vn.Switch(...r);function $u(r){return Vn&&Vn.addToStack(r),r}I("toStack",$u);const h0=new yt("color"),T=new yt("float",zu.float),w=new yt("int",zu.ints),k=new yt("uint",zu.uint),Us=new yt("bool",zu.bool),z=new yt("vec2"),ft=new yt("ivec2"),uf=new yt("uvec2"),d0=new yt("bvec2"),E=new yt("vec3"),hf=new yt("ivec3"),Ar=new yt("uvec3"),df=new yt("bvec3"),ie=new yt("vec4"),pf=new yt("ivec4"),ff=new yt("uvec4"),p0=new yt("bvec4"),Wu=new yt("mat2"),wt=new yt("mat3"),Dn=new yt("mat4"),uA=(r="")=>new zs(r,"string"),hA=r=>new zs(r,"ArrayBuffer");I("toColor",h0);I("toFloat",T);I("toInt",w);I("toUint",k);I("toBool",Us);I("toVec2",z);I("toIVec2",ft);I("toUVec2",uf);I("toBVec2",d0);I("toVec3",E);I("toIVec3",hf);I("toUVec3",Ar);I("toBVec3",df);I("toVec4",ie);I("toIVec4",pf);I("toUVec4",ff);I("toBVec4",p0);I("toMat2",Wu);I("toMat3",wt);I("toMat4",Dn);const f0=ue(Cr).setParameterLength(2),m0=(r,e)=>new a0(Z(r),e),dA=(r,e)=>new o0(Z(r),e);I("element",f0);I("convert",m0);const pA=r=>(W("TSL: append() has been renamed to Stack().",new ct),$u(r));I("append",r=>(W("TSL: .append() has been renamed to .toStack().",new ct),$u(r)));class Re extends Q{static get type(){return"PropertyNode"}constructor(e,t=null,s=!1){super(e),this.name=t,this.varying=s,this.isPropertyNode=!0,this.global=!0}customCacheKey(){return Ia(this.type+":"+(this.name||"")+":"+(this.varying?"1":"0"))}getHash(e){return this.name||super.getHash(e)}generate(e){let t;return this.varying===!0?(t=e.getVaryingFromNode(this,this.name),t.needsInterpolation=!0):t=e.getVarFromNode(this,this.name),e.getPropertyName(t)}}const Ji=(r,e)=>new Re(r,e),qo=(r,e)=>new Re(r,e,!0),Oe=H(Re,"vec4","DiffuseColor"),ur=H(Re,"vec3","DiffuseContribution"),up=H(Re,"vec3","EmissiveColor"),yi=H(Re,"float","Roughness"),ji=H(Re,"float","Metalness"),cu=H(Re,"float","Clearcoat"),ba=H(Re,"float","ClearcoatRoughness"),hs=H(Re,"vec3","Sheen"),Mn=H(Re,"float","SheenRoughness"),Hu=H(Re,"float","Iridescence"),uu=H(Re,"float","IridescenceIOR"),hu=H(Re,"float","IridescenceThickness"),du=H(Re,"float","AlphaT"),Sn=H(Re,"float","Anisotropy"),Fo=H(Re,"vec3","AnisotropyT"),_r=H(Re,"vec3","AnisotropyB"),kn=H(Re,"color","SpecularColor"),fr=H(Re,"color","SpecularColorBlended"),mr=H(Re,"float","SpecularF90"),pu=H(Re,"float","Shininess"),Ta=H(Re,"vec4","Output"),xc=H(Re,"float","dashSize"),hp=H(Re,"float","gapSize"),fA=H(Re,"float","pointWidth"),Bo=H(Re,"float","IOR"),fu=H(Re,"float","Transmission"),mf=H(Re,"float","Thickness"),gf=H(Re,"float","AttenuationDistance"),yf=H(Re,"color","AttenuationColor"),xf=H(Re,"float","Dispersion");class g0 extends Q{static get type(){return"UniformGroupNode"}constructor(e,t=!1,s=1){super("string"),this.name=e,this.shared=t,this.order=s,this.isUniformGroup=!0}serialize(e){super.serialize(e),e.name=this.name,e.version=this.version,e.shared=this.shared}deserialize(e){super.deserialize(e),this.name=e.name,this.version=e.version,this.shared=e.shared}}const y0=r=>new g0(r),ju=(r,e=0)=>new g0(r,!0,e),x0=ju("frame"),se=ju("render"),_f=y0("object");class Jo extends rf{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=_f}setName(e){return this.name=e,this}label(e){return W('TSL: "label()" has been deprecated. Use "setName()" instead.',new ct),this.setName(e)}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){return e=e.bind(this),super.onUpdate(s=>{const i=e(s,this);i!==void 0&&(this.value=i)},t)}getInputType(e){let t=super.getInputType(e);return t==="bool"&&(t="uint"),t}generate(e,t){const s=this.getNodeType(e),i=this.getUniformHash(e);let n=e.getNodeFromHash(i);n===void 0&&(e.setHashNode(this,i),n=this);const a=n.getInputType(e),o=e.getUniformFromNode(n,a,e.shaderStage,this.name||e.context.nodeName),l=e.getPropertyName(o);e.context.nodeName!==void 0&&delete e.context.nodeName;let c=l;if(s==="bool"){const u=e.getDataFromNode(this);let h=u.propertyName;if(h===void 0){const d=e.getVarFromNode(this,null,"bool");h=e.getPropertyName(d),u.propertyName=h,c=e.format(l,a,s),e.addLineFlowCode(`${h} = ${c}`,this)}c=h}return e.format(c,s,t)}}const ee=(r,e)=>{const t=u0(e||r);if(t===r&&(r=nf(t)),r&&r.isNode===!0){let s=r.value;r.traverse(i=>{i.isConstNode===!0&&(s=i.value)}),r=s}return new Jo(r,t)};class yg extends ot{static get type(){return"ArrayNode"}constructor(e,t,s=null){super(e),this.count=t,this.values=s,this.isArrayNode=!0}getArrayCount(){return this.count}getNodeType(e){return this.nodeType===null?this.values[0].getNodeType(e):this.nodeType}getElementType(e){return this.getNodeType(e)}getMemberType(e,t){return this.nodeType===null?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 _0=(...r)=>{let e;if(r.length===1){const t=r[0];e=new yg(null,t.length,t)}else{const t=r[0],s=r[1];e=new yg(t,s)}return Z(e)};I("toArray",(r,e)=>_0(Array(e).fill(r)));class mA extends ot{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t,this.isAssignNode=!0}hasDependencies(){return!1}getNodeType(e,t){return t!=="void"?this.targetNode.getNodeType(e):"void"}needsSplitAssign(e){const{targetNode:t}=this;if(e.isAvailable("swizzleAssign")===!1&&t.isSplitNode&&t.components.length>1){const s=e.getTypeLength(t.node.getNodeType(e));return wr.join("").slice(0,s)!==t.components}return!1}setup(e){const{targetNode:t,sourceNode:s}=this,i=t.getScope(),n=e.getDataFromNode(i);n.assign=!0;const a=e.getNodeProperties(this);a.sourceNode=s,a.targetNode=t.context({assign:!0})}generate(e,t){const{targetNode:s,sourceNode:i}=e.getNodeProperties(this),n=this.needsSplitAssign(e),a=s.build(e),o=s.getNodeType(e),l=i.build(e,o),c=i.getNodeType(e),u=e.getDataFromNode(this);let h;if(u.initialized===!0)t!=="void"&&(h=a);else if(n){const d=e.getVarFromNode(this,null,o),p=e.getPropertyName(d);e.addLineFlowCode(`${p} = ${l}`,this);const f=s.node,x=f.node.context({assign:!0}).build(e);for(let y=0;y<f.components.length;y++){const b=f.components[y];e.addLineFlowCode(`${x}.${b} = ${p}[ ${y} ]`,this)}t!=="void"&&(h=a)}else h=`${a} = ${l}`,(t==="void"||c==="void")&&(e.addLineFlowCode(h,this),t!=="void"&&(h=a));return u.initialized=!0,e.format(h,o,t)}}const b0=ue(mA).setParameterLength(2);I("assign",b0);class gA extends ot{static get type(){return"FunctionCallNode"}constructor(e=null,t={}){super(),this.functionNode=e,this.parameters=t}setParameters(e){return this.parameters=e,this}getParameters(){return this.parameters}getNodeType(e){return this.functionNode.getNodeType(e)}getMemberType(e,t){return this.functionNode.getMemberType(e,t)}generate(e){const t=[],s=this.functionNode,i=s.getInputs(e),n=this.parameters,a=(l,c)=>{const u=c.type,h=u==="pointer";let d;return h?d="&"+l.build(e):d=l.build(e,u),d};if(Array.isArray(n)){if(n.length>i.length)$("TSL: The number of provided parameters exceeds the expected number of inputs in 'Fn()'."),n.length=i.length;else if(n.length<i.length)for($("TSL: The number of provided parameters is less than the expected number of inputs in 'Fn()'.");n.length<i.length;)n.push(T(0));for(let l=0;l<n.length;l++)t.push(a(n[l],i[l]))}else for(const l of i){const c=n[l.name];c!==void 0?t.push(a(c,l)):($(`TSL: Input '${l.name}' not found in 'Fn()'.`),t.push(a(T(0),l)))}return`${s.build(e,"property")}( ${t.join(", ")} )`}}const T0=(r,...e)=>(e=e.length>1||e[0]&&e[0].isNode===!0?xr(e):Gu(e[0]),new gA(Z(r),e));I("call",T0);const yA={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class et extends ot{static get type(){return"OperatorNode"}constructor(e,t,s,...i){if(super(),i.length>0){let n=new et(e,t,s);for(let a=0;a<i.length-1;a++)n=new et(e,n,i[a]);t=n,s=i[i.length-1]}this.op=e,this.aNode=t,this.bNode=s,this.isOperatorNode=!0}getOperatorMethod(e,t){return e.getMethod(yA[this.op],t)}getNodeType(e,t=null){const s=this.op,i=this.aNode,n=this.bNode,a=i.getNodeType(e),o=n?n.getNodeType(e):null;if(a==="void"||o==="void")return t||"void";if(s==="%")return a;if(s==="~"||s==="&"||s==="|"||s==="^"||s===">>"||s==="<<")return e.getIntegerType(a);if(s==="!"||s==="&&"||s==="||"||s==="^^")return"bool";if(s==="=="||s==="!="||s==="<"||s===">"||s==="<="||s===">="){const l=Math.max(e.getTypeLength(a),e.getTypeLength(o));return l>1?`bvec${l}`:"bool"}else{if(e.isMatrix(a)){if(o==="float")return a;if(e.isVector(o))return e.getVectorFromMatrix(a);if(e.isMatrix(o))return a}else if(e.isMatrix(o)){if(a==="float")return o;if(e.isVector(a))return e.getVectorFromMatrix(o)}return e.getTypeLength(o)>e.getTypeLength(a)?o:a}}generate(e,t){const s=this.op,{aNode:i,bNode:n}=this,a=this.getNodeType(e,t);let o=null,l=null;a!=="void"?(o=i.getNodeType(e),l=n?n.getNodeType(e):null,s==="<"||s===">"||s==="<="||s===">="||s==="=="||s==="!="?e.isVector(o)?l=o:e.isVector(l)?o=l:o!==l&&(o=l="float"):s===">>"||s==="<<"?(o=a,l=e.changeComponentType(l,"uint")):s==="%"?(o=a,l=e.isInteger(o)&&e.isInteger(l)?l:o):e.isMatrix(o)?l==="float"?l="float":e.isVector(l)?l=e.getVectorFromMatrix(o):e.isMatrix(l)||(o=l=a):e.isMatrix(l)?o==="float"?o="float":e.isVector(o)?o=e.getVectorFromMatrix(l):o=l=a:o=l=a):o=l=a;const c=i.build(e,o),u=n?n.build(e,l):null,h=e.getFunctionOperator(s);if(t!=="void"){const d=e.renderer.coordinateSystem===gs;if(s==="=="||s==="!="||s==="<"||s===">"||s==="<="||s===">=")return d?e.isVector(o)?e.format(`${this.getOperatorMethod(e,t)}( ${c}, ${u} )`,a,t):e.format(`( ${c} ${s} ${u} )`,a,t):e.format(`( ${c} ${s} ${u} )`,a,t);if(s==="%")return e.isInteger(l)?e.format(`( ${c} % ${u} )`,a,t):e.format(`${this.getOperatorMethod(e,a)}( ${c}, ${u} )`,a,t);if(s==="!"||s==="~")return e.format(`(${s}${c})`,o,t);if(h)return e.format(`${h}( ${c}, ${u} )`,a,t);if(e.isMatrix(o)&&l==="float")return e.format(`( ${u} ${s} ${c} )`,a,t);if(o==="float"&&e.isMatrix(l))return e.format(`${c} ${s} ${u}`,a,t);{let p=`( ${c} ${s} ${u} )`;return!d&&a==="bool"&&e.isVector(o)&&e.isVector(l)&&(p=`all${p}`),e.format(p,a,t)}}else if(o!=="void")return h?e.format(`${h}( ${c}, ${u} )`,a,t):e.isMatrix(o)&&l==="float"?e.format(`${u} ${s} ${c}`,a,t):e.format(`${c} ${s} ${u}`,a,t)}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const dt=G(et,"+").setParameterLength(2,1/0).setName("add"),Te=G(et,"-").setParameterLength(2,1/0).setName("sub"),ae=G(et,"*").setParameterLength(2,1/0).setName("mul"),bs=G(et,"/").setParameterLength(2,1/0).setName("div"),el=G(et,"%").setParameterLength(2).setName("mod"),S0=G(et,"==").setParameterLength(2).setName("equal"),v0=G(et,"!=").setParameterLength(2).setName("notEqual"),M0=G(et,"<").setParameterLength(2).setName("lessThan"),bf=G(et,">").setParameterLength(2).setName("greaterThan"),w0=G(et,"<=").setParameterLength(2).setName("lessThanEqual"),C0=G(et,">=").setParameterLength(2).setName("greaterThanEqual"),A0=G(et,"&&").setParameterLength(2,1/0).setName("and"),E0=G(et,"||").setParameterLength(2,1/0).setName("or"),N0=G(et,"!").setParameterLength(1).setName("not"),R0=G(et,"^^").setParameterLength(2).setName("xor"),P0=G(et,"&").setParameterLength(2).setName("bitAnd"),F0=G(et,"~").setParameterLength(1).setName("bitNot"),B0=G(et,"|").setParameterLength(2).setName("bitOr"),D0=G(et,"^").setParameterLength(2).setName("bitXor"),O0=G(et,"<<").setParameterLength(2).setName("shiftLeft"),L0=G(et,">>").setParameterLength(2).setName("shiftRight"),I0=R(([r])=>(r.addAssign(1),r)),U0=R(([r])=>(r.subAssign(1),r)),V0=R(([r])=>{const e=w(r).toConst();return r.addAssign(1),e}),k0=R(([r])=>{const e=w(r).toConst();return r.subAssign(1),e});I("add",dt);I("sub",Te);I("mul",ae);I("div",bs);I("mod",el);I("equal",S0);I("notEqual",v0);I("lessThan",M0);I("greaterThan",bf);I("lessThanEqual",w0);I("greaterThanEqual",C0);I("and",A0);I("or",E0);I("not",N0);I("xor",R0);I("bitAnd",P0);I("bitNot",F0);I("bitOr",B0);I("bitXor",D0);I("shiftLeft",O0);I("shiftRight",L0);I("incrementBefore",I0);I("decrementBefore",U0);I("increment",V0);I("decrement",k0);const z0=(r,e)=>(W('TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.',new ct),el(w(r),w(e)));I("modInt",z0);class O extends ot{static get type(){return"MathNode"}constructor(e,t,s=null,i=null){if(super(),(e===O.MAX||e===O.MIN)&&arguments.length>3){let n=new O(e,t,s);for(let a=2;a<arguments.length-1;a++)n=new O(e,n,arguments[a]);t=n,s=arguments[arguments.length-1],i=null}this.method=e,this.aNode=t,this.bNode=s,this.cNode=i,this.isMathNode=!0}getInputType(e){const t=this.aNode.getNodeType(e),s=this.bNode?this.bNode.getNodeType(e):null,i=this.cNode?this.cNode.getNodeType(e):null,n=e.isMatrix(t)?0:e.getTypeLength(t),a=e.isMatrix(s)?0:e.getTypeLength(s),o=e.isMatrix(i)?0:e.getTypeLength(i);return n>a&&n>o?t:a>o?s:o>n?i:t}getNodeType(e){const t=this.method;return t===O.LENGTH||t===O.DISTANCE||t===O.DOT?"float":t===O.CROSS?"vec3":t===O.ALL||t===O.ANY?"bool":t===O.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):this.getInputType(e)}setup(e){const{aNode:t,bNode:s,method:i}=this;let n=null;if(i===O.ONE_MINUS)n=Te(1,t);else if(i===O.RECIPROCAL)n=bs(1,t);else if(i===O.DIFFERENCE)n=We(Te(t,s));else if(i===O.TRANSFORM_DIRECTION){let a=t,o=s;e.isMatrix(a.getNodeType(e))?o=ie(E(o),0):a=ie(E(a),0);const l=ae(a,o).xyz;n=is(l)}return n!==null?n: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),a=this.getInputType(e),o=this.aNode,l=this.bNode,c=this.cNode,u=e.renderer.coordinateSystem;if(i===O.NEGATE)return e.format("( - "+o.build(e,a)+" )",n,t);{const h=[];return i===O.CROSS?h.push(o.build(e,n),l.build(e,n)):u===gs&&i===O.STEP?h.push(o.build(e,e.getTypeLength(o.getNodeType(e))===1?"float":a),l.build(e,a)):u===gs&&(i===O.MIN||i===O.MAX)?h.push(o.build(e,a),l.build(e,e.getTypeLength(l.getNodeType(e))===1?"float":a)):i===O.REFRACT?h.push(o.build(e,a),l.build(e,a),c.build(e,"float")):i===O.MIX?h.push(o.build(e,a),l.build(e,a),c.build(e,e.getTypeLength(c.getNodeType(e))===1?"float":a)):(u===Ls&&i===O.ATAN&&l!==null&&(i="atan2"),e.shaderStage!=="fragment"&&(i===O.DFDX||i===O.DFDY)&&(W(`TSL: '${i}' is not supported in the ${e.shaderStage} stage.`,this.stackTrace),i="/*"+i+"*/"),h.push(o.build(e,a)),l!==null&&h.push(l.build(e,a)),c!==null&&h.push(c.build(e,a))),e.format(`${e.getMethod(i,n)}( ${h.join(", ")} )`,n,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}O.ALL="all";O.ANY="any";O.RADIANS="radians";O.DEGREES="degrees";O.EXP="exp";O.EXP2="exp2";O.LOG="log";O.LOG2="log2";O.SQRT="sqrt";O.INVERSE_SQRT="inversesqrt";O.FLOOR="floor";O.CEIL="ceil";O.NORMALIZE="normalize";O.FRACT="fract";O.SIN="sin";O.COS="cos";O.TAN="tan";O.ASIN="asin";O.ACOS="acos";O.ATAN="atan";O.ABS="abs";O.SIGN="sign";O.LENGTH="length";O.NEGATE="negate";O.ONE_MINUS="oneMinus";O.DFDX="dFdx";O.DFDY="dFdy";O.ROUND="round";O.RECIPROCAL="reciprocal";O.TRUNC="trunc";O.FWIDTH="fwidth";O.TRANSPOSE="transpose";O.DETERMINANT="determinant";O.INVERSE="inverse";O.EQUALS="equals";O.MIN="min";O.MAX="max";O.STEP="step";O.REFLECT="reflect";O.DISTANCE="distance";O.DIFFERENCE="difference";O.DOT="dot";O.CROSS="cross";O.POW="pow";O.TRANSFORM_DIRECTION="transformDirection";O.MIX="mix";O.CLAMP="clamp";O.REFRACT="refract";O.SMOOTHSTEP="smoothstep";O.FACEFORWARD="faceforward";const Tf=T(1e-6),xA=T(1e6),mu=T(Math.PI),_A=T(Math.PI*2),bA=T(Math.PI*2),TA=T(Math.PI*.5),G0=G(O,O.ALL).setParameterLength(1),$0=G(O,O.ANY).setParameterLength(1),W0=G(O,O.RADIANS).setParameterLength(1),H0=G(O,O.DEGREES).setParameterLength(1),Sf=G(O,O.EXP).setParameterLength(1),Pa=G(O,O.EXP2).setParameterLength(1),qu=G(O,O.LOG).setParameterLength(1),vi=G(O,O.LOG2).setParameterLength(1),Zt=G(O,O.SQRT).setParameterLength(1),vf=G(O,O.INVERSE_SQRT).setParameterLength(1),Mi=G(O,O.FLOOR).setParameterLength(1),Xu=G(O,O.CEIL).setParameterLength(1),is=G(O,O.NORMALIZE).setParameterLength(1),Js=G(O,O.FRACT).setParameterLength(1),jt=G(O,O.SIN).setParameterLength(1),Xs=G(O,O.COS).setParameterLength(1),j0=G(O,O.TAN).setParameterLength(1),q0=G(O,O.ASIN).setParameterLength(1),Mf=G(O,O.ACOS).setParameterLength(1),wf=G(O,O.ATAN).setParameterLength(1,2),We=G(O,O.ABS).setParameterLength(1),Cf=G(O,O.SIGN).setParameterLength(1),wi=G(O,O.LENGTH).setParameterLength(1),Af=G(O,O.NEGATE).setParameterLength(1),X0=G(O,O.ONE_MINUS).setParameterLength(1),Ef=G(O,O.DFDX).setParameterLength(1),Nf=G(O,O.DFDY).setParameterLength(1),Y0=G(O,O.ROUND).setParameterLength(1),Z0=G(O,O.RECIPROCAL).setParameterLength(1),Rf=G(O,O.TRUNC).setParameterLength(1),Pf=G(O,O.FWIDTH).setParameterLength(1),Q0=G(O,O.TRANSPOSE).setParameterLength(1),K0=G(O,O.DETERMINANT).setParameterLength(1),J0=G(O,O.INVERSE).setParameterLength(1),ns=G(O,O.MIN).setParameterLength(2,1/0),tt=G(O,O.MAX).setParameterLength(2,1/0),Fa=G(O,O.STEP).setParameterLength(2),e_=G(O,O.REFLECT).setParameterLength(2),t_=G(O,O.DISTANCE).setParameterLength(2),s_=G(O,O.DIFFERENCE).setParameterLength(2),Vs=G(O,O.DOT).setParameterLength(2),tn=G(O,O.CROSS).setParameterLength(2),Rs=G(O,O.POW).setParameterLength(2),Ff=r=>ae(r,r),i_=r=>ae(r,r,r),Bf=r=>ae(r,r,r,r),n_=G(O,O.TRANSFORM_DIRECTION).setParameterLength(2),r_=r=>ae(Cf(r),Rs(We(r),1/3)),Df=r=>Vs(r,r),ye=G(O,O.MIX).setParameterLength(3),ei=(r,e=0,t=1)=>new O(O.CLAMP,Z(r),Z(e),Z(t)),Yu=r=>ei(r),Of=G(O,O.REFRACT).setParameterLength(3),ti=G(O,O.SMOOTHSTEP).setParameterLength(3),Lf=G(O,O.FACEFORWARD).setParameterLength(3),a_=R(([r])=>{const s=43758.5453,i=Vs(r.xy,z(12.9898,78.233)),n=el(i,mu);return Js(jt(n).mul(s))}),o_=(r,e,t)=>ye(e,t,r),l_=(r,e,t)=>ti(e,t,r),c_=(r,e)=>Fa(e,r),SA=Lf,vA=vf;I("all",G0);I("any",$0);I("radians",W0);I("degrees",H0);I("exp",Sf);I("exp2",Pa);I("log",qu);I("log2",vi);I("sqrt",Zt);I("inverseSqrt",vf);I("floor",Mi);I("ceil",Xu);I("normalize",is);I("fract",Js);I("sin",jt);I("cos",Xs);I("tan",j0);I("asin",q0);I("acos",Mf);I("atan",wf);I("abs",We);I("sign",Cf);I("length",wi);I("lengthSq",Df);I("negate",Af);I("oneMinus",X0);I("dFdx",Ef);I("dFdy",Nf);I("round",Y0);I("reciprocal",Z0);I("trunc",Rf);I("fwidth",Pf);I("min",ns);I("max",tt);I("step",c_);I("reflect",e_);I("distance",t_);I("dot",Vs);I("cross",tn);I("pow",Rs);I("pow2",Ff);I("pow3",i_);I("pow4",Bf);I("transformDirection",n_);I("mix",o_);I("clamp",ei);I("refract",Of);I("smoothstep",l_);I("faceForward",Lf);I("difference",s_);I("saturate",Yu);I("cbrt",r_);I("transpose",Q0);I("determinant",K0);I("inverse",J0);I("rand",a_);class MA extends Q{static get type(){return"ConditionalNode"}constructor(e,t,s=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=s}getNodeType(e){const{ifNode:t,elseNode:s}=e.getNodeProperties(this);if(t===void 0)return e.flowBuildStage(this,"setup"),this.getNodeType(e);const i=t.getNodeType(e);if(s!==null){const n=s.getNodeType(e);if(e.getTypeLength(n)>e.getTypeLength(i))return n}return i}setup(e){const t=this.condNode,s=this.ifNode.isolate(),i=this.elseNode?this.elseNode.isolate():null,n=e.context.nodeBlock;e.getDataFromNode(s).parentNodeBlock=n,i!==null&&(e.getDataFromNode(i).parentNodeBlock=n);const a=e.context.uniformFlow,o=e.getNodeProperties(this);o.condNode=t,o.ifNode=a?s:s.context({nodeBlock:s}),o.elseNode=i?a?i:i.context({nodeBlock:i}):null}generate(e,t){const s=this.getNodeType(e),i=e.getDataFromNode(this);if(i.nodeProperty!==void 0)return i.nodeProperty;const{condNode:n,ifNode:a,elseNode:o}=e.getNodeProperties(this),l=e.currentFunctionNode,c=t!=="void",u=c?Ji(s).build(e):"";i.nodeProperty=u;const h=n.build(e,"bool");if(e.context.uniformFlow&&o!==null){const f=a.build(e,s),m=o.build(e,s),x=e.getTernary(h,f,m);return e.format(x,s,t)}e.addFlowCode(`
33
- ${e.tab}if ( ${h} ) {
34
-
35
- `).addFlowTab();let p=a.build(e,s);if(p&&(c?p=u+" = "+p+";":(p="return "+p+";",l===null&&(W("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.",this.stackTrace),p="// "+p))),e.removeFlowTab().addFlowCode(e.tab+" "+p+`
36
-
37
- `+e.tab+"}"),o!==null){e.addFlowCode(` else {
38
-
39
- `).addFlowTab();let f=o.build(e,s);f&&(c?f=u+" = "+f+";":(f="return "+f+";",l===null&&(W("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.",this.stackTrace),f="// "+f))),e.removeFlowTab().addFlowCode(e.tab+" "+f+`
40
-
41
- `+e.tab+`}
42
-
43
- `)}else e.addFlowCode(`
44
-
45
- `);return e.format(u,s,t)}}const Vt=ue(MA).setParameterLength(2,3);I("select",Vt);class u_ extends Q{static get type(){return"ContextNode"}constructor(e=null,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}getNodeType(e){return this.node.getNodeType(e)}getFlowContextData(){const e=[];return this.traverse(t=>{t.isContextNode===!0&&e.push(t.value)}),Object.assign({},...e)}getMemberType(e,t){return this.node.getMemberType(e,t)}analyze(e){const t=e.addContext(this.value);this.node.build(e),e.setContext(t)}setup(e){const t=e.addContext(this.value);this.node.build(e),e.setContext(t)}generate(e,t){const s=e.addContext(this.value),i=this.node.build(e,t);return e.setContext(s),i}}const rn=(r=null,e={})=>{let t=r;return(t===null||t.isNode!==!0)&&(e=t||e,t=null),new u_(t,e)},h_=r=>rn(r,{uniformFlow:!0}),If=(r,e)=>rn(r,{nodeName:e});function d_(r,e,t=null){return rn(t,{getShadow:({light:s,shadowColorNode:i})=>e===s?i.mul(r):i})}function p_(r,e=null){return rn(e,{getAO:(t,{material:s})=>s.transparent===!0?t:t!==null?t.mul(r):r})}function f_(r,e){return W('TSL: "label()" has been deprecated. Use "setName()" instead.'),If(r,e)}I("context",rn);I("label",f_);I("uniformFlow",h_);I("setName",If);I("builtinShadowContext",(r,e,t)=>d_(e,t,r));I("builtinAOContext",(r,e)=>p_(e,r));class _c extends Q{static get type(){return"VarNode"}constructor(e,t=null,s=!1){super(),this.node=e,this.name=t,this.global=!0,this.isVarNode=!0,this.readOnly=s,this.parents=!0,this.intent=!1}setIntent(e){return this.intent=e,this}isIntent(e){return e.getDataFromNode(this).forceDeclaration===!0?!1:this.intent}getIntent(){return this.intent}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}getNodeType(e){return this.node.getNodeType(e)}getArrayCount(e){return this.node.getArrayCount(e)}isAssign(e){return e.getDataFromNode(this).assign}build(...e){const t=e[0];if(this._hasStack(t)===!1&&t.buildStage==="setup"&&(t.context.nodeLoop||t.context.nodeBlock)){let s=!1;if(this.node.isShaderCallNodeInternal&&this.node.shaderNode.getLayout()===null&&t.fnCall&&t.fnCall.shaderNode&&t.getDataFromNode(this.node.shaderNode).hasLoop){const a=t.getDataFromNode(this);a.forceDeclaration=!0,s=!0}const i=t.getBaseStack();s?i.addToStackBefore(this):i.addToStack(this)}return this.isIntent(t)&&this.isAssign(t)!==!0?this.node.build(...e):super.build(...e)}generate(e){const{node:t,name:s,readOnly:i}=this,{renderer:n}=e,a=n.backend.isWebGPUBackend===!0;let o=!1,l=!1;i&&(o=e.isDeterministic(t),l=a?i:o);const c=this.getNodeType(e);if(c=="void")return this.isIntent(e)!==!0&&$('TSL: ".toVar()" can not be used with void type.',this.stackTrace),t.build(e);const u=e.getVectorType(c),h=t.build(e,u),d=e.getVarFromNode(this,s,u,void 0,l),p=e.getPropertyName(d);let f=p;if(l)if(a)f=o?`const ${p}`:`let ${p}`;else{const m=t.getArrayCount(e);f=`const ${e.getVar(d.type,p,m)}`}return e.addLineFlowCode(`${f} = ${h}`,this),p}_hasStack(e){return e.getDataFromNode(this).stack!==void 0}}const Uf=ue(_c),m_=(r,e=null)=>Uf(r,e).toStack(),g_=(r,e=null)=>Uf(r,e,!0).toStack(),y_=r=>Uf(r).setIntent(!0).toStack();I("toVar",m_);I("toConst",g_);I("toVarIntent",y_);class wA extends Q{static get type(){return"SubBuild"}constructor(e,t,s=null){super(s),this.node=e,this.name=t,this.isSubBuildNode=!0}getNodeType(e){if(this.nodeType!==null)return this.nodeType;e.addSubBuild(this.name);const t=this.node.getNodeType(e);return e.removeSubBuild(),t}build(e,...t){e.addSubBuild(this.name);const s=this.node.build(e,...t);return e.removeSubBuild(),s}}const br=(r,e,t=null)=>new wA(Z(r),e,t);class CA extends Q{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=br(e,"VERTEX"),this.name=t,this.isVaryingNode=!0,this.interpolationType=null,this.interpolationSampling=null,this.global=!0}setInterpolation(e,t=null){return this.interpolationType=e,this.interpolationSampling=t,this}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}setupVarying(e){const t=e.getNodeProperties(this);let s=t.varying;if(s===void 0){const i=this.name,n=this.getNodeType(e),a=this.interpolationType,o=this.interpolationSampling;t.varying=s=e.getVaryingFromNode(this,i,n,a,o),t.node=br(this.node,"VERTEX")}return s.needsInterpolation||(s.needsInterpolation=e.shaderStage==="fragment"),s}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(xo.VERTEX,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(xo.VERTEX,this.node)}generate(e){const t=e.getSubBuildProperty("property",e.currentStack),s=e.getNodeProperties(this),i=this.setupVarying(e);if(s[t]===void 0){const n=this.getNodeType(e),a=e.getPropertyName(i,xo.VERTEX);e.flowNodeFromShaderStage(xo.VERTEX,s.node,n,a),s[t]=a}return e.getPropertyName(i)}}const $n=ue(CA).setParameterLength(1,2),x_=r=>$n(r);I("toVarying",$n);I("toVertexStage",x_);const __=R(([r])=>{const e=r.mul(.9478672986).add(.0521327014).pow(2.4),t=r.mul(.0773993808),s=r.lessThanEqual(.04045);return ye(e,t,s)}).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),b_=R(([r])=>{const e=r.pow(.41666).mul(1.055).sub(.055),t=r.mul(12.92),s=r.lessThanEqual(.0031308);return ye(e,t,s)}).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),Vf="WorkingColorSpace",AA="OutputColorSpace";class kf extends ot{static get type(){return"ColorSpaceNode"}constructor(e,t,s){super("vec4"),this.colorNode=e,this.source=t,this.target=s}resolveColorSpace(e,t){return t===Vf?Ae.workingColorSpace:t===AA?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){const{colorNode:t}=this,s=this.resolveColorSpace(e,this.source),i=this.resolveColorSpace(e,this.target);let n=t;return Ae.enabled===!1||s===i||!s||!i||(Ae.getTransfer(s)===ce&&(n=ie(__(n.rgb),n.a)),Ae.getPrimaries(s)!==Ae.getPrimaries(i)&&(n=ie(wt(Ae._getMatrix(new as,s,i)).mul(n.rgb),n.a)),Ae.getTransfer(i)===ce&&(n=ie(b_(n.rgb),n.a))),n}}const T_=(r,e)=>new kf(Z(r),Vf,e),Zu=(r,e)=>new kf(Z(r),e,Vf),EA=(r,e,t)=>new kf(Z(r),e,t);I("workingToColorSpace",T_);I("colorSpaceToWorking",Zu);let NA=class extends Cr{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),s=this.referenceNode.getNodeType(),i=this.getNodeType();return e.format(t,s,i)}};class S_ extends Q{static get type(){return"ReferenceBaseNode"}constructor(e,t,s=null,i=null){super(),this.property=e,this.uniformType=t,this.object=s,this.count=i,this.properties=e.split("."),this.reference=s,this.node=null,this.group=null,this.updateType=re.OBJECT}setGroup(e){return this.group=e,this}element(e){return new NA(this,Z(e))}setNodeType(e){const t=ee(null,e);this.group!==null&&t.setGroup(this.group),this.node=t}getNodeType(e){return this.node===null&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let s=e[t[0]];for(let i=1;i<t.length;i++)s=s[t[i]];return s}updateReference(e){return this.reference=this.object!==null?this.object:e.object,this.reference}setup(){return this.updateValue(),this.node}update(){this.updateValue()}updateValue(){this.node===null&&this.setNodeType(this.uniformType);const e=this.getValueFromReference();Array.isArray(e)?this.node.array=e:this.node.value=e}}const RA=(r,e,t)=>new S_(r,e,t);class PA extends S_{static get type(){return"RendererReferenceNode"}constructor(e,t,s=null){super(e,t,s),this.renderer=s,this.setGroup(se)}updateReference(e){return this.reference=this.renderer!==null?this.renderer:e.renderer,this.reference}}const v_=(r,e,t=null)=>new PA(r,e,t);class FA extends ot{static get type(){return"ToneMappingNode"}constructor(e,t=w_,s=null){super("vec3"),this._toneMapping=e,this.exposureNode=t,this.colorNode=s}customCacheKey(){return Ro(this._toneMapping)}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup(e){const t=this.colorNode||e.context.color,s=this._toneMapping;if(s===dr)return t;let i=null;const n=e.renderer.library.getToneMappingFunction(s);return n!==null?i=ie(n(t.rgb,this.exposureNode),t.a):($("ToneMappingNode: Unsupported Tone Mapping configuration.",s),i=t),i}}const M_=(r,e,t)=>new FA(r,Z(e),Z(t)),w_=v_("toneMappingExposure","float");I("toneMapping",(r,e,t)=>M_(e,t,r));const xg=new WeakMap;function _g(r,e){let t=xg.get(r);return t===void 0&&(t=new Qx(r,e),xg.set(r,t)),t}class pn extends rf{static get type(){return"BufferAttributeNode"}constructor(e,t=null,s=0,i=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=s,this.bufferOffset=i,this.usage=Na,this.instanced=!1,this.attribute=null,this.global=!0,e&&e.isBufferAttribute===!0&&e.itemSize<=4&&(this.attribute=e,this.usage=e.usage,this.instanced=e.isInstancedBufferAttribute)}getHash(e){if(this.bufferStride===0&&this.bufferOffset===0){let t=e.globalCache.getData(this.value);return t===void 0&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getNodeType(e){return this.bufferType===null&&(this.bufferType=e.getTypeFromAttribute(this.attribute)),this.bufferType}setup(e){if(this.attribute!==null)return;const t=this.getNodeType(e),s=e.getTypeLength(t),i=this.value,n=this.bufferStride||s,a=this.bufferOffset;let o;i.isInterleavedBuffer===!0?o=i:i.isBufferAttribute===!0?o=_g(i.array,n):o=_g(i,n);const l=new jp(o,s,a);o.setUsage(this.usage),this.attribute=l,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),s=e.getBufferAttributeFromNode(this,t),i=e.getPropertyName(s);let n=null;return e.shaderStage==="vertex"||e.shaderStage==="compute"?(this.name=i,n=i):n=$n(this).build(e,t),n}getInputType(){return"bufferAttribute"}setUsage(e){return this.usage=e,this.attribute&&this.attribute.isBufferAttribute===!0&&(this.attribute.usage=e),this}setInstanced(e){return this.instanced=e,this}}function Qu(r,e=null,t=0,s=0,i=Na,n=!1){return e==="mat3"||e===null&&r.itemSize===9?wt(new pn(r,"vec3",9,0).setUsage(i).setInstanced(n),new pn(r,"vec3",9,3).setUsage(i).setInstanced(n),new pn(r,"vec3",9,6).setUsage(i).setInstanced(n)):e==="mat4"||e===null&&r.itemSize===16?Dn(new pn(r,"vec4",16,0).setUsage(i).setInstanced(n),new pn(r,"vec4",16,4).setUsage(i).setInstanced(n),new pn(r,"vec4",16,8).setUsage(i).setInstanced(n),new pn(r,"vec4",16,12).setUsage(i).setInstanced(n)):new pn(r,e,t,s).setUsage(i)}const zf=(r,e=null,t=0,s=0)=>Qu(r,e,t,s),BA=(r,e=null,t=0,s=0)=>Qu(r,e,t,s,Wo),gu=(r,e=null,t=0,s=0)=>Qu(r,e,t,s,Na,!0),dp=(r,e=null,t=0,s=0)=>Qu(r,e,t,s,Wo,!0);I("toAttribute",r=>zf(r.value));class DA extends Q{static get type(){return"ComputeNode"}constructor(e,t){super("void"),this.isComputeNode=!0,this.computeNode=e,this.workgroupSize=t,this.count=null,this.version=1,this.name="",this.updateBeforeType=re.OBJECT,this.onInitFunction=null}setCount(e){return this.count=e,this}getCount(){return this.count}dispose(){this.dispatchEvent({type:"dispose"})}setName(e){return this.name=e,this}label(e){return W('TSL: "label()" has been deprecated. Use "setName()" instead.',new ct),this.setName(e)}onInit(e){return this.onInitFunction=e,this}updateBefore({renderer:e}){e.compute(this)}setup(e){const t=this.computeNode.build(e);if(t){const s=e.getNodeProperties(this);s.outputComputeNode=t.outputNode,t.outputNode=null}return t}generate(e,t){const{shaderStage:s}=e;if(s==="compute"){const i=this.computeNode.build(e,"void");i!==""&&e.addLineFlowCode(i,this)}else{const n=e.getNodeProperties(this).outputComputeNode;if(n)return n.build(e,t)}}}const Gf=(r,e=[64])=>{(e.length===0||e.length>3)&&$("TSL: compute() workgroupSize must have 1, 2, or 3 elements",new ct);for(let t=0;t<e.length;t++){const s=e[t];(typeof s!="number"||s<=0||!Number.isInteger(s))&&$(`TSL: compute() workgroupSize element at index [ ${t} ] must be a positive integer`,new ct)}for(;e.length<3;)e.push(1);return new DA(Z(r),e)},C_=(r,e,t)=>Gf(r,t).setCount(e);I("compute",C_);I("computeKernel",Gf);class OA extends Q{static get type(){return"IsolateNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isIsolateNode=!0}getNodeType(e){const t=e.getCache(),s=e.getCacheFromNode(this,this.parent);e.setCache(s);const i=this.node.getNodeType(e);return e.setCache(t),i}build(e,...t){const s=e.getCache(),i=e.getCacheFromNode(this,this.parent);e.setCache(i);const n=this.node.build(e,...t);return e.setCache(s),n}setParent(e){return this.parent=e,this}getParent(){return this.parent}}const Sa=r=>new OA(Z(r));function A_(r,e=!0){return W('TSL: "cache()" has been deprecated. Use "isolate()" instead.'),Sa(r).setParent(e)}I("cache",A_);I("isolate",Sa);class LA extends Q{static get type(){return"BypassNode"}constructor(e,t){super(),this.isBypassNode=!0,this.outputNode=e,this.callNode=t}getNodeType(e){return this.outputNode.getNodeType(e)}generate(e){const t=this.callNode.build(e,"void");return t!==""&&e.addLineFlowCode(t,this),this.outputNode.build(e)}}const E_=ue(LA).setParameterLength(2);I("bypass",E_);class N_ extends Q{static get type(){return"RemapNode"}constructor(e,t,s,i=T(0),n=T(1)){super(),this.node=e,this.inLowNode=t,this.inHighNode=s,this.outLowNode=i,this.outHighNode=n,this.doClamp=!0}setup(){const{node:e,inLowNode:t,inHighNode:s,outLowNode:i,outHighNode:n,doClamp:a}=this;let o=e.sub(t).div(s.sub(t));return a===!0&&(o=o.clamp()),o.mul(n.sub(i)).add(i)}}const R_=ue(N_,null,null,{doClamp:!1}).setParameterLength(3,5),P_=ue(N_).setParameterLength(3,5);I("remap",R_);I("remapClamp",P_);class bc extends Q{static get type(){return"ExpressionNode"}constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){const s=this.getNodeType(e),i=this.snippet;if(s==="void")e.addLineFlowCode(i,this);else return e.format(i,s,t)}}const Ks=ue(bc).setParameterLength(1,2),F_=r=>(r?Vt(r,Ks("discard")):Ks("discard")).toStack(),IA=()=>Ks("return").toStack();I("discard",F_);class UA extends ot{static get type(){return"RenderOutputNode"}constructor(e,t,s){super("vec4"),this.colorNode=e,this._toneMapping=t,this.outputColorSpace=s,this.isRenderOutputNode=!0}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup({context:e}){let t=this.colorNode||e.color;const s=(this._toneMapping!==null?this._toneMapping:e.toneMapping)||dr,i=(this.outputColorSpace!==null?this.outputColorSpace:e.outputColorSpace)||In;return s!==dr&&(t=t.toneMapping(s)),i!==In&&i!==Ae.workingColorSpace&&(t=t.workingToColorSpace(i)),t}}const B_=(r,e=null,t=null)=>new UA(Z(r),e,t);I("renderOutput",B_);class VA extends ot{static get type(){return"DebugNode"}constructor(e,t=null){super(),this.node=e,this.callback=t}getNodeType(e){return this.node.getNodeType(e)}setup(e){return this.node.build(e)}analyze(e){return this.node.build(e)}generate(e){const t=this.callback,s=this.node.build(e);if(t!==null)t(e,s);else{const i="--- TSL debug - "+e.shaderStage+" shader ---",n="-".repeat(i.length);let a="";a+="// #"+i+`#
46
- `,a+=e.flow.code.replace(/^\t/mg,"")+`
47
- `,a+="/* ... */ "+s+` /* ... */
48
- `,a+="// #"+n+`#
49
- `,rp(a)}return s}}const D_=(r,e=null)=>new VA(Z(r),e).toStack();I("debug",D_);class O_{constructor(){this._renderer=null,this.currentFrame=null}get nodeFrame(){return this._renderer._nodes.nodeFrame}setRenderer(e){return this._renderer=e,this}getRenderer(){return this._renderer}init(){}begin(){}finish(){}inspect(){}computeAsync(){}beginCompute(){}finishCompute(){}beginRender(){}finishRender(){}copyTextureToTexture(){}copyFramebufferToTexture(){}}class kA extends Q{static get type(){return"InspectorNode"}constructor(e,t="",s=null){super(),this.node=e,this.name=t,this.callback=s,this.updateType=re.FRAME,this.isInspectorNode=!0}getName(){return this.name||this.node.name}update(e){e.renderer.inspector.inspect(this)}getNodeType(e){return this.node.getNodeType(e)}setup(e){let t=this.node;return e.context.inspector===!0&&this.callback!==null&&(t=this.callback(t)),e.renderer.backend.isWebGPUBackend!==!0&&e.renderer.inspector.constructor!==O_&&Le('TSL: ".toInspector()" is only available with WebGPU.'),t}}function L_(r,e="",t=null){return r=Z(r),r.before(new kA(r,e,t))}I("toInspector",L_);function zA(r){W("TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add",r)}class I_ extends Q{static get type(){return"AttributeNode"}constructor(e,t=null){super(t),this.global=!0,this._attributeName=e}getHash(e){return this.getAttributeName(e)}getNodeType(e){let t=this.nodeType;if(t===null){const s=this.getAttributeName(e);if(e.hasGeometryAttribute(s)){const i=e.geometry.getAttribute(s);t=e.getTypeFromAttribute(i)}else t="float"}return t}setAttributeName(e){return this._attributeName=e,this}getAttributeName(){return this._attributeName}generate(e){const t=this.getAttributeName(e),s=this.getNodeType(e);if(e.hasGeometryAttribute(t)===!0){const n=e.geometry.getAttribute(t),a=e.getTypeFromAttribute(n),o=e.getAttribute(t,a);return e.shaderStage==="vertex"?e.format(o.name,a,s):$n(this).build(e,s)}else return W(`AttributeNode: Vertex attribute "${t}" not found on geometry.`),e.generateConst(s)}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 sn=(r,e=null)=>new I_(r,e),ze=(r=0)=>sn("uv"+(r>0?r:""),"vec2");class GA extends Q{static get type(){return"TextureSizeNode"}constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e,t){const s=this.textureNode.build(e,"property"),i=this.levelNode===null?"0":this.levelNode.build(e,"int");return e.format(`${e.getMethod("textureDimensions")}( ${s}, ${i} )`,this.getNodeType(e),t)}}const On=ue(GA).setParameterLength(1,2);class $A extends Jo{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=re.FRAME}get textureNode(){return this._textureNode}get texture(){return this._textureNode.value}update(){const e=this.texture,t=e.images,s=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(s&&s.width!==void 0){const{width:i,height:n}=s;this.value=Math.log2(Math.max(i,n))}}}const $f=ue($A).setParameterLength(1);class U_ extends Error{constructor(e,t=null){super(e),this.name="NodeError",this.stackTrace=t}}const Wf=new kt;class Pi extends Jo{static get type(){return"TextureNode"}constructor(e=Wf,t=null,s=null,i=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=s,this.biasNode=i,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.offsetNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=re.NONE,this.referenceNode=null,this._value=e,this._matrixUniform=null,this._flipYUniform=null,this.setUpdateMatrix(t===null)}set value(e){this.referenceNode?this.referenceNode.value=e:this._value=e}get value(){return this.referenceNode?this.referenceNode.value:this._value}getUniformHash(){return this.value.uuid}getNodeType(){return this.value.isDepthTexture===!0?"float":this.value.type===rt?"uvec4":this.value.type===Lt?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return ze(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return this._matrixUniform===null&&(this._matrixUniform=ee(this.value.matrix)),this._matrixUniform.mul(E(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this}setupUV(e,t){return e.isFlipY()&&(this._flipYUniform===null&&(this._flipYUniform=ee(!1)),t=t.toVar(),this.sampler?t=this._flipYUniform.select(t.flipY(),t):t=this._flipYUniform.select(t.setY(w(On(this,this.levelNode).y).sub(t.y).sub(1)),t)),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;const s=this.value;if(!s||s.isTexture!==!0)throw new U_("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().",this.stackTrace);const i=R(()=>{let l=this.uvNode;return(l===null||e.context.forceUVContext===!0)&&e.context.getUV&&(l=e.context.getUV(this,e)),l||(l=this.getDefaultUV()),this.updateMatrix===!0&&(l=this.getTransformedUV(l)),l=this.setupUV(e,l),this.updateType=this._matrixUniform!==null||this._flipYUniform!==null?re.OBJECT:re.NONE,l})();let n=this.levelNode;n===null&&e.context.getTextureLevel&&(n=e.context.getTextureLevel(this));let a=null,o=null;this.compareNode!==null&&(e.renderer.hasCompatibility(Bn.TEXTURE_COMPARE)?a=this.compareNode:this.value.compareFunction===null||this.value.compareFunction===$p?o=this.compareNode:(a=this.compareNode,Le('TSL: Only "LessCompare" is supported for depth texture comparison fallback.'))),t.uvNode=i,t.levelNode=n,t.biasNode=this.biasNode,t.compareNode=a,t.compareStepNode=o,t.gradNode=this.gradNode,t.depthNode=this.depthNode,t.offsetNode=this.offsetNode}generateUV(e,t){return t.build(e,this.sampler===!0?"vec2":"ivec2")}generateOffset(e,t){return t.build(e,"ivec2")}generateSnippet(e,t,s,i,n,a,o,l,c){const u=this.value;let h;return n?h=e.generateTextureBias(u,t,s,n,a,c):l?h=e.generateTextureGrad(u,t,s,l,a,c):o?h=e.generateTextureCompare(u,t,s,o,a,c):this.sampler===!1?h=e.generateTextureLoad(u,t,s,i,a,c):i?h=e.generateTextureLevel(u,t,s,i,a,c):h=e.generateTexture(u,t,s,a,c),h}generate(e,t){const s=this.value,i=e.getNodeProperties(this),n=super.generate(e,"property");if(/^sampler/.test(t))return n+"_sampler";if(e.isReference(t))return n;{const a=e.getDataFromNode(this),o=this.getNodeType(e);let l=a.propertyName;if(l===void 0){const{uvNode:u,levelNode:h,biasNode:d,compareNode:p,compareStepNode:f,depthNode:m,gradNode:x,offsetNode:y}=i,b=this.generateUV(e,u),v=h?h.build(e,"float"):null,S=d?d.build(e,"float"):null,M=m?m.build(e,"int"):null,A=p?p.build(e,"float"):null,C=f?f.build(e,"float"):null,P=x?[x[0].build(e,"vec2"),x[1].build(e,"vec2")]:null,B=y?this.generateOffset(e,y):null,V=e.getVarFromNode(this);l=e.getPropertyName(V);let Y=this.generateSnippet(e,n,b,v,S,M,A,P,B);C!==null&&(Y=Fa(Ks(C,"float"),Ks(Y,o)).build(e,o)),e.addLineFlowCode(`${l} = ${Y}`,this),a.snippet=Y,a.propertyName=l}let c=l;return e.needsToWorkingColorSpace(s)&&(c=Zu(Ks(c,o),s.colorSpace).setup(e).build(e,o)),e.format(c,o,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}sample(e){const t=this.clone();return t.uvNode=Z(e),t.referenceNode=this.getBase(),Z(t)}load(e){return this.sample(e).setSampler(!1)}blur(e){const t=this.clone();t.biasNode=Z(e).mul($f(t)),t.referenceNode=this.getBase();const s=t.value;return t.generateMipmaps===!1&&(s&&s.generateMipmaps===!1||s.minFilter===at||s.magFilter===at)&&(W("TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),Z(t)}level(e){const t=this.clone();return t.levelNode=Z(e),t.referenceNode=this.getBase(),Z(t)}size(e){return On(this,e)}bias(e){const t=this.clone();return t.biasNode=Z(e),t.referenceNode=this.getBase(),Z(t)}getBase(){return this.referenceNode?this.referenceNode.getBase():this}compare(e){const t=this.clone();return t.compareNode=Z(e),t.referenceNode=this.getBase(),Z(t)}grad(e,t){const s=this.clone();return s.gradNode=[Z(e),Z(t)],s.referenceNode=this.getBase(),Z(s)}depth(e){const t=this.clone();return t.depthNode=Z(e),t.referenceNode=this.getBase(),Z(t)}offset(e){const t=this.clone();return t.offsetNode=Z(e),t.referenceNode=this.getBase(),Z(t)}serialize(e){super.serialize(e),e.value=this.value.toJSON(e.meta).uuid,e.sampler=this.sampler,e.updateMatrix=this.updateMatrix,e.updateType=this.updateType}deserialize(e){super.deserialize(e),this.value=e.meta.textures[e.value],this.sampler=e.sampler,this.updateMatrix=e.updateMatrix,this.updateType=e.updateType}update(){const e=this.value,t=this._matrixUniform;t!==null&&(t.value=e.matrix),e.matrixAutoUpdate===!0&&e.updateMatrix();const s=this._flipYUniform;s!==null&&(s.value=e.image instanceof ImageBitmap&&e.flipY===!0||e.isRenderTargetTexture===!0||e.isFramebufferTexture===!0||e.isDepthTexture===!0)}clone(){const e=new this.constructor(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e}}const WA=ue(Pi).setParameterLength(1,4).setName("texture"),we=(r=Wf,e=null,t=null,s=null)=>{let i;return r&&r.isTextureNode===!0?(i=Z(r.clone()),i.referenceNode=r.getBase(),e!==null&&(i.uvNode=Z(e)),t!==null&&(i.levelNode=Z(t)),s!==null&&(i.biasNode=Z(s))):i=WA(r,e,t,s),i},HA=(r=Wf)=>we(r),nt=(...r)=>we(...r).setSampler(!1),jA=(r,e,t)=>we(r,e).level(t),qA=r=>(r.isNode===!0?r:we(r)).convert("sampler"),XA=r=>(r.isNode===!0?r:we(r)).convert("samplerComparison");class Hf extends Jo{static get type(){return"BufferNode"}constructor(e,t,s=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=s,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 tl=(r,e,t)=>new Hf(r,e,t);class YA extends Cr{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),s=this.getNodeType(),i=this.node.getPaddedType();return e.format(t,i,s)}}class ZA extends Hf{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=t===null?Nn(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=re.RENDER,this.isArrayBufferNode=!0}getNodeType(){return this.paddedType}getElementType(){return this.elementType}getPaddedType(){const e=this.elementType;let t="vec4";return e==="mat2"?t="mat2":/mat/.test(e)===!0?t="mat4":e.charAt(0)==="i"?t="ivec4":e.charAt(0)==="u"&&(t="uvec4"),t}update(){const{array:e,value:t}=this,s=this.elementType;if(s==="float"||s==="int"||s==="uint")for(let i=0;i<e.length;i++){const n=i*4;t[n]=e[i]}else if(s==="color")for(let i=0;i<e.length;i++){const n=i*4,a=e[i];t[n]=a.r,t[n+1]=a.g,t[n+2]=a.b||0}else if(s==="mat2")for(let i=0;i<e.length;i++){const n=i*4,a=e[i];t[n]=a.elements[0],t[n+1]=a.elements[1],t[n+2]=a.elements[2],t[n+3]=a.elements[3]}else if(s==="mat3")for(let i=0;i<e.length;i++){const n=i*16,a=e[i];t[n]=a.elements[0],t[n+1]=a.elements[1],t[n+2]=a.elements[2],t[n+4]=a.elements[3],t[n+5]=a.elements[4],t[n+6]=a.elements[5],t[n+8]=a.elements[6],t[n+9]=a.elements[7],t[n+10]=a.elements[8],t[n+15]=1}else if(s==="mat4")for(let i=0;i<e.length;i++){const n=i*16,a=e[i];for(let o=0;o<a.elements.length;o++)t[n+o]=a.elements[o]}else for(let i=0;i<e.length;i++){const n=i*4,a=e[i];t[n]=a.x,t[n+1]=a.y,t[n+2]=a.z||0,t[n+3]=a.w||0}}setup(e){const t=this.array.length,s=this.elementType;let i=Float32Array;const n=this.paddedType,a=e.getTypeLength(n);return s.charAt(0)==="i"&&(i=Int32Array),s.charAt(0)==="u"&&(i=Uint32Array),this.value=new i(t*a),this.bufferCount=t,this.bufferType=n,this.update(),super.setup(e)}element(e){return new YA(this,Z(e))}}const It=(r,e)=>new ZA(r,e);class QA extends Q{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}const an=ue(QA).setParameterLength(1);let qa,Xa;class qe extends Q{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this._output=null,this.isViewportNode=!0}getNodeType(){return this.scope===qe.DPR?"float":this.scope===qe.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=re.NONE;return(this.scope===qe.SIZE||this.scope===qe.VIEWPORT||this.scope===qe.DPR)&&(e=re.RENDER),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===qe.VIEWPORT?t!==null?Xa.copy(t.viewport):(e.getViewport(Xa),Xa.multiplyScalar(e.getPixelRatio())):this.scope===qe.DPR?this._output.value=e.getPixelRatio():t!==null?(qa.width=t.width,qa.height=t.height):e.getDrawingBufferSize(qa)}setup(){const e=this.scope;let t=null;return e===qe.SIZE?t=ee(qa||(qa=new xe)):e===qe.VIEWPORT?t=ee(Xa||(Xa=new Ee)):e===qe.DPR?t=ee(1):t=z(Er.div(Tr)),this._output=t,t}generate(e){if(this.scope===qe.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const s=e.getNodeProperties(Tr).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${s}.y - ${t}.y )`}return t}return super.generate(e)}}qe.COORDINATE="coordinate";qe.VIEWPORT="viewport";qe.SIZE="size";qe.UV="uv";qe.DPR="dpr";const V_=H(qe,qe.DPR),Ci=H(qe,qe.UV),Tr=H(qe,qe.SIZE),Er=H(qe,qe.COORDINATE),jf=H(qe,qe.VIEWPORT),qf=jf.zw,k_=Er.sub(jf.xy),KA=k_.div(qf),JA=R(()=>(W('TSL: "viewportResolution" is deprecated. Use "screenSize" instead.',new ct),Tr),"vec2").once()();let qh=null,Pl=null,Xh=null,Fl=null,Yh=null,Bl=null,Zh=null,Dl=null,Qh=null,Ol=null,Kh=null,Ll=null,Jh=null,Il=null;const Wn=ee(0,"uint").setName("u_cameraIndex").setGroup(ju("cameraIndex")).toVarying("v_cameraIndex"),wn=ee("float").setName("cameraNear").setGroup(se).onRenderUpdate(({camera:r})=>r.near),Cn=ee("float").setName("cameraFar").setGroup(se).onRenderUpdate(({camera:r})=>r.far),en=R(({camera:r})=>{let e;if(r.isArrayCamera&&r.cameras.length>0){const t=[];for(const s of r.cameras)t.push(s.projectionMatrix);Pl===null?Pl=It(t).setGroup(se).setName("cameraProjectionMatrices"):Pl.array=t,e=Pl.element(r.isMultiViewCamera?an("gl_ViewID_OVR"):Wn).toConst("cameraProjectionMatrix")}else qh===null&&(qh=ee(r.projectionMatrix).setName("cameraProjectionMatrix").setGroup(se).onRenderUpdate(({camera:t})=>t.projectionMatrix)),e=qh;return e}).once()(),z_=R(({camera:r})=>{let e;if(r.isArrayCamera&&r.cameras.length>0){const t=[];for(const s of r.cameras)t.push(s.projectionMatrixInverse);Fl===null?Fl=It(t).setGroup(se).setName("cameraProjectionMatricesInverse"):Fl.array=t,e=Fl.element(r.isMultiViewCamera?an("gl_ViewID_OVR"):Wn).toConst("cameraProjectionMatrixInverse")}else Xh===null&&(Xh=ee(r.projectionMatrixInverse).setName("cameraProjectionMatrixInverse").setGroup(se).onRenderUpdate(({camera:t})=>t.projectionMatrixInverse)),e=Xh;return e}).once()(),Gs=R(({camera:r})=>{let e;if(r.isArrayCamera&&r.cameras.length>0){const t=[];for(const s of r.cameras)t.push(s.matrixWorldInverse);Bl===null?Bl=It(t).setGroup(se).setName("cameraViewMatrices"):Bl.array=t,e=Bl.element(r.isMultiViewCamera?an("gl_ViewID_OVR"):Wn).toConst("cameraViewMatrix")}else Yh===null&&(Yh=ee(r.matrixWorldInverse).setName("cameraViewMatrix").setGroup(se).onRenderUpdate(({camera:t})=>t.matrixWorldInverse)),e=Yh;return e}).once()(),e1=R(({camera:r})=>{let e;if(r.isArrayCamera&&r.cameras.length>0){const t=[];for(const s of r.cameras)t.push(s.matrixWorld);Dl===null?Dl=It(t).setGroup(se).setName("cameraWorldMatrices"):Dl.array=t,e=Dl.element(r.isMultiViewCamera?an("gl_ViewID_OVR"):Wn).toConst("cameraWorldMatrix")}else Zh===null&&(Zh=ee(r.matrixWorld).setName("cameraWorldMatrix").setGroup(se).onRenderUpdate(({camera:t})=>t.matrixWorld)),e=Zh;return e}).once()(),t1=R(({camera:r})=>{let e;if(r.isArrayCamera&&r.cameras.length>0){const t=[];for(const s of r.cameras)t.push(s.normalMatrix);Ol===null?Ol=It(t).setGroup(se).setName("cameraNormalMatrices"):Ol.array=t,e=Ol.element(r.isMultiViewCamera?an("gl_ViewID_OVR"):Wn).toConst("cameraNormalMatrix")}else Qh===null&&(Qh=ee(r.normalMatrix).setName("cameraNormalMatrix").setGroup(se).onRenderUpdate(({camera:t})=>t.normalMatrix)),e=Qh;return e}).once()(),G_=R(({camera:r})=>{let e;if(r.isArrayCamera&&r.cameras.length>0){const t=[];for(let s=0,i=r.cameras.length;s<i;s++)t.push(new D);Ll===null?Ll=It(t).setGroup(se).setName("cameraPositions").onRenderUpdate(({camera:s},i)=>{const n=s.cameras,a=i.array;for(let o=0,l=n.length;o<l;o++)a[o].setFromMatrixPosition(n[o].matrixWorld)}):Ll.array=t,e=Ll.element(r.isMultiViewCamera?an("gl_ViewID_OVR"):Wn).toConst("cameraPosition")}else Kh===null&&(Kh=ee(new D).setName("cameraPosition").setGroup(se).onRenderUpdate(({camera:t},s)=>s.value.setFromMatrixPosition(t.matrixWorld))),e=Kh;return e}).once()(),s1=R(({camera:r})=>{let e;if(r.isArrayCamera&&r.cameras.length>0){const t=[];for(const s of r.cameras)t.push(s.viewport);Il===null?Il=It(t,"vec4").setGroup(se).setName("cameraViewports"):Il.array=t,e=Il.element(Wn).toConst("cameraViewport")}else Jh===null&&(Jh=ie(0,0,Tr.x,Tr.y).toConst("cameraViewport")),e=Jh;return e}).once()(),bg=new Lu;class _e extends Q{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=re.OBJECT,this.uniformNode=new Jo(null)}getNodeType(){const e=this.scope;if(e===_e.WORLD_MATRIX)return"mat4";if(e===_e.POSITION||e===_e.VIEW_POSITION||e===_e.DIRECTION||e===_e.SCALE)return"vec3";if(e===_e.RADIUS)return"float"}update(e){const t=this.object3d,s=this.uniformNode,i=this.scope;if(i===_e.WORLD_MATRIX)s.value=t.matrixWorld;else if(i===_e.POSITION)s.value=s.value||new D,s.value.setFromMatrixPosition(t.matrixWorld);else if(i===_e.SCALE)s.value=s.value||new D,s.value.setFromMatrixScale(t.matrixWorld);else if(i===_e.DIRECTION)s.value=s.value||new D,t.getWorldDirection(s.value);else if(i===_e.VIEW_POSITION){const n=e.camera;s.value=s.value||new D,s.value.setFromMatrixPosition(t.matrixWorld),s.value.applyMatrix4(n.matrixWorldInverse)}else if(i===_e.RADIUS){const n=e.object.geometry;n.boundingSphere===null&&n.computeBoundingSphere(),bg.copy(n.boundingSphere).applyMatrix4(t.matrixWorld),s.value=bg.radius}}generate(e){const t=this.scope;return t===_e.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===_e.POSITION||t===_e.VIEW_POSITION||t===_e.DIRECTION||t===_e.SCALE?this.uniformNode.nodeType="vec3":t===_e.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}}_e.WORLD_MATRIX="worldMatrix";_e.POSITION="position";_e.SCALE="scale";_e.VIEW_POSITION="viewPosition";_e.DIRECTION="direction";_e.RADIUS="radius";const i1=ue(_e,_e.DIRECTION).setParameterLength(1),n1=ue(_e,_e.WORLD_MATRIX).setParameterLength(1),r1=ue(_e,_e.POSITION).setParameterLength(1),a1=ue(_e,_e.SCALE).setParameterLength(1),o1=ue(_e,_e.VIEW_POSITION).setParameterLength(1),l1=ue(_e,_e.RADIUS).setParameterLength(1);class ks extends _e{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const c1=H(ks,ks.DIRECTION),Ps=H(ks,ks.WORLD_MATRIX),u1=H(ks,ks.POSITION),h1=H(ks,ks.SCALE),d1=H(ks,ks.VIEW_POSITION),p1=H(ks,ks.RADIUS),$_=ee(new as).onObjectUpdate(({object:r},e)=>e.value.getNormalMatrix(r.matrixWorld)),f1=ee(new ve).onObjectUpdate(({object:r},e)=>e.value.copy(r.matrixWorld).invert()),Hn=R(r=>r.context.modelViewMatrix||W_).once()().toVar("modelViewMatrix"),W_=Gs.mul(Ps),pp=R(r=>(r.context.isHighPrecisionModelViewMatrix=!0,ee("mat4").onObjectUpdate(({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))).once()().toVar("highpModelViewMatrix"),fp=R(r=>{const e=r.context.isHighPrecisionModelViewMatrix;return ee("mat3").onObjectUpdate(({object:t,camera:s})=>(e!==!0&&t.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,t.matrixWorld),t.normalMatrix.getNormalMatrix(t.modelViewMatrix)))}).once()().toVar("highpModelNormalViewMatrix"),H_=R(r=>r.shaderStage!=="fragment"?(Le("TSL: `clipSpace` is only available in fragment stage."),ie()):r.context.clipSpace.toVarying("v_clipSpace")).once()(),sl=sn("position","vec3"),Je=sl.toVarying("positionLocal"),Ba=sl.toVarying("positionPrevious"),Ai=R(r=>Ps.mul(Je).xyz.toVarying(r.getSubBuildProperty("v_positionWorld")),"vec3").once(["POSITION"])(),Xf=R(()=>Je.transformDirection(Ps).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection"),"vec3").once(["POSITION"])(),lt=R(r=>{if(r.shaderStage==="fragment"&&r.material.vertexNode){const e=z_.mul(H_);return e.xyz.div(e.w).toVar("positionView")}return r.context.setupPositionView().toVarying("v_positionView")},"vec3").once(["POSITION","VERTEX"])(),Ge=R(r=>{let e;return r.camera.isOrthographicCamera?e=E(0,0,1):e=lt.negate().toVarying("v_positionViewDirection").normalize(),e.toVar("positionViewDirection")},"vec3").once(["POSITION"])();class m1 extends Q{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){if(e.shaderStage!=="fragment")return"true";const{material:t}=e;return t.side===Rt?"false":e.getFrontFacing()}}const j_=H(m1),Yf=T(j_).mul(2).sub(1),Ua=R(([r],{material:e})=>{const t=e.side;return t===Rt?r=r.mul(-1):t===qi&&(r=r.mul(Yf)),r}),Ku=sn("normal","vec3"),rs=R(r=>r.geometry.hasAttribute("normal")===!1?(W('TSL: Vertex attribute "normal" not found on geometry.'),E(0,1,0)):Ku,"vec3").once()().toVar("normalLocal"),q_=lt.dFdx().cross(lt.dFdy()).normalize().toVar("normalFlat"),Da=R(r=>{let e;return r.isFlatShading()?e=q_:e=Zf(rs).toVarying("v_normalViewGeometry").normalize(),e},"vec3").once()().toVar("normalViewGeometry"),X_=R(r=>{let e=Da.transformDirection(Gs);return r.isFlatShading()!==!0&&(e=e.toVarying("v_normalWorldGeometry")),e.normalize().toVar("normalWorldGeometry")},"vec3").once()(),Me=R(r=>{let e;return r.subBuildFn==="NORMAL"||r.subBuildFn==="VERTEX"?(e=Da,r.isFlatShading()!==!0&&(e=Ua(e))):e=r.context.setupNormal().context({getUV:null,getTextureLevel:null}),e},"vec3").once(["NORMAL","VERTEX"])().toVar("normalView"),jn=Me.transformDirection(Gs).toVar("normalWorld"),An=R(({subBuildFn:r,context:e})=>{let t;return r==="NORMAL"||r==="VERTEX"?t=Me:t=e.setupClearcoatNormal().context({getUV:null,getTextureLevel:null}),t},"vec3").once(["NORMAL","VERTEX"])().toVar("clearcoatNormalView"),Y_=R(([r,e=Ps])=>{const t=wt(e),s=r.div(E(t[0].dot(t[0]),t[1].dot(t[1]),t[2].dot(t[2])));return t.mul(s).xyz}),Zf=R(([r],e)=>{const t=e.context.modelNormalViewMatrix;if(t)return t.transformDirection(r);const s=$_.mul(r);return Gs.transformDirection(s)}),g1=R(()=>(W('TSL: "transformedNormalView" is deprecated. Use "normalView" instead.'),Me)).once(["NORMAL","VERTEX"])(),y1=R(()=>(W('TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.'),jn)).once(["NORMAL","VERTEX"])(),x1=R(()=>(W('TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.'),An)).once(["NORMAL","VERTEX"])(),Tg=new Is,ed=new ve,Z_=ee(0).onReference(({material:r})=>r).onObjectUpdate(({material:r})=>r.refractionRatio),Tc=ee(1).onReference(({material:r})=>r).onObjectUpdate(function({material:r,scene:e}){return r.envMap?r.envMapIntensity:e.environmentIntensity}),Qf=ee(new ve).onReference(function(r){return r.material}).onObjectUpdate(function({material:r,scene:e}){const t=e.environment!==null&&r.envMap===null?e.environmentRotation:r.envMapRotation;return t?(Tg.copy(t),ed.makeRotationFromEuler(Tg)):ed.identity(),ed}),Q_=Ge.negate().reflect(Me),K_=Ge.negate().refract(Me,Z_),J_=Q_.transformDirection(Gs).toVar("reflectVector"),eb=K_.transformDirection(Gs).toVar("reflectVector"),tb=new Iu;class _1 extends Pi{static get type(){return"CubeTextureNode"}constructor(e,t=null,s=null,i=null){super(e,t,s,i),this.isCubeTextureNode=!0}getInputType(){return this.value.isDepthTexture===!0?"cubeDepthTexture":"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===Ca?J_:e.mapping===Dc?eb:($('CubeTextureNode: Mapping "%s" not supported.',e.mapping),E(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const s=this.value;return s.isDepthTexture===!0?e.renderer.coordinateSystem===Ls?E(t.x,t.y.negate(),t.z):t:((e.renderer.coordinateSystem===Ls||!s.isRenderTargetTexture)&&(t=E(t.x.negate(),t.yz)),Qf.mul(t))}generateUV(e,t){return t.build(e,this.sampler===!0?"vec3":"ivec3")}}const Kf=ue(_1).setParameterLength(1,4).setName("cubeTexture"),Xt=(r=tb,e=null,t=null,s=null)=>{let i;return r&&r.isCubeTextureNode===!0?(i=Z(r.clone()),i.referenceNode=r,e!==null&&(i.uvNode=Z(e)),t!==null&&(i.levelNode=Z(t)),s!==null&&(i.biasNode=Z(s))):i=Kf(r,e,t,s),i},b1=(r=tb)=>Kf(r);class T1 extends Cr{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),s=this.referenceNode.getNodeType(),i=this.getNodeType();return e.format(t,s,i)}}class Ju extends Q{static get type(){return"ReferenceNode"}constructor(e,t,s=null,i=null){super(),this.property=e,this.uniformType=t,this.object=s,this.count=i,this.properties=e.split("."),this.reference=s,this.node=null,this.group=null,this.name=null,this.updateType=re.OBJECT}element(e){return new T1(this,Z(e))}setGroup(e){return this.group=e,this}setName(e){return this.name=e,this}label(e){return W('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}setNodeType(e){let t=null;this.count!==null?t=tl(null,e,this.count):Array.isArray(this.getValueFromReference())?t=It(null,e):e==="texture"?t=we(null):e==="cubeTexture"?t=Xt(null):t=ee(null,e),this.group!==null&&t.setGroup(this.group),this.name!==null&&t.setName(this.name),this.node=t}getNodeType(e){return this.node===null&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let s=e[t[0]];for(let i=1;i<t.length;i++)s=s[t[i]];return s}updateReference(e){return this.reference=this.object!==null?this.object:e.object,this.reference}setup(){return this.updateValue(),this.node}update(){this.updateValue()}updateValue(){this.node===null&&this.setNodeType(this.uniformType);const e=this.getValueFromReference();Array.isArray(e)?this.node.array=e:this.node.value=e}}const Ye=(r,e,t)=>new Ju(r,e,t),mp=(r,e,t,s)=>new Ju(r,e,s,t);class S1 extends Ju{static get type(){return"MaterialReferenceNode"}constructor(e,t,s=null){super(e,t,s),this.material=s,this.isMaterialReferenceNode=!0}updateReference(e){return this.reference=this.material!==null?this.material:e.material,this.reference}}const Wi=(r,e,t=null)=>new S1(r,e,t),sb=ze(),v1=lt.dFdx(),M1=lt.dFdy(),ib=sb.dFdx(),nb=sb.dFdy(),rb=Me,ab=M1.cross(rb),ob=rb.cross(v1),gp=ab.mul(ib.x).add(ob.mul(nb.x)),yp=ab.mul(ib.y).add(ob.mul(nb.y)),Sg=gp.dot(gp).max(yp.dot(yp)),lb=Sg.equal(0).select(0,Sg.inverseSqrt()),w1=gp.mul(lb).toVar("tangentViewFrame"),C1=yp.mul(lb).toVar("bitangentViewFrame"),eh=sn("tangent","vec4"),Oa=eh.xyz.toVar("tangentLocal"),th=R(r=>{let e;return r.subBuildFn==="VERTEX"||r.geometry.hasAttribute("tangent")?e=Hn.mul(ie(Oa,0)).xyz.toVarying("v_tangentView").normalize():e=w1,r.isFlatShading()!==!0&&(e=Ua(e)),e},"vec3").once(["NORMAL","VERTEX"])().toVar("tangentView"),cb=th.transformDirection(Gs).toVarying("v_tangentWorld").normalize().toVar("tangentWorld"),sh=R(([r,e],t)=>{let s=r.mul(eh.w).xyz;return t.subBuildFn==="NORMAL"&&t.isFlatShading()!==!0&&(s=s.toVarying(e)),s}).once(["NORMAL"]),A1=sh(Ku.cross(eh),"v_bitangentGeometry").normalize().toVar("bitangentGeometry"),E1=sh(rs.cross(Oa),"v_bitangentLocal").normalize().toVar("bitangentLocal"),ub=R(r=>{let e;return r.subBuildFn==="VERTEX"||r.geometry.hasAttribute("tangent")?e=sh(Me.cross(th),"v_bitangentView").normalize():e=C1,r.isFlatShading()!==!0&&(e=Ua(e)),e},"vec3").once(["NORMAL","VERTEX"])().toVar("bitangentView"),N1=sh(jn.cross(cb),"v_bitangentWorld").normalize().toVar("bitangentWorld"),gr=wt(th,ub,Me).toVar("TBNViewMatrix"),hb=Ge.mul(gr),R1=(r,e)=>r.sub(hb.mul(e)),db=R(()=>{let r=_r.cross(Ge);return r=r.cross(_r).normalize(),r=ye(r,Me,Sn.mul(yi.oneMinus()).oneMinus().pow2().pow2()).normalize(),r}).once()(),pb=r=>Z(r).mul(.5).add(.5),P1=r=>Z(r).mul(2).sub(1),xp=r=>E(r,Zt(Yu(T(1).sub(Vs(r,r)))));class F1 extends ot{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=Zi,this.unpackNormalMode=vh}setup(e){const{normalMapType:t,scaleNode:s,unpackNormalMode:i}=this;let n=this.node.mul(2).sub(1);if(t===Zi?i===Ix?n=xp(n.xy):i===iw?n=xp(n.yw):i!==vh&&console.error(`THREE.NodeMaterial: Unexpected unpack normal mode: ${i}`):i!==vh&&console.error(`THREE.NodeMaterial: Normal map type '${t}' is not compatible with unpack normal mode '${i}'`),s!==null){let o=s;e.isFlatShading()===!0&&(o=Ua(o)),n=E(n.xy.mul(o),n.z)}let a=null;return t===sw?a=Zf(n):t===Zi?a=gr.mul(n).normalize():($(`NodeMaterial: Unsupported normal map type: ${t}`),a=Me),a}}const _p=ue(F1).setParameterLength(1,2),B1=R(({textureNode:r,bumpScale:e})=>{const t=i=>r.isolate().context({getUV:n=>i(n.uvNode||ze()),forceUVContext:!0}),s=T(t(i=>i));return z(T(t(i=>i.add(i.dFdx()))).sub(s),T(t(i=>i.add(i.dFdy()))).sub(s)).mul(e)}),D1=R(r=>{const{surf_pos:e,surf_norm:t,dHdxy:s}=r,i=e.dFdx().normalize(),n=e.dFdy().normalize(),a=t,o=n.cross(a),l=a.cross(i),c=i.dot(o).mul(Yf),u=c.sign().mul(s.x.mul(o).add(s.y.mul(l)));return c.abs().mul(t).sub(u).normalize()});class O1 extends ot{static get type(){return"BumpMapNode"}constructor(e,t=null){super("vec3"),this.textureNode=e,this.scaleNode=t}setup(){const e=this.scaleNode!==null?this.scaleNode:1,t=B1({textureNode:this.textureNode,bumpScale:e});return D1({surf_pos:lt,surf_norm:Me,dHdxy:t})}}const Jf=ue(O1).setParameterLength(1,2),vg=new Map;class U extends Q{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let s=vg.get(e);return s===void 0&&(s=Wi(e,t),vg.set(e,s)),s}getFloat(e){return this.getCache(e,"float")}getColor(e){return this.getCache(e,"color")}getTexture(e){return this.getCache(e==="map"?"map":e+"Map","texture")}setup(e){const t=e.context.material,s=this.scope;let i=null;if(s===U.COLOR){const n=t.color!==void 0?this.getColor(s):E();t.map&&t.map.isTexture===!0?i=n.mul(this.getTexture("map")):i=n}else if(s===U.OPACITY){const n=this.getFloat(s);t.alphaMap&&t.alphaMap.isTexture===!0?i=n.mul(this.getTexture("alpha")):i=n}else if(s===U.SPECULAR_STRENGTH)t.specularMap&&t.specularMap.isTexture===!0?i=this.getTexture("specular").r:i=T(1);else if(s===U.SPECULAR_INTENSITY){const n=this.getFloat(s);t.specularIntensityMap&&t.specularIntensityMap.isTexture===!0?i=n.mul(this.getTexture(s).a):i=n}else if(s===U.SPECULAR_COLOR){const n=this.getColor(s);t.specularColorMap&&t.specularColorMap.isTexture===!0?i=n.mul(this.getTexture(s).rgb):i=n}else if(s===U.ROUGHNESS){const n=this.getFloat(s);t.roughnessMap&&t.roughnessMap.isTexture===!0?i=n.mul(this.getTexture(s).g):i=n}else if(s===U.METALNESS){const n=this.getFloat(s);t.metalnessMap&&t.metalnessMap.isTexture===!0?i=n.mul(this.getTexture(s).b):i=n}else if(s===U.EMISSIVE){const n=this.getFloat("emissiveIntensity"),a=this.getColor(s).mul(n);t.emissiveMap&&t.emissiveMap.isTexture===!0?i=a.mul(this.getTexture(s)):i=a}else if(s===U.NORMAL)t.normalMap?(i=_p(this.getTexture("normal"),this.getCache("normalScale","vec2")),i.normalMapType=t.normalMapType,(t.normalMap.format==_i||t.normalMap.format==$o||t.normalMap.format==Go)&&(i.unpackNormalMode=Ix)):t.bumpMap?i=Jf(this.getTexture("bump").r,this.getFloat("bumpScale")):i=Me;else if(s===U.CLEARCOAT){const n=this.getFloat(s);t.clearcoatMap&&t.clearcoatMap.isTexture===!0?i=n.mul(this.getTexture(s).r):i=n}else if(s===U.CLEARCOAT_ROUGHNESS){const n=this.getFloat(s);t.clearcoatRoughnessMap&&t.clearcoatRoughnessMap.isTexture===!0?i=n.mul(this.getTexture(s).r):i=n}else if(s===U.CLEARCOAT_NORMAL)t.clearcoatNormalMap?i=_p(this.getTexture(s),this.getCache(s+"Scale","vec2")):i=Me;else if(s===U.SHEEN){const n=this.getColor("sheenColor").mul(this.getFloat("sheen"));t.sheenColorMap&&t.sheenColorMap.isTexture===!0?i=n.mul(this.getTexture("sheenColor").rgb):i=n}else if(s===U.SHEEN_ROUGHNESS){const n=this.getFloat(s);t.sheenRoughnessMap&&t.sheenRoughnessMap.isTexture===!0?i=n.mul(this.getTexture(s).a):i=n,i=i.clamp(1e-4,1)}else if(s===U.ANISOTROPY)if(t.anisotropyMap&&t.anisotropyMap.isTexture===!0){const n=this.getTexture(s);i=Wu(oa.x,oa.y,oa.y.negate(),oa.x).mul(n.rg.mul(2).sub(z(1)).normalize().mul(n.b))}else i=oa;else if(s===U.IRIDESCENCE_THICKNESS){const n=Ye("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const a=Ye("0","float",t.iridescenceThicknessRange);i=n.sub(a).mul(this.getTexture(s).g).add(a)}else i=n}else if(s===U.TRANSMISSION){const n=this.getFloat(s);t.transmissionMap?i=n.mul(this.getTexture(s).r):i=n}else if(s===U.THICKNESS){const n=this.getFloat(s);t.thicknessMap?i=n.mul(this.getTexture(s).g):i=n}else if(s===U.IOR)i=this.getFloat(s);else if(s===U.LIGHT_MAP)i=this.getTexture(s).rgb.mul(this.getFloat("lightMapIntensity"));else if(s===U.AO)i=this.getTexture(s).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else if(s===U.LINE_DASH_OFFSET)i=t.dashOffset?this.getFloat(s):T(0);else{const n=this.getNodeType(e);i=this.getCache(s,n)}return i}}U.ALPHA_TEST="alphaTest";U.COLOR="color";U.OPACITY="opacity";U.SHININESS="shininess";U.SPECULAR="specular";U.SPECULAR_STRENGTH="specularStrength";U.SPECULAR_INTENSITY="specularIntensity";U.SPECULAR_COLOR="specularColor";U.REFLECTIVITY="reflectivity";U.ROUGHNESS="roughness";U.METALNESS="metalness";U.NORMAL="normal";U.CLEARCOAT="clearcoat";U.CLEARCOAT_ROUGHNESS="clearcoatRoughness";U.CLEARCOAT_NORMAL="clearcoatNormal";U.EMISSIVE="emissive";U.ROTATION="rotation";U.SHEEN="sheen";U.SHEEN_ROUGHNESS="sheenRoughness";U.ANISOTROPY="anisotropy";U.IRIDESCENCE="iridescence";U.IRIDESCENCE_IOR="iridescenceIOR";U.IRIDESCENCE_THICKNESS="iridescenceThickness";U.IOR="ior";U.TRANSMISSION="transmission";U.THICKNESS="thickness";U.ATTENUATION_DISTANCE="attenuationDistance";U.ATTENUATION_COLOR="attenuationColor";U.LINE_SCALE="scale";U.LINE_DASH_SIZE="dashSize";U.LINE_GAP_SIZE="gapSize";U.LINE_WIDTH="linewidth";U.LINE_DASH_OFFSET="dashOffset";U.POINT_SIZE="size";U.DISPERSION="dispersion";U.LIGHT_MAP="light";U.AO="ao";const fb=H(U,U.ALPHA_TEST),mb=H(U,U.COLOR),gb=H(U,U.SHININESS),yb=H(U,U.EMISSIVE),em=H(U,U.OPACITY),xb=H(U,U.SPECULAR),bp=H(U,U.SPECULAR_INTENSITY),_b=H(U,U.SPECULAR_COLOR),Do=H(U,U.SPECULAR_STRENGTH),Sc=H(U,U.REFLECTIVITY),bb=H(U,U.ROUGHNESS),Tb=H(U,U.METALNESS),Sb=H(U,U.NORMAL),vb=H(U,U.CLEARCOAT),Mb=H(U,U.CLEARCOAT_ROUGHNESS),wb=H(U,U.CLEARCOAT_NORMAL),Cb=H(U,U.ROTATION),Ab=H(U,U.SHEEN),Eb=H(U,U.SHEEN_ROUGHNESS),Nb=H(U,U.ANISOTROPY),Rb=H(U,U.IRIDESCENCE),Pb=H(U,U.IRIDESCENCE_IOR),Fb=H(U,U.IRIDESCENCE_THICKNESS),Bb=H(U,U.TRANSMISSION),Db=H(U,U.THICKNESS),Ob=H(U,U.IOR),Lb=H(U,U.ATTENUATION_DISTANCE),Ib=H(U,U.ATTENUATION_COLOR),Ub=H(U,U.LINE_SCALE),Vb=H(U,U.LINE_DASH_SIZE),kb=H(U,U.LINE_GAP_SIZE),L1=H(U,U.LINE_WIDTH),zb=H(U,U.LINE_DASH_OFFSET),Gb=H(U,U.POINT_SIZE),$b=H(U,U.DISPERSION),tm=H(U,U.LIGHT_MAP),Wb=H(U,U.AO),oa=ee(new xe).onReference(function(r){return r.material}).onRenderUpdate(function({material:r}){this.value.set(r.anisotropy*Math.cos(r.anisotropyRotation),r.anisotropy*Math.sin(r.anisotropyRotation))}),Hb=R(r=>r.context.setupModelViewProjection(),"vec4").once()().toVarying("v_modelViewProjection");class I1 extends Cr{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 s=this.storageBufferNode.structTypeNode;return s?s.getMemberType(e,t):"void"}setup(e){return e.isAvailable("storageBuffer")===!1&&this.node.isPBO===!0&&e.setupPBO(this.node),super.setup(e)}generate(e,t){let s;const i=e.context.assign;if(e.isAvailable("storageBuffer")===!1?this.node.isPBO===!0&&i!==!0&&(this.node.value.isInstancedBufferAttribute||e.shaderStage!=="compute")?s=e.generatePBO(this):s=this.node.build(e):s=super.generate(e),i!==!0){const n=this.getNodeType(e);s=e.format(s,n,t)}return s}}const U1=ue(I1).setParameterLength(2);class V1 extends Hf{static get type(){return"StorageBufferNode"}constructor(e,t=null,s=0){let i,n=null;t&&t.isStruct?(i="struct",n=t.layout,(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(s=e.count)):t===null&&(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)?(i=s0(e.itemSize),s=e.count):i=t,super(e,i,s),this.isStorageBufferNode=!0,this.structTypeNode=n,this.access=Nt.READ_WRITE,this.isAtomic=!1,this.isPBO=!1,this._attribute=null,this._varying=null,this.global=!0,e.isStorageBufferAttribute!==!0&&e.isStorageInstancedBufferAttribute!==!0&&(e.isInstancedBufferAttribute?e.isStorageInstancedBufferAttribute=!0:e.isStorageBufferAttribute=!0)}getHash(e){if(this.bufferCount===0){let t=e.globalCache.getData(this.value);return t===void 0&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getInputType(){return this.value.isIndirectStorageBufferAttribute?"indirectStorageBuffer":"storageBuffer"}element(e){return U1(this,e)}setPBO(e){return this.isPBO=e,this}getPBO(){return this.isPBO}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(Nt.READ_ONLY)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return this._attribute===null&&(this._attribute=zf(this.value),this._varying=$n(this._attribute)),{attribute:this._attribute,varying:this._varying}}getNodeType(e){if(this.structTypeNode!==null)return this.structTypeNode.getNodeType(e);if(e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.getNodeType(e);const{attribute:t}=this.getAttributeData();return t.getNodeType(e)}getMemberType(e,t){return this.structTypeNode!==null?this.structTypeNode.getMemberType(e,t):"void"}generate(e){if(this.structTypeNode!==null&&this.structTypeNode.build(e),e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.generate(e);const{attribute:t,varying:s}=this.getAttributeData(),i=s.build(e);return e.registerTransform(i,t),i}}const Ln=(r,e=null,t=0)=>new V1(r,e,t);class Ze extends Q{static get type(){return"IndexNode"}constructor(e){super("uint"),this.scope=e,this.isIndexNode=!0}generate(e){const t=this.getNodeType(e),s=this.scope;let i;if(s===Ze.VERTEX)i=e.getVertexIndex();else if(s===Ze.INSTANCE)i=e.getInstanceIndex();else if(s===Ze.DRAW)i=e.getDrawIndex();else if(s===Ze.INVOCATION_LOCAL)i=e.getInvocationLocalIndex();else if(s===Ze.INVOCATION_SUBGROUP)i=e.getInvocationSubgroupIndex();else if(s===Ze.SUBGROUP)i=e.getSubgroupIndex();else throw new Error("THREE.IndexNode: Unknown scope: "+s);let n;return e.shaderStage==="vertex"||e.shaderStage==="compute"?n=i:n=$n(this).build(e,t),n}}Ze.VERTEX="vertex";Ze.INSTANCE="instance";Ze.SUBGROUP="subgroup";Ze.INVOCATION_LOCAL="invocationLocal";Ze.INVOCATION_SUBGROUP="invocationSubgroup";Ze.DRAW="draw";const jb=H(Ze,Ze.VERTEX),Ei=H(Ze,Ze.INSTANCE),k1=H(Ze,Ze.SUBGROUP),z1=H(Ze,Ze.INVOCATION_SUBGROUP),G1=H(Ze,Ze.INVOCATION_LOCAL),qb=H(Ze,Ze.DRAW);class Xb extends Q{static get type(){return"InstanceNode"}constructor(e,t,s=null){super("void"),this.count=e,this.instanceMatrix=t,this.instanceColor=s,this.instanceMatrixNode=null,this.instanceColorNode=null,this.updateType=re.FRAME,this.buffer=null,this.bufferColor=null,this.previousInstanceMatrixNode=null}get isStorageMatrix(){const{instanceMatrix:e}=this;return e&&e.isStorageInstancedBufferAttribute===!0}get isStorageColor(){const{instanceColor:e}=this;return e&&e.isStorageInstancedBufferAttribute===!0}setup(e){let{instanceMatrixNode:t,instanceColorNode:s}=this;t===null&&(t=this._createInstanceMatrixNode(!0,e),this.instanceMatrixNode=t);const{instanceColor:i,isStorageColor:n}=this;if(i&&s===null){if(n)s=Ln(i,"vec3",Math.max(i.count,1)).element(Ei);else{const o=new _a(i.array,3),l=i.usage===Wo?dp:gu;this.bufferColor=o,s=E(l(o,"vec3",3,0))}this.instanceColorNode=s}const a=t.mul(Je).xyz;if(Je.assign(a),e.needsPreviousData()&&Ba.assign(this.getPreviousInstancedPosition(e)),e.hasGeometryAttribute("normal")){const o=Y_(rs,t);rs.assign(o)}this.instanceColorNode!==null&&qo("vec3","vInstanceColor").assign(this.instanceColorNode)}update(e){this.buffer!==null&&this.isStorageMatrix!==!0&&(this.buffer.clearUpdateRanges(),this.buffer.updateRanges.push(...this.instanceMatrix.updateRanges),this.instanceMatrix.version!==this.buffer.version&&(this.buffer.version=this.instanceMatrix.version)),this.instanceColor&&this.bufferColor!==null&&this.isStorageColor!==!0&&(this.bufferColor.clearUpdateRanges(),this.bufferColor.updateRanges.push(...this.instanceColor.updateRanges),this.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceColor.version)),this.previousInstanceMatrixNode!==null&&e.object.previousInstanceMatrix.array.set(this.instanceMatrix.array)}getPreviousInstancedPosition(e){const t=e.object;return this.previousInstanceMatrixNode===null&&(t.previousInstanceMatrix=this.instanceMatrix.clone(),this.previousInstanceMatrixNode=this._createInstanceMatrixNode(!1,e)),this.previousInstanceMatrixNode.mul(Ba).xyz}_createInstanceMatrixNode(e,t){let s;const{instanceMatrix:i}=this,{count:n}=i;if(this.isStorageMatrix)s=Ln(i,"mat4",Math.max(n,1)).element(Ei);else if(n*16*4<=t.getUniformBufferLimit())s=tl(i.array,"mat4",Math.max(n,1)).element(Ei);else{const o=new NC(i.array,16,1);e===!0&&(this.buffer=o);const l=i.usage===Wo?dp:gu,c=[l(o,"vec4",16,0),l(o,"vec4",16,4),l(o,"vec4",16,8),l(o,"vec4",16,12)];s=Dn(...c)}return s}}const $1=ue(Xb).setParameterLength(2,3);class W1 extends Xb{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:s,instanceColor:i}=e;super(t,s,i),this.instancedMesh=e}}const Yb=ue(W1).setParameterLength(1);class H1 extends Q{static get type(){return"BatchNode"}constructor(e){super("void"),this.batchMesh=e,this.batchingIdNode=null}setup(e){this.batchingIdNode===null&&(e.getDrawIndex()===null?this.batchingIdNode=Ei:this.batchingIdNode=qb);const s=R(([f])=>{const m=w(On(nt(this.batchMesh._indirectTexture),0).x).toConst(),x=w(f).mod(m).toConst(),y=w(f).div(m).toConst();return nt(this.batchMesh._indirectTexture,ft(x,y)).x}).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]})(w(this.batchingIdNode)),i=this.batchMesh._matricesTexture,n=w(On(nt(i),0).x).toConst(),a=T(s).mul(4).toInt().toConst(),o=a.mod(n).toConst(),l=a.div(n).toConst(),c=Dn(nt(i,ft(o,l)),nt(i,ft(o.add(1),l)),nt(i,ft(o.add(2),l)),nt(i,ft(o.add(3),l))),u=this.batchMesh._colorsTexture;if(u!==null){const m=R(([x])=>{const y=w(On(nt(u),0).x).toConst(),b=x,v=b.mod(y).toConst(),S=b.div(y).toConst();return nt(u,ft(v,S)).rgb}).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]})(s);qo("vec3","vBatchColor").assign(m)}const h=wt(c);Je.assign(c.mul(Je));const d=rs.div(E(h[0].dot(h[0]),h[1].dot(h[1]),h[2].dot(h[2]))),p=h.mul(d).xyz;rs.assign(p),e.hasGeometryAttribute("tangent")&&Oa.mulAssign(h)}}const Zb=ue(H1).setParameterLength(1),Mg=new WeakMap;class Qb extends Q{static get type(){return"SkinningNode"}constructor(e){super("void"),this.skinnedMesh=e,this.updateType=re.OBJECT,this.skinIndexNode=sn("skinIndex","uvec4"),this.skinWeightNode=sn("skinWeight","vec4"),this.bindMatrixNode=Ye("bindMatrix","mat4"),this.bindMatrixInverseNode=Ye("bindMatrixInverse","mat4"),this.boneMatricesNode=mp("skeleton.boneMatrices","mat4",e.skeleton.bones.length),this.positionNode=Je,this.toPositionNode=Je,this.previousBoneMatricesNode=null}getSkinnedPosition(e=this.boneMatricesNode,t=this.positionNode){const{skinIndexNode:s,skinWeightNode:i,bindMatrixNode:n,bindMatrixInverseNode:a}=this,o=e.element(s.x),l=e.element(s.y),c=e.element(s.z),u=e.element(s.w),h=n.mul(t),d=dt(o.mul(i.x).mul(h),l.mul(i.y).mul(h),c.mul(i.z).mul(h),u.mul(i.w).mul(h));return a.mul(d).xyz}getSkinnedNormalAndTangent(e=this.boneMatricesNode,t=rs,s=Oa){const{skinIndexNode:i,skinWeightNode:n,bindMatrixNode:a,bindMatrixInverseNode:o}=this,l=e.element(i.x),c=e.element(i.y),u=e.element(i.z),h=e.element(i.w);let d=dt(n.x.mul(l),n.y.mul(c),n.z.mul(u),n.w.mul(h));d=o.mul(d).mul(a);const p=d.transformDirection(t).xyz,f=d.transformDirection(s).xyz;return{skinNormal:p,skinTangent:f}}getPreviousSkinnedPosition(e){const t=e.object;return this.previousBoneMatricesNode===null&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=mp("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,Ba)}setup(e){e.needsPreviousData()&&Ba.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(this.toPositionNode&&this.toPositionNode.assign(t),e.hasGeometryAttribute("normal")){const{skinNormal:s,skinTangent:i}=this.getSkinnedNormalAndTangent();rs.assign(s),e.hasGeometryAttribute("tangent")&&Oa.assign(i)}return t}generate(e,t){if(t!=="void")return super.generate(e,t)}update(e){const t=e.object&&e.object.skeleton?e.object.skeleton:this.skinnedMesh.skeleton;Mg.get(t)!==e.frameId&&(Mg.set(t,e.frameId),this.previousBoneMatricesNode!==null&&(t.previousBoneMatrices===null&&(t.previousBoneMatrices=new Float32Array(t.boneMatrices)),t.previousBoneMatrices.set(t.boneMatrices)),t.update())}}const Kb=r=>new Qb(r),j1=(r,e=null)=>{const t=new Qb(r);return t.positionNode=Ln(new _a(r.geometry.getAttribute("position").array,3),"vec3").setPBO(!0).toReadOnly().element(Ei).toVar(),t.skinIndexNode=Ln(new _a(new Uint32Array(r.geometry.getAttribute("skinIndex").array),4),"uvec4").setPBO(!0).toReadOnly().element(Ei).toVar(),t.skinWeightNode=Ln(new _a(r.geometry.getAttribute("skinWeight").array,4),"vec4").setPBO(!0).toReadOnly().element(Ei).toVar(),t.bindMatrixNode=ee(r.bindMatrix,"mat4"),t.bindMatrixInverseNode=ee(r.bindMatrixInverse,"mat4"),t.boneMatricesNode=tl(r.skeleton.boneMatrices,"mat4",r.skeleton.bones.length),t.toPositionNode=e,Z(t)};class q1 extends Q{static get type(){return"LoopNode"}constructor(e=[]){super("void"),this.params=e}getVarName(e){return String.fromCharCode(105+e)}getProperties(e){const t=e.getNodeProperties(this);if(t.stackNode!==void 0)return t;const s={};for(let o=0,l=this.params.length-1;o<l;o++){const c=this.params[o],u=c.isNode!==!0&&c.name||this.getVarName(o),h=c.isNode!==!0&&c.type||"int";s[u]=Ks(u,h)}const i=e.addStack(),n=this.params[this.params.length-1](s);t.returnsNode=n.context({nodeLoop:n}),t.stackNode=i;const a=this.params[0];if(a.isNode!==!0&&typeof a.update=="function"){const o=R(this.params[0].update)(s);t.updateNode=o.context({nodeLoop:o})}return e.removeStack(),t}setup(e){if(this.getProperties(e),e.fnCall){const t=e.getDataFromNode(e.fnCall.shaderNode);t.hasLoop=!0}}generate(e){const t=this.getProperties(e),s=this.params,i=t.stackNode;for(let a=0,o=s.length-1;a<o;a++){const l=s[a];let c=!1,u=null,h=null,d=null,p=null,f=null,m=null;l.isNode?l.getNodeType(e)==="bool"?(c=!0,p="bool",h=l.build(e,p)):(p="int",d=this.getVarName(a),u="0",h=l.build(e,p),f="<"):(p=l.type||"int",d=l.name||this.getVarName(a),u=l.start,h=l.end,f=l.condition,m=l.update,typeof u=="number"?u=e.generateConst(p,u):u&&u.isNode&&(u=u.build(e,p)),typeof h=="number"?h=e.generateConst(p,h):h&&h.isNode&&(h=h.build(e,p)),u!==void 0&&h===void 0?(u=u+" - 1",h="0",f=">="):h!==void 0&&u===void 0&&(u="0",f="<"),f===void 0&&(Number(u)>Number(h)?f=">=":f="<"));let x;if(c)x=`while ( ${h} )`;else{const y={start:u,end:h},b=y.start,v=y.end;let S;const M=()=>f.includes("<")?"+=":"-=";if(m!=null)switch(typeof m){case"function":S=e.flowStagesNode(t.updateNode,"void").code.replace(/\t|;/g,"");break;case"number":S=d+" "+M()+" "+e.generateConst(p,m);break;case"string":S=d+" "+m;break;default:m.isNode?S=d+" "+M()+" "+m.build(e):($("TSL: 'Loop( { update: ... } )' is not a function, string or number.",this.stackTrace),S="break /* invalid update */")}else p==="int"||p==="uint"?m=f.includes("<")?"++":"--":m=M()+" 1.",S=d+" "+m;const A=e.getVar(p,d)+" = "+b,C=d+" "+f+" "+v;x=`for ( ${A}; ${C}; ${S} )`}e.addFlowCode((a===0?`
50
- `:"")+e.tab+x+` {
51
-
52
- `).addFlowTab()}const n=i.build(e,"void");t.returnsNode.build(e,"void"),e.removeFlowTab().addFlowCode(`
53
- `+e.tab+n);for(let a=0,o=this.params.length-1;a<o;a++)e.addFlowCode((a===0?"":e.tab)+`}
54
-
55
- `).removeFlowTab();e.addFlowTab()}}const Ie=(...r)=>new q1(xr(r,"int")).toStack(),X1=()=>Ks("continue").toStack(),Jb=()=>Ks("break").toStack(),td=new WeakMap,us=new Ee,wg=R(({bufferMap:r,influence:e,stride:t,width:s,depth:i,offset:n})=>{const a=w(jb).mul(t).add(n),o=a.div(s),l=a.sub(o.mul(s));return nt(r,ft(l,o)).depth(i).xyz.mul(e)});function Y1(r){const e=r.morphAttributes.position!==void 0,t=r.morphAttributes.normal!==void 0,s=r.morphAttributes.color!==void 0,i=r.morphAttributes.position||r.morphAttributes.normal||r.morphAttributes.color,n=i!==void 0?i.length:0;let a=td.get(r);if(a===void 0||a.count!==n){let y=function(){m.dispose(),td.delete(r),r.removeEventListener("dispose",y)};a!==void 0&&a.texture.dispose();const o=r.morphAttributes.position||[],l=r.morphAttributes.normal||[],c=r.morphAttributes.color||[];let u=0;e===!0&&(u=1),t===!0&&(u=2),s===!0&&(u=3);let h=r.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*n),m=new kw(f,h,d,n);m.type=es,m.needsUpdate=!0;const x=u*4;for(let b=0;b<n;b++){const v=o[b],S=l[b],M=c[b],A=h*d*4*b;for(let C=0;C<v.count;C++){const P=C*x;e===!0&&(us.fromBufferAttribute(v,C),f[A+P+0]=us.x,f[A+P+1]=us.y,f[A+P+2]=us.z,f[A+P+3]=0),t===!0&&(us.fromBufferAttribute(S,C),f[A+P+4]=us.x,f[A+P+5]=us.y,f[A+P+6]=us.z,f[A+P+7]=0),s===!0&&(us.fromBufferAttribute(M,C),f[A+P+8]=us.x,f[A+P+9]=us.y,f[A+P+10]=us.z,f[A+P+11]=M.itemSize===4?us.w:1)}}a={count:n,texture:m,stride:u,size:new xe(h,d)},td.set(r,a),r.addEventListener("dispose",y)}return a}class Z1 extends Q{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=ee(1),this.updateType=re.OBJECT}setup(e){const{geometry:t}=e,s=t.morphAttributes.position!==void 0,i=t.hasAttribute("normal")&&t.morphAttributes.normal!==void 0,n=t.morphAttributes.position||t.morphAttributes.normal||t.morphAttributes.color,a=n!==void 0?n.length:0,{texture:o,stride:l,size:c}=Y1(t);s===!0&&Je.mulAssign(this.morphBaseInfluence),i===!0&&rs.mulAssign(this.morphBaseInfluence);const u=w(c.width);Ie(a,({i:h})=>{const d=T(0).toVar();this.mesh.count>1&&this.mesh.morphTexture!==null&&this.mesh.morphTexture!==void 0?d.assign(nt(this.mesh.morphTexture,ft(w(h).add(1),w(Ei))).r):d.assign(Ye("morphTargetInfluences","float").element(h).toVar()),ne(d.notEqual(0),()=>{s===!0&&Je.addAssign(wg({bufferMap:o,influence:d,stride:l,width:u,depth:h,offset:w(0)})),i===!0&&rs.addAssign(wg({bufferMap:o,influence:d,stride:l,width:u,depth:h,offset:w(1)}))})})}update(){const e=this.morphBaseInfluence;this.mesh.geometry.morphTargetsRelative?e.value=1:e.value=1-this.mesh.morphTargetInfluences.reduce((t,s)=>t+s,0)}}const eT=ue(Z1).setParameterLength(1);class Va extends Q{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class Q1 extends Va{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class K1 extends u_{static get type(){return"LightingContextNode"}constructor(e,t=null,s=null,i=null){super(e),this.lightingModel=t,this.backdropNode=s,this.backdropAlphaNode=i,this._value=null}getContext(){const{backdropNode:e,backdropAlphaNode:t}=this,s=E().toVar("directDiffuse"),i=E().toVar("directSpecular"),n=E().toVar("indirectDiffuse"),a=E().toVar("indirectSpecular"),o={directDiffuse:s,directSpecular:i,indirectDiffuse:n,indirectSpecular:a};return{radiance:E().toVar("radiance"),irradiance:E().toVar("irradiance"),iblIrradiance:E().toVar("iblIrradiance"),ambientOcclusion:T(1).toVar("ambientOcclusion"),reflectedLight:o,backdrop:e,backdropAlpha:t}}setup(e){return this.value=this._value||(this._value=this.getContext()),this.value.lightingModel=this.lightingModel||e.context.lightingModel,super.setup(e)}}const tT=ue(K1);class J1 extends Va{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}const qr=new xe;class ih extends Pi{static get type(){return"ViewportTextureNode"}constructor(e=Ci,t=null,s=null){let i=null;s===null?(i=new Yp,i.minFilter=Pn,s=i):i=s,super(s,e,t),this.generateMipmaps=!1,this.defaultFramebuffer=i,this.isOutputTextureNode=!0,this.updateBeforeType=re.RENDER,this._cacheTextures=new WeakMap}getTextureForReference(e=null){let t,s;if(this.referenceNode?(t=this.referenceNode.defaultFramebuffer,s=this.referenceNode._cacheTextures):(t=this.defaultFramebuffer,s=this._cacheTextures),e===null)return t;if(s.has(e)===!1){const i=t.clone();s.set(e,i)}return s.get(e)}updateReference(e){const t=e.renderer.getRenderTarget();return this.value=this.getTextureForReference(t),this.value}updateBefore(e){const t=e.renderer,s=t.getRenderTarget();s===null?t.getDrawingBufferSize(qr):qr.set(s.width,s.height);const i=this.getTextureForReference(s);(i.image.width!==qr.width||i.image.height!==qr.height)&&(i.image.width=qr.width,i.image.height=qr.height,i.needsUpdate=!0);const n=i.generateMipmaps;i.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(i),i.generateMipmaps=n}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const eE=ue(ih).setParameterLength(0,3),sm=ue(ih,null,null,{generateMipmaps:!0}).setParameterLength(0,3),tE=sm(),sT=(r=Ci,e=null)=>tE.sample(r,e);let Ul=null;class sE extends ih{static get type(){return"ViewportDepthTextureNode"}constructor(e=Ci,t=null){Ul===null&&(Ul=new Bs),super(e,t,Ul)}getTextureForReference(){return Ul}}const im=ue(sE).setParameterLength(0,2);class ts extends Q{static get type(){return"ViewportDepthNode"}constructor(e,t=null){super("float"),this.scope=e,this.valueNode=t,this.isViewportDepthNode=!0}generate(e){const{scope:t}=this;return t===ts.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,s=this.valueNode;let i=null;if(t===ts.DEPTH_BASE)s!==null&&(i=nT().assign(s));else if(t===ts.DEPTH)e.isPerspectiveCamera?i=nm(lt.z,wn,Cn):i=va(lt.z,wn,Cn);else if(t===ts.LINEAR_DEPTH)if(s!==null)if(e.isPerspectiveCamera){const n=rm(s,wn,Cn);i=va(n,wn,Cn)}else i=s;else i=va(lt.z,wn,Cn);return i}}ts.DEPTH_BASE="depthBase";ts.DEPTH="depth";ts.LINEAR_DEPTH="linearDepth";const va=(r,e,t)=>r.add(e).div(e.sub(t)),iE=(r,e,t)=>r.add(t).div(t.sub(e)),nE=R(([r,e,t],s)=>s.renderer.reversedDepthBuffer===!0?t.sub(e).mul(r).sub(t):e.sub(t).mul(r).sub(e)),nm=(r,e,t)=>e.add(r).mul(t).div(t.sub(e).mul(r)),iT=(r,e,t)=>e.mul(r.add(t)).div(r.mul(e.sub(t))),rm=R(([r,e,t],s)=>s.renderer.reversedDepthBuffer===!0?e.mul(t).div(e.sub(t).mul(r).sub(e)):e.mul(t).div(t.sub(e).mul(r).sub(t))),am=(r,e,t)=>{e=e.max(1e-6).toVar();const s=vi(r.negate().div(e)),i=vi(t.div(e));return s.div(i)},rE=(r,e,t)=>{const s=r.mul(qu(t.div(e)));return T(Math.E).pow(s).mul(e).negate()},nT=ue(ts,ts.DEPTH_BASE),om=H(ts,ts.DEPTH),yu=ue(ts,ts.LINEAR_DEPTH).setParameterLength(0,1),aE=yu(im());om.assign=r=>nT(r);class Ds extends Q{static get type(){return"ClippingNode"}constructor(e=Ds.DEFAULT){super(),this.scope=e}setup(e){super.setup(e);const t=e.clippingContext,{intersectionPlanes:s,unionPlanes:i}=t;return this.hardwareClipping=e.material.hardwareClipping,this.scope===Ds.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(s,i):this.scope===Ds.HARDWARE?this.setupHardwareClipping(i,e):this.setupDefault(s,i)}setupAlphaToCoverage(e,t){return R(()=>{const s=T().toVar("distanceToPlane"),i=T().toVar("distanceToGradient"),n=T(1).toVar("clipOpacity"),a=t.length;if(this.hardwareClipping===!1&&a>0){const l=It(t).setGroup(se);Ie(a,({i:c})=>{const u=l.element(c);s.assign(lt.dot(u.xyz).negate().add(u.w)),i.assign(s.fwidth().div(2)),n.mulAssign(ti(i.negate(),i,s))})}const o=e.length;if(o>0){const l=It(e).setGroup(se),c=T(1).toVar("intersectionClipOpacity");Ie(o,({i:u})=>{const h=l.element(u);s.assign(lt.dot(h.xyz).negate().add(h.w)),i.assign(s.fwidth().div(2)),c.mulAssign(ti(i.negate(),i,s).oneMinus())}),n.mulAssign(c.oneMinus())}Oe.a.mulAssign(n),Oe.a.equal(0).discard()})()}setupDefault(e,t){return R(()=>{const s=t.length;if(this.hardwareClipping===!1&&s>0){const n=It(t).setGroup(se);Ie(s,({i:a})=>{const o=n.element(a);lt.dot(o.xyz).greaterThan(o.w).discard()})}const i=e.length;if(i>0){const n=It(e).setGroup(se),a=Us(!0).toVar("clipped");Ie(i,({i:o})=>{const l=n.element(o);a.assign(lt.dot(l.xyz).greaterThan(l.w).and(a))}),a.discard()}})()}setupHardwareClipping(e,t){const s=e.length;return t.enableHardwareClipping(s),R(()=>{const i=It(e).setGroup(se),n=an(t.getClipDistance());Ie(s,({i:a})=>{const o=i.element(a),l=lt.dot(o.xyz).sub(o.w).negate();n.element(a).assign(l)})})()}}Ds.ALPHA_TO_COVERAGE="alphaToCoverage";Ds.DEFAULT="default";Ds.HARDWARE="hardware";const oE=()=>new Ds,lE=()=>new Ds(Ds.ALPHA_TO_COVERAGE),cE=()=>new Ds(Ds.HARDWARE),uE=.05,Cg=R(([r])=>Js(ae(1e4,jt(ae(17,r.x).add(ae(.1,r.y)))).mul(dt(.1,We(jt(ae(13,r.y).add(r.x))))))),Ag=R(([r])=>Cg(z(Cg(r.xy),r.z))),hE=R(([r])=>{const e=tt(wi(Ef(r.xyz)),wi(Nf(r.xyz))),t=T(1).div(T(uE).mul(e)).toVar("pixScale"),s=z(Pa(Mi(vi(t))),Pa(Xu(vi(t)))),i=z(Ag(Mi(s.x.mul(r.xyz))),Ag(Mi(s.y.mul(r.xyz)))),n=Js(vi(t)),a=dt(ae(n.oneMinus(),i.x),ae(n,i.y)),o=ns(n,n.oneMinus()),l=E(a.mul(a).div(ae(2,o).mul(Te(1,o))),a.sub(ae(.5,o)).div(Te(1,o)),Te(1,Te(1,a).mul(Te(1,a)).div(ae(2,o).mul(Te(1,o))))),c=a.lessThan(o.oneMinus()).select(a.lessThan(o).select(l.x,l.y),l.z);return ei(c,1e-6,1)}).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class dE extends I_{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),s=e.hasGeometryAttribute(t);let i;return s===!0?i=super.generate(e):i=e.generateConst(this.nodeType,new Ee(1,1,1,1)),i}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const rT=(r=0)=>new dE(r),pE=R(([r,e])=>ns(1,r.oneMinus().div(e)).oneMinus()).setLayout({name:"blendBurn",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),fE=R(([r,e])=>ns(r.div(e.oneMinus()),1)).setLayout({name:"blendDodge",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),mE=R(([r,e])=>r.oneMinus().mul(e.oneMinus()).oneMinus()).setLayout({name:"blendScreen",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),gE=R(([r,e])=>ye(r.mul(2).mul(e),r.oneMinus().mul(2).mul(e.oneMinus()).oneMinus(),Fa(.5,r))).setLayout({name:"blendOverlay",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),yE=R(([r,e])=>{const t=e.a.add(r.a.mul(e.a.oneMinus()));return ie(e.rgb.mul(e.a).add(r.rgb.mul(r.a).mul(e.a.oneMinus())).div(t),t)}).setLayout({name:"blendColor",type:"vec4",inputs:[{name:"base",type:"vec4"},{name:"blend",type:"vec4"}]}),aT=R(([r])=>ie(r.rgb.mul(r.a),r.a),{color:"vec4",return:"vec4"}),xE=R(([r])=>(ne(r.a.equal(0),()=>ie(0)),ie(r.rgb.div(r.a),r.a)),{color:"vec4",return:"vec4"});class st extends _s{static get type(){return"NodeMaterial"}get type(){return this.constructor.type}set type(e){}constructor(){super(),this.isNodeMaterial=!0,this.fog=!0,this.lights=!1,this.hardwareClipping=!1,this.lightsNode=null,this.envNode=null,this.aoNode=null,this.colorNode=null,this.normalNode=null,this.opacityNode=null,this.backdropNode=null,this.backdropAlphaNode=null,this.alphaTestNode=null,this.maskNode=null,this.maskShadowNode=null,this.positionNode=null,this.geometryNode=null,this.depthNode=null,this.receivedShadowPositionNode=null,this.castShadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null,this.contextNode=null}_getNodeChildren(){const e=[];for(const t of Object.getOwnPropertyNames(this)){if(t.startsWith("_")===!0)continue;const s=this[t];s&&s.isNode===!0&&e.push({property:t,childNode:s})}return e}customProgramCacheKey(){const e=[];for(const{property:t,childNode:s}of this._getNodeChildren())e.push(Ia(t.slice(0,-4)),s.getCacheKey());return this.type+Ko(e)}build(e){this.setup(e)}setupObserver(e){return new BC(e)}setup(e){e.context.setupNormal=()=>br(this.setupNormal(e),"NORMAL","vec3"),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);const t=e.renderer,s=t.getRenderTarget();t.contextNode.isContextNode===!0?e.context={...e.context,...t.contextNode.getFlowContextData()}:$('NodeMaterial: "renderer.contextNode" must be an instance of `context()`.'),this.contextNode!==null&&(this.contextNode.isContextNode===!0?e.context={...e.context,...this.contextNode.getFlowContextData()}:$('NodeMaterial: "material.contextNode" must be an instance of `context()`.')),e.addStack();const i=this.setupVertex(e),n=br(this.vertexNode||i,"VERTEX");e.context.clipSpace=n,e.stack.outputNode=n,this.setupHardwareClipping(e),this.geometryNode!==null&&(e.stack.outputNode=e.stack.outputNode.bypass(this.geometryNode)),e.addFlow("vertex",e.removeStack()),e.addStack();let a;const o=this.setupClipping(e);if((this.depthWrite===!0||this.depthTest===!0)&&(s!==null?s.depthBuffer===!0&&this.setupDepth(e):t.depth===!0&&this.setupDepth(e)),this.fragmentNode===null){this.setupDiffuseColor(e),this.setupVariants(e);const l=this.setupLighting(e);o!==null&&e.stack.addToStack(o);const c=ie(l,Oe.a).max(0);a=this.setupOutput(e,c),Ta.assign(a);const u=this.outputNode!==null;if(u&&(a=this.outputNode),e.context.getOutput&&(a=e.context.getOutput(a,e)),s!==null){const h=t.getMRT(),d=this.mrtNode;h!==null?(u&&Ta.assign(a),a=h,d!==null&&(a=h.merge(d))):d!==null&&(a=d)}}else{let l=this.fragmentNode;l.isOutputStructNode!==!0&&(l=ie(l)),a=this.setupOutput(e,l)}e.stack.outputNode=a,e.addFlow("fragment",e.removeStack()),e.observer=this.setupObserver(e)}setupClipping(e){if(e.clippingContext===null)return null;const{unionPlanes:t,intersectionPlanes:s}=e.clippingContext;let i=null;if(t.length>0||s.length>0){const n=e.renderer.currentSamples;this.alphaToCoverage&&n>1?i=lE():e.stack.addToStack(oE())}return i}setupHardwareClipping(e){if(this.hardwareClipping=!1,e.clippingContext===null)return;const t=e.clippingContext.unionPlanes.length;t>0&&t<=8&&e.isAvailable("clipDistance")&&(e.stack.addToStack(cE()),this.hardwareClipping=!0)}setupDepth(e){const{renderer:t,camera:s}=e;let i=this.depthNode;if(i===null){const n=t.getMRT();n&&n.has("depth")?i=n.get("depth"):t.logarithmicDepthBuffer===!0&&(s.isPerspectiveCamera?i=am(lt.z,wn,Cn):i=va(lt.z,wn,Cn))}i!==null&&om.assign(i).toStack()}setupPositionView(){return Hn.mul(Je).xyz}setupModelViewProjection(){return en.mul(lt)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.position=e.removeStack(),Hb}setupPosition(e){const{object:t,geometry:s}=e;if((s.morphAttributes.position||s.morphAttributes.normal||s.morphAttributes.color)&&eT(t).toStack(),t.isSkinnedMesh===!0&&Kb(t).toStack(),this.displacementMap){const i=Wi("displacementMap","texture"),n=Wi("displacementScale","float"),a=Wi("displacementBias","float");Je.addAssign(rs.normalize().mul(i.x.mul(n).add(a)))}return t.isBatchedMesh&&Zb(t).toStack(),t.isInstancedMesh&&t.instanceMatrix&&t.instanceMatrix.isInstancedBufferAttribute===!0&&Yb(t).toStack(),this.positionNode!==null&&Je.assign(br(this.positionNode,"POSITION","vec3")),Je}setupDiffuseColor(e){const{object:t,geometry:s}=e;this.maskNode!==null&&Us(this.maskNode).not().discard();let i=this.colorNode?ie(this.colorNode):mb;this.vertexColors===!0&&s.hasAttribute("color")&&(i=i.mul(rT())),t.instanceColor&&(i=qo("vec3","vInstanceColor").mul(i)),t.isBatchedMesh&&t._colorsTexture&&(i=qo("vec3","vBatchColor").mul(i)),Oe.assign(i);const n=this.opacityNode?T(this.opacityNode):em;Oe.a.assign(Oe.a.mul(n));let a=null;(this.alphaTestNode!==null||this.alphaTest>0)&&(a=this.alphaTestNode!==null?T(this.alphaTestNode):fb,this.alphaToCoverage===!0?(Oe.a=ti(a,a.add(Pf(Oe.a)),Oe.a),Oe.a.lessThanEqual(0).discard()):Oe.a.lessThanEqual(a).discard()),this.alphaHash===!0&&Oe.a.lessThan(hE(Je)).discard(),e.isOpaque()&&Oe.a.assign(1)}setupVariants(){}setupOutgoingLight(){return this.lights===!0?E(0):Oe.rgb}setupNormal(){return this.normalNode?E(this.normalNode):Sb}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?Wi("envMap","cubeTexture"):Wi("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new J1(tm)),t}setupLights(e){const t=[],s=this.setupEnvironment(e);s&&s.isLightingNode&&t.push(s);const i=this.setupLightMap(e);i&&i.isLightingNode&&t.push(i);let n=this.aoNode;n===null&&e.material.aoMap&&(n=Wb),e.context.getAO&&(n=e.context.getAO(n,e)),n&&t.push(new Q1(n));let a=this.lightsNode||e.lightsNode;return t.length>0&&(a=e.renderer.lighting.createNode([...a.getLights(),...t])),a}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:s,backdropAlphaNode:i,emissiveNode:n}=this,o=this.lights===!0||this.lightsNode!==null?this.setupLights(e):null;let l=this.setupOutgoingLight(e);if(o&&o.getScope().hasLights){const c=this.setupLightingModel(e)||null;l=tT(o,c,s,i)}else s!==null&&(l=E(i!==null?ye(l,s,i):s));return(n&&n.isNode===!0||t.emissive&&t.emissive.isColor===!0)&&(up.assign(E(n||yb)),l=l.add(up)),l}setupFog(e,t){const s=e.fogNode;return s&&(Ta.assign(t),t=ie(s.toVar())),t}setupPremultipliedAlpha(e,t){return aT(t)}setupOutput(e,t){return this.fog===!0&&(t=this.setupFog(e,t)),this.premultipliedAlpha===!0&&(t=this.setupPremultipliedAlpha(e,t)),t}setDefaultValues(e){for(const s in e){const i=e[s];this[s]===void 0&&(this[s]=i,i&&i.clone&&(this[s]=i.clone()))}const t=Object.getOwnPropertyDescriptors(e.constructor.prototype);for(const s in t)Object.getOwnPropertyDescriptor(this.constructor.prototype,s)===void 0&&t[s].get!==void 0&&Object.defineProperty(this.constructor.prototype,s,t[s])}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{},nodes:{}});const s=_s.prototype.toJSON.call(this,e);s.inputNodes={};for(const{property:n,childNode:a}of this._getNodeChildren())s.inputNodes[n]=a.toJSON(e).uuid;function i(n){const a=[];for(const o in n){const l=n[o];delete l.metadata,a.push(l)}return a}if(t){const n=i(e.textures),a=i(e.images),o=i(e.nodes);n.length>0&&(s.textures=n),a.length>0&&(s.images=a),o.length>0&&(s.nodes=o)}return s}copy(e){return this.lightsNode=e.lightsNode,this.envNode=e.envNode,this.aoNode=e.aoNode,this.colorNode=e.colorNode,this.normalNode=e.normalNode,this.opacityNode=e.opacityNode,this.backdropNode=e.backdropNode,this.backdropAlphaNode=e.backdropAlphaNode,this.alphaTestNode=e.alphaTestNode,this.maskNode=e.maskNode,this.maskShadowNode=e.maskShadowNode,this.positionNode=e.positionNode,this.geometryNode=e.geometryNode,this.depthNode=e.depthNode,this.receivedShadowPositionNode=e.receivedShadowPositionNode,this.castShadowPositionNode=e.castShadowPositionNode,this.receivedShadowNode=e.receivedShadowNode,this.castShadowNode=e.castShadowNode,this.outputNode=e.outputNode,this.mrtNode=e.mrtNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,this.contextNode=e.contextNode,super.copy(e)}}const _E=new Jx;class bE extends st{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(_E),this.setValues(e)}}const TE=new gC;class SE extends st{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(TE),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?T(this.offsetNode):zb,t=this.dashScaleNode?T(this.dashScaleNode):Ub,s=this.dashSizeNode?T(this.dashSizeNode):Vb,i=this.gapSizeNode?T(this.gapSizeNode):kb;xc.assign(s),hp.assign(i);const n=$n(sn("lineDistance").mul(t));(e?n.add(e):n).mod(xc.add(hp)).greaterThan(xc).discard()}}const vE=new pC;class oT extends st{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(vE),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?T(this.opacityNode):em;Oe.assign(Zu(ie(pb(Me),e),ds))}}const lm=R(([r=Xf])=>{const e=r.z.atan(r.x).mul(1/(Math.PI*2)).add(.5),t=r.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5);return z(e,t)});class lT extends nn{constructor(e=1,t={}){super(e,e,t),this.isCubeRenderTarget=!0;const s={width:e,height:e,depth:1},i=[s,s,s,s,s,s];this.texture=new Iu(i),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){const s=t.minFilter,i=t.generateMipmaps;t.generateMipmaps=!0,this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const n=new Uu(5,5,5),a=lm(Xf),o=new st;o.colorNode=we(t,a,0),o.side=Rt,o.blending=Xi;const l=new Un(n,o),c=new qx;c.add(l),t.minFilter===Pn&&(t.minFilter=Gt);const u=new AC(1,10,this),h=e.getMRT();return e.setMRT(null),u.update(e,c),e.setMRT(h),t.minFilter=s,t.currentGenerateMipmaps=i,l.geometry.dispose(),l.material.dispose(),this}clear(e,t=!0,s=!0,i=!0){const n=e.getRenderTarget();for(let a=0;a<6;a++)e.setRenderTarget(this,a),e.clear(t,s,i);e.setRenderTarget(n)}}const Oo=new WeakMap;class ME extends ot{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=Xt(null);const t=new Iu;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=re.RENDER}updateBefore(e){const{renderer:t,material:s}=e,i=this.envNode;if(i.isTextureNode||i.isMaterialReferenceNode){const n=i.isTextureNode?i.value:s[i.property];if(n&&n.isTexture){const a=n.mapping;if(a===Vp||a===kp){if(Oo.has(n)){const o=Oo.get(n);Eg(o,n.mapping),this._cubeTexture=o}else{const o=n.image;if(wE(o)){const l=new lT(o.height);l.fromEquirectangularTexture(t,n),Eg(l.texture,n.mapping),this._cubeTexture=l.texture,Oo.set(n,l.texture),n.addEventListener("dispose",cT)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function wE(r){return r==null?!1:r.height>0}function cT(r){const e=r.target;e.removeEventListener("dispose",cT);const t=Oo.get(e);t!==void 0&&(Oo.delete(e),t.dispose())}function Eg(r,e){e===Vp?r.mapping=Ca:e===kp&&(r.mapping=Dc)}const uT=ue(ME).setParameterLength(1);class cm extends Va{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=uT(this.envNode)}}class CE extends Va{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=T(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class nh{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class hT extends nh{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,s=e.reflectedLight,i=e.irradianceLightMap;s.indirectDiffuse.assign(ie(0)),i?s.indirectDiffuse.addAssign(i):s.indirectDiffuse.addAssign(ie(1,1,1,0)),s.indirectDiffuse.mulAssign(t),s.indirectDiffuse.mulAssign(Oe.rgb)}finish(e){const{material:t,context:s}=e,i=s.outgoingLight,n=e.context.environment;if(n)switch(t.combine){case Eu:i.rgb.assign(ye(i.rgb,i.rgb.mul(n.rgb),Do.mul(Sc)));break;case WM:i.rgb.assign(ye(i.rgb,n.rgb,Do.mul(Sc)));break;case HM:i.rgb.addAssign(n.rgb.mul(Do.mul(Sc)));break;default:W("BasicLightingModel: Unsupported .combine value:",t.combine);break}}}const AE=new vn;class um extends st{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(AE),this.setValues(e)}setupNormal(){return Ua(Da)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new cm(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new CE(tm)),t}setupOutgoingLight(){return Oe.rgb}setupLightingModel(){return new hT}}const La=R(({f0:r,f90:e,dotVH:t})=>{const s=t.mul(-5.55473).sub(6.98316).mul(t).exp2();return r.mul(s.oneMinus()).add(e.mul(s))}),Sr=R(r=>r.diffuseColor.mul(1/Math.PI)),EE=()=>T(.25),NE=R(({dotNH:r})=>pu.mul(T(.5)).add(1).mul(T(1/Math.PI)).mul(r.pow(pu))),RE=R(({lightDirection:r})=>{const e=r.add(Ge).normalize(),t=Me.dot(e).clamp(),s=Ge.dot(e).clamp(),i=La({f0:kn,f90:1,dotVH:s}),n=EE(),a=NE({dotNH:t});return i.mul(n).mul(a)});class dT extends hT{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const n=Me.dot(e).clamp().mul(t);s.directDiffuse.addAssign(n.mul(Sr({diffuseColor:Oe.rgb}))),this.specular===!0&&s.directSpecular.addAssign(n.mul(RE({lightDirection:e})).mul(Do))}indirect(e){const{ambientOcclusion:t,irradiance:s,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(s.mul(Sr({diffuseColor:Oe}))),i.indirectDiffuse.mulAssign(t)}}const PE=new fC;class FE extends st{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(PE),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new cm(t):null}setupLightingModel(){return new dT(!1)}}const BE=new hC;class DE extends st{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(BE),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new cm(t):null}setupLightingModel(){return new dT}setupVariants(){const e=(this.shininessNode?T(this.shininessNode):gb).max(1e-4);pu.assign(e);const t=this.specularNode||xb;kn.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const pT=R(r=>{if(r.geometry.hasAttribute("normal")===!1)return T(0);const e=Da.dFdx().abs().max(Da.dFdy().abs());return e.x.max(e.y).max(e.z)}),hm=R(r=>{const{roughness:e}=r,t=pT();let s=e.max(.0525);return s=s.add(t),s=s.min(1),s}),fT=R(({alpha:r,dotNL:e,dotNV:t})=>{const s=r.pow2(),i=e.mul(s.add(s.oneMinus().mul(t.pow2())).sqrt()),n=t.mul(s.add(s.oneMinus().mul(e.pow2())).sqrt());return bs(.5,i.add(n).max(Tf))}).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),OE=R(({alphaT:r,alphaB:e,dotTV:t,dotBV:s,dotTL:i,dotBL:n,dotNV:a,dotNL:o})=>{const l=o.mul(E(r.mul(t),e.mul(s),a).length()),c=a.mul(E(r.mul(i),e.mul(n),o).length());return bs(.5,l.add(c))}).setLayout({name:"V_GGX_SmithCorrelated_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotTV",type:"float",qualifier:"in"},{name:"dotBV",type:"float",qualifier:"in"},{name:"dotTL",type:"float",qualifier:"in"},{name:"dotBL",type:"float",qualifier:"in"},{name:"dotNV",type:"float",qualifier:"in"},{name:"dotNL",type:"float",qualifier:"in"}]}),mT=R(({alpha:r,dotNH:e})=>{const t=r.pow2(),s=e.pow2().mul(t.oneMinus()).oneMinus();return t.div(s.pow2()).mul(1/Math.PI)}).setLayout({name:"D_GGX",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNH",type:"float"}]}),LE=T(1/Math.PI),IE=R(({alphaT:r,alphaB:e,dotNH:t,dotTH:s,dotBH:i})=>{const n=r.mul(e),a=E(e.mul(s),r.mul(i),n.mul(t)),o=a.dot(a),l=n.div(o);return LE.mul(n.mul(l.pow2()))}).setLayout({name:"D_GGX_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotNH",type:"float",qualifier:"in"},{name:"dotTH",type:"float",qualifier:"in"},{name:"dotBH",type:"float",qualifier:"in"}]}),dm=R(({lightDirection:r,f0:e,f90:t,roughness:s,f:i,normalView:n=Me,USE_IRIDESCENCE:a,USE_ANISOTROPY:o})=>{const l=s.pow2(),c=r.add(Ge).normalize(),u=n.dot(r).clamp(),h=n.dot(Ge).clamp(),d=n.dot(c).clamp(),p=Ge.dot(c).clamp();let f=La({f0:e,f90:t,dotVH:p}),m,x;if(Ho(a)&&(f=Hu.mix(f,i)),Ho(o)){const y=Fo.dot(r),b=Fo.dot(Ge),v=Fo.dot(c),S=_r.dot(r),M=_r.dot(Ge),A=_r.dot(c);m=OE({alphaT:du,alphaB:l,dotTV:b,dotBV:M,dotTL:y,dotBL:S,dotNV:h,dotNL:u}),x=IE({alphaT:du,alphaB:l,dotNH:d,dotTH:v,dotBH:A})}else m=fT({alpha:l,dotNL:u,dotNV:h}),x=mT({alpha:l,dotNH:d});return f.mul(m).mul(x)}),UE=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 li=null;const Xo=R(({roughness:r,dotNV:e})=>{li===null&&(li=new Kx(UE,16,16,_i,Et),li.name="DFG_LUT",li.minFilter=Gt,li.magFilter=Gt,li.wrapS=xi,li.wrapT=xi,li.generateMipmaps=!1,li.needsUpdate=!0);const t=z(r,e);return we(li,t).rg}),VE=R(({lightDirection:r,f0:e,f90:t,roughness:s,f:i,USE_IRIDESCENCE:n,USE_ANISOTROPY:a})=>{const o=dm({lightDirection:r,f0:e,f90:t,roughness:s,f:i,USE_IRIDESCENCE:n,USE_ANISOTROPY:a}),l=Me.dot(r).clamp(),c=Me.dot(Ge).clamp(),u=Xo({roughness:s,dotNV:c}),h=Xo({roughness:s,dotNV:l}),d=e.mul(u.x).add(t.mul(u.y)),p=e.mul(h.x).add(t.mul(h.y)),f=u.x.add(u.y),m=h.x.add(h.y),x=T(1).sub(f),y=T(1).sub(m),b=e.add(e.oneMinus().mul(.047619)),v=d.mul(p).mul(b).div(T(1).sub(x.mul(y).mul(b).mul(b)).add(Tf)),S=x.mul(y),M=v.mul(S);return o.add(M)}),gT=R(r=>{const{dotNV:e,specularColor:t,specularF90:s,roughness:i}=r,n=Xo({dotNV:e,roughness:i});return t.mul(n.x).add(s.mul(n.y))}),Tp=R(({f:r,f90:e,dotVH:t})=>{const s=t.oneMinus().saturate(),i=s.mul(s),n=s.mul(i,i).clamp(0,.9999);return r.sub(E(e).mul(n)).div(n.oneMinus())}).setLayout({name:"Schlick_to_F0",type:"vec3",inputs:[{name:"f",type:"vec3"},{name:"f90",type:"float"},{name:"dotVH",type:"float"}]}),kE=R(({roughness:r,dotNH:e})=>{const t=r.pow2(),s=T(1).div(t),n=e.pow2().oneMinus().max(.0078125);return T(2).add(s).mul(n.pow(s.mul(.5))).div(2*Math.PI)}).setLayout({name:"D_Charlie",type:"float",inputs:[{name:"roughness",type:"float"},{name:"dotNH",type:"float"}]}),zE=R(({dotNV:r,dotNL:e})=>T(1).div(T(4).mul(e.add(r).sub(e.mul(r))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),GE=R(({lightDirection:r})=>{const e=r.add(Ge).normalize(),t=Me.dot(r).clamp(),s=Me.dot(Ge).clamp(),i=Me.dot(e).clamp(),n=kE({roughness:Mn,dotNH:i}),a=zE({dotNV:s,dotNL:t});return hs.mul(n).mul(a)}),Ng=R(({N:r,V:e,roughness:t})=>{const n=.0078125,a=r.dot(e).saturate(),o=z(t,a.oneMinus().sqrt());return o.assign(o.mul(.984375).add(n)),o}).setLayout({name:"LTC_Uv",type:"vec2",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"roughness",type:"float"}]}),$E=R(({f:r})=>{const e=r.length();return tt(e.mul(e).add(r.z).div(e.add(1)),0)}).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),Vl=R(({v1:r,v2:e})=>{const t=r.dot(e),s=t.abs().toVar(),i=s.mul(.0145206).add(.4965155).mul(s).add(.8543985).toVar(),n=s.add(4.1616724).mul(s).add(3.417594).toVar(),a=i.div(n),o=t.greaterThan(0).select(a,tt(t.mul(t).oneMinus(),1e-7).inverseSqrt().mul(.5).sub(a));return r.cross(e).mul(o)}).setLayout({name:"LTC_EdgeVectorFormFactor",type:"vec3",inputs:[{name:"v1",type:"vec3"},{name:"v2",type:"vec3"}]}),sd=R(({N:r,V:e,P:t,mInv:s,p0:i,p1:n,p2:a,p3:o})=>{const l=n.sub(i).toVar(),c=o.sub(i).toVar(),u=l.cross(c),h=E().toVar();return ne(u.dot(t.sub(i)).greaterThanEqual(0),()=>{const d=e.sub(r.mul(e.dot(r))).normalize(),p=r.cross(d).negate(),f=s.mul(wt(d,p,r).transpose()).toVar(),m=f.mul(i.sub(t)).normalize().toVar(),x=f.mul(n.sub(t)).normalize().toVar(),y=f.mul(a.sub(t)).normalize().toVar(),b=f.mul(o.sub(t)).normalize().toVar(),v=E(0).toVar();v.addAssign(Vl({v1:m,v2:x})),v.addAssign(Vl({v1:x,v2:y})),v.addAssign(Vl({v1:y,v2:b})),v.addAssign(Vl({v1:b,v2:m})),h.assign(E($E({f:v})))}),h}).setLayout({name:"LTC_Evaluate",type:"vec3",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"P",type:"vec3"},{name:"mInv",type:"mat3"},{name:"p0",type:"vec3"},{name:"p1",type:"vec3"},{name:"p2",type:"vec3"},{name:"p3",type:"vec3"}]}),rh=1/6,yT=r=>ae(rh,ae(r,ae(r,r.negate().add(3)).sub(3)).add(1)),Sp=r=>ae(rh,ae(r,ae(r,ae(3,r).sub(6))).add(4)),xT=r=>ae(rh,ae(r,ae(r,ae(-3,r).add(3)).add(3)).add(1)),vp=r=>ae(rh,Rs(r,3)),Rg=r=>yT(r).add(Sp(r)),Pg=r=>xT(r).add(vp(r)),Fg=r=>dt(-1,Sp(r).div(yT(r).add(Sp(r)))),Bg=r=>dt(1,vp(r).div(xT(r).add(vp(r)))),Dg=(r,e,t)=>{const s=r.uvNode,i=ae(s,e.zw).add(.5),n=Mi(i),a=Js(i),o=Rg(a.x),l=Pg(a.x),c=Fg(a.x),u=Bg(a.x),h=Fg(a.y),d=Bg(a.y),p=z(n.x.add(c),n.y.add(h)).sub(.5).mul(e.xy),f=z(n.x.add(u),n.y.add(h)).sub(.5).mul(e.xy),m=z(n.x.add(c),n.y.add(d)).sub(.5).mul(e.xy),x=z(n.x.add(u),n.y.add(d)).sub(.5).mul(e.xy),y=Rg(a.y).mul(dt(o.mul(r.sample(p).level(t)),l.mul(r.sample(f).level(t)))),b=Pg(a.y).mul(dt(o.mul(r.sample(m).level(t)),l.mul(r.sample(x).level(t))));return y.add(b)},pm=R(([r,e])=>{const t=z(r.size(w(e))),s=z(r.size(w(e.add(1)))),i=bs(1,t),n=bs(1,s),a=Dg(r,ie(i,t),Mi(e)),o=Dg(r,ie(n,s),Xu(e));return Js(e).mix(a,o)}),WE=R(([r,e])=>{const t=e.mul($f(r));return pm(r,t)}),Og=R(([r,e,t,s,i])=>{const n=E(Of(e.negate(),is(r),bs(1,s))),a=E(wi(i[0].xyz),wi(i[1].xyz),wi(i[2].xyz));return is(n).mul(t.mul(a))}).setLayout({name:"getVolumeTransmissionRay",type:"vec3",inputs:[{name:"n",type:"vec3"},{name:"v",type:"vec3"},{name:"thickness",type:"float"},{name:"ior",type:"float"},{name:"modelMatrix",type:"mat4"}]}),HE=R(([r,e])=>r.mul(ei(e.mul(2).sub(2),0,1))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),jE=sm(),qE=sT(),Lg=R(([r,e,t],{material:s})=>{const n=(s.side===Rt?jE:qE).sample(r),a=vi(Tr.x).mul(HE(e,t));return pm(n,a)}),Ig=R(([r,e,t])=>(ne(t.notEqual(0),()=>{const s=qu(e).negate().div(t);return Sf(s.negate().mul(r))}),E(1))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),XE=R(([r,e,t,s,i,n,a,o,l,c,u,h,d,p,f])=>{let m,x;if(f){m=ie().toVar(),x=E().toVar();const M=u.sub(1).mul(f.mul(.025)),A=E(u.sub(M),u,u.add(M));Ie({start:0,end:3},({i:C})=>{const P=A.element(C),B=Og(r,e,h,P,o),V=a.add(B),Y=c.mul(l.mul(ie(V,1))),J=z(Y.xy.div(Y.w)).toVar();J.addAssign(1),J.divAssign(2),J.assign(z(J.x,J.y.oneMinus()));const K=Lg(J,t,P);m.element(C).assign(K.element(C)),m.a.addAssign(K.a),x.element(C).assign(s.element(C).mul(Ig(wi(B),d,p).element(C)))}),m.a.divAssign(3)}else{const M=Og(r,e,h,u,o),A=a.add(M),C=c.mul(l.mul(ie(A,1))),P=z(C.xy.div(C.w)).toVar();P.addAssign(1),P.divAssign(2),P.assign(z(P.x,P.y.oneMinus())),m=Lg(P,t,u),x=s.mul(Ig(wi(M),d,p))}const y=x.rgb.mul(m.rgb),b=r.dot(e).clamp(),v=E(gT({dotNV:b,specularColor:i,specularF90:n,roughness:t})),S=x.r.add(x.g,x.b).div(3);return ie(v.oneMinus().mul(y),m.a.oneMinus().mul(S).oneMinus())}),YE=wt(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),ZE=r=>{const e=r.sqrt();return E(1).add(e).div(E(1).sub(e))},Ug=(r,e)=>r.sub(e).div(r.add(e)).pow2(),QE=(r,e)=>{const t=r.mul(2*Math.PI*1e-9),s=E(54856e-17,44201e-17,52481e-17),i=E(1681e3,1795300,2208400),n=E(43278e5,93046e5,66121e5),a=T(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(t.mul(2239900).add(e.x).cos()).mul(t.pow2().mul(-45282e5).exp());let o=s.mul(n.mul(2*Math.PI).sqrt()).mul(i.mul(t).add(e).cos()).mul(t.pow2().negate().mul(n).exp());return o=E(o.x.add(a),o.y,o.z).div(10685e-11),YE.mul(o)},Vg=R(({outsideIOR:r,eta2:e,cosTheta1:t,thinFilmThickness:s,baseF0:i})=>{const n=ye(r,e,ti(0,.03,s)),o=r.div(n).pow2().mul(t.pow2().oneMinus()).oneMinus();ne(o.lessThan(0),()=>E(1));const l=o.sqrt(),c=Ug(n,r),u=La({f0:c,f90:1,dotVH:t}),h=u.oneMinus(),d=n.lessThan(r).select(Math.PI,0),p=T(Math.PI).sub(d),f=ZE(i.clamp(0,.9999)),m=Ug(f,n.toVec3()),x=La({f0:m,f90:1,dotVH:l}),y=E(f.x.lessThan(n).select(Math.PI,0),f.y.lessThan(n).select(Math.PI,0),f.z.lessThan(n).select(Math.PI,0)),b=n.mul(s,l,2),v=E(p).add(y),S=u.mul(x).clamp(1e-5,.9999),M=S.sqrt(),A=h.pow2().mul(x).div(E(1).sub(S)),P=u.add(A).toVar(),B=A.sub(h).toVar();return Ie({start:1,end:2,condition:"<=",name:"m"},({m:V})=>{B.mulAssign(M);const Y=QE(T(V).mul(b),T(V).mul(v)).mul(2);P.addAssign(B.mul(Y))}),P.max(E(0))}).setLayout({name:"evalIridescence",type:"vec3",inputs:[{name:"outsideIOR",type:"float"},{name:"eta2",type:"float"},{name:"cosTheta1",type:"float"},{name:"thinFilmThickness",type:"float"},{name:"baseF0",type:"vec3"}]}),Ya=R(({normal:r,viewDir:e,roughness:t})=>{const s=r.dot(e).saturate(),i=t.mul(t),n=t.add(.1).reciprocal(),a=T(-1.9362).add(t.mul(1.0678)).add(i.mul(.4573)).sub(n.mul(.8469)),o=T(-.6014).add(t.mul(.5538)).sub(i.mul(.467)).sub(n.mul(.1255));return a.mul(s).add(o).exp().saturate()}),Za=E(.04),kl=T(1);class _T extends nh{constructor(e=!1,t=!1,s=!1,i=!1,n=!1,a=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=s,this.anisotropy=i,this.transmission=n,this.dispersion=a,this.clearcoatRadiance=null,this.clearcoatSpecularDirect=null,this.clearcoatSpecularIndirect=null,this.sheenSpecularDirect=null,this.sheenSpecularIndirect=null,this.iridescenceFresnel=null,this.iridescenceF0=null,this.iridescenceF0Dielectric=null,this.iridescenceF0Metallic=null}start(e){if(this.clearcoat===!0&&(this.clearcoatRadiance=E().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=E().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=E().toVar("clearcoatSpecularIndirect")),this.sheen===!0&&(this.sheenSpecularDirect=E().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=E().toVar("sheenSpecularIndirect")),this.iridescence===!0){const t=Me.dot(Ge).clamp(),s=Vg({outsideIOR:T(1),eta2:uu,cosTheta1:t,thinFilmThickness:hu,baseF0:kn}),i=Vg({outsideIOR:T(1),eta2:uu,cosTheta1:t,thinFilmThickness:hu,baseF0:Oe.rgb});this.iridescenceFresnel=ye(s,i,ji),this.iridescenceF0Dielectric=Tp({f:s,f90:1,dotVH:t}),this.iridescenceF0Metallic=Tp({f:i,f90:1,dotVH:t}),this.iridescenceF0=ye(this.iridescenceF0Dielectric,this.iridescenceF0Metallic,ji)}if(this.transmission===!0){const t=Ai,s=G_.sub(Ai).normalize(),i=jn,n=e.context;n.backdrop=XE(i,s,yi,ur,fr,mr,t,Ps,Gs,en,Bo,mf,yf,gf,this.dispersion?xf:null),n.backdropAlpha=fu,Oe.a.mulAssign(ye(1,n.backdrop.a,fu))}super.start(e)}computeMultiscattering(e,t,s,i,n=null){const a=Me.dot(Ge).clamp(),o=Xo({roughness:yi,dotNV:a}),l=n?Hu.mix(i,n):i,c=l.mul(o.x).add(s.mul(o.y)),h=o.x.add(o.y).oneMinus(),d=l.add(l.oneMinus().mul(.047619)),p=c.mul(d).div(h.mul(d).oneMinus());e.addAssign(c),t.addAssign(p.mul(h))}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const n=Me.dot(e).clamp().mul(t).toVar();if(this.sheen===!0){this.sheenSpecularDirect.addAssign(n.mul(GE({lightDirection:e})));const a=Ya({normal:Me,viewDir:Ge,roughness:Mn}),o=Ya({normal:Me,viewDir:e,roughness:Mn}),l=hs.r.max(hs.g).max(hs.b).mul(a.max(o)).oneMinus();n.mulAssign(l)}if(this.clearcoat===!0){const o=An.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(o.mul(dm({lightDirection:e,f0:Za,f90:kl,roughness:ba,normalView:An})))}s.directDiffuse.addAssign(n.mul(Sr({diffuseColor:ur}))),s.directSpecular.addAssign(n.mul(VE({lightDirection:e,f0:fr,f90:1,roughness:yi,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy})))}directRectArea({lightColor:e,lightPosition:t,halfWidth:s,halfHeight:i,reflectedLight:n,ltc_1:a,ltc_2:o}){const l=t.add(s).sub(i),c=t.sub(s).sub(i),u=t.sub(s).add(i),h=t.add(s).add(i),d=Me,p=Ge,f=lt.toVar(),m=Ng({N:d,V:p,roughness:yi}),x=a.sample(m).toVar(),y=o.sample(m).toVar(),b=wt(E(x.x,0,x.y),E(0,1,0),E(x.z,0,x.w)).toVar(),v=fr.mul(y.x).add(mr.sub(fr).mul(y.y)).toVar();if(n.directSpecular.addAssign(e.mul(v).mul(sd({N:d,V:p,P:f,mInv:b,p0:l,p1:c,p2:u,p3:h}))),n.directDiffuse.addAssign(e.mul(ur).mul(sd({N:d,V:p,P:f,mInv:wt(1,0,0,0,1,0,0,0,1),p0:l,p1:c,p2:u,p3:h}))),this.clearcoat===!0){const S=An,M=Ng({N:S,V:p,roughness:ba}),A=a.sample(M),C=o.sample(M),P=wt(E(A.x,0,A.y),E(0,1,0),E(A.z,0,A.w)),B=Za.mul(C.x).add(kl.sub(Za).mul(C.y));this.clearcoatSpecularDirect.addAssign(e.mul(B).mul(sd({N:S,V:p,P:f,mInv:P,p0:l,p1:c,p2:u,p3:h})))}}indirect(e){this.indirectDiffuse(e),this.indirectSpecular(e),this.ambientOcclusion(e)}indirectDiffuse(e){const{irradiance:t,reflectedLight:s}=e.context,i=t.mul(Sr({diffuseColor:ur})).toVar();if(this.sheen===!0){const n=Ya({normal:Me,viewDir:Ge,roughness:Mn}),a=hs.r.max(hs.g).max(hs.b).mul(n).oneMinus();i.mulAssign(a)}s.indirectDiffuse.addAssign(i)}indirectSpecular(e){const{radiance:t,iblIrradiance:s,reflectedLight:i}=e.context;if(this.sheen===!0&&this.sheenSpecularIndirect.addAssign(s.mul(hs,Ya({normal:Me,viewDir:Ge,roughness:Mn}))),this.clearcoat===!0){const x=An.dot(Ge).clamp(),y=gT({dotNV:x,specularColor:Za,specularF90:kl,roughness:ba});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(y))}const n=E().toVar("singleScatteringDielectric"),a=E().toVar("multiScatteringDielectric"),o=E().toVar("singleScatteringMetallic"),l=E().toVar("multiScatteringMetallic");this.computeMultiscattering(n,a,mr,kn,this.iridescenceF0Dielectric),this.computeMultiscattering(o,l,mr,Oe.rgb,this.iridescenceF0Metallic);const c=ye(n,o,ji),u=ye(a,l,ji),h=n.add(a),d=ur.mul(h.oneMinus()),p=s.mul(1/Math.PI),f=t.mul(c).add(u.mul(p)).toVar(),m=d.mul(p).toVar();if(this.sheen===!0){const x=Ya({normal:Me,viewDir:Ge,roughness:Mn}),y=hs.r.max(hs.g).max(hs.b).mul(x).oneMinus();f.mulAssign(y),m.mulAssign(y)}i.indirectSpecular.addAssign(f),i.indirectDiffuse.addAssign(m)}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:s}=e.context,n=Me.dot(Ge).clamp().add(t),a=yi.mul(-16).oneMinus().negate().exp2(),o=t.sub(n.pow(a).oneMinus()).clamp();this.clearcoat===!0&&this.clearcoatSpecularIndirect.mulAssign(t),this.sheen===!0&&this.sheenSpecularIndirect.mulAssign(t),s.indirectDiffuse.mulAssign(t),s.indirectSpecular.mulAssign(o)}finish({context:e}){const{outgoingLight:t}=e;if(this.clearcoat===!0){const s=An.dot(Ge).clamp(),i=La({dotVH:s,f0:Za,f90:kl}),n=t.mul(cu.mul(i).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(cu));t.assign(n)}if(this.sheen===!0){const s=t.add(this.sheenSpecularDirect,this.sheenSpecularIndirect.mul(1/Math.PI));t.assign(s)}}}const kg=T(1),Mp=T(-2),zl=T(.8),id=T(-1),Gl=T(.4),nd=T(2),$l=T(.305),rd=T(3),zg=T(.21),KE=T(4),Gg=T(4),JE=T(16),eN=R(([r])=>{const e=E(We(r)).toVar(),t=T(-1).toVar();return ne(e.x.greaterThan(e.z),()=>{ne(e.x.greaterThan(e.y),()=>{t.assign(Vt(r.x.greaterThan(0),0,3))}).Else(()=>{t.assign(Vt(r.y.greaterThan(0),1,4))})}).Else(()=>{ne(e.z.greaterThan(e.y),()=>{t.assign(Vt(r.z.greaterThan(0),2,5))}).Else(()=>{t.assign(Vt(r.y.greaterThan(0),1,4))})}),t}).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),tN=R(([r,e])=>{const t=z().toVar();return ne(e.equal(0),()=>{t.assign(z(r.z,r.y).div(We(r.x)))}).ElseIf(e.equal(1),()=>{t.assign(z(r.x.negate(),r.z.negate()).div(We(r.y)))}).ElseIf(e.equal(2),()=>{t.assign(z(r.x.negate(),r.y).div(We(r.z)))}).ElseIf(e.equal(3),()=>{t.assign(z(r.z.negate(),r.y).div(We(r.x)))}).ElseIf(e.equal(4),()=>{t.assign(z(r.x.negate(),r.z).div(We(r.y)))}).Else(()=>{t.assign(z(r.x,r.y).div(We(r.z)))}),ae(.5,t.add(1))}).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),sN=R(([r])=>{const e=T(0).toVar();return ne(r.greaterThanEqual(zl),()=>{e.assign(kg.sub(r).mul(id.sub(Mp)).div(kg.sub(zl)).add(Mp))}).ElseIf(r.greaterThanEqual(Gl),()=>{e.assign(zl.sub(r).mul(nd.sub(id)).div(zl.sub(Gl)).add(id))}).ElseIf(r.greaterThanEqual($l),()=>{e.assign(Gl.sub(r).mul(rd.sub(nd)).div(Gl.sub($l)).add(nd))}).ElseIf(r.greaterThanEqual(zg),()=>{e.assign($l.sub(r).mul(KE.sub(rd)).div($l.sub(zg)).add(rd))}).Else(()=>{e.assign(T(-2).mul(vi(ae(1.16,r))))}),e}).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),bT=R(([r,e])=>{const t=r.toVar();t.assign(ae(2,t).sub(1));const s=E(t,1).toVar();return ne(e.equal(0),()=>{s.assign(s.zyx)}).ElseIf(e.equal(1),()=>{s.assign(s.xzy),s.xz.mulAssign(-1)}).ElseIf(e.equal(2),()=>{s.x.mulAssign(-1)}).ElseIf(e.equal(3),()=>{s.assign(s.zyx),s.xz.mulAssign(-1)}).ElseIf(e.equal(4),()=>{s.assign(s.xzy),s.xy.mulAssign(-1)}).ElseIf(e.equal(5),()=>{s.z.mulAssign(-1)}),s}).setLayout({name:"getDirection",type:"vec3",inputs:[{name:"uv",type:"vec2"},{name:"face",type:"float"}]}),TT=R(([r,e,t,s,i,n])=>{const a=T(t),o=E(e),l=ei(sN(a),Mp,n),c=Js(l),u=Mi(l),h=E(Yo(r,o,u,s,i,n)).toVar();return ne(c.notEqual(0),()=>{const d=E(Yo(r,o,u.add(1),s,i,n)).toVar();h.assign(ye(h,d,c))}),h}),Yo=R(([r,e,t,s,i,n])=>{const a=T(t).toVar(),o=E(e),l=T(eN(o)).toVar(),c=T(tt(Gg.sub(a),0)).toVar();a.assign(tt(a,Gg));const u=T(Pa(a)).toVar(),h=z(tN(o,l).mul(u.sub(2)).add(1)).toVar();return ne(l.greaterThan(2),()=>{h.y.addAssign(u),l.subAssign(3)}),h.x.addAssign(l.mul(u)),h.x.addAssign(c.mul(ae(3,JE))),h.y.addAssign(ae(4,Pa(n).sub(u))),h.x.mulAssign(s),h.y.mulAssign(i),r.sample(h).grad(z(),z())}),ad=R(({envMap:r,mipInt:e,outputDirection:t,theta:s,axis:i,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const l=Xs(s),c=t.mul(l).add(i.cross(t).mul(jt(s))).add(i.mul(i.dot(t).mul(l.oneMinus())));return Yo(r,c,e,n,a,o)}),ST=R(({n:r,latitudinal:e,poleAxis:t,outputDirection:s,weights:i,samples:n,dTheta:a,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:h})=>{const d=E(Vt(e,t,tn(t,s))).toVar();ne(d.equal(E(0)),()=>{d.assign(E(s.z,0,s.x.negate()))}),d.assign(is(d));const p=E().toVar();return p.addAssign(i.element(0).mul(ad({theta:0,axis:d,outputDirection:s,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:h}))),Ie({start:w(1),end:r},({i:f})=>{ne(f.greaterThanEqual(n),()=>{Jb()});const m=T(a.mul(T(f))).toVar();p.addAssign(i.element(f).mul(ad({theta:m.mul(-1),axis:d,outputDirection:s,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:h}))),p.addAssign(i.element(f).mul(ad({theta:m,axis:d,outputDirection:s,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:h})))}),ie(p,1)}),iN=R(([r])=>{const e=k(r).toVar();return e.assign(e.shiftLeft(k(16)).bitOr(e.shiftRight(k(16)))),e.assign(e.bitAnd(k(1431655765)).shiftLeft(k(1)).bitOr(e.bitAnd(k(2863311530)).shiftRight(k(1)))),e.assign(e.bitAnd(k(858993459)).shiftLeft(k(2)).bitOr(e.bitAnd(k(3435973836)).shiftRight(k(2)))),e.assign(e.bitAnd(k(252645135)).shiftLeft(k(4)).bitOr(e.bitAnd(k(4042322160)).shiftRight(k(4)))),e.assign(e.bitAnd(k(16711935)).shiftLeft(k(8)).bitOr(e.bitAnd(k(4278255360)).shiftRight(k(8)))),T(e).mul(23283064365386963e-26)}),nN=R(([r,e])=>z(T(r).div(T(e)),iN(r))),rN=R(([r,e,t])=>{const s=t.mul(t).toConst(),i=E(1,0,0).toConst(),n=tn(e,i).toConst(),a=Zt(r.x).toConst(),o=ae(2,3.14159265359).mul(r.y).toConst(),l=a.mul(Xs(o)).toConst(),c=a.mul(jt(o)).toVar(),u=ae(.5,e.z.add(1)).toConst();c.assign(u.oneMinus().mul(Zt(l.mul(l).oneMinus())).add(u.mul(c)));const h=i.mul(l).add(n.mul(c)).add(e.mul(Zt(tt(0,l.mul(l).add(c.mul(c)).oneMinus()))));return is(E(s.mul(h.x),s.mul(h.y),tt(0,h.z)))}),vT=R(({roughness:r,mipInt:e,envMap:t,N_immutable:s,GGX_SAMPLES:i,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const l=E(s).toVar(),c=E(0).toVar(),u=T(0).toVar();return ne(r.lessThan(.001),()=>{c.assign(Yo(t,l,e,n,a,o))}).Else(()=>{const h=Vt(We(l.z).lessThan(.999),E(0,0,1),E(1,0,0)),d=is(tn(h,l)).toVar(),p=tn(l,d).toVar();Ie({start:k(0),end:i},({i:f})=>{const m=nN(f,i),x=rN(m,E(0,0,1),r),y=is(d.mul(x.x).add(p.mul(x.y)).add(l.mul(x.z))),b=is(y.mul(Vs(l,y).mul(2)).sub(l)),v=tt(Vs(l,b),0);ne(v.greaterThan(0),()=>{const S=Yo(t,b,e,n,a,o);c.addAssign(S.mul(v)),u.addAssign(v)})}),ne(u.greaterThan(0),()=>{c.assign(c.div(u))})}),ie(c,1)}),Rn=4,$g=[.125,.215,.35,.446,.526,.582],hr=20,aN=512,Qa=new tf(-1,1,1,-1,0,1),oN=new fs(90,1),Wg=new Ne;let od=null,ld=0,cd=0;const lN=new D,xu=new WeakMap,cN=[3,1,5,0,4,2],ud=bT(ze(),sn("faceIndex")).normalize(),ah=E(ud.x,ud.y,ud.z);class uN{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._blurMaterial=null,this._ggxMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._backgroundBox=null}get _hasInitialized(){return this._renderer.hasInitialized()}fromScene(e,t=0,s=.1,i=100,n={}){const{size:a=256,position:o=lN,renderTarget:l=null}=n;if(this._setSize(a),this._hasInitialized===!1){W('PMREMGenerator: ".fromScene()" called before the backend is initialized. Try using "await renderer.init()" instead.');const u=l||this._allocateTarget();return n.renderTarget=u,this.fromSceneAsync(e,t,s,i,n),u}od=this._renderer.getRenderTarget(),ld=this._renderer.getActiveCubeFace(),cd=this._renderer.getActiveMipmapLevel();const c=l||this._allocateTarget();return c.depthBuffer=!0,this._init(c),this._sceneToCubeUV(e,s,i,c,o),t>0&&this._blur(c,0,0,t),this._applyPMREM(c),this._cleanup(c),c}async fromSceneAsync(e,t=0,s=.1,i=100,n={}){return Le('PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this.fromScene(e,t,s,i,n)}fromEquirectangular(e,t=null){if(this._hasInitialized===!1){W('PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using "await renderer.init()" instead.'),this._setSizeFromTexture(e);const s=t||this._allocateTarget();return this.fromEquirectangularAsync(e,s),s}return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return Le('PMREMGenerator: ".fromEquirectangularAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}fromCubemap(e,t=null){if(this._hasInitialized===!1){W("PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead."),this._setSizeFromTexture(e);const s=t||this._allocateTarget();return this.fromCubemapAsync(e,t),s}return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return Le('PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=jg(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=qg(),await this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSizeFromTexture(e){e.mapping===Ca||e.mapping===Dc?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4)}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodMeshes.length;e++)this._lodMeshes[e].geometry.dispose()}_cleanup(e){this._renderer.setRenderTarget(od,ld,cd),e.scissorTest=!1,Xr(e,0,0,e.width,e.height)}_fromTexture(e,t){this._setSizeFromTexture(e),od=this._renderer.getRenderTarget(),ld=this._renderer.getActiveCubeFace(),cd=this._renderer.getActiveMipmapLevel();const s=t||this._allocateTarget();return this._init(s),this._textureToCubeUV(e,s),this._applyPMREM(s),this._cleanup(s),s}_allocateTarget(){const e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize;return Hg(e,t)}_init(e){if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e.width||this._pingPongRenderTarget.height!==e.height){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=Hg(e.width,e.height);const{_lodMax:t}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=hN(t)),this._blurMaterial=dN(t,e.width,e.height),this._ggxMaterial=pN(t,e.width,e.height)}}async _compileMaterial(e){const t=new Un(new Bi,e);await this._renderer.compile(t,Qa)}_sceneToCubeUV(e,t,s,i,n){const a=oN;a.near=t,a.far=s;const o=[1,1,1,1,-1,1],l=[1,-1,1,-1,1,-1],c=this._renderer,u=c.autoClear;c.getClearColor(Wg),c.autoClear=!1,this._backgroundBox===null&&(this._backgroundBox=new Un(new Uu,new vn({name:"PMREM.Background",side:Rt,depthWrite:!1,depthTest:!1})));const h=this._backgroundBox,d=h.material;let p=!1;const f=e.background;f?f.isColor&&(d.color.copy(f),e.background=null,p=!0):(d.color.copy(Wg),p=!0),c.setRenderTarget(i),c.clear(),p&&c.render(h,a);for(let m=0;m<6;m++){const x=m%3;x===0?(a.up.set(0,o[m],0),a.position.set(n.x,n.y,n.z),a.lookAt(n.x+l[m],n.y,n.z)):x===1?(a.up.set(0,0,o[m]),a.position.set(n.x,n.y,n.z),a.lookAt(n.x,n.y+l[m],n.z)):(a.up.set(0,o[m],0),a.position.set(n.x,n.y,n.z),a.lookAt(n.x,n.y,n.z+l[m]));const y=this._cubeSize;Xr(i,x*y,m>2?y:0,y,y),c.render(e,a)}c.autoClear=u,e.background=f}_textureToCubeUV(e,t){const s=this._renderer,i=e.mapping===Ca||e.mapping===Dc;i?this._cubemapMaterial===null&&(this._cubemapMaterial=jg(e)):this._equirectMaterial===null&&(this._equirectMaterial=qg(e));const n=i?this._cubemapMaterial:this._equirectMaterial;n.fragmentNode.value=e;const a=this._lodMeshes[0];a.material=n;const o=this._cubeSize;Xr(t,0,0,3*o,2*o),s.setRenderTarget(t),s.render(a,Qa)}_applyPMREM(e){const t=this._renderer,s=t.autoClear;t.autoClear=!1;const i=this._lodMeshes.length;for(let n=1;n<i;n++)this._applyGGXFilter(e,n-1,n);t.autoClear=s}_applyGGXFilter(e,t,s){const i=this._renderer,n=this._pingPongRenderTarget,a=this._ggxMaterial,o=this._lodMeshes[s];o.material=a;const l=xu.get(a),c=s/(this._lodMeshes.length-1),u=t/(this._lodMeshes.length-1),h=Math.sqrt(c*c-u*u),d=0+c*1.25,p=h*d,{_lodMax:f}=this,m=this._sizeLods[s],x=3*m*(s>f-Rn?s-f+Rn:0),y=4*(this._cubeSize-m);e.texture.frame=(e.texture.frame||0)+1,l.envMap.value=e.texture,l.roughness.value=p,l.mipInt.value=f-t,Xr(n,x,y,3*m,2*m),i.setRenderTarget(n),i.render(o,Qa),n.texture.frame=(n.texture.frame||0)+1,l.envMap.value=n.texture,l.roughness.value=0,l.mipInt.value=f-s,Xr(e,x,y,3*m,2*m),i.setRenderTarget(e),i.render(o,Qa)}_blur(e,t,s,i,n){const a=this._pingPongRenderTarget;this._halfBlur(e,a,t,s,i,"latitudinal",n),this._halfBlur(a,e,s,s,i,"longitudinal",n)}_halfBlur(e,t,s,i,n,a,o){const l=this._renderer,c=this._blurMaterial;a!=="latitudinal"&&a!=="longitudinal"&&$("blur direction must be either latitudinal or longitudinal!");const u=3,h=this._lodMeshes[i];h.material=c;const d=xu.get(c),p=this._sizeLods[s]-1,f=isFinite(n)?Math.PI/(2*p):2*Math.PI/(2*hr-1),m=n/f,x=isFinite(n)?1+Math.floor(u*m):hr;x>hr&&W(`sigmaRadians, ${n}, is too large and will clip, as it requested ${x} samples when the maximum is set to ${hr}`);const y=[];let b=0;for(let C=0;C<hr;++C){const P=C/m,B=Math.exp(-P*P/2);y.push(B),C===0?b+=B:C<x&&(b+=2*B)}for(let C=0;C<y.length;C++)y[C]=y[C]/b;e.texture.frame=(e.texture.frame||0)+1,d.envMap.value=e.texture,d.samples.value=x,d.weights.array=y,d.latitudinal.value=a==="latitudinal"?1:0,o&&(d.poleAxis.value=o);const{_lodMax:v}=this;d.dTheta.value=f,d.mipInt.value=v-s;const S=this._sizeLods[i],M=3*S*(i>v-Rn?i-v+Rn:0),A=4*(this._cubeSize-S);Xr(t,M,A,3*S,2*S),l.setRenderTarget(t),l.render(h,Qa)}}function hN(r){const e=[],t=[],s=[];let i=r;const n=r-Rn+1+$g.length;for(let a=0;a<n;a++){const o=Math.pow(2,i);e.push(o);let l=1/o;a>r-Rn?l=$g[a-r+Rn-1]:a===0&&(l=0),t.push(l);const c=1/(o-2),u=-c,h=1+c,d=[u,u,h,u,h,h,u,u,h,h,u,h],p=6,f=6,m=3,x=2,y=1,b=new Float32Array(m*f*p),v=new Float32Array(x*f*p),S=new Float32Array(y*f*p);for(let A=0;A<p;A++){const C=A%3*2/3-1,P=A>2?0:-1,B=[C,P,0,C+2/3,P,0,C+2/3,P+1,0,C,P,0,C+2/3,P+1,0,C,P+1,0],V=cN[A];b.set(B,m*f*V),v.set(d,x*f*V);const Y=[V,V,V,V,V,V];S.set(Y,y*f*V)}const M=new Bi;M.setAttribute("position",new ys(b,m)),M.setAttribute("uv",new ys(v,x)),M.setAttribute("faceIndex",new ys(S,y)),s.push(new Un(M,null)),i>Rn&&i--}return{lodMeshes:s,sizeLods:e,sigmas:t}}function Hg(r,e){const t={magFilter:Gt,minFilter:Gt,generateMipmaps:!1,type:Et,format:ms,colorSpace:ru},s=new nn(r,e,t);return s.texture.mapping=Qd,s.texture.name="PMREM.cubeUv",s.texture.isPMREMTexture=!0,s.scissorTest=!0,s}function Xr(r,e,t,s,i){r.viewport.set(e,t,s,i),r.scissor.set(e,t,s,i)}function oh(r){const e=new st;return e.depthTest=!1,e.depthWrite=!1,e.blending=Xi,e.name=`PMREM_${r}`,e}function dN(r,e,t){const s=It(new Array(hr).fill(0)),i=ee(new D(0,1,0)),n=ee(0),a=T(hr),o=ee(0),l=ee(1),c=we(),u=ee(0),h=T(1/e),d=T(1/t),p=T(r),f={n:a,latitudinal:o,weights:s,poleAxis:i,outputDirection:ah,dTheta:n,samples:l,envMap:c,mipInt:u,CUBEUV_TEXEL_WIDTH:h,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:p},m=oh("blur");return m.fragmentNode=ST({...f,latitudinal:o.equal(1)}),xu.set(m,f),m}function pN(r,e,t){const s=we(),i=ee(0),n=ee(0),a=T(1/e),o=T(1/t),l=T(r),c={envMap:s,roughness:i,mipInt:n,CUBEUV_TEXEL_WIDTH:a,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:l},u=oh("ggx");return u.fragmentNode=vT({...c,N_immutable:ah,GGX_SAMPLES:k(aN)}),xu.set(u,c),u}function jg(r){const e=oh("cubemap");return e.fragmentNode=Xt(r,ah),e}function qg(r){const e=oh("equirect");return e.fragmentNode=we(r,lm(ah),0),e}const Xg=new WeakMap;function fN(r){const e=Math.log2(r)-2,t=1/r;return{texelWidth:1/(3*Math.max(Math.pow(2,e),7*16)),texelHeight:t,maxMip:e}}function mN(r,e,t){const s=gN(e);let i=s.get(r);if((i!==void 0?i.pmremVersion:-1)!==r.pmremVersion){const a=r.image;if(r.isCubeTexture)if(xN(a))i=t.fromCubemap(r,i);else return null;else if(_N(a))i=t.fromEquirectangular(r,i);else return null;i.pmremVersion=r.pmremVersion,s.set(r,i)}return i.texture}function gN(r){let e=Xg.get(r);return e===void 0&&(e=new WeakMap,Xg.set(r,e)),e}class yN extends ot{static get type(){return"PMREMNode"}constructor(e,t=null,s=null){super("vec3"),this._value=e,this._pmrem=null,this.uvNode=t,this.levelNode=s,this._generator=null;const i=new kt;i.isRenderTargetTexture=!0,this._texture=we(i),this._width=ee(0),this._height=ee(0),this._maxMip=ee(0),this.updateBeforeType=re.RENDER}set value(e){this._value=e,this._pmrem=null}get value(){return this._value}updateFromTexture(e){const t=fN(e.image.height);this._texture.value=e,this._width.value=t.texelWidth,this._height.value=t.texelHeight,this._maxMip.value=t.maxMip}updateBefore(e){let t=this._pmrem;const s=t?t.pmremVersion:-1,i=this._value;s!==i.pmremVersion&&(i.isPMREMTexture===!0?t=i:t=mN(i,e.renderer,this._generator),t!==null&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){this._generator===null&&(this._generator=new uN(e.renderer)),this.updateBefore(e);let t=this.uvNode;t===null&&e.context.getUV&&(t=e.context.getUV(this,e)),t=Qf.mul(E(t.x,t.y.negate(),t.z));let s=this.levelNode;return s===null&&e.context.getTextureLevel&&(s=e.context.getTextureLevel(this)),TT(this._texture,t,s,this._width,this._height,this._maxMip)}dispose(){super.dispose(),this._generator!==null&&this._generator.dispose()}}function xN(r){if(r==null)return!1;let e=0;const t=6;for(let s=0;s<t;s++)r[s]!==void 0&&e++;return e===t}function _N(r){return r==null?!1:r.height>0}const fm=ue(yN).setParameterLength(1,3),Yg=new WeakMap;class bN extends Va{static get type(){return"EnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){const{material:t}=e;let s=this.envNode;if(s.isTextureNode||s.isMaterialReferenceNode){const h=s.isTextureNode?s.value:t[s.property],d=this._getPMREMNodeCache(e.renderer);let p=d.get(h);p===void 0&&(p=fm(h),d.set(h,p)),s=p}const n=t.useAnisotropy===!0||t.anisotropy>0?db:Me,a=s.context(Zg(yi,n)).mul(Tc),o=s.context(TN(jn)).mul(Math.PI).mul(Tc),l=Sa(a),c=Sa(o);e.context.radiance.addAssign(l),e.context.iblIrradiance.addAssign(c);const u=e.context.lightingModel.clearcoatRadiance;if(u){const h=s.context(Zg(ba,An)).mul(Tc),d=Sa(h);u.addAssign(d)}}_getPMREMNodeCache(e){let t=Yg.get(e);return t===void 0&&(t=new WeakMap,Yg.set(e,t)),t}}const Zg=(r,e)=>{let t=null;return{getUV:()=>(t===null&&(t=Ge.negate().reflect(e),t=Bf(r).mix(t,e).normalize(),t=t.transformDirection(Gs)),t),getTextureLevel:()=>r}},TN=r=>({getUV:()=>r,getTextureLevel:()=>T(1)}),SN=new e0;class MT extends st{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(SN),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return t===null&&e.environmentNode&&(t=e.environmentNode),t?new bN(t):null}setupLightingModel(){return new _T}setupSpecular(){const e=ye(E(.04),Oe.rgb,ji);kn.assign(E(.04)),fr.assign(e),mr.assign(1)}setupVariants(){const e=this.metalnessNode?T(this.metalnessNode):Tb;ji.assign(e);let t=this.roughnessNode?T(this.roughnessNode):bb;t=hm({roughness:t}),yi.assign(t),this.setupSpecular(),ur.assign(Oe.rgb.mul(e.oneMinus()))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const vN=new uC;class MN extends MT{static get type(){return"MeshPhysicalNodeMaterial"}constructor(e){super(),this.isMeshPhysicalNodeMaterial=!0,this.clearcoatNode=null,this.clearcoatRoughnessNode=null,this.clearcoatNormalNode=null,this.sheenNode=null,this.sheenRoughnessNode=null,this.iridescenceNode=null,this.iridescenceIORNode=null,this.iridescenceThicknessNode=null,this.specularIntensityNode=null,this.specularColorNode=null,this.iorNode=null,this.transmissionNode=null,this.thicknessNode=null,this.attenuationDistanceNode=null,this.attenuationColorNode=null,this.dispersionNode=null,this.anisotropyNode=null,this.setDefaultValues(vN),this.setValues(e)}get useClearcoat(){return this.clearcoat>0||this.clearcoatNode!==null}get useIridescence(){return this.iridescence>0||this.iridescenceNode!==null}get useSheen(){return this.sheen>0||this.sheenNode!==null}get useAnisotropy(){return this.anisotropy>0||this.anisotropyNode!==null}get useTransmission(){return this.transmission>0||this.transmissionNode!==null}get useDispersion(){return this.dispersion>0||this.dispersionNode!==null}setupSpecular(){const e=this.iorNode?T(this.iorNode):Ob;Bo.assign(e),kn.assign(ns(Ff(Bo.sub(1).div(Bo.add(1))).mul(_b),E(1)).mul(bp)),fr.assign(ye(kn,Oe.rgb,ji)),mr.assign(ye(bp,1,ji))}setupLightingModel(){return new _T(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const t=this.clearcoatNode?T(this.clearcoatNode):vb,s=this.clearcoatRoughnessNode?T(this.clearcoatRoughnessNode):Mb;cu.assign(t),ba.assign(hm({roughness:s}))}if(this.useSheen){const t=this.sheenNode?E(this.sheenNode):Ab,s=this.sheenRoughnessNode?T(this.sheenRoughnessNode):Eb;hs.assign(t),Mn.assign(s)}if(this.useIridescence){const t=this.iridescenceNode?T(this.iridescenceNode):Rb,s=this.iridescenceIORNode?T(this.iridescenceIORNode):Pb,i=this.iridescenceThicknessNode?T(this.iridescenceThicknessNode):Fb;Hu.assign(t),uu.assign(s),hu.assign(i)}if(this.useAnisotropy){const t=(this.anisotropyNode?z(this.anisotropyNode):Nb).toVar();Sn.assign(t.length()),ne(Sn.equal(0),()=>{t.assign(z(1,0))}).Else(()=>{t.divAssign(z(Sn)),Sn.assign(Sn.saturate())}),du.assign(Sn.pow2().mix(yi.pow2(),1)),Fo.assign(gr[0].mul(t.x).add(gr[1].mul(t.y))),_r.assign(gr[1].mul(t.x).sub(gr[0].mul(t.y)))}if(this.useTransmission){const t=this.transmissionNode?T(this.transmissionNode):Bb,s=this.thicknessNode?T(this.thicknessNode):Db,i=this.attenuationDistanceNode?T(this.attenuationDistanceNode):Lb,n=this.attenuationColorNode?E(this.attenuationColorNode):Ib;if(fu.assign(t),mf.assign(s),gf.assign(i),yf.assign(n),this.useDispersion){const a=this.dispersionNode?T(this.dispersionNode):$b;xf.assign(a)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?E(this.clearcoatNormalNode):wb}setup(e){e.context.setupClearcoatNormal=()=>br(this.setupClearcoatNormal(e),"NORMAL","vec3"),super.setup(e)}copy(e){return this.clearcoatNode=e.clearcoatNode,this.clearcoatRoughnessNode=e.clearcoatRoughnessNode,this.clearcoatNormalNode=e.clearcoatNormalNode,this.sheenNode=e.sheenNode,this.sheenRoughnessNode=e.sheenRoughnessNode,this.iridescenceNode=e.iridescenceNode,this.iridescenceIORNode=e.iridescenceIORNode,this.iridescenceThicknessNode=e.iridescenceThicknessNode,this.specularIntensityNode=e.specularIntensityNode,this.specularColorNode=e.specularColorNode,this.iorNode=e.iorNode,this.transmissionNode=e.transmissionNode,this.thicknessNode=e.thicknessNode,this.attenuationDistanceNode=e.attenuationDistanceNode,this.attenuationColorNode=e.attenuationColorNode,this.dispersionNode=e.dispersionNode,this.anisotropyNode=e.anisotropyNode,super.copy(e)}}const wN=R(({normal:r,lightDirection:e,builder:t})=>{const s=r.dot(e),i=z(s.mul(.5).add(.5),0);if(t.material.gradientMap){const n=Wi("gradientMap","texture").context({getUV:()=>i});return E(n.r)}else{const n=i.fwidth().mul(.5);return ye(E(.7),E(1),ti(T(.7).sub(n.x),T(.7).add(n.x),i.x))}});class CN extends nh{direct({lightDirection:e,lightColor:t,reflectedLight:s},i){const n=wN({normal:Ku,lightDirection:e,builder:i}).mul(t);s.directDiffuse.addAssign(n.mul(Sr({diffuseColor:Oe.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:s,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(s.mul(Sr({diffuseColor:Oe}))),i.indirectDiffuse.mulAssign(t)}}const AN=new dC;class EN extends st{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(AN),this.setValues(e)}setupLightingModel(){return new CN}}const wT=R(()=>{const r=E(Ge.z,0,Ge.x.negate()).normalize(),e=Ge.cross(r);return z(r.dot(Me),e.dot(Me)).mul(.495).add(.5)}).once(["NORMAL","VERTEX"])().toVar("matcapUV"),NN=new mC;class RN extends st{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(NN),this.setValues(e)}setupVariants(e){const t=wT;let s;e.material.matcap?s=Wi("matcap","texture").context({getUV:()=>t}):s=E(ye(.2,.8,t.y)),Oe.rgb.mulAssign(s.rgb)}}class PN extends ot{static get type(){return"RotateNode"}constructor(e,t){super(),this.positionNode=e,this.rotationNode=t}getNodeType(e){return this.positionNode.getNodeType(e)}setup(e){const{rotationNode:t,positionNode:s}=this;if(this.getNodeType(e)==="vec2"){const n=t.cos(),a=t.sin();return Wu(n,a,a.negate(),n).mul(s)}else{const n=t,a=Dn(ie(1,0,0,0),ie(0,Xs(n.x),jt(n.x).negate(),0),ie(0,jt(n.x),Xs(n.x),0),ie(0,0,0,1)),o=Dn(ie(Xs(n.y),0,jt(n.y),0),ie(0,1,0,0),ie(jt(n.y).negate(),0,Xs(n.y),0),ie(0,0,0,1)),l=Dn(ie(Xs(n.z),jt(n.z).negate(),0,0),ie(jt(n.z),Xs(n.z),0,0),ie(0,0,1,0),ie(0,0,0,1));return a.mul(o).mul(l).mul(ie(s,1)).xyz}}}const il=ue(PN).setParameterLength(2),FN=new tC;class CT extends st{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(FN),this.setValues(e)}setupPositionView(e){const{object:t,camera:s}=e,{positionNode:i,rotationNode:n,scaleNode:a,sizeAttenuation:o}=this,l=Hn.mul(E(i||0));let c=z(Ps[0].xyz.length(),Ps[1].xyz.length());a!==null&&(c=c.mul(z(a))),s.isPerspectiveCamera&&o===!1&&(c=c.mul(l.z.negate()));let u=sl.xy;if(t.center&&t.center.isVector2===!0){const p=RA("center","vec2",t);u=u.sub(p.sub(.5))}u=u.mul(c);const h=T(n||Cb),d=il(u,h);return ie(l.xy.add(d),l.zw)}copy(e){return this.positionNode=e.positionNode,this.rotationNode=e.rotationNode,this.scaleNode=e.scaleNode,super.copy(e)}get sizeAttenuation(){return this._useSizeAttenuation}set sizeAttenuation(e){this._useSizeAttenuation!==e&&(this._useSizeAttenuation=e,this.needsUpdate=!0)}}const BN=new oC,DN=new xe;class ON extends CT{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(BN),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return Hn.mul(E(e||Je)).xyz}setupVertexSprite(e){const{material:t,camera:s}=e,{rotationNode:i,scaleNode:n,sizeNode:a,sizeAttenuation:o}=this;let l=super.setupVertex(e);if(t.isNodeMaterial!==!0)return l;let c=a!==null?z(a):Gb;c=c.mul(V_),s.isPerspectiveCamera&&o===!0&&(c=c.mul(LN.div(lt.z.negate()))),n&&n.isNode&&(c=c.mul(z(n)));let u=sl.xy;if(i&&i.isNode){const h=T(i);u=il(u,h)}return u=u.mul(c),u=u.div(qf.div(2)),u=u.mul(l.w),l=l.add(ie(u,0,0)),l}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 LN=ee(1).onFrameUpdate(function({renderer:r}){const e=r.getSize(DN);this.value=.5*e.y});class IN extends nh{constructor(){super(),this.shadowNode=T(1).toVar("shadowMask")}direct({lightNode:e}){e.shadowNode!==null&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){Oe.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(Oe.rgb)}}const UN=new cC;class VN extends st{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(UN),this.setValues(e)}setupLightingModel(){return new IN}}Ji("vec3");Ji("vec3");Ji("vec3");class kN{constructor(e,t,s){this.renderer=e,this.nodes=t,this.info=s,this._context=typeof self<"u"?self:null,this._animationLoop=null,this._requestId=null}start(){const e=(t,s)=>{this._requestId=this._context.requestAnimationFrame(e),this.info.autoReset===!0&&this.info.reset(),this.nodes.nodeFrame.update(),this.info.frame=this.nodes.nodeFrame.frameId,this.renderer._inspector.begin(),this._animationLoop!==null&&this._animationLoop(t,s),this.renderer._inspector.finish()};e()}stop(){this._context.cancelAnimationFrame(this._requestId),this._requestId=null}getAnimationLoop(){return this._animationLoop}setAnimationLoop(e){this._animationLoop=e}getContext(){return this._context}setContext(e){this._context=e}dispose(){this.stop()}}class zn{constructor(){this.weakMaps={}}_getWeakMap(e){const t=e.length;let s=this.weakMaps[t];return s===void 0&&(s=new WeakMap,this.weakMaps[t]=s),s}get(e){let t=this._getWeakMap(e);for(let s=0;s<e.length-1;s++)if(t=t.get(e[s]),t===void 0)return;return t.get(e[e.length-1])}set(e,t){let s=this._getWeakMap(e);for(let i=0;i<e.length-1;i++){const n=e[i];s.has(n)===!1&&s.set(n,new WeakMap),s=s.get(n)}return s.set(e[e.length-1],t),this}delete(e){let t=this._getWeakMap(e);for(let s=0;s<e.length-1;s++)if(t=t.get(e[s]),t===void 0)return!1;return t.delete(e[e.length-1])}}let zN=0;function GN(r){const e=Object.keys(r);let t=Object.getPrototypeOf(r);for(;t;){const s=Object.getOwnPropertyDescriptors(t);for(const i in s)if(s[i]!==void 0){const n=s[i];n&&typeof n.get=="function"&&e.push(i)}t=Object.getPrototypeOf(t)}return e}class $N{constructor(e,t,s,i,n,a,o,l,c,u){this.id=zN++,this._nodes=e,this._geometries=t,this.renderer=s,this.object=i,this.material=n,this.scene=a,this.camera=o,this.lightsNode=l,this.context=c,this.geometry=i.geometry,this.version=n.version,this.drawRange=null,this.attributes=null,this.attributesId=null,this.pipeline=null,this.group=null,this.vertexBuffers=null,this.drawParams=null,this.bundle=null,this.clippingContext=u,this.clippingContextCacheKey=u!==null?u.cacheKey:"",this.initialNodesCacheKey=this.getDynamicCacheKey(),this.initialCacheKey=this.getCacheKey(),this._nodeBuilderState=null,this._bindings=null,this._monitor=null,this.onDispose=null,this.isRenderObject=!0,this.onMaterialDispose=()=>{this.dispose()},this.onGeometryDispose=()=>{this.attributes=null,this.attributesId=null},this.material.addEventListener("dispose",this.onMaterialDispose),this.geometry.addEventListener("dispose",this.onGeometryDispose)}updateClipping(e){this.clippingContext=e}get clippingNeedsUpdate(){return this.clippingContext===null||this.clippingContext.cacheKey===this.clippingContextCacheKey?!1:(this.clippingContextCacheKey=this.clippingContext.cacheKey,!0)}get hardwareClippingPlanes(){return this.material.hardwareClipping===!0?this.clippingContext.unionClippingCount:0}getNodeBuilderState(){return this._nodeBuilderState||(this._nodeBuilderState=this._nodes.getForRender(this))}getMonitor(){return this._monitor||(this._monitor=this.getNodeBuilderState().observer)}getBindings(){return this._bindings||(this._bindings=this.getNodeBuilderState().createBindings())}getBindingGroup(e){for(const t of this.getBindings())if(t.name===e)return t}getIndex(){return this._geometries.getIndex(this)}getIndirect(){return this._geometries.getIndirect(this)}getIndirectOffset(){return this._geometries.getIndirectOffset(this)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}setGeometry(e){this.geometry=e,this.attributes=null,this.attributesId=null}getAttributes(){if(this.attributes!==null)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,s=[],i=new Set,n={};for(const a of e){let o;if(a.node&&a.node.attribute?o=a.node.attribute:(o=t.getAttribute(a.name),n[a.name]=o.id),o===void 0)continue;s.push(o);const l=o.isInterleavedBufferAttribute?o.data:o;i.add(l)}return this.attributes=s,this.attributesId=n,this.vertexBuffers=Array.from(i.values()),s}getVertexBuffers(){return this.vertexBuffers===null&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){const{object:e,material:t,geometry:s,group:i,drawRange:n}=this,a=this.drawParams||(this.drawParams={vertexCount:0,firstVertex:0,instanceCount:0,firstInstance:0}),o=this.getIndex(),l=o!==null;let c=1;if(s.isInstancedBufferGeometry===!0?c=s.instanceCount:e.count!==void 0&&(c=Math.max(0,e.count)),c===0)return null;if(a.instanceCount=c,e.isBatchedMesh===!0)return a;let u=1;t.wireframe===!0&&!e.isPoints&&!e.isLineSegments&&!e.isLine&&!e.isLineLoop&&(u=2);let h=n.start*u,d=(n.start+n.count)*u;i!==null&&(h=Math.max(h,i.start*u),d=Math.min(d,(i.start+i.count)*u));const p=s.attributes.position;let f=1/0;l?f=o.count:p!=null&&(f=p.count),h=Math.max(h,0),d=Math.min(d,f);const m=d-h;return m<0||m===1/0?null:(a.vertexCount=m,a.firstVertex=h,a)}getGeometryCacheKey(){const{geometry:e}=this;let t="";for(const s of Object.keys(e.attributes).sort()){const i=e.attributes[s];t+=s+",",i.data&&(t+=i.data.stride+","),i.offset&&(t+=i.offset+","),i.itemSize&&(t+=i.itemSize+","),i.normalized&&(t+="n,")}for(const s of Object.keys(e.morphAttributes).sort()){const i=e.morphAttributes[s];t+="morph-"+s+",";for(let n=0,a=i.length;n<a;n++){const o=i[n];t+=o.id+","}}return e.index&&(t+="index,"),t}getMaterialCacheKey(){const{object:e,material:t,renderer:s}=this;let i=t.customProgramCacheKey();for(const n of GN(t)){if(/^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test(n))continue;const a=t[n];let o;if(a!==null){const l=typeof a;l==="number"?o=a!==0?"1":"0":l==="object"?(o="{",a.isTexture&&(o+=a.mapping,s.backend.isWebGPUBackend===!0&&(o+=a.magFilter,o+=a.minFilter,o+=a.wrapS,o+=a.wrapT,o+=a.wrapR)),o+="}"):o=String(a)}else o=String(a);i+=o+","}return i+=this.clippingContextCacheKey+",",e.geometry&&(i+=this.getGeometryCacheKey()),e.skeleton&&(i+=e.skeleton.bones.length+","),e.isBatchedMesh&&(i+=e._matricesTexture.uuid+",",e._colorsTexture!==null&&(i+=e._colorsTexture.uuid+",")),(e.isInstancedMesh||e.count>1||Array.isArray(e.morphTargetInfluences))&&(i+=e.uuid+","),i+=this.context.id+",",i+=e.receiveShadow+",",Ia(i)}get needsGeometryUpdate(){if(this.geometry.id!==this.object.geometry.id)return!0;if(this.attributes!==null){const e=this.attributesId;for(const t in e){const s=this.geometry.getAttribute(t);if(s===void 0||e[t]!==s.id)return!0}}return!1}get needsUpdate(){return this.initialNodesCacheKey!==this.getDynamicCacheKey()||this.clippingNeedsUpdate}getDynamicCacheKey(){let e=0;return this.material.isShadowPassMaterial!==!0&&(e=this._nodes.getCacheKey(this.scene,this.lightsNode)),this.camera.isArrayCamera&&(e=Ro(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=Ro(e,1)),e=Ro(e,this.renderer.contextNode.id,this.renderer.contextNode.version),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.geometry.removeEventListener("dispose",this.onGeometryDispose),this.onDispose()}}const ci=[];class WN{constructor(e,t,s,i,n,a){this.renderer=e,this.nodes=t,this.geometries=s,this.pipelines=i,this.bindings=n,this.info=a,this.chainMaps={}}get(e,t,s,i,n,a,o,l){const c=this.getChainMap(l);ci[0]=e,ci[1]=t,ci[2]=a,ci[3]=n;let u=c.get(ci);return u===void 0?(u=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,s,i,n,a,o,l),c.set(ci,u)):(u.camera=i,u.updateClipping(o),u.needsGeometryUpdate&&u.setGeometry(e.geometry),(u.version!==t.version||u.needsUpdate)&&(u.initialCacheKey!==u.getCacheKey()?(u.dispose(),u=this.get(e,t,s,i,n,a,o,l)):u.version=t.version)),ci[0]=null,ci[1]=null,ci[2]=null,ci[3]=null,u}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new zn)}dispose(){this.chainMaps={}}createRenderObject(e,t,s,i,n,a,o,l,c,u,h){const d=this.getChainMap(h),p=new $N(e,t,s,i,n,a,o,l,c,u);return p.onDispose=()=>{this.pipelines.delete(p),this.bindings.deleteForRender(p),this.nodes.delete(p),d.delete(p.getChainArray())},p}}class qn{constructor(){this.data=new WeakMap}get(e){let t=this.data.get(e);return t===void 0&&(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 Fs={VERTEX:1,INDEX:2,STORAGE:3,INDIRECT:4},En=16,HN=211,jN=212;class qN extends qn{constructor(e){super(),this.backend=e}delete(e){const t=super.delete(e);return t!==null&&this.backend.destroyAttribute(e),t}update(e,t){const s=this.get(e);if(s.version===void 0)t===Fs.VERTEX?this.backend.createAttribute(e):t===Fs.INDEX?this.backend.createIndexAttribute(e):t===Fs.STORAGE?this.backend.createStorageAttribute(e):t===Fs.INDIRECT&&this.backend.createIndirectStorageAttribute(e),s.version=this._getBufferAttribute(e).version;else{const i=this._getBufferAttribute(e);(s.version<i.version||i.usage===Wo)&&(this.backend.updateAttribute(e),s.version=i.version)}}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}function AT(r){return r.index!==null?r.index.version:r.attributes.position.version}function ET(r){return r.index!==null?r.index.id:r.attributes.position.id}function Qg(r){const e=[],t=r.index,s=r.attributes.position;if(t!==null){const n=t.array;for(let a=0,o=n.length;a<o;a+=3){const l=n[a+0],c=n[a+1],u=n[a+2];e.push(l,c,c,u,u,l)}}else{const n=s.array;for(let a=0,o=n.length/3-1;a<o;a+=3){const l=a+0,c=a+1,u=a+2;e.push(l,c,c,u,u,l)}}const i=new(s.count>=65535?Yx:Xx)(e,1);return i.version=AT(r),i.__id=ET(r),i}class XN extends qn{constructor(e,t){super(),this.attributes=e,this.info=t,this.wireframes=new WeakMap,this.attributeCall=new WeakMap,this._geometryDisposeListeners=new Map}has(e){const t=e.geometry;return super.has(t)&&this.get(t).initialized===!0}updateForRender(e){this.has(e)===!1&&this.initGeometry(e),this.updateAttributes(e)}initGeometry(e){const t=e.geometry,s=this.get(t);s.initialized=!0,this.info.memory.geometries++;const i=()=>{this.info.memory.geometries--;const n=t.index,a=e.getAttributes();n!==null&&this.attributes.delete(n);for(const l of a)this.attributes.delete(l);const o=this.wireframes.get(t);o!==void 0&&this.attributes.delete(o),t.removeEventListener("dispose",i),this._geometryDisposeListeners.delete(t)};t.addEventListener("dispose",i),this._geometryDisposeListeners.set(t,i)}updateAttributes(e){const t=e.getAttributes();for(const n of t)n.isStorageBufferAttribute||n.isStorageInstancedBufferAttribute?this.updateAttribute(n,Fs.STORAGE):this.updateAttribute(n,Fs.VERTEX);const s=this.getIndex(e);s!==null&&this.updateAttribute(s,Fs.INDEX);const i=e.geometry.indirect;i!==null&&this.updateAttribute(i,Fs.INDIRECT)}updateAttribute(e,t){const s=this.info.render.calls;e.isInterleavedBufferAttribute?this.attributeCall.get(e)===void 0?(this.attributes.update(e,t),this.attributeCall.set(e,s)):this.attributeCall.get(e.data)!==s&&(this.attributes.update(e,t),this.attributeCall.set(e.data,s),this.attributeCall.set(e,s)):this.attributeCall.get(e)!==s&&(this.attributes.update(e,t),this.attributeCall.set(e,s))}getIndirect(e){return e.geometry.indirect}getIndirectOffset(e){return e.geometry.indirectOffset}getIndex(e){const{geometry:t,material:s}=e;let i=t.index;if(s.wireframe===!0){const n=this.wireframes;let a=n.get(t);a===void 0?(a=Qg(t),n.set(t,a)):(a.version!==AT(t)||a.__id!==ET(t))&&(this.attributes.delete(a),a=Qg(t),n.set(t,a)),i=a}return i}dispose(){for(const[e,t]of this._geometryDisposeListeners.entries())e.removeEventListener("dispose",t);this._geometryDisposeListeners.clear()}}class YN{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,frameCalls:0,drawCalls:0,triangles:0,points:0,lines:0,timestamp:0},this.compute={calls:0,frameCalls:0,timestamp:0},this.memory={geometries:0,textures:0}}update(e,t,s){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=s*(t/3):e.isPoints?this.render.points+=s*t:e.isLineSegments?this.render.lines+=s*(t/2):e.isLine?this.render.lines+=s*(t-1):$("WebGPUInfo: Unknown object type.")}reset(){this.render.drawCalls=0,this.render.frameCalls=0,this.compute.frameCalls=0,this.render.triangles=0,this.render.points=0,this.render.lines=0}dispose(){this.reset(),this.calls=0,this.render.calls=0,this.compute.calls=0,this.render.timestamp=0,this.compute.timestamp=0,this.memory.geometries=0,this.memory.textures=0}}class NT{constructor(e){this.cacheKey=e,this.usedTimes=0}}class ZN extends NT{constructor(e,t,s){super(e),this.vertexProgram=t,this.fragmentProgram=s}}class QN extends NT{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let KN=0;class hd{constructor(e,t,s,i=null,n=null){this.id=KN++,this.code=e,this.stage=t,this.name=s,this.transforms=i,this.attributes=n,this.usedTimes=0}}class JN extends qn{constructor(e,t){super(),this.backend=e,this.nodes=t,this.bindings=null,this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}getForCompute(e,t){const{backend:s}=this,i=this.get(e);if(this._needsComputeUpdate(e)){const n=i.pipeline;n&&(n.usedTimes--,n.computeProgram.usedTimes--);const a=this.nodes.getForCompute(e);let o=this.programs.compute.get(a.computeShader);o===void 0&&(n&&n.computeProgram.usedTimes===0&&this._releaseProgram(n.computeProgram),o=new hd(a.computeShader,"compute",e.name,a.transforms,a.nodeAttributes),this.programs.compute.set(a.computeShader,o),s.createProgram(o));const l=this._getComputeCacheKey(e,o);let c=this.caches.get(l);c===void 0&&(n&&n.usedTimes===0&&this._releasePipeline(n),c=this._getComputePipeline(e,o,l,t)),c.usedTimes++,o.usedTimes++,i.version=e.version,i.pipeline=c}return i.pipeline}getForRender(e,t=null){const{backend:s}=this,i=this.get(e);if(this._needsRenderUpdate(e)){const n=i.pipeline;n&&(n.usedTimes--,n.vertexProgram.usedTimes--,n.fragmentProgram.usedTimes--);const a=e.getNodeBuilderState(),o=e.material?e.material.name:"";let l=this.programs.vertex.get(a.vertexShader);l===void 0&&(n&&n.vertexProgram.usedTimes===0&&this._releaseProgram(n.vertexProgram),l=new hd(a.vertexShader,"vertex",o),this.programs.vertex.set(a.vertexShader,l),s.createProgram(l));let c=this.programs.fragment.get(a.fragmentShader);c===void 0&&(n&&n.fragmentProgram.usedTimes===0&&this._releaseProgram(n.fragmentProgram),c=new hd(a.fragmentShader,"fragment",o),this.programs.fragment.set(a.fragmentShader,c),s.createProgram(c));const u=this._getRenderCacheKey(e,l,c);let h=this.caches.get(u);h===void 0?(n&&n.usedTimes===0&&this._releasePipeline(n),h=this._getRenderPipeline(e,l,c,u,t)):e.pipeline=h,h.usedTimes++,l.usedTimes++,c.usedTimes++,i.pipeline=h}return i.pipeline}delete(e){const t=this.get(e).pipeline;return t&&(t.usedTimes--,t.usedTimes===0&&this._releasePipeline(t),t.isComputePipeline?(t.computeProgram.usedTimes--,t.computeProgram.usedTimes===0&&this._releaseProgram(t.computeProgram)):(t.fragmentProgram.usedTimes--,t.vertexProgram.usedTimes--,t.vertexProgram.usedTimes===0&&this._releaseProgram(t.vertexProgram),t.fragmentProgram.usedTimes===0&&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,s,i){s=s||this._getComputeCacheKey(e,t);let n=this.caches.get(s);return n===void 0&&(n=new QN(s,t),this.caches.set(s,n),this.backend.createComputePipeline(n,i)),n}_getRenderPipeline(e,t,s,i,n){i=i||this._getRenderCacheKey(e,t,s);let a=this.caches.get(i);return a===void 0&&(a=new ZN(i,t,s),this.caches.set(i,a),e.pipeline=a,this.backend.createRenderPipeline(e,n)),a}_getComputeCacheKey(e,t){return e.id+","+t.id}_getRenderCacheKey(e,t,s){return t.id+","+s.id+","+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.caches.delete(e.cacheKey)}_releaseProgram(e){const t=e.code,s=e.stage;this.programs[s].delete(t)}_needsComputeUpdate(e){const t=this.get(e);return t.pipeline===void 0||t.version!==e.version}_needsRenderUpdate(e){return this.get(e).pipeline===void 0||this.backend.needsRenderUpdate(e)}}class eR extends qn{constructor(e,t,s,i,n,a){super(),this.backend=e,this.textures=s,this.pipelines=n,this.attributes=i,this.nodes=t,this.info=a,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings();for(const s of t){const i=this.get(s);i.bindGroup===void 0&&(this._init(s),this.backend.createBindings(s,t,0),i.bindGroup=s)}return t}getForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const s of t){const i=this.get(s);i.bindGroup===void 0&&(this._init(s),this.backend.createBindings(s,t,0),i.bindGroup=s)}return t}updateForCompute(e){this._updateBindings(this.getForCompute(e))}updateForRender(e){this._updateBindings(this.getForRender(e))}deleteForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const s of t)this.backend.deleteBindGroupData(s),this.delete(s)}deleteForRender(e){const t=e.getBindings();for(const s of t)this.backend.deleteBindGroupData(s),this.delete(s)}_updateBindings(e){for(const t of e)this._update(t,e)}_init(e){for(const t of e.bindings)if(t.isSampledTexture)this.textures.updateTexture(t.texture);else if(t.isSampler)this.textures.updateSampler(t.texture);else if(t.isStorageBuffer){const s=t.attribute,i=s.isIndirectStorageBufferAttribute?Fs.INDIRECT:Fs.STORAGE;this.attributes.update(s,i)}}_update(e,t){const{backend:s}=this;let i=!1,n=!0,a=0,o=0;for(const l of e.bindings)if(this.nodes.updateGroup(l)!==!1){if(l.isStorageBuffer){const u=l.attribute,h=u.isIndirectStorageBufferAttribute?Fs.INDIRECT:Fs.STORAGE,d=s.get(l);this.attributes.update(u,h),d.attribute!==u&&(d.attribute=u,i=!0)}if(l.isUniformBuffer)l.update()&&s.updateBinding(l);else if(l.isSampledTexture){const u=l.update(),h=l.texture,d=this.textures.get(h);if(u&&(this.textures.updateTexture(h),l.generation!==d.generation&&(l.generation=d.generation,i=!0),d.bindGroups.add(e)),s.get(h).externalTexture!==void 0||d.isDefaultTexture?n=!1:(a=a*10+h.id,o+=h.version),h.isStorageTexture===!0&&h.mipmapsAutoUpdate===!0){const f=this.get(h);l.store===!0?f.needsMipmap=!0:this.textures.needsMipmaps(h)&&f.needsMipmap===!0&&(this.backend.generateMipmaps(h),f.needsMipmap=!1)}}else if(l.isSampler&&l.update()){const h=this.textures.updateSampler(l.texture);l.samplerKey!==h&&(l.samplerKey=h,i=!0)}l.isBuffer&&l.updateRanges.length>0&&l.clearUpdateRanges()}i===!0&&this.backend.updateBindings(e,t,n?a:0,o)}}function tR(r,e){return r.groupOrder!==e.groupOrder?r.groupOrder-e.groupOrder:r.renderOrder!==e.renderOrder?r.renderOrder-e.renderOrder:r.z!==e.z?r.z-e.z:r.id-e.id}function Kg(r,e){return r.groupOrder!==e.groupOrder?r.groupOrder-e.groupOrder:r.renderOrder!==e.renderOrder?r.renderOrder-e.renderOrder:r.z!==e.z?e.z-r.z:r.id-e.id}function Jg(r){return(r.transmission>0||r.transmissionNode&&r.transmissionNode.isNode)&&r.side===qi&&r.forceSinglePass===!1}class sR{constructor(e,t,s){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparentDoublePass=[],this.transparent=[],this.bundles=[],this.lightsNode=e.getNode(t,s),this.lightsArray=[],this.scene=t,this.camera=s,this.occlusionQueryCount=0}begin(){return this.renderItemsIndex=0,this.opaque.length=0,this.transparentDoublePass.length=0,this.transparent.length=0,this.bundles.length=0,this.lightsArray.length=0,this.occlusionQueryCount=0,this}getNextRenderItem(e,t,s,i,n,a,o){let l=this.renderItems[this.renderItemsIndex];return l===void 0?(l={id:e.id,object:e,geometry:t,material:s,groupOrder:i,renderOrder:e.renderOrder,z:n,group:a,clippingContext:o},this.renderItems[this.renderItemsIndex]=l):(l.id=e.id,l.object=e,l.geometry=t,l.material=s,l.groupOrder=i,l.renderOrder=e.renderOrder,l.z=n,l.group=a,l.clippingContext=o),this.renderItemsIndex++,l}push(e,t,s,i,n,a,o){const l=this.getNextRenderItem(e,t,s,i,n,a,o);e.occlusionTest===!0&&this.occlusionQueryCount++,s.transparent===!0||s.transmission>0||s.transmissionNode&&s.transmissionNode.isNode||s.backdropNode&&s.backdropNode.isNode?(Jg(s)&&this.transparentDoublePass.push(l),this.transparent.push(l)):this.opaque.push(l)}unshift(e,t,s,i,n,a,o){const l=this.getNextRenderItem(e,t,s,i,n,a,o);s.transparent===!0||s.transmission>0||s.transmissionNode&&s.transmissionNode.isNode||s.backdropNode&&s.backdropNode.isNode?(Jg(s)&&this.transparentDoublePass.unshift(l),this.transparent.unshift(l)):this.opaque.unshift(l)}pushBundle(e){this.bundles.push(e)}pushLight(e){this.lightsArray.push(e)}sort(e,t){this.opaque.length>1&&this.opaque.sort(e||tR),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||Kg),this.transparent.length>1&&this.transparent.sort(t||Kg)}finish(){this.lightsNode.setLights(this.lightsArray);for(let e=this.renderItemsIndex,t=this.renderItems.length;e<t;e++){const s=this.renderItems[e];if(s.id===null)break;s.id=null,s.object=null,s.geometry=null,s.material=null,s.groupOrder=null,s.renderOrder=null,s.z=null,s.group=null,s.clippingContext=null}}}const Yr=[];class iR{constructor(e){this.lighting=e,this.lists=new zn}get(e,t){const s=this.lists;Yr[0]=e,Yr[1]=t;let i=s.get(Yr);return i===void 0&&(i=new sR(this.lighting,e,t),s.set(Yr,i)),Yr[0]=null,Yr[1]=null,i}dispose(){this.lists=new zn}}let nR=0;class rR{constructor(){this.id=nR++,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 Ee,this.scissor=!1,this.scissorValue=new Ee,this.renderTarget=null,this.textures=null,this.depthTexture=null,this.activeCubeFace=0,this.activeMipmapLevel=0,this.sampleCount=1,this.width=0,this.height=0,this.occlusionQueryCount=0,this.clippingContext=null,this.camera=null,this.isRenderContext=!0}getCacheKey(){return RT(this)}}function RT(r){const{textures:e,activeCubeFace:t,activeMipmapLevel:s}=r,i=[t,s];for(const n of e)i.push(n.id);return Ko(i)}class aR{constructor(e){this.renderer=e,this._renderContexts={}}get(e=null,t=null,s=0){let i;if(e===null)i="default";else{const l=e.texture.format,c=e.texture.type;i=`${e.textures.length}:${l}:${c}:${e.samples}:${e.depthBuffer}:${e.stencilBuffer}`}const n=t!==null?t.id:"default",a=i+"-"+n+"-"+s;let o=this._renderContexts[a];return o===void 0&&(o=new rR,o.mrt=t,this._renderContexts[a]=o),e!==null&&(o.sampleCount=e.samples===0?1:e.samples),o.clearDepthValue=this.renderer.getClearDepth(),o.clearStencilValue=this.renderer.getClearStencil(),o}dispose(){this._renderContexts={}}}const oR=new D;class lR extends qn{constructor(e,t,s){super(),this.renderer=e,this.backend=t,this.info=s}updateRenderTarget(e,t=0){const s=this.get(e),i=e.samples===0?1:e.samples,n=s.depthTextureMips||(s.depthTextureMips={}),a=e.textures,o=this.getSize(a[0]),l=o.width>>t,c=o.height>>t;let u=e.depthTexture||n[t];const h=e.depthBuffer===!0||e.stencilBuffer===!0;let d=!1;u===void 0&&h&&(u=new Bs,u.format=e.stencilBuffer?Yi:Qs,u.type=e.stencilBuffer?Fn:rt,u.image.width=l,u.image.height=c,u.image.depth=o.depth,u.renderTarget=e,u.isArrayTexture=e.multiview===!0&&o.depth>1,n[t]=u),(s.width!==o.width||o.height!==s.height)&&(d=!0,u&&(u.needsUpdate=!0,u.image.width=l,u.image.height=c,u.image.depth=u.isArrayTexture?u.image.depth:1)),s.width=o.width,s.height=o.height,s.textures=a,s.depthTexture=u||null,s.depth=e.depthBuffer,s.stencil=e.stencilBuffer,s.renderTarget=e,s.sampleCount!==i&&(d=!0,u&&(u.needsUpdate=!0),s.sampleCount=i);const p={sampleCount:i};if(e.isXRRenderTarget!==!0){for(let f=0;f<a.length;f++){const m=a[f];d&&(m.needsUpdate=!0),this.updateTexture(m,p)}u&&this.updateTexture(u,p)}s.initialized!==!0&&(s.initialized=!0,s.onDispose=()=>{this._destroyRenderTarget(e)},e.addEventListener("dispose",s.onDispose))}updateTexture(e,t={}){const s=this.get(e);if(s.initialized===!0&&s.version===e.version)return;const i=e.isRenderTargetTexture||e.isDepthTexture||e.isFramebufferTexture,n=this.backend;if(i&&s.initialized===!0&&n.destroyTexture(e),e.isFramebufferTexture){const c=this.renderer.getRenderTarget();c?e.type=c.texture.type:e.type=Ut}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&&t.levels++,i||e.isStorageTexture===!0||e.isExternalTexture===!0)n.createTexture(e,t),s.generation=e.version;else if(e.version>0){const c=e.image;if(c===void 0)W("Renderer: Texture marked for update but image is undefined.");else if(c.complete===!1)W("Renderer: Texture marked for update but image is incomplete.");else{if(e.images){const h=[];for(const d of e.images)h.push(d);t.images=h}else t.image=c;(s.isDefaultTexture===void 0||s.isDefaultTexture===!0)&&(n.createTexture(e,t),s.isDefaultTexture=!1,s.generation=e.version),e.source.dataReady===!0&&n.updateTexture(e,t);const u=e.isStorageTexture===!0&&e.mipmapsAutoUpdate===!1;t.needsMipmaps&&e.mipmaps.length===0&&!u&&n.generateMipmaps(e),e.onUpdate&&e.onUpdate(e)}}else n.createDefaultTexture(e),s.isDefaultTexture=!0,s.generation=e.version;s.initialized!==!0&&(s.initialized=!0,s.generation=e.version,s.bindGroups=new Set,this.info.memory.textures++,e.isVideoTexture&&Ae.enabled===!0&&Ae.getTransfer(e.colorSpace)!==ce&&W("WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace."),s.onDispose=()=>{this._destroyTexture(e)},e.addEventListener("dispose",s.onDispose)),s.version=e.version}updateSampler(e){return this.backend.updateSampler(e)}getSize(e,t=oR){let s=e.images?e.images[0]:e.image;return s?(s.image!==void 0&&(s=s.image),typeof HTMLVideoElement<"u"&&s instanceof HTMLVideoElement?(t.width=s.videoWidth||1,t.height=s.videoHeight||1,t.depth=1):typeof VideoFrame<"u"&&s instanceof VideoFrame?(t.width=s.displayWidth||1,t.height=s.displayHeight||1,t.depth=1):(t.width=s.width||1,t.height=s.height||1,t.depth=e.isCubeTexture?6:s.depth||1)):t.width=t.height=t.depth=1,t}getMipLevels(e,t,s){let i;return e.mipmaps.length>0?i=e.mipmaps.length:e.isCompressedTexture===!0?i=1:i=Math.floor(Math.log2(Math.max(t,s)))+1,i}needsMipmaps(e){return e.generateMipmaps===!0||e.mipmaps.length>0}_destroyRenderTarget(e){if(this.has(e)===!0){const t=this.get(e),s=t.textures,i=t.depthTexture;e.removeEventListener("dispose",t.onDispose);for(let n=0;n<s.length;n++)this._destroyTexture(s[n]);i&&this._destroyTexture(i),this.delete(e),this.backend.delete(e)}}_destroyTexture(e){if(this.has(e)===!0){const t=this.get(e);e.removeEventListener("dispose",t.onDispose);const s=t.isDefaultTexture;if(this.backend.destroyTexture(e,s),t.bindGroups)for(const i of t.bindGroups){const n=this.backend.get(i);n.groups=void 0,n.versions=void 0}this.delete(e),this.info.memory.textures--}}}class mm extends Ne{constructor(e,t,s,i=1){super(e,t,s),this.a=i}set(e,t,s,i=1){return this.a=i,super.set(e,t,s)}copy(e){return e.a!==void 0&&(this.a=e.a),super.copy(e)}clone(){return new this.constructor(this.r,this.g,this.b,this.a)}}class PT extends Re{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getMemberType(e,t){const s=this.getNodeType(e),i=e.getStructTypeNode(s);let n;return i!==null?n=i.getMemberType(e,t):($(`TSL: Member "${t}" not found in struct "${s}".`,new ct),n="float"),n}getHash(){return this.uuid}generate(){return this.name}}const cR=(r,e)=>new PT(r,e);class uR extends Q{static get type(){return"StackNode"}constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this._expressionNode=null,this._currentNode=null,this.isStackNode=!0}getElementType(e){return this.hasOutput(e)?this.outputNode.getElementType(e):"void"}getNodeType(e){return this.hasOutput(e)?this.outputNode.getNodeType(e):"void"}getMemberType(e,t){return this.hasOutput(e)?this.outputNode.getMemberType(e,t):"void"}addToStack(e,t=this.nodes.length){return e.isNode!==!0?($("TSL: Invalid node added to stack.",new ct),this):(this.nodes.splice(t,0,e),this)}addToStackBefore(e){const t=this._currentNode?this.nodes.indexOf(this._currentNode):0;return this.addToStack(e,t)}If(e,t){const s=new pa(t);return this._currentCond=Vt(e,s),this.addToStack(this._currentCond)}ElseIf(e,t){const s=new pa(t),i=Vt(e,s);return this._currentCond.elseNode=i,this._currentCond=i,this}Else(e){return this._currentCond.elseNode=new pa(e),this}Switch(e){return this._expressionNode=Z(e),this}Case(...e){const t=[];if(e.length>=2)for(let o=0;o<e.length-1;o++)t.push(this._expressionNode.equal(Z(e[o])));else $("TSL: Invalid parameter length. Case() requires at least two parameters.",new ct);const s=e[e.length-1],i=new pa(s);let n=t[0];for(let o=1;o<t.length;o++)n=n.or(t[o]);const a=Vt(n,i);return this._currentCond===null?(this._currentCond=a,this.addToStack(this._currentCond)):(this._currentCond.elseNode=a,this._currentCond=a,this)}Default(e){return this.Else(e),this}setup(e){const t=e.getNodeProperties(this);let s=0;for(const i of this.getChildren())i.isVarNode&&i.isIntent(e)&&i.isAssign(e)!==!0||(t["node"+s++]=i);return t.outputNode||null}hasOutput(e){return this.outputNode&&this.outputNode.isNode&&this.outputNode.getNodeType(e)!=="void"}build(e,...t){const s=cf(),i=e.buildStage;jo(this),e.setActiveStack(this);const n=c=>{if(this._currentNode=c,!(c.isVarNode&&c.isIntent(e)&&c.isAssign(e)!==!0)){if(i==="setup")c.build(e);else if(i==="analyze")c.build(e,this);else if(i==="generate"){const u=e.getDataFromNode(c,"any").stages,h=u&&u[e.shaderStage];if(c.isVarNode&&h&&h.length===1&&h[0]&&h[0].isStackNode)return;c.build(e,"void")}}},a=[...this.nodes];for(const c of a)n(c);this._currentNode=null;const o=this.nodes.filter(c=>a.indexOf(c)===-1);for(const c of o)n(c);let l;return this.hasOutput(e)?l=this.outputNode.build(e,...t):l=super.build(e,...t),jo(s),e.removeActiveStack(this),l}}const vc=ue(uR).setParameterLength(0,1);function hR(r){return Object.entries(r).map(([e,t])=>typeof t=="string"?{name:e,type:t,atomic:!1}:{name:e,type:t.type,atomic:t.atomic||!1})}class dR extends Q{static get type(){return"StructTypeNode"}constructor(e,t=null){super("struct"),this.membersLayout=hR(e),this.name=t,this.isStructLayoutNode=!0}getLength(){const e=Float32Array.BYTES_PER_ELEMENT;let t=1,s=0;for(const i of this.membersLayout){const n=i.type,a=IC(n),o=UC(n)/e;t=Math.max(t,o);const c=s%t%o;c!==0&&(s+=o-c),s+=a}return Math.ceil(s/t)*t}getMemberType(e,t){const s=this.membersLayout.find(i=>i.name===t);return s?s.type:"void"}getNodeType(e){return e.getStructTypeFromNode(this,this.membersLayout,this.name).name}setup(e){e.getStructTypeFromNode(this,this.membersLayout,this.name),e.addInclude(this)}generate(e){return this.getNodeType(e)}}class pR extends Q{static get type(){return"StructNode"}constructor(e,t){super("vec3"),this.structTypeNode=e,this.values=t,this.isStructNode=!0}getNodeType(e){return this.structTypeNode.getNodeType(e)}getMemberType(e,t){return this.structTypeNode.getMemberType(e,t)}_getChildren(){const e=super._getChildren(),t=e.find(s=>s.childNode===this.structTypeNode);return e.splice(e.indexOf(t),1),e.push(t),e}generate(e){const t=e.getVarFromNode(this),s=t.type,i=e.getPropertyName(t);return e.addLineFlowCode(`${i} = ${e.generateStruct(s,this.structTypeNode.membersLayout,this.values)}`,this),t.name}}const fR=(r,e=null)=>{const t=new dR(r,e),s=(...i)=>{let n=null;if(i.length>0)if(i[0].isNode){n={};const a=Object.keys(r);for(let o=0;o<i.length;o++)n[a[o]]=i[o]}else n=i[0];return new pR(t,n)};return s.layout=t,s.isStruct=!0,s};class FT extends Q{static get type(){return"OutputStructNode"}constructor(...e){super(),this.members=e,this.isOutputStructNode=!0}getNodeType(){return"OutputType"}generate(e){const t=e.getDataFromNode(this);if(t.membersLayout===void 0){const a=this.members,o=[];for(let l=0;l<a.length;l++){const c="m"+l,u=a[l].getNodeType(e);o.push({name:c,type:u,index:l})}t.membersLayout=o,t.structType=e.getOutputStructTypeFromNode(this,t.membersLayout)}const s=e.getOutputStructName(),i=this.members,n=s!==""?s+".":"";for(let a=0;a<i.length;a++){const o=i[a].build(e);e.addLineFlowCode(`${n}m${a} = ${o}`,this)}return s}}const mR=ue(FT);class BT{constructor(e=Es){this.blending=e,this.blendSrc=Vo,this.blendDst=ko,this.blendEquation=Ns,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.premultiplyAlpha=!1}copy(e){return this.blending=e.blending,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.premultiplyAlpha=e.premultiplyAlpha,this}clone(){return new this.constructor().copy(this)}}const gR=new BT(Xi),yR=new BT(Ip);function DT(r,e){for(let t=0;t<r.length;t++)if(r[t].name===e)return t;return-1}class xR extends FT{static get type(){return"MRTNode"}constructor(e){super(),this.outputNodes=e,this.blendModes={output:yR},this.isMRTNode=!0}setBlendMode(e,t){return this.blendModes[e]=t,this}getBlendMode(e){return this.blendModes[e]||gR}has(e){return this.outputNodes[e]!==void 0}get(e){return this.outputNodes[e]}merge(e){const t={...this.outputNodes,...e.outputNodes},s={...this.blendModes,...e.blendModes},i=OT(t);return i.blendings=s,i}setup(e){const t=this.outputNodes,s=e.renderer.getRenderTarget(),i=[],n=s.textures;for(const a in t){const o=DT(n,a);i[o]=ie(t[a])}return this.members=i,super.setup(e)}}const OT=ue(xR);class nl extends ot{static get type(){return"BitcastNode"}constructor(e,t,s=null){super(),this.valueNode=e,this.conversionType=t,this.inputType=s,this.isBitcastNode=!0}getNodeType(e){if(this.inputType!==null){const t=this.valueNode.getNodeType(e),s=e.getTypeLength(t);return e.getTypeFromLength(s,this.conversionType)}return this.conversionType}generate(e){const t=this.getNodeType(e);let s="";if(this.inputType!==null){const i=this.valueNode.getNodeType(e);s=e.getTypeLength(i)===1?this.inputType:e.changeComponentType(i,this.inputType)}else s=this.valueNode.getNodeType(e);return`${e.getBitcastMethod(t,s)}( ${this.valueNode.build(e,s)} )`}}const LT=G(nl).setParameterLength(2),_R=r=>new nl(r,"int","float"),IT=r=>new nl(r,"uint","float"),bR=r=>new nl(r,"float","int"),TR=r=>new nl(r,"float","uint"),Wl={};class xs extends O{static get type(){return"BitcountNode"}constructor(e,t){super(e,t),this.isBitcountNode=!0}_resolveElementType(e,t,s){s==="int"?t.assign(LT(e,"uint")):t.assign(e)}_returnDataNode(e){switch(e){case"uint":return k;case"int":return w;case"uvec2":return uf;case"uvec3":return Ar;case"uvec4":return ff;case"ivec2":return ft;case"ivec3":return hf;case"ivec4":return pf}}_createTrailingZerosBaseLayout(e,t){const s=this._returnDataNode(t);return R(([n])=>{const a=k(0);this._resolveElementType(n,a,t);const o=T(a.bitAnd(Af(a))),c=IT(o).shiftRight(23).sub(127);return s(c)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}_createLeadingZerosBaseLayout(e,t){const s=this._returnDataNode(t);return R(([n])=>{ne(n.equal(k(0)),()=>k(32));const a=k(0),o=k(0);return this._resolveElementType(n,a,t),ne(a.shiftRight(16).equal(0),()=>{o.addAssign(16),a.shiftLeftAssign(16)}),ne(a.shiftRight(24).equal(0),()=>{o.addAssign(8),a.shiftLeftAssign(8)}),ne(a.shiftRight(28).equal(0),()=>{o.addAssign(4),a.shiftLeftAssign(4)}),ne(a.shiftRight(30).equal(0),()=>{o.addAssign(2),a.shiftLeftAssign(2)}),ne(a.shiftRight(31).equal(0),()=>{o.addAssign(1)}),s(o)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}_createOneBitsBaseLayout(e,t){const s=this._returnDataNode(t);return R(([n])=>{const a=k(0);this._resolveElementType(n,a,t),a.assign(a.sub(a.shiftRight(k(1)).bitAnd(k(1431655765)))),a.assign(a.bitAnd(k(858993459)).add(a.shiftRight(k(2)).bitAnd(k(858993459))));const o=a.add(a.shiftRight(k(4))).bitAnd(k(252645135)).mul(k(16843009)).shiftRight(k(24));return s(o)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}_createMainLayout(e,t,s,i){const n=this._returnDataNode(t);return R(([o])=>{if(s===1)return n(i(o));{const l=n(0),c=["x","y","z","w"];for(let u=0;u<s;u++){const h=c[u];l[h].assign(i(o[h]))}return l}}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}setup(e){const{method:t,aNode:s}=this,{renderer:i}=e;if(i.backend.isWebGPUBackend)return super.setup(e);const n=this.getInputType(e),a=e.getElementType(n),o=e.getTypeLength(n),l=`${t}_base_${a}`,c=`${t}_${n}`;let u=Wl[l];if(u===void 0){switch(t){case xs.COUNT_LEADING_ZEROS:{u=this._createLeadingZerosBaseLayout(l,a);break}case xs.COUNT_TRAILING_ZEROS:{u=this._createTrailingZerosBaseLayout(l,a);break}case xs.COUNT_ONE_BITS:{u=this._createOneBitsBaseLayout(l,a);break}}Wl[l]=u}let h=Wl[c];return h===void 0&&(h=this._createMainLayout(c,n,o,u),Wl[c]=h),R(()=>h(s))()}}xs.COUNT_TRAILING_ZEROS="countTrailingZeros";xs.COUNT_LEADING_ZEROS="countLeadingZeros";xs.COUNT_ONE_BITS="countOneBits";const SR=G(xs,xs.COUNT_TRAILING_ZEROS).setParameterLength(1),vR=G(xs,xs.COUNT_LEADING_ZEROS).setParameterLength(1),MR=G(xs,xs.COUNT_ONE_BITS).setParameterLength(1),wR=R(([r])=>{const e=r.toUint().mul(747796405).add(2891336453),t=e.shiftRight(e.shiftRight(28).add(4)).bitXor(e).mul(277803737);return t.shiftRight(22).bitXor(t).toFloat().mul(1/2**32)}),wp=(r,e)=>Rs(ae(4,r.mul(Te(1,r))),e),CR=(r,e)=>r.lessThan(.5)?wp(r.mul(2),e).div(2):Te(1,wp(ae(Te(1,r),2),e).div(2)),AR=(r,e,t)=>Rs(bs(Rs(r,e),dt(Rs(r,e),Rs(Te(1,r),t))),1/e),ER=(r,e)=>jt(mu.mul(e.mul(r).sub(1))).div(mu.mul(e.mul(r).sub(1)));class gm extends ot{static get type(){return"PackFloatNode"}constructor(e,t){super(),this.vectorNode=t,this.encoding=e,this.isPackFloatNode=!0}getNodeType(){return"uint"}generate(e){const t=this.vectorNode.getNodeType(e);return`${e.getFloatPackingMethod(this.encoding)}(${this.vectorNode.build(e,t)})`}}const NR=G(gm,"snorm").setParameterLength(1),RR=G(gm,"unorm").setParameterLength(1),PR=G(gm,"float16").setParameterLength(1);class ym extends ot{static get type(){return"UnpackFloatNode"}constructor(e,t){super(),this.uintNode=t,this.encoding=e,this.isUnpackFloatNode=!0}getNodeType(){return"vec2"}generate(e){const t=this.uintNode.getNodeType(e);return`${e.getFloatUnpackingMethod(this.encoding)}(${this.uintNode.build(e,t)})`}}const FR=G(ym,"snorm").setParameterLength(1),BR=G(ym,"unorm").setParameterLength(1),DR=G(ym,"float16").setParameterLength(1),Gi=R(([r])=>r.fract().sub(.5).abs()).setLayout({name:"tri",type:"float",inputs:[{name:"x",type:"float"}]}),OR=R(([r])=>E(Gi(r.z.add(Gi(r.y.mul(1)))),Gi(r.z.add(Gi(r.x.mul(1)))),Gi(r.y.add(Gi(r.x.mul(1)))))).setLayout({name:"tri3",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),LR=R(([r,e,t])=>{const s=E(r).toVar(),i=T(1.4).toVar(),n=T(0).toVar(),a=E(s).toVar();return Ie({start:T(0),end:T(3),type:"float",condition:"<="},()=>{const o=E(OR(a.mul(2))).toVar();s.addAssign(o.add(t.mul(T(.1).mul(e)))),a.mulAssign(1.8),i.mulAssign(1.5),s.mulAssign(1.2);const l=T(Gi(s.z.add(Gi(s.x.add(Gi(s.y)))))).toVar();n.addAssign(l.div(i)),a.addAssign(.14)}),n}).setLayout({name:"triNoise3D",type:"float",inputs:[{name:"position",type:"vec3"},{name:"speed",type:"float"},{name:"time",type:"float"}]});class IR extends Q{static get type(){return"FunctionOverloadingNode"}constructor(e=[],...t){super(),this.functionNodes=e,this.parametersNodes=t,this._candidateFn=null,this.global=!0}getNodeType(e){return this.getCandidateFn(e).shaderNode.layout.type}getCandidateFn(e){const t=this.parametersNodes;let s=this._candidateFn;if(s===null){let i=null,n=-1;for(const a of this.functionNodes){const l=a.shaderNode.layout;if(l===null)throw new Error("FunctionOverloadingNode: FunctionNode must be a layout.");const c=l.inputs;if(t.length===c.length){let u=0;for(let h=0;h<t.length;h++){const d=t[h],p=c[h];d.getNodeType(e)===p.type&&u++}u>n&&(i=a,n=u)}}this._candidateFn=s=i}return s}setup(e){return this.getCandidateFn(e)(...this.parametersNodes)}}const UR=ue(IR),Pt=r=>(...e)=>UR(r,...e),ka=ee(0).setGroup(se).onRenderUpdate(r=>r.time),VR=ee(0).setGroup(se).onRenderUpdate(r=>r.deltaTime),UT=ee(0,"uint").setGroup(se).onRenderUpdate(r=>r.frameId),kR=(r=ka)=>r.add(.75).mul(Math.PI*2).sin().mul(.5).add(.5),zR=(r=ka)=>r.fract().round(),GR=(r=ka)=>r.add(.5).fract().mul(2).sub(1).abs(),$R=(r=ka)=>r.fract();function WR(r,e=null){return rn(e,{getUV:typeof r=="function"?r:()=>r})}const HR=R(([r,e,t=z(.5)])=>il(r.sub(t),e).add(t)),jR=R(([r,e,t=z(.5)])=>{const s=r.sub(t),i=s.dot(s),a=i.mul(i).mul(e);return r.add(s.mul(a))}),qR=R(({position:r=null,horizontal:e=!0,vertical:t=!1})=>{let s;r!==null?(s=Ps.toVar(),s[3][0]=r.x,s[3][1]=r.y,s[3][2]=r.z):s=Ps;const i=Gs.mul(s);return Ho(e)&&(i[0][0]=Ps[0].length(),i[0][1]=0,i[0][2]=0),Ho(t)&&(i[1][0]=0,i[1][1]=Ps[1].length(),i[1][2]=0),i[2][0]=0,i[2][1]=0,i[2][2]=1,en.mul(i).mul(Je)}),XR=R(([r=null])=>{const e=yu();return yu(im(r)).sub(e).lessThan(0).select(Ci,r)}),YR=R(([r,e=ze(),t=T(0)])=>{const s=r.x,i=r.y,n=t.mod(s.mul(i)).floor(),a=n.mod(s),o=i.sub(n.add(1).div(s).ceil()),l=r.reciprocal(),c=z(a,o);return e.add(c).mul(l)}),VT=R(([r,e=null,t=null,s=T(1),i=Je,n=rs])=>{let a=n.abs().normalize();a=a.div(a.dot(E(1)));const o=i.yz.mul(s),l=i.zx.mul(s),c=i.xy.mul(s),u=r.value,h=e!==null?e.value:u,d=t!==null?t.value:u,p=we(u,o).mul(a.x),f=we(h,l).mul(a.y),m=we(d,c).mul(a.z);return dt(p,f,m)}),ZR=(...r)=>VT(...r),Zr=new Tn,Jn=new D,Qr=new D,dd=new D,Ka=new ve,Hl=new D(0,0,-1),ui=new Ee,Ja=new D,jl=new D,eo=new Ee,ql=new xe,_u=new nn,QR=Ci.flipX();_u.depthTexture=new Bs(1,1);let Xl=!1;class xm extends Pi{static get type(){return"ReflectorNode"}constructor(e={}){super(e.defaultTexture||_u.texture,QR),this._reflectorBaseNode=e.reflector||new KR(this,e),this._depthNode=null,this.setUpdateMatrix(!1)}get reflector(){return this._reflectorBaseNode}get target(){return this._reflectorBaseNode.target}getDepthNode(){if(this._depthNode===null){if(this._reflectorBaseNode.depth!==!0)throw new Error("THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ");this._depthNode=new xm({defaultTexture:_u.depthTexture,reflector:this._reflectorBaseNode})}return this._depthNode}setup(e){return e.object.isQuadMesh||this._reflectorBaseNode.build(e),super.setup(e)}clone(){const e=new this.constructor(this.reflectorNode);return e.uvNode=this.uvNode,e.levelNode=this.levelNode,e.biasNode=this.biasNode,e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e._reflectorBaseNode=this._reflectorBaseNode,e}dispose(){super.dispose(),this._reflectorBaseNode.dispose()}}class KR extends Q{static get type(){return"ReflectorBaseNode"}constructor(e,t={}){super();const{target:s=new gt,resolutionScale:i=1,generateMipmaps:n=!1,bounces:a=!0,depth:o=!1,samples:l=0}=t;this.textureNode=e,this.target=s,this.resolutionScale=i,t.resolution!==void 0&&(Le('ReflectorNode: The "resolution" parameter has been renamed to "resolutionScale".'),this.resolutionScale=t.resolution),this.generateMipmaps=n,this.bounces=a,this.depth=o,this.samples=l,this.updateBeforeType=a?re.RENDER:re.FRAME,this.virtualCameras=new WeakMap,this.renderTargets=new Map,this.forceUpdate=!1,this.hasOutput=!1}_updateResolution(e,t){const s=this.resolutionScale;t.getDrawingBufferSize(ql),e.setSize(Math.round(ql.width*s),Math.round(ql.height*s))}setup(e){return this._updateResolution(_u,e.renderer),super.setup(e)}dispose(){super.dispose();for(const e of this.renderTargets.values())e.dispose()}getVirtualCamera(e){let t=this.virtualCameras.get(e);return t===void 0&&(t=e.clone(),this.virtualCameras.set(e,t)),t}getRenderTarget(e){let t=this.renderTargets.get(e);return t===void 0&&(t=new nn(0,0,{type:Et,samples:this.samples}),this.generateMipmaps===!0&&(t.texture.minFilter=KM,t.texture.generateMipmaps=!0),this.depth===!0&&(t.depthTexture=new Bs),this.renderTargets.set(e,t)),t}updateBefore(e){if(this.bounces===!1&&Xl)return!1;Xl=!0;const{scene:t,camera:s,renderer:i,material:n}=e,{target:a}=this,o=this.getVirtualCamera(s),l=this.getRenderTarget(o);i.getDrawingBufferSize(ql),this._updateResolution(l,i),Qr.setFromMatrixPosition(a.matrixWorld),dd.setFromMatrixPosition(s.matrixWorld),Ka.extractRotation(a.matrixWorld),Jn.set(0,0,1),Jn.applyMatrix4(Ka),Ja.subVectors(Qr,dd);const c=Ja.dot(Jn)>0;let u=!1;if(c===!0&&this.forceUpdate===!1){if(this.hasOutput===!1){Xl=!1;return}u=!0}Ja.reflect(Jn).negate(),Ja.add(Qr),Ka.extractRotation(s.matrixWorld),Hl.set(0,0,-1),Hl.applyMatrix4(Ka),Hl.add(dd),jl.subVectors(Qr,Hl),jl.reflect(Jn).negate(),jl.add(Qr),o.coordinateSystem=s.coordinateSystem,o.position.copy(Ja),o.up.set(0,1,0),o.up.applyMatrix4(Ka),o.up.reflect(Jn),o.lookAt(jl),o.near=s.near,o.far=s.far,o.updateMatrixWorld(),o.projectionMatrix.copy(s.projectionMatrix),Zr.setFromNormalAndCoplanarPoint(Jn,Qr),Zr.applyMatrix4(o.matrixWorldInverse),ui.set(Zr.normal.x,Zr.normal.y,Zr.normal.z,Zr.constant);const h=o.projectionMatrix;eo.x=(Math.sign(ui.x)+h.elements[8])/h.elements[0],eo.y=(Math.sign(ui.y)+h.elements[9])/h.elements[5],eo.z=-1,eo.w=(1+h.elements[10])/h.elements[14],ui.multiplyScalar(1/ui.dot(eo));const d=0;h.elements[2]=ui.x,h.elements[6]=ui.y,h.elements[10]=i.coordinateSystem===Ls?ui.z-d:ui.z+1-d,h.elements[14]=ui.w,this.textureNode.value=l.texture,this.depth===!0&&(this.textureNode.getDepthNode().value=l.depthTexture),n.visible=!1;const p=i.getRenderTarget(),f=i.getMRT(),m=i.autoClear;i.setMRT(null),i.setRenderTarget(l),i.autoClear=!0;const x=t.name;t.name=(t.name||"Scene")+" [ Reflector ]",u?(i.clear(),this.hasOutput=!1):(i.render(t,o),this.hasOutput=!0),t.name=x,i.setMRT(f),i.setRenderTarget(p),i.autoClear=m,n.visible=!0,Xl=!1,this.forceUpdate=!1}get resolution(){return Le('ReflectorNode: The "resolution" property has been renamed to "resolutionScale".'),this.resolutionScale}set resolution(e){Le('ReflectorNode: The "resolution" property has been renamed to "resolutionScale".'),this.resolutionScale=e}}const JR=r=>new xm(r),pd=new tf(-1,1,1,-1,0,1);class eP extends Bi{constructor(e=!1){super();const t=e===!1?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new Yt([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new Yt(t,2))}}const tP=new eP;class lh extends Un{constructor(e=null){super(tP,e),this.camera=pd,this.isQuadMesh=!0}async renderAsync(e){Le('QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await e.init(),e.render(this,pd)}render(e){e.render(this,pd)}}const sP=new xe;class iP extends Pi{static get type(){return"RTTNode"}constructor(e,t=null,s=null,i={type:Et}){const n=new nn(t,s,i);super(n.texture,ze()),this.isRTTNode=!0,this.node=e,this.width=t,this.height=s,this.pixelRatio=1,this.renderTarget=n,this.textureNeedsUpdate=!0,this.autoUpdate=!0,this._rttNode=null,this._quadMesh=new lh(new st),this.updateBeforeType=re.RENDER}get autoResize(){return this.width===null}setup(e){return this._rttNode=this.node.context(e.getSharedContext()),this._quadMesh.material.name="RTT",this._quadMesh.material.needsUpdate=!0,super.setup(e)}setSize(e,t){this.width=e,this.height=t;const s=e*this.pixelRatio,i=t*this.pixelRatio;this.renderTarget.setSize(s,i),this.textureNeedsUpdate=!0}setPixelRatio(e){this.pixelRatio=e,this.setSize(this.width,this.height)}updateBefore({renderer:e}){if(this.textureNeedsUpdate===!1&&this.autoUpdate===!1)return;if(this.textureNeedsUpdate=!1,this.autoResize===!0){const i=e.getPixelRatio(),n=e.getSize(sP),a=Math.floor(n.width*i),o=Math.floor(n.height*i);(a!==this.renderTarget.width||o!==this.renderTarget.height)&&(this.renderTarget.setSize(a,o),this.textureNeedsUpdate=!0)}let t="RTT";this.node.name&&(t=this.node.name+" [ "+t+" ]"),this._quadMesh.material.fragmentNode=this._rttNode,this._quadMesh.name=t;const s=e.getRenderTarget();e.setRenderTarget(this.renderTarget),this._quadMesh.render(e),e.setRenderTarget(s)}clone(){const e=new Pi(this.value,this.uvNode,this.levelNode);return e.sampler=this.sampler,e.referenceNode=this,e}}const kT=(r,...e)=>new iP(Z(r),...e),nP=(r,...e)=>r.isSampleNode||r.isTextureNode?r:r.isPassNode?r.getTextureNode():kT(r,...e),la=R(([r,e,t],s)=>{let i;s.renderer.coordinateSystem===Ls?(r=z(r.x,r.y.oneMinus()).mul(2).sub(1),i=ie(E(r,e),1)):i=ie(E(r.x,r.y.oneMinus(),e).mul(2).sub(1),1);const n=ie(t.mul(i));return n.xyz.div(n.w)}),rP=R(([r,e])=>{const t=e.mul(ie(r,1)),s=t.xy.div(t.w).mul(.5).add(.5).toVar();return z(s.x,s.y.oneMinus())}),aP=R(([r,e,t])=>{const s=On(nt(e)),i=ft(r.mul(s)).toVar(),n=nt(e,i).toVar(),a=nt(e,i.sub(ft(2,0))).toVar(),o=nt(e,i.sub(ft(1,0))).toVar(),l=nt(e,i.add(ft(1,0))).toVar(),c=nt(e,i.add(ft(2,0))).toVar(),u=nt(e,i.add(ft(0,2))).toVar(),h=nt(e,i.add(ft(0,1))).toVar(),d=nt(e,i.sub(ft(0,1))).toVar(),p=nt(e,i.sub(ft(0,2))).toVar(),f=We(Te(T(2).mul(o).sub(a),n)).toVar(),m=We(Te(T(2).mul(l).sub(c),n)).toVar(),x=We(Te(T(2).mul(h).sub(u),n)).toVar(),y=We(Te(T(2).mul(d).sub(p),n)).toVar(),b=la(r,n,t).toVar(),v=f.lessThan(m).select(b.sub(la(r.sub(z(T(1).div(s.x),0)),o,t)),b.negate().add(la(r.add(z(T(1).div(s.x),0)),l,t))),S=x.lessThan(y).select(b.sub(la(r.add(z(0,T(1).div(s.y))),h,t)),b.negate().add(la(r.sub(z(0,T(1).div(s.y))),d,t)));return is(tn(v,S))}),_m=R(([r])=>Js(T(52.9829189).mul(Js(Vs(r,z(.06711056,.00583715)))))).setLayout({name:"interleavedGradientNoise",type:"float",inputs:[{name:"position",type:"vec2"}]}),Zs=R(([r,e,t])=>{const s=T(2.399963229728653),i=Zt(T(r).add(.5).div(T(e))),n=T(r).mul(s).add(t);return z(Xs(n),jt(n)).mul(i)}).setLayout({name:"vogelDiskSample",type:"vec2",inputs:[{name:"sampleIndex",type:"int"},{name:"samplesCount",type:"int"},{name:"phi",type:"float"}]});class oP extends Q{static get type(){return"SampleNode"}constructor(e,t=null){super(),this.callback=e,this.uvNode=t,this.isSampleNode=!0}setup(){return this.sample(ze())}sample(e){return this.callback(e)}}const lP=(r,e=null)=>new oP(r,Z(e));class ss extends Q{static get type(){return"EventNode"}constructor(e,t){super("void"),this.eventType=e,this.callback=t,e===ss.OBJECT?this.updateType=re.OBJECT:e===ss.MATERIAL?this.updateType=re.RENDER:e===ss.BEFORE_OBJECT?this.updateBeforeType=re.OBJECT:e===ss.BEFORE_MATERIAL&&(this.updateBeforeType=re.RENDER)}update(e){this.callback(e)}updateBefore(e){this.callback(e)}}ss.OBJECT="object";ss.MATERIAL="material";ss.BEFORE_OBJECT="beforeObject";ss.BEFORE_MATERIAL="beforeMaterial";const ch=(r,e)=>new ss(r,e).toStack(),cP=r=>ch(ss.OBJECT,r),uP=r=>ch(ss.MATERIAL,r),hP=r=>ch(ss.BEFORE_OBJECT,r),dP=r=>ch(ss.BEFORE_MATERIAL,r);class pP extends _a{constructor(e,t,s=Float32Array){const i=ArrayBuffer.isView(e)?e:new s(e*t);super(i,t),this.isStorageInstancedBufferAttribute=!0}}class fP extends ys{constructor(e,t,s=Float32Array){const i=ArrayBuffer.isView(e)?e:new s(e*t);super(i,t),this.isStorageBufferAttribute=!0}}const mP=(r,e="float")=>{let t,s;e.isStruct===!0?(t=e.layout.getLength(),s=lu("float")):(t=i0(e),s=lu(e));const i=new fP(r,t,s);return Ln(i,e,r)},gP=(r,e="float")=>{let t,s;e.isStruct===!0?(t=e.layout.getLength(),s=lu("float")):(t=i0(e),s=lu(e));const i=new pP(r,t,s);return Ln(i,e,i.count)};class yP extends Q{static get type(){return"PointUVNode"}constructor(){super("vec2"),this.isPointUVNode=!0}generate(){return"vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )"}}const xP=H(yP),to=new Is,fd=new ve,zT=ee(0).setGroup(se).onRenderUpdate(({scene:r})=>r.backgroundBlurriness),Cp=ee(1).setGroup(se).onRenderUpdate(({scene:r})=>r.backgroundIntensity),GT=ee(new ve).setGroup(se).onRenderUpdate(({scene:r})=>{const e=r.background;return e!==null&&e.isTexture&&e.mapping!==Up?(to.copy(r.backgroundRotation),to.x*=-1,to.y*=-1,to.z*=-1,fd.makeRotationFromEuler(to)):fd.identity(),fd});class _P extends Pi{static get type(){return"StorageTextureNode"}constructor(e,t,s=null){super(e,t),this.storeNode=s,this.mipLevel=0,this.isStorageTextureNode=!0,this.access=Nt.WRITE_ONLY}getInputType(){return"storageTexture"}setup(e){super.setup(e);const t=e.getNodeProperties(this);return t.storeNode=this.storeNode,t}setAccess(e){return this.access=e,this}setMipLevel(e){return this.mipLevel=e,this}generate(e,t){let s;return this.storeNode!==null?s=this.generateStore(e):s=super.generate(e,t),s}generateSnippet(e,t,s,i,n,a,o,l,c){const u=this.value;return e.generateStorageTextureLoad(u,t,s,i,a,c)}toReadWrite(){return this.setAccess(Nt.READ_WRITE)}toReadOnly(){return this.setAccess(Nt.READ_ONLY)}toWriteOnly(){return this.setAccess(Nt.WRITE_ONLY)}generateStore(e){const t=e.getNodeProperties(this),{uvNode:s,storeNode:i,depthNode:n}=t,a=super.generate(e,"property"),o=s.build(e,this.value.is3DTexture===!0?"uvec3":"uvec2"),l=i.build(e,"vec4"),c=n?n.build(e,"int"):null,u=e.generateTextureStore(e,a,o,c,l);e.addLineFlowCode(u,this)}clone(){const e=super.clone();return e.storeNode=this.storeNode,e.mipLevel=this.mipLevel,e.access=this.access,e}}const $T=ue(_P).setParameterLength(1,3),bP=(r,e,t)=>{let s;return r.isStorageTextureNode===!0?(s=r.clone(),s.uvNode=e,s.storeNode=t):s=$T(r,e,t),t!==null&&s.toStack(),s},TP=R(({texture:r,uv:e})=>{const s=E().toVar();return ne(e.x.lessThan(1e-4),()=>{s.assign(E(1,0,0))}).ElseIf(e.y.lessThan(1e-4),()=>{s.assign(E(0,1,0))}).ElseIf(e.z.lessThan(1e-4),()=>{s.assign(E(0,0,1))}).ElseIf(e.x.greaterThan(1-1e-4),()=>{s.assign(E(-1,0,0))}).ElseIf(e.y.greaterThan(1-1e-4),()=>{s.assign(E(0,-1,0))}).ElseIf(e.z.greaterThan(1-1e-4),()=>{s.assign(E(0,0,-1))}).Else(()=>{const n=r.sample(e.add(E(-.01,0,0))).r.sub(r.sample(e.add(E(.01,0,0))).r),a=r.sample(e.add(E(0,-.01,0))).r.sub(r.sample(e.add(E(0,.01,0))).r),o=r.sample(e.add(E(0,0,-.01))).r.sub(r.sample(e.add(E(0,0,.01))).r);s.assign(E(n,a,o))}),s.normalize()});class SP extends Pi{static get type(){return"Texture3DNode"}constructor(e,t=null,s=null){super(e,t,s),this.isTexture3DNode=!0}getInputType(){return"texture3D"}getDefaultUV(){return E(.5,.5,.5)}setUpdateMatrix(){}generateUV(e,t){return t.build(e,this.sampler===!0?"vec3":"ivec3")}generateOffset(e,t){return t.build(e,"ivec3")}normal(e){return TP({texture:this,uv:e})}}const uh=ue(SP).setParameterLength(1,3),vP=(...r)=>uh(...r).setSampler(!1),MP=(r,e,t)=>uh(r,e).level(t);class wP extends Ju{static get type(){return"UserDataNode"}constructor(e,t,s=null){super(e,t,s),this.userData=s}updateReference(e){return this.reference=this.userData!==null?this.userData:e.object.userData,this.reference}}const CP=(r,e,t)=>new wP(r,e,t),ey=new WeakMap;class AP extends ot{static get type(){return"VelocityNode"}constructor(){super("vec2"),this.projectionMatrix=null,this.updateType=re.OBJECT,this.updateAfterType=re.OBJECT,this.previousModelWorldMatrix=ee(new ve),this.previousProjectionMatrix=ee(new ve).setGroup(se),this.previousCameraViewMatrix=ee(new ve)}setProjectionMatrix(e){this.projectionMatrix=e}update({frameId:e,camera:t,object:s}){const i=ty(s);this.previousModelWorldMatrix.value.copy(i);const n=WT(t);n.frameId!==e&&(n.frameId=e,n.previousProjectionMatrix===void 0?(n.previousProjectionMatrix=new ve,n.previousCameraViewMatrix=new ve,n.currentProjectionMatrix=new ve,n.currentCameraViewMatrix=new ve,n.previousProjectionMatrix.copy(this.projectionMatrix||t.projectionMatrix),n.previousCameraViewMatrix.copy(t.matrixWorldInverse)):(n.previousProjectionMatrix.copy(n.currentProjectionMatrix),n.previousCameraViewMatrix.copy(n.currentCameraViewMatrix)),n.currentProjectionMatrix.copy(this.projectionMatrix||t.projectionMatrix),n.currentCameraViewMatrix.copy(t.matrixWorldInverse),this.previousProjectionMatrix.value.copy(n.previousProjectionMatrix),this.previousCameraViewMatrix.value.copy(n.previousCameraViewMatrix))}updateAfter({object:e}){ty(e).copy(e.matrixWorld)}setup(){const e=this.projectionMatrix===null?en:ee(this.projectionMatrix),t=this.previousCameraViewMatrix.mul(this.previousModelWorldMatrix),s=e.mul(Hn).mul(Je),i=this.previousProjectionMatrix.mul(t).mul(Ba),n=s.xy.div(s.w),a=i.xy.div(i.w);return Te(n,a)}}function WT(r){let e=ey.get(r);return e===void 0&&(e={},ey.set(r,e)),e}function ty(r,e=0){const t=WT(r);let s=t[e];return s===void 0&&(t[e]=s=new ve,t[e].copy(r.matrixWorld)),s}const EP=H(AP),NP=R(([r])=>bm(r.rgb)),RP=R(([r,e=T(1)])=>e.mix(bm(r.rgb),r.rgb)),PP=R(([r,e=T(1)])=>{const t=dt(r.r,r.g,r.b).div(3),s=r.r.max(r.g.max(r.b)),i=s.sub(t).mul(e).mul(-3);return ye(r.rgb,s,i)}),FP=R(([r,e=T(1)])=>{const t=E(.57735,.57735,.57735),s=e.cos();return E(r.rgb.mul(s).add(t.cross(r.rgb).mul(e.sin()).add(t.mul(Vs(t,r.rgb).mul(s.oneMinus())))))}),bm=(r,e=E(Ae.getLuminanceCoefficients(new D)))=>Vs(r,e),BP=R(([r,e=E(1),t=E(0),s=E(1),i=T(1),n=E(Ae.getLuminanceCoefficients(new D,ru))])=>{const a=r.rgb.dot(E(n)),o=tt(r.rgb.mul(e).add(t),0).toVar(),l=o.pow(s).toVar();return ne(o.r.greaterThan(0),()=>{o.r.assign(l.r)}),ne(o.g.greaterThan(0),()=>{o.g.assign(l.g)}),ne(o.b.greaterThan(0),()=>{o.b.assign(l.b)}),o.assign(a.add(o.sub(a).mul(i))),ie(o.rgb,r.a)}),DP=R(([r,e])=>r.mul(e).floor().div(e));let Yl=null;class OP extends ih{static get type(){return"ViewportSharedTextureNode"}constructor(e=Ci,t=null){Yl===null&&(Yl=new Yp),super(e,t,Yl)}getTextureForReference(){return Yl}updateReference(){return this}}const LP=ue(OP).setParameterLength(0,2),Zl=new xe;class HT extends Pi{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.isPassTextureNode=!0,this.setUpdateMatrix(!1)}setup(e){const t=e.getNodeProperties(this);return t.passNode=this.passNode,super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class sy extends HT{static get type(){return"PassMultipleTextureNode"}constructor(e,t,s=!1){super(e,null),this.textureName=t,this.previousTexture=s,this.isPassMultipleTextureNode=!0}updateTexture(){this.value=this.previousTexture?this.passNode.getPreviousTexture(this.textureName):this.passNode.getTexture(this.textureName)}setup(e){return this.updateTexture(),super.setup(e)}clone(){const e=new this.constructor(this.passNode,this.textureName,this.previousTexture);return e.uvNode=this.uvNode,e.levelNode=this.levelNode,e.biasNode=this.biasNode,e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e}}class Fi extends ot{static get type(){return"PassNode"}constructor(e,t,s,i={}){super("vec4"),this.scope=e,this.scene=t,this.camera=s,this.options=i,this._pixelRatio=1,this._width=1,this._height=1;const n=new Bs;n.isRenderTargetTexture=!0,n.name="depth";const a=new nn(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:Et,...i});a.texture.name="output",a.depthTexture=n,this.renderTarget=a,this.overrideMaterial=null,this.transparent=!0,this.opaque=!0,this.contextNode=null,this._contextNodeCache=null,this._textures={output:a.texture,depth:n},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=ee(0),this._cameraFar=ee(0),this._mrt=null,this._layers=null,this._resolutionScale=1,this._viewport=null,this._scissor=null,this.isPassNode=!0,this.updateBeforeType=re.FRAME,this.global=!0}setResolutionScale(e){return this._resolutionScale=e,this}getResolutionScale(){return this._resolutionScale}setResolution(e){return W("PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead."),this.setResolutionScale(e)}getResolution(){return W("PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead."),this.getResolutionScale()}setLayers(e){return this._layers=e,this}getLayers(){return this._layers}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getTexture(e){let t=this._textures[e];return t===void 0&&(t=this.renderTarget.texture.clone(),t.name=e,this._textures[e]=t,this.renderTarget.textures.push(t)),t}getPreviousTexture(e){let t=this._previousTextures[e];return t===void 0&&(t=this.getTexture(e).clone(),this._previousTextures[e]=t),t}toggleTexture(e){const t=this._previousTextures[e];if(t!==void 0){const s=this._textures[e],i=this.renderTarget.textures.indexOf(s);this.renderTarget.textures[i]=t,this._textures[e]=t,this._previousTextures[e]=s,this._textureNodes[e].updateTexture(),this._previousTextureNodes[e].updateTexture()}}getTextureNode(e="output"){let t=this._textureNodes[e];return t===void 0&&(t=new sy(this,e),t.updateTexture(),this._textureNodes[e]=t),t}getPreviousTextureNode(e="output"){let t=this._previousTextureNodes[e];return t===void 0&&(this._textureNodes[e]===void 0&&this.getTextureNode(e),t=new sy(this,e,!0),t.updateTexture(),this._previousTextureNodes[e]=t),t}getViewZNode(e="depth"){let t=this._viewZNodes[e];if(t===void 0){const s=this._cameraNear,i=this._cameraFar;this._viewZNodes[e]=t=rm(this.getTextureNode(e),s,i)}return t}getLinearDepthNode(e="depth"){let t=this._linearDepthNodes[e];if(t===void 0){const s=this._cameraNear,i=this._cameraFar,n=this.getViewZNode(e);this._linearDepthNodes[e]=t=va(n,s,i)}return t}async compileAsync(e){const t=e.getRenderTarget(),s=e.getMRT();e.setRenderTarget(this.renderTarget),e.setMRT(this._mrt),await e.compileAsync(this.scene,this.camera),e.setRenderTarget(t),e.setMRT(s)}setup({renderer:e}){return this.renderTarget.samples=this.options.samples===void 0?e.samples:this.options.samples,this.renderTarget.texture.type=e.getOutputBufferType(),this.scope===Fi.COLOR?this.getTextureNode():this.getLinearDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:s}=this;let i,n;const a=t.getOutputRenderTarget();a&&a.isXRRenderTarget===!0?(n=1,i=t.xr.getCamera(),t.xr.updateCamera(i),Zl.set(a.width,a.height)):(i=this.camera,n=t.getPixelRatio(),t.getSize(Zl)),this._pixelRatio=n,this.setSize(Zl.width,Zl.height);const o=t.getRenderTarget(),l=t.getMRT(),c=t.autoClear,u=t.transparent,h=t.opaque,d=i.layers.mask,p=t.contextNode,f=s.overrideMaterial;this._cameraNear.value=i.near,this._cameraFar.value=i.far,this._layers!==null&&(i.layers.mask=this._layers.mask);for(const x in this._previousTextures)this.toggleTexture(x);this.overrideMaterial!==null&&(s.overrideMaterial=this.overrideMaterial),t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.autoClear=!0,t.transparent=this.transparent,t.opaque=this.opaque,this.contextNode!==null&&((this._contextNodeCache===null||this._contextNodeCache.version!==this.version)&&(this._contextNodeCache={version:this.version,context:rn({...t.contextNode.getFlowContextData(),...this.contextNode.getFlowContextData()})}),t.contextNode=this._contextNodeCache.context);const m=s.name;s.name=this.name?this.name:s.name,t.render(s,i),s.name=m,s.overrideMaterial=f,t.setRenderTarget(o),t.setMRT(l),t.autoClear=c,t.transparent=u,t.opaque=h,t.contextNode=p,i.layers.mask=d}setSize(e,t){this._width=e,this._height=t;const s=Math.floor(this._width*this._pixelRatio*this._resolutionScale),i=Math.floor(this._height*this._pixelRatio*this._resolutionScale);this.renderTarget.setSize(s,i),this._scissor!==null&&this.renderTarget.scissor.copy(this._scissor),this._viewport!==null&&this.renderTarget.viewport.copy(this._viewport)}setScissor(e,t,s,i){e===null?this._scissor=null:(this._scissor===null&&(this._scissor=new Ee),e.isVector4?this._scissor.copy(e):this._scissor.set(e,t,s,i),this._scissor.multiplyScalar(this._pixelRatio*this._resolutionScale).floor())}setViewport(e,t,s,i){e===null?this._viewport=null:(this._viewport===null&&(this._viewport=new Ee),e.isVector4?this._viewport.copy(e):this._viewport.set(e,t,s,i),this._viewport.multiplyScalar(this._pixelRatio*this._resolutionScale).floor())}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}Fi.COLOR="color";Fi.DEPTH="depth";const IP=(r,e,t)=>new Fi(Fi.COLOR,r,e,t),UP=(r,e)=>new HT(r,e),VP=(r,e,t)=>new Fi(Fi.DEPTH,r,e,t);class kP extends Fi{static get type(){return"ToonOutlinePassNode"}constructor(e,t,s,i,n){super(Fi.COLOR,e,t),this.colorNode=s,this.thicknessNode=i,this.alphaNode=n,this._materialCache=new WeakMap,this.name="Outline Pass"}updateBefore(e){const{renderer:t}=e,s=t.getRenderObjectFunction();t.setRenderObjectFunction((i,n,a,o,l,c,u,h)=>{if((l.isMeshToonMaterial||l.isMeshToonNodeMaterial)&&l.wireframe===!1){const d=this._getOutlineMaterial(l);t.renderObject(i,n,a,o,d,c,u,h)}t.renderObject(i,n,a,o,l,c,u,h)}),super.updateBefore(e),t.setRenderObjectFunction(s)}_createMaterial(){const e=new st;e.isMeshToonOutlineMaterial=!0,e.name="Toon_Outline",e.side=Rt;const t=rs.negate(),s=en.mul(Hn),i=T(1),n=s.mul(ie(Je,1)),a=s.mul(ie(Je.add(t),1)),o=is(n.sub(a));return e.vertexNode=n.add(o.mul(this.thicknessNode).mul(n.w).mul(i)),e.colorNode=ie(this.colorNode,this.alphaNode),e}_getOutlineMaterial(e){let t=this._materialCache.get(e);return t===void 0&&(t=this._createMaterial(),this._materialCache.set(e,t)),t}}const zP=(r,e,t=new Ne(0,0,0),s=.003,i=1)=>new kP(r,e,Z(t),Z(s),Z(i)),jT=R(([r,e])=>r.mul(e).clamp()).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),qT=R(([r,e])=>(r=r.mul(e),r.div(r.add(1)).clamp())).setLayout({name:"reinhardToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),XT=R(([r,e])=>{r=r.mul(e),r=r.sub(.004).max(0);const t=r.mul(r.mul(6.2).add(.5)),s=r.mul(r.mul(6.2).add(1.7)).add(.06);return t.div(s).pow(2.2)}).setLayout({name:"cineonToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),GP=R(([r])=>{const e=r.mul(r.add(.0245786)).sub(90537e-9),t=r.mul(r.add(.432951).mul(.983729)).add(.238081);return e.div(t)}),YT=R(([r,e])=>{const t=wt(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),s=wt(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return r=r.mul(e).div(.6),r=t.mul(r),r=GP(r),r=s.mul(r),r.clamp()}).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),$P=wt(E(1.6605,-.1246,-.0182),E(-.5876,1.1329,-.1006),E(-.0728,-.0083,1.1187)),WP=wt(E(.6274,.0691,.0164),E(.3293,.9195,.088),E(.0433,.0113,.8956)),HP=R(([r])=>{const e=E(r).toVar(),t=E(e.mul(e)).toVar(),s=E(t.mul(t)).toVar();return T(15.5).mul(s.mul(t)).sub(ae(40.14,s.mul(e))).add(ae(31.96,s).sub(ae(6.868,t.mul(e))).add(ae(.4298,t).add(ae(.1191,e).sub(.00232))))}),ZT=R(([r,e])=>{const t=E(r).toVar(),s=wt(E(.856627153315983,.137318972929847,.11189821299995),E(.0951212405381588,.761241990602591,.0767994186031903),E(.0482516061458583,.101439036467562,.811302368396859)),i=wt(E(1.1271005818144368,-.1413297634984383,-.14132976349843826),E(-.11060664309660323,1.157823702216272,-.11060664309660294),E(-.016493938717834573,-.016493938717834257,1.2519364065950405)),n=T(-12.47393),a=T(4.026069);return t.mulAssign(e),t.assign(WP.mul(t)),t.assign(s.mul(t)),t.assign(tt(t,1e-10)),t.assign(vi(t)),t.assign(t.sub(n).div(a.sub(n))),t.assign(ei(t,0,1)),t.assign(HP(t)),t.assign(i.mul(t)),t.assign(Rs(tt(E(0),t),E(2.2))),t.assign($P.mul(t)),t.assign(ei(t,0,1)),t}).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),QT=R(([r,e])=>{const t=T(.76),s=T(.15);r=r.mul(e);const i=ns(r.r,ns(r.g,r.b)),n=Vt(i.lessThan(.08),i.sub(ae(6.25,i.mul(i))),.04);r.subAssign(n);const a=tt(r.r,tt(r.g,r.b));ne(a.lessThan(t),()=>r);const o=Te(1,t),l=Te(1,o.mul(o).div(a.add(o.sub(t))));r.mulAssign(l.div(a));const c=Te(1,bs(1,s.mul(a.sub(l)).add(1)));return ye(r,E(l),c)}).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class _t extends Q{static get type(){return"CodeNode"}constructor(e="",t=[],s=""){super("code"),this.isCodeNode=!0,this.global=!0,this.code=e,this.includes=t,this.language=s}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);const s=e.getCodeFromNode(this,this.getNodeType(e));return s.code=this.code,s.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}}const hh=ue(_t).setParameterLength(1,3),jP=(r,e)=>hh(r,e,"js"),qP=(r,e)=>hh(r,e,"wgsl"),XP=(r,e)=>hh(r,e,"glsl");class KT extends _t{static get type(){return"FunctionNode"}constructor(e="",t=[],s=""){super(e,t,s)}getNodeType(e){return this.getNodeFunction(e).type}getMemberType(e,t){const s=this.getNodeType(e);return e.getStructTypeNode(s).getMemberType(e,t)}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){const t=e.getDataFromNode(this);let s=t.nodeFunction;return s===void 0&&(s=e.parser.parseFunction(this.code),t.nodeFunction=s),s}generate(e,t){super.generate(e);const s=this.getNodeFunction(e),i=s.name,n=s.type,a=e.getCodeFromNode(this,n);i!==""&&(a.name=i);const o=e.getPropertyName(a),l=this.getNodeFunction(e).getCode(o);return a.code=l+`
56
- `,t==="property"?o:e.format(`${o}()`,n,t)}}const JT=(r,e=[],t="")=>{for(let n=0;n<e.length;n++){const a=e[n];typeof a=="function"&&(e[n]=a.functionNode)}const s=new KT(r,e,t),i=(...n)=>s.call(...n);return i.functionNode=s,i},YP=(r,e)=>JT(r,e,"glsl"),ZP=(r,e)=>JT(r,e,"wgsl");function Tm(r){let e;const t=r.context.getViewZ;return t!==void 0&&(e=t(this)),(e||lt.z).negate()}const eS=R(([r,e],t)=>{const s=Tm(t);return ti(r,e,s)}),tS=R(([r],e)=>{const t=Tm(e);return r.mul(r,t,t).negate().exp().oneMinus()}),QP=R(([r,e],t)=>{const s=Tm(t),n=e.sub(Ai.y).max(0).toConst().mul(s).toConst();return r.mul(r,n,n).negate().exp().oneMinus()}),Ap=R(([r,e])=>ie(e.toFloat().mix(Ta.rgb,r.toVec3()),Ta.a));let er=null,tr=null;class KP extends Q{static get type(){return"RangeNode"}constructor(e=T(),t=T()){super(),this.minNode=e,this.maxNode=t}getVectorLength(e){const t=this.getConstNode(this.minNode),s=this.getConstNode(this.maxNode),i=e.getTypeLength(Nn(t.value)),n=e.getTypeLength(Nn(s.value));return i>n?i:n}getNodeType(e){return e.object.count>1?e.getTypeFromLength(this.getVectorLength(e)):"float"}getConstNode(e){let t=null;if(e.traverse(s=>{s.isConstNode===!0&&(t=s)}),t===null)throw new U_('THREE.TSL: No "ConstNode" found in node graph.',this.stackTrace);return t}setup(e){const t=e.object;let s=null;if(t.count>1){const i=this.getConstNode(this.minNode),n=this.getConstNode(this.maxNode),a=i.value,o=n.value,l=e.getTypeLength(Nn(a)),c=e.getTypeLength(Nn(o));er=er||new Ee,tr=tr||new Ee,er.setScalar(0),tr.setScalar(0),l===1?er.setScalar(a):a.isColor?er.set(a.r,a.g,a.b,1):er.set(a.x,a.y,a.z||0,a.w||0),c===1?tr.setScalar(o):o.isColor?tr.set(o.r,o.g,o.b,1):tr.set(o.x,o.y,o.z||0,o.w||0);const u=4,h=u*t.count,d=new Float32Array(h);for(let m=0;m<h;m++){const x=m%u,y=er.getComponent(x),b=tr.getComponent(x);d[m]=Hx.lerp(y,b,Math.random())}const p=this.getNodeType(e);if(t.count*4*4<=e.getUniformBufferLimit())s=tl(d,"vec4",t.count).element(Ei).convert(p);else{const m=new _a(d,4);e.geometry.setAttribute("__range"+this.id,m),s=gu(m).convert(p)}}else s=T(0);return s}}const JP=ue(KP).setParameterLength(2);class eF extends Q{static get type(){return"ComputeBuiltinNode"}constructor(e,t){super(t),this._builtinName=e}getHash(e){return this.getBuiltinName(e)}getNodeType(){return this.nodeType}setBuiltinName(e){return this._builtinName=e,this}getBuiltinName(){return this._builtinName}hasBuiltin(e){return e.hasBuiltin(this._builtinName)}generate(e,t){const s=this.getBuiltinName(e),i=this.getNodeType(e);return e.shaderStage==="compute"?e.format(s,i,t):(W(`ComputeBuiltinNode: Compute built-in value ${s} can not be accessed in the ${e.shaderStage} stage`),e.generateConst(i))}serialize(e){super.serialize(e),e.global=this.global,e._builtinName=this._builtinName}deserialize(e){super.deserialize(e),this.global=e.global,this._builtinName=e._builtinName}}const rl=(r,e)=>new eF(r,e),tF=rl("numWorkgroups","uvec3"),sF=rl("workgroupId","uvec3"),iF=rl("globalId","uvec3"),nF=rl("localId","uvec3"),rF=rl("subgroupSize","uint");class aF extends Q{constructor(e){super(),this.scope=e}generate(e){const{scope:t}=this,{renderer:s}=e;s.backend.isWebGLBackend===!0?e.addFlowCode(` // ${t}Barrier
57
- `):e.addLineFlowCode(`${t}Barrier()`,this)}}const Sm=ue(aF),oF=()=>Sm("workgroup").toStack(),lF=()=>Sm("storage").toStack(),cF=()=>Sm("texture").toStack();class uF extends Cr{constructor(e,t){super(e,t),this.isWorkgroupInfoElementNode=!0}generate(e,t){let s;const i=e.context.assign;if(s=super.generate(e),i!==!0){const n=this.getNodeType(e);s=e.format(s,n,t)}return s}}class hF extends Q{constructor(e,t,s=0){super(t),this.bufferType=t,this.bufferCount=s,this.isWorkgroupInfoNode=!0,this.elementType=t,this.scope=e,this.name=""}setName(e){return this.name=e,this}label(e){return W('TSL: "label()" has been deprecated. Use "setName()" instead.',new ct),this.setName(e)}setScope(e){return this.scope=e,this}getElementType(){return this.elementType}getInputType(){return`${this.scope}Array`}element(e){return new uF(this,e)}generate(e){const t=this.name!==""?this.name:`${this.scope}Array_${this.id}`;return e.getScopedArray(t,this.scope.toLowerCase(),this.bufferType,this.bufferCount)}}const dF=(r,e)=>new hF("Workgroup",r,e);class St extends Q{static get type(){return"AtomicFunctionNode"}constructor(e,t,s){super("uint"),this.method=e,this.pointerNode=t,this.valueNode=s,this.parents=!0}getInputType(e){return this.pointerNode.getNodeType(e)}getNodeType(e){return this.getInputType(e)}generate(e){const t=e.getNodeProperties(this),s=t.parents,i=this.method,n=this.getNodeType(e),a=this.getInputType(e),o=this.pointerNode,l=this.valueNode,c=[];c.push(`&${o.build(e,a)}`),l!==null&&c.push(l.build(e,a));const u=`${e.getMethod(i,n)}( ${c.join(", ")} )`;if(s?s.length===1&&s[0].isStackNode===!0:!1)e.addLineFlowCode(u,this);else return t.constNode===void 0&&(t.constNode=Ks(u,n).toConst()),t.constNode.build(e)}}St.ATOMIC_LOAD="atomicLoad";St.ATOMIC_STORE="atomicStore";St.ATOMIC_ADD="atomicAdd";St.ATOMIC_SUB="atomicSub";St.ATOMIC_MAX="atomicMax";St.ATOMIC_MIN="atomicMin";St.ATOMIC_AND="atomicAnd";St.ATOMIC_OR="atomicOr";St.ATOMIC_XOR="atomicXor";const pF=ue(St),Di=(r,e,t)=>pF(r,e,t).toStack(),fF=r=>Di(St.ATOMIC_LOAD,r,null),mF=(r,e)=>Di(St.ATOMIC_STORE,r,e),gF=(r,e)=>Di(St.ATOMIC_ADD,r,e),yF=(r,e)=>Di(St.ATOMIC_SUB,r,e),xF=(r,e)=>Di(St.ATOMIC_MAX,r,e),_F=(r,e)=>Di(St.ATOMIC_MIN,r,e),bF=(r,e)=>Di(St.ATOMIC_AND,r,e),TF=(r,e)=>Di(St.ATOMIC_OR,r,e),SF=(r,e)=>Di(St.ATOMIC_XOR,r,e);class j extends ot{static get type(){return"SubgroupFunctionNode"}constructor(e,t=null,s=null){super(),this.method=e,this.aNode=t,this.bNode=s}getInputType(e){const t=this.aNode?this.aNode.getNodeType(e):null,s=this.bNode?this.bNode.getNodeType(e):null,i=e.isMatrix(t)?0:e.getTypeLength(t),n=e.isMatrix(s)?0:e.getTypeLength(s);return i>n?t:s}getNodeType(e){const t=this.method;return t===j.SUBGROUP_ELECT?"bool":t===j.SUBGROUP_BALLOT?"uvec4":this.getInputType(e)}generate(e,t){const s=this.method,i=this.getNodeType(e),n=this.getInputType(e),a=this.aNode,o=this.bNode,l=[];if(s===j.SUBGROUP_BROADCAST||s===j.SUBGROUP_SHUFFLE||s===j.QUAD_BROADCAST){const u=o.getNodeType(e);l.push(a.build(e,i),o.build(e,u==="float"?"int":i))}else s===j.SUBGROUP_SHUFFLE_XOR||s===j.SUBGROUP_SHUFFLE_DOWN||s===j.SUBGROUP_SHUFFLE_UP?l.push(a.build(e,i),o.build(e,"uint")):(a!==null&&l.push(a.build(e,n)),o!==null&&l.push(o.build(e,n)));const c=l.length===0?"()":`( ${l.join(", ")} )`;return e.format(`${e.getMethod(s,i)}${c}`,i,t)}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}j.SUBGROUP_ELECT="subgroupElect";j.SUBGROUP_BALLOT="subgroupBallot";j.SUBGROUP_ADD="subgroupAdd";j.SUBGROUP_INCLUSIVE_ADD="subgroupInclusiveAdd";j.SUBGROUP_EXCLUSIVE_AND="subgroupExclusiveAdd";j.SUBGROUP_MUL="subgroupMul";j.SUBGROUP_INCLUSIVE_MUL="subgroupInclusiveMul";j.SUBGROUP_EXCLUSIVE_MUL="subgroupExclusiveMul";j.SUBGROUP_AND="subgroupAnd";j.SUBGROUP_OR="subgroupOr";j.SUBGROUP_XOR="subgroupXor";j.SUBGROUP_MIN="subgroupMin";j.SUBGROUP_MAX="subgroupMax";j.SUBGROUP_ALL="subgroupAll";j.SUBGROUP_ANY="subgroupAny";j.SUBGROUP_BROADCAST_FIRST="subgroupBroadcastFirst";j.QUAD_SWAP_X="quadSwapX";j.QUAD_SWAP_Y="quadSwapY";j.QUAD_SWAP_DIAGONAL="quadSwapDiagonal";j.SUBGROUP_BROADCAST="subgroupBroadcast";j.SUBGROUP_SHUFFLE="subgroupShuffle";j.SUBGROUP_SHUFFLE_XOR="subgroupShuffleXor";j.SUBGROUP_SHUFFLE_UP="subgroupShuffleUp";j.SUBGROUP_SHUFFLE_DOWN="subgroupShuffleDown";j.QUAD_BROADCAST="quadBroadcast";const vF=G(j,j.SUBGROUP_ELECT).setParameterLength(0),MF=G(j,j.SUBGROUP_BALLOT).setParameterLength(1),wF=G(j,j.SUBGROUP_ADD).setParameterLength(1),CF=G(j,j.SUBGROUP_INCLUSIVE_ADD).setParameterLength(1),AF=G(j,j.SUBGROUP_EXCLUSIVE_AND).setParameterLength(1),EF=G(j,j.SUBGROUP_MUL).setParameterLength(1),NF=G(j,j.SUBGROUP_INCLUSIVE_MUL).setParameterLength(1),RF=G(j,j.SUBGROUP_EXCLUSIVE_MUL).setParameterLength(1),PF=G(j,j.SUBGROUP_AND).setParameterLength(1),FF=G(j,j.SUBGROUP_OR).setParameterLength(1),BF=G(j,j.SUBGROUP_XOR).setParameterLength(1),DF=G(j,j.SUBGROUP_MIN).setParameterLength(1),OF=G(j,j.SUBGROUP_MAX).setParameterLength(1),LF=G(j,j.SUBGROUP_ALL).setParameterLength(0),IF=G(j,j.SUBGROUP_ANY).setParameterLength(0),UF=G(j,j.SUBGROUP_BROADCAST_FIRST).setParameterLength(2),VF=G(j,j.QUAD_SWAP_X).setParameterLength(1),kF=G(j,j.QUAD_SWAP_Y).setParameterLength(1),zF=G(j,j.QUAD_SWAP_DIAGONAL).setParameterLength(1),GF=G(j,j.SUBGROUP_BROADCAST).setParameterLength(2),$F=G(j,j.SUBGROUP_SHUFFLE).setParameterLength(2),WF=G(j,j.SUBGROUP_SHUFFLE_XOR).setParameterLength(2),HF=G(j,j.SUBGROUP_SHUFFLE_UP).setParameterLength(2),jF=G(j,j.SUBGROUP_SHUFFLE_DOWN).setParameterLength(2),qF=G(j,j.QUAD_BROADCAST).setParameterLength(1);let Ql;function dh(r){Ql=Ql||new WeakMap;let e=Ql.get(r);return e===void 0&&Ql.set(r,e={}),e}function ph(r){const e=dh(r);return e.shadowMatrix||(e.shadowMatrix=ee("mat4").setGroup(se).onRenderUpdate(t=>((r.castShadow!==!0||t.renderer.shadowMap.enabled===!1)&&(r.shadow.camera.coordinateSystem!==t.camera.coordinateSystem&&(r.shadow.camera.coordinateSystem=t.camera.coordinateSystem,r.shadow.camera.updateProjectionMatrix()),r.shadow.updateMatrices(r)),r.shadow.matrix)))}function sS(r,e=Ai){const t=ph(r).mul(e);return t.xyz.div(t.w)}function vm(r){const e=dh(r);return e.position||(e.position=ee(new D).setGroup(se).onRenderUpdate((t,s)=>s.value.setFromMatrixPosition(r.matrixWorld)))}function iS(r){const e=dh(r);return e.targetPosition||(e.targetPosition=ee(new D).setGroup(se).onRenderUpdate((t,s)=>s.value.setFromMatrixPosition(r.target.matrixWorld)))}function Mm(r){const e=dh(r);return e.viewPosition||(e.viewPosition=ee(new D).setGroup(se).onRenderUpdate(({camera:t},s)=>{s.value=s.value||new D,s.value.setFromMatrixPosition(r.matrixWorld),s.value.applyMatrix4(t.matrixWorldInverse)}))}const wm=r=>Gs.transformDirection(vm(r).sub(iS(r))),XF=r=>r.sort((e,t)=>e.id-t.id),YF=(r,e)=>{for(const t of e)if(t.isAnalyticLightNode&&t.light.id===r)return t;return null},md=new WeakMap,so=[];class Cm extends Q{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=Ji("vec3","totalDiffuse"),this.totalSpecularNode=Ji("vec3","totalSpecular"),this.outgoingLightNode=Ji("vec3","outgoingLight"),this._lights=[],this._lightNodes=null,this._lightNodesHash=null,this.global=!0}customCacheKey(){const e=this._lights;for(let s=0;s<e.length;s++){const i=e[s];if(so.push(i.id),so.push(i.castShadow?1:0),i.isSpotLight===!0){const n=i.map!==null?i.map.id:-1,a=i.colorNode?i.colorNode.getCacheKey():-1;so.push(n,a)}}const t=Ko(so);return so.length=0,t}getHash(e){if(this._lightNodesHash===null){this._lightNodes===null&&this.setupLightsNode(e);const t=[];for(const s of this._lightNodes)t.push(s.getHash());this._lightNodesHash="lights-"+t.join(",")}return this._lightNodesHash}analyze(e){const t=e.getNodeProperties(this);for(const s of t.nodes)s.build(e);t.outputNode.build(e)}setupLightsNode(e){const t=[],s=this._lightNodes,i=XF(this._lights),n=e.renderer.library;for(const a of i)if(a.isNode)t.push(Z(a));else{let o=null;if(s!==null&&(o=YF(a.id,s)),o===null){const l=n.getLightNodeClass(a.constructor);if(l===null){W(`LightsNode.setupNodeLights: Light node not found for ${a.constructor.name}`);continue}let c=null;md.has(a)?c=md.get(a):(c=new l(a),md.set(a,c)),t.push(c)}}this._lightNodes=t}setupDirectLight(e,t,s){const{lightingModel:i,reflectedLight:n}=e.context;i.direct({...s,lightNode:t,reflectedLight:n},e)}setupDirectRectAreaLight(e,t,s){const{lightingModel:i,reflectedLight:n}=e.context;i.directRectArea({...s,lightNode:t,reflectedLight:n},e)}setupLights(e,t){for(const s of t)s.build(e)}getLightNodes(e){return this._lightNodes===null&&this.setupLightsNode(e),this._lightNodes}setup(e){const t=e.lightsNode;e.lightsNode=this;let s=this.outgoingLightNode;const i=e.context,n=i.lightingModel,a=e.getNodeProperties(this);if(n){const{totalDiffuseNode:o,totalSpecularNode:l}=this;i.outgoingLight=s;const c=e.addStack();a.nodes=c.nodes,n.start(e);const{backdrop:u,backdropAlpha:h}=i,{directDiffuse:d,directSpecular:p,indirectDiffuse:f,indirectSpecular:m}=i.reflectedLight;let x=d.add(f);u!==null&&(h!==null?x=E(h.mix(x,u)):x=E(u)),o.assign(x),l.assign(p.add(m)),s.assign(o.add(l)),n.finish(e),s=s.bypass(e.removeStack())}else a.nodes=[];return e.lightsNode=t,s}setLights(e){return this._lights=e,this._lightNodes=null,this._lightNodesHash=null,this}getLights(){return this._lights}get hasLights(){return this._lights.length>0}}const ZF=(r=[])=>new Cm().setLights(r);class QF extends Q{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=re.RENDER,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){Am.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||Ai)}}const Am=Ji("vec3","shadowPositionWorld");function KF(r,e={}){return e.toneMapping=r.toneMapping,e.toneMappingExposure=r.toneMappingExposure,e.outputColorSpace=r.outputColorSpace,e.renderTarget=r.getRenderTarget(),e.activeCubeFace=r.getActiveCubeFace(),e.activeMipmapLevel=r.getActiveMipmapLevel(),e.renderObjectFunction=r.getRenderObjectFunction(),e.pixelRatio=r.getPixelRatio(),e.mrt=r.getMRT(),e.clearColor=r.getClearColor(e.clearColor||new Ne),e.clearAlpha=r.getClearAlpha(),e.autoClear=r.autoClear,e.scissorTest=r.getScissorTest(),e}function JF(r,e){return e=KF(r,e),r.setMRT(null),r.setRenderObjectFunction(null),r.setClearColor(0,1),r.autoClear=!0,e}function eB(r,e){r.toneMapping=e.toneMapping,r.toneMappingExposure=e.toneMappingExposure,r.outputColorSpace=e.outputColorSpace,r.setRenderTarget(e.renderTarget,e.activeCubeFace,e.activeMipmapLevel),r.setRenderObjectFunction(e.renderObjectFunction),r.setPixelRatio(e.pixelRatio),r.setMRT(e.mrt),r.setClearColor(e.clearColor,e.clearAlpha),r.autoClear=e.autoClear,r.setScissorTest(e.scissorTest)}function tB(r,e={}){return e.background=r.background,e.backgroundNode=r.backgroundNode,e.overrideMaterial=r.overrideMaterial,e}function sB(r,e){return e=tB(r,e),r.background=null,r.backgroundNode=null,r.overrideMaterial=null,e}function iB(r,e){r.background=e.background,r.backgroundNode=e.backgroundNode,r.overrideMaterial=e.overrideMaterial}function nB(r,e,t){return t=JF(r,t),t=sB(e,t),t}function rB(r,e,t){eB(r,t),iB(e,t)}const bu=new WeakMap,nS=R(({depthTexture:r,shadowCoord:e,depthLayer:t})=>{let s=we(r,e.xy).setName("t_basic");return r.isArrayTexture&&(s=s.depth(t)),s.compare(e.z)}),rS=R(({depthTexture:r,shadowCoord:e,shadow:t,depthLayer:s})=>{const i=(u,h)=>{let d=we(r,u);return r.isArrayTexture&&(d=d.depth(s)),d.compare(h)},n=Ye("mapSize","vec2",t).setGroup(se),a=Ye("radius","float",t).setGroup(se),o=z(1).div(n),l=a.mul(o.x),c=_m(Er.xy).mul(6.28318530718);return dt(i(e.xy.add(Zs(0,5,c).mul(l)),e.z),i(e.xy.add(Zs(1,5,c).mul(l)),e.z),i(e.xy.add(Zs(2,5,c).mul(l)),e.z),i(e.xy.add(Zs(3,5,c).mul(l)),e.z),i(e.xy.add(Zs(4,5,c).mul(l)),e.z)).mul(1/5)}),aS=R(({depthTexture:r,shadowCoord:e,shadow:t,depthLayer:s})=>{const i=(h,d)=>{let p=we(r,h);return r.isArrayTexture&&(p=p.depth(s)),p.compare(d)},n=Ye("mapSize","vec2",t).setGroup(se),a=z(1).div(n),o=a.x,l=a.y,c=e.xy,u=Js(c.mul(n).add(.5));return c.subAssign(u.mul(a)),dt(i(c,e.z),i(c.add(z(o,0)),e.z),i(c.add(z(0,l)),e.z),i(c.add(a),e.z),ye(i(c.add(z(o.negate(),0)),e.z),i(c.add(z(o.mul(2),0)),e.z),u.x),ye(i(c.add(z(o.negate(),l)),e.z),i(c.add(z(o.mul(2),l)),e.z),u.x),ye(i(c.add(z(0,l.negate())),e.z),i(c.add(z(0,l.mul(2))),e.z),u.y),ye(i(c.add(z(o,l.negate())),e.z),i(c.add(z(o,l.mul(2))),e.z),u.y),ye(ye(i(c.add(z(o.negate(),l.negate())),e.z),i(c.add(z(o.mul(2),l.negate())),e.z),u.x),ye(i(c.add(z(o.negate(),l.mul(2))),e.z),i(c.add(z(o.mul(2),l.mul(2))),e.z),u.x),u.y)).mul(1/9)}),oS=R(({depthTexture:r,shadowCoord:e,depthLayer:t},s)=>{let i=we(r).sample(e.xy);r.isArrayTexture&&(i=i.depth(t)),i=i.rg;const n=i.x,a=tt(1e-7,i.y.mul(i.y)),o=s.renderer.reversedDepthBuffer?Fa(n,e.z):Fa(e.z,n),l=T(1).toVar();return ne(o.notEqual(1),()=>{const c=e.z.sub(n);let u=a.div(a.add(c.mul(c)));u=ei(Te(u,.3).div(.65)),l.assign(tt(o,u))}),l}),lS=r=>{let e=bu.get(r);return e===void 0&&(e=new st,e.colorNode=ie(0,0,0,1),e.isShadowPassMaterial=!0,e.name="ShadowMaterial",e.blending=Xi,e.fog=!1,bu.set(r,e)),e},cS=r=>{const e=bu.get(r);e!==void 0&&(e.dispose(),bu.delete(r))},iy=new zn,Kr=[],uS=(r,e,t,s)=>{Kr[0]=r,Kr[1]=e;let i=iy.get(Kr);return(i===void 0||i.shadowType!==t||i.useVelocity!==s)&&(i=(n,a,o,l,c,u,...h)=>{(n.castShadow===!0||n.receiveShadow&&t===vo)&&(s&&(n0(n).useVelocity=!0),n.onBeforeShadow(r,n,o,e.camera,l,a.overrideMaterial,u),r.renderObject(n,a,o,l,c,u,...h),n.onAfterShadow(r,n,o,e.camera,l,a.overrideMaterial,u))},i.shadowType=t,i.useVelocity=s,iy.set(Kr,i)),Kr[0]=null,Kr[1]=null,i},aB=R(({samples:r,radius:e,size:t,shadowPass:s,depthLayer:i})=>{const n=T(0).toVar("meanVertical"),a=T(0).toVar("squareMeanVertical"),o=r.lessThanEqual(T(1)).select(T(0),T(2).div(r.sub(1))),l=r.lessThanEqual(T(1)).select(T(0),T(-1));Ie({start:w(0),end:w(r),type:"int",condition:"<"},({i:u})=>{const h=l.add(T(u).mul(o));let d=s.sample(dt(Er.xy,z(0,h).mul(e)).div(t));s.value.isArrayTexture&&(d=d.depth(i)),d=d.x,n.addAssign(d),a.addAssign(d.mul(d))}),n.divAssign(r),a.divAssign(r);const c=Zt(a.sub(n.mul(n)).max(0));return z(n,c)}),oB=R(({samples:r,radius:e,size:t,shadowPass:s,depthLayer:i})=>{const n=T(0).toVar("meanHorizontal"),a=T(0).toVar("squareMeanHorizontal"),o=r.lessThanEqual(T(1)).select(T(0),T(2).div(r.sub(1))),l=r.lessThanEqual(T(1)).select(T(0),T(-1));Ie({start:w(0),end:w(r),type:"int",condition:"<"},({i:u})=>{const h=l.add(T(u).mul(o));let d=s.sample(dt(Er.xy,z(h,0).mul(e)).div(t));s.value.isArrayTexture&&(d=d.depth(i)),n.addAssign(d.x),a.addAssign(dt(d.y.mul(d.y),d.x.mul(d.x)))}),n.divAssign(r),a.divAssign(r);const c=Zt(a.sub(n.mul(n)).max(0));return z(n,c)}),lB=[nS,rS,aS,oS];let gd;const Kl=new lh;class hS extends QF{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:s,shadowCoord:i,shadow:n,depthLayer:a}){const o=i.x.greaterThanEqual(0).and(i.x.lessThanEqual(1)).and(i.y.greaterThanEqual(0)).and(i.y.lessThanEqual(1)).and(i.z.lessThanEqual(1)),l=t({depthTexture:s,shadowCoord:i,shadow:n,depthLayer:a});return o.select(l,T(1))}setupShadowCoord(e,t){const{shadow:s}=this,{renderer:i}=e,n=s.biasNode||Ye("bias","float",s).setGroup(se);let a=t,o;if(s.camera.isOrthographicCamera||i.logarithmicDepthBuffer!==!0)a=a.xyz.div(a.w),o=a.z;else{const l=a.w;a=a.xy.div(l);const c=Ye("near","float",s.camera).setGroup(se),u=Ye("far","float",s.camera).setGroup(se);o=am(l.negate(),c,u)}return a=E(a.x,a.y.oneMinus(),i.reversedDepthBuffer?o.sub(n):o.add(n)),a}getShadowFilterFn(e){return lB[e]}setupRenderTarget(e,t){const s=new Bs(e.mapSize.width,e.mapSize.height);s.name="ShadowDepthTexture",s.compareFunction=t.renderer.reversedDepthBuffer?Ou:Du;const i=t.createRenderTarget(e.mapSize.width,e.mapSize.height);return i.texture.name="ShadowMap",i.texture.type=e.mapType,i.depthTexture=s,{shadowMap:i,depthTexture:s}}setupShadow(e){const{renderer:t,camera:s}=e,{light:i,shadow:n}=this,{depthTexture:a,shadowMap:o}=this.setupRenderTarget(n,e),l=t.shadowMap.type;if(l===Sx||l===zM?(a.minFilter=Gt,a.magFilter=Gt):(a.minFilter=at,a.magFilter=at),n.camera.coordinateSystem=s.coordinateSystem,n.camera.updateProjectionMatrix(),l===vo&&n.isPointLightShadow!==!0){a.compareFunction=null,o.depth>1?(o._vsmShadowMapVertical||(o._vsmShadowMapVertical=e.createRenderTarget(n.mapSize.width,n.mapSize.height,{format:_i,type:Et,depth:o.depth,depthBuffer:!1}),o._vsmShadowMapVertical.texture.name="VSMVertical"),this.vsmShadowMapVertical=o._vsmShadowMapVertical,o._vsmShadowMapHorizontal||(o._vsmShadowMapHorizontal=e.createRenderTarget(n.mapSize.width,n.mapSize.height,{format:_i,type:Et,depth:o.depth,depthBuffer:!1}),o._vsmShadowMapHorizontal.texture.name="VSMHorizontal"),this.vsmShadowMapHorizontal=o._vsmShadowMapHorizontal):(this.vsmShadowMapVertical=e.createRenderTarget(n.mapSize.width,n.mapSize.height,{format:_i,type:Et,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(n.mapSize.width,n.mapSize.height,{format:_i,type:Et,depthBuffer:!1}));let v=we(a);a.isArrayTexture&&(v=v.depth(this.depthLayer));let S=we(this.vsmShadowMapVertical.texture);a.isArrayTexture&&(S=S.depth(this.depthLayer));const M=Ye("blurSamples","float",n).setGroup(se),A=Ye("radius","float",n).setGroup(se),C=Ye("mapSize","vec2",n).setGroup(se);let P=this.vsmMaterialVertical||(this.vsmMaterialVertical=new st);P.fragmentNode=aB({samples:M,radius:A,size:C,shadowPass:v,depthLayer:this.depthLayer}).context(e.getSharedContext()),P.name="VSMVertical",P=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new st),P.fragmentNode=oB({samples:M,radius:A,size:C,shadowPass:S,depthLayer:this.depthLayer}).context(e.getSharedContext()),P.name="VSMHorizontal"}const c=Ye("intensity","float",n).setGroup(se),u=Ye("normalBias","float",n).setGroup(se),h=ph(i).mul(Am.add(jn.mul(u))),d=this.setupShadowCoord(e,h),p=n.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(p===null)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const f=l===vo&&n.isPointLightShadow!==!0?this.vsmShadowMapHorizontal.texture:a,m=this.setupShadowFilter(e,{filterFn:p,shadowTexture:o.texture,depthTexture:f,shadowCoord:d,shadow:n,depthLayer:this.depthLayer});let x;t.shadowMap.transmitted===!0&&(o.texture.isCubeTexture?x=Xt(o.texture,d.xyz):(x=we(o.texture,d),a.isArrayTexture&&(x=x.depth(this.depthLayer))));let y;x?y=ye(1,m.rgb.mix(x,1),c.mul(x.a)).toVar():y=ye(1,m,c).toVar(),this.shadowMap=o,this.shadow.map=o;const b=`${this.light.type} Shadow [ ${this.light.name||"ID: "+this.light.id} ]`;return x&&y.toInspector(`${b} / Color`,()=>this.shadowMap.texture.isCubeTexture?Xt(this.shadowMap.texture):we(this.shadowMap.texture)),y.toInspector(`${b} / Depth`,()=>this.shadowMap.texture.isCubeTexture?Xt(this.shadowMap.texture).r.oneMinus():nt(this.shadowMap.depthTexture,ze().mul(On(we(this.shadowMap.depthTexture)))).r.oneMinus())}setup(e){if(e.renderer.shadowMap.enabled!==!1)return R(()=>{const t=e.renderer.shadowMap.type;this._currentShadowType!==t&&(this._reset(),this._node=null);let s=this._node;return this.setupShadowPosition(e),s===null&&(this._node=s=this.setupShadow(e),this._currentShadowType=t),e.material.receivedShadowNode&&(s=e.material.receivedShadowNode(s)),s})()}renderShadow(e){const{shadow:t,shadowMap:s,light:i}=this,{renderer:n,scene:a}=e;t.updateMatrices(i),s.setSize(t.mapSize.width,t.mapSize.height,s.depth);const o=a.name;a.name=`Shadow Map [ ${i.name||"ID: "+i.id} ]`,n.render(a,t.camera),a.name=o}updateShadow(e){const{shadowMap:t,light:s,shadow:i}=this,{renderer:n,scene:a,camera:o}=e,l=n.shadowMap.type,c=t.depthTexture.version;this._depthVersionCached=c;const u=i.camera.layers.mask;(i.camera.layers.mask&4294967294)===0&&(i.camera.layers.mask=o.layers.mask);const h=n.getRenderObjectFunction(),d=n.getMRT(),p=d?d.has("velocity"):!1;gd=nB(n,a,gd),a.overrideMaterial=lS(s),n.setRenderObjectFunction(uS(n,i,l,p)),n.setClearColor(0,0),n.setRenderTarget(t),this.renderShadow(e),n.setRenderObjectFunction(h),l===vo&&i.isPointLightShadow!==!0&&this.vsmPass(n),i.camera.layers.mask=u,rB(n,a,gd)}vsmPass(e){const{shadow:t}=this,s=this.shadowMap.depth;this.vsmShadowMapVertical.setSize(t.mapSize.width,t.mapSize.height,s),this.vsmShadowMapHorizontal.setSize(t.mapSize.width,t.mapSize.height,s),e.setRenderTarget(this.vsmShadowMapVertical),Kl.material=this.vsmMaterialVertical,Kl.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),Kl.material=this.vsmMaterialHorizontal,Kl.render(e)}dispose(){this._reset(),super.dispose()}_reset(){this._currentShadowType=null,cS(this.light),this.shadowMap&&(this.shadowMap.dispose(),this.shadowMap=null),this.vsmShadowMapVertical!==null&&(this.vsmShadowMapVertical.dispose(),this.vsmShadowMapVertical=null,this.vsmMaterialVertical.dispose(),this.vsmMaterialVertical=null),this.vsmShadowMapHorizontal!==null&&(this.vsmShadowMapHorizontal.dispose(),this.vsmShadowMapHorizontal=null,this.vsmMaterialHorizontal.dispose(),this.vsmMaterialHorizontal=null)}updateBefore(e){const{shadow:t}=this;let s=t.needsUpdate||t.autoUpdate;s&&(this._cameraFrameId[e.camera]===e.frameId&&(s=!1),this._cameraFrameId[e.camera]=e.frameId),s&&(this.updateShadow(e),this.shadowMap.depthTexture.version===this._depthVersionCached&&(t.needsUpdate=!1))}}const dS=(r,e)=>new hS(r,e),cB=new Ne,ny=new ve,io=new D,yd=new D,uB=[new D(1,0,0),new D(-1,0,0),new D(0,-1,0),new D(0,1,0),new D(0,0,1),new D(0,0,-1)],hB=[new D(0,-1,0),new D(0,-1,0),new D(0,0,-1),new D(0,0,1),new D(0,-1,0),new D(0,-1,0)],dB=[new D(1,0,0),new D(-1,0,0),new D(0,1,0),new D(0,-1,0),new D(0,0,1),new D(0,0,-1)],pB=[new D(0,-1,0),new D(0,-1,0),new D(0,0,1),new D(0,0,-1),new D(0,-1,0),new D(0,-1,0)],pS=R(({depthTexture:r,bd3D:e,dp:t})=>Xt(r,e).compare(t)),fS=R(({depthTexture:r,bd3D:e,dp:t,shadow:s})=>{const i=Ye("radius","float",s).setGroup(se),n=Ye("mapSize","vec2",s).setGroup(se),a=i.div(n.x),o=We(e),l=is(tn(e,o.x.greaterThan(o.z).select(E(0,1,0),E(1,0,0)))),c=tn(e,l),u=_m(Er.xy).mul(6.28318530718),h=Zs(0,5,u),d=Zs(1,5,u),p=Zs(2,5,u),f=Zs(3,5,u),m=Zs(4,5,u);return Xt(r,e.add(l.mul(h.x).add(c.mul(h.y)).mul(a))).compare(t).add(Xt(r,e.add(l.mul(d.x).add(c.mul(d.y)).mul(a))).compare(t)).add(Xt(r,e.add(l.mul(p.x).add(c.mul(p.y)).mul(a))).compare(t)).add(Xt(r,e.add(l.mul(f.x).add(c.mul(f.y)).mul(a))).compare(t)).add(Xt(r,e.add(l.mul(m.x).add(c.mul(m.y)).mul(a))).compare(t)).mul(1/5)}),fB=R(({filterFn:r,depthTexture:e,shadowCoord:t,shadow:s},i)=>{const n=t.xyz.toConst(),a=n.abs().toConst(),o=a.x.max(a.y).max(a.z),l=ee("float").setGroup(se).onRenderUpdate(()=>s.camera.near),c=ee("float").setGroup(se).onRenderUpdate(()=>s.camera.far),u=Ye("bias","float",s).setGroup(se),h=T(1).toVar();return ne(o.sub(c).lessThanEqual(0).and(o.sub(l).greaterThanEqual(0)),()=>{let d;i.renderer.reversedDepthBuffer?(d=iT(o.negate(),l,c),d.subAssign(u)):(d=nm(o.negate(),l,c),d.addAssign(u));const p=n.normalize();h.assign(r({depthTexture:e,bd3D:p,dp:d,shadow:s}))}),h});class mB extends hS{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return e===kM?pS:fS}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,depthTexture:s,shadowCoord:i,shadow:n}){return fB({filterFn:t,depthTexture:s,shadowCoord:i,shadow:n})}setupRenderTarget(e,t){const s=new lC(e.mapSize.width);s.name="PointShadowDepthTexture",s.compareFunction=t.renderer.reversedDepthBuffer?Ou:Du;const i=t.createCubeRenderTarget(e.mapSize.width);return i.texture.name="PointShadowMap",i.depthTexture=s,{shadowMap:i,depthTexture:s}}renderShadow(e){const{shadow:t,shadowMap:s,light:i}=this,{renderer:n,scene:a}=e,o=t.camera,l=t.matrix,c=n.coordinateSystem===Ls,u=c?uB:dB,h=c?hB:pB;s.setSize(t.mapSize.width,t.mapSize.width);const d=n.autoClear,p=n.getClearColor(cB),f=n.getClearAlpha();n.autoClear=!1,n.setClearColor(t.clearColor,t.clearAlpha);for(let m=0;m<6;m++){n.setRenderTarget(s,m),n.clear();const x=i.distance||o.far;x!==o.far&&(o.far=x,o.updateProjectionMatrix()),io.setFromMatrixPosition(i.matrixWorld),o.position.copy(io),yd.copy(o.position),yd.add(u[m]),o.up.copy(h[m]),o.lookAt(yd),o.updateMatrixWorld(),l.makeTranslation(-io.x,-io.y,-io.z),ny.multiplyMatrices(o.projectionMatrix,o.matrixWorldInverse),t._frustum.setFromProjectionMatrix(ny,o.coordinateSystem,o.reversedDepth);const y=a.name;a.name=`Point Light Shadow [ ${i.name||"ID: "+i.id} ] - Face ${m+1}`,n.render(a,o),a.name=y}n.autoClear=d,n.setClearColor(p,f)}}const mS=(r,e)=>new mB(r,e);class Nr extends Va{static get type(){return"AnalyticLightNode"}constructor(e=null){super(),this.light=e,this.color=new Ne,this.colorNode=e&&e.colorNode||ee(this.color).setGroup(se),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=re.FRAME,e&&e.shadow&&(this._shadowDisposeListener=()=>{this.disposeShadow()},e.addEventListener("dispose",this._shadowDisposeListener))}dispose(){this._shadowDisposeListener&&this.light.removeEventListener("dispose",this._shadowDisposeListener),super.dispose()}disposeShadow(){this.shadowNode!==null&&(this.shadowNode.dispose(),this.shadowNode=null),this.shadowColorNode=null,this.baseColorNode!==null&&(this.colorNode=this.baseColorNode,this.baseColorNode=null)}getHash(){return this.light.uuid}getLightVector(e){return Mm(this.light).sub(e.context.positionView||lt)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return dS(this.light)}setupShadow(e){const{renderer:t}=e;if(t.shadowMap.enabled===!1)return;let s=this.shadowColorNode;if(s===null){const i=this.light.shadow.shadowNode;let n;i!==void 0?n=Z(i):n=this.setupShadowNode(),this.shadowNode=n,this.shadowColorNode=s=this.colorNode.mul(n),this.baseColorNode=this.colorNode}e.context.getShadow&&(s=e.context.getShadow(this,e)),this.colorNode=s}setup(e){this.colorNode=this.baseColorNode||this.colorNode,this.light.castShadow?e.object.receiveShadow&&this.setupShadow(e):this.shadowNode!==null&&(this.shadowNode.dispose(),this.shadowNode=null,this.shadowColorNode=null);const t=this.setupDirect(e),s=this.setupDirectRectArea(e);t&&e.lightsNode.setupDirectLight(e,this,t),s&&e.lightsNode.setupDirectRectAreaLight(e,this,s)}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}const Em=R(({lightDistance:r,cutoffDistance:e,decayExponent:t})=>{const s=r.pow(t).max(.01).reciprocal();return e.greaterThan(0).select(s.mul(r.div(e).pow4().oneMinus().clamp().pow2()),s)}),gS=({color:r,lightVector:e,cutoffDistance:t,decayExponent:s})=>{const i=e.normalize(),n=e.length(),a=Em({lightDistance:n,cutoffDistance:t,decayExponent:s}),o=r.mul(a);return{lightDirection:i,lightColor:o}};class gB extends Nr{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=ee(0).setGroup(se),this.decayExponentNode=ee(2).setGroup(se)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return mS(this.light)}setupDirect(e){return gS({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}const yB=R(([r=ze()])=>{const e=r.mul(2),t=e.x.floor(),s=e.y.floor();return t.add(s).mod(2).sign()}),xB=R(([r=ze()],{renderer:e,material:t})=>{const s=Df(r.mul(2).sub(1));let i;if(t.alphaToCoverage&&e.currentSamples>0){const n=T(s.fwidth()).toVar();i=ti(n.oneMinus(),n.add(1),s).oneMinus()}else i=Vt(s.greaterThan(1),0,1);return i}),Lo=R(([r,e,t])=>{const s=T(t).toVar(),i=T(e).toVar(),n=Us(r).toVar();return Vt(n,i,s)}).setLayout({name:"mx_select",type:"float",inputs:[{name:"b",type:"bool"},{name:"t",type:"float"},{name:"f",type:"float"}]}),Tu=R(([r,e])=>{const t=Us(e).toVar(),s=T(r).toVar();return Vt(t,s.negate(),s)}).setLayout({name:"mx_negate_if",type:"float",inputs:[{name:"val",type:"float"},{name:"b",type:"bool"}]}),ht=R(([r])=>{const e=T(r).toVar();return w(Mi(e))}).setLayout({name:"mx_floor",type:"int",inputs:[{name:"x",type:"float"}]}),Qe=R(([r,e])=>{const t=T(r).toVar();return e.assign(ht(t)),t.sub(T(e))}),_B=R(([r,e,t,s,i,n])=>{const a=T(n).toVar(),o=T(i).toVar(),l=T(s).toVar(),c=T(t).toVar(),u=T(e).toVar(),h=T(r).toVar(),d=T(Te(1,o)).toVar();return Te(1,a).mul(h.mul(d).add(u.mul(o))).add(a.mul(c.mul(d).add(l.mul(o))))}).setLayout({name:"mx_bilerp_0",type:"float",inputs:[{name:"v0",type:"float"},{name:"v1",type:"float"},{name:"v2",type:"float"},{name:"v3",type:"float"},{name:"s",type:"float"},{name:"t",type:"float"}]}),bB=R(([r,e,t,s,i,n])=>{const a=T(n).toVar(),o=T(i).toVar(),l=E(s).toVar(),c=E(t).toVar(),u=E(e).toVar(),h=E(r).toVar(),d=T(Te(1,o)).toVar();return Te(1,a).mul(h.mul(d).add(u.mul(o))).add(a.mul(c.mul(d).add(l.mul(o))))}).setLayout({name:"mx_bilerp_1",type:"vec3",inputs:[{name:"v0",type:"vec3"},{name:"v1",type:"vec3"},{name:"v2",type:"vec3"},{name:"v3",type:"vec3"},{name:"s",type:"float"},{name:"t",type:"float"}]}),yS=Pt([_B,bB]),TB=R(([r,e,t,s,i,n,a,o,l,c,u])=>{const h=T(u).toVar(),d=T(c).toVar(),p=T(l).toVar(),f=T(o).toVar(),m=T(a).toVar(),x=T(n).toVar(),y=T(i).toVar(),b=T(s).toVar(),v=T(t).toVar(),S=T(e).toVar(),M=T(r).toVar(),A=T(Te(1,p)).toVar(),C=T(Te(1,d)).toVar();return T(Te(1,h)).toVar().mul(C.mul(M.mul(A).add(S.mul(p))).add(d.mul(v.mul(A).add(b.mul(p))))).add(h.mul(C.mul(y.mul(A).add(x.mul(p))).add(d.mul(m.mul(A).add(f.mul(p))))))}).setLayout({name:"mx_trilerp_0",type:"float",inputs:[{name:"v0",type:"float"},{name:"v1",type:"float"},{name:"v2",type:"float"},{name:"v3",type:"float"},{name:"v4",type:"float"},{name:"v5",type:"float"},{name:"v6",type:"float"},{name:"v7",type:"float"},{name:"s",type:"float"},{name:"t",type:"float"},{name:"r",type:"float"}]}),SB=R(([r,e,t,s,i,n,a,o,l,c,u])=>{const h=T(u).toVar(),d=T(c).toVar(),p=T(l).toVar(),f=E(o).toVar(),m=E(a).toVar(),x=E(n).toVar(),y=E(i).toVar(),b=E(s).toVar(),v=E(t).toVar(),S=E(e).toVar(),M=E(r).toVar(),A=T(Te(1,p)).toVar(),C=T(Te(1,d)).toVar();return T(Te(1,h)).toVar().mul(C.mul(M.mul(A).add(S.mul(p))).add(d.mul(v.mul(A).add(b.mul(p))))).add(h.mul(C.mul(y.mul(A).add(x.mul(p))).add(d.mul(m.mul(A).add(f.mul(p))))))}).setLayout({name:"mx_trilerp_1",type:"vec3",inputs:[{name:"v0",type:"vec3"},{name:"v1",type:"vec3"},{name:"v2",type:"vec3"},{name:"v3",type:"vec3"},{name:"v4",type:"vec3"},{name:"v5",type:"vec3"},{name:"v6",type:"vec3"},{name:"v7",type:"vec3"},{name:"s",type:"float"},{name:"t",type:"float"},{name:"r",type:"float"}]}),xS=Pt([TB,SB]),vB=R(([r,e,t])=>{const s=T(t).toVar(),i=T(e).toVar(),n=k(r).toVar(),a=k(n.bitAnd(k(7))).toVar(),o=T(Lo(a.lessThan(k(4)),i,s)).toVar(),l=T(ae(2,Lo(a.lessThan(k(4)),s,i))).toVar();return Tu(o,Us(a.bitAnd(k(1)))).add(Tu(l,Us(a.bitAnd(k(2)))))}).setLayout({name:"mx_gradient_float_0",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"}]}),MB=R(([r,e,t,s])=>{const i=T(s).toVar(),n=T(t).toVar(),a=T(e).toVar(),o=k(r).toVar(),l=k(o.bitAnd(k(15))).toVar(),c=T(Lo(l.lessThan(k(8)),a,n)).toVar(),u=T(Lo(l.lessThan(k(4)),n,Lo(l.equal(k(12)).or(l.equal(k(14))),a,i))).toVar();return Tu(c,Us(l.bitAnd(k(1)))).add(Tu(u,Us(l.bitAnd(k(2)))))}).setLayout({name:"mx_gradient_float_1",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"},{name:"z",type:"float"}]}),Mt=Pt([vB,MB]),wB=R(([r,e,t])=>{const s=T(t).toVar(),i=T(e).toVar(),n=Ar(r).toVar();return E(Mt(n.x,i,s),Mt(n.y,i,s),Mt(n.z,i,s))}).setLayout({name:"mx_gradient_vec3_0",type:"vec3",inputs:[{name:"hash",type:"uvec3"},{name:"x",type:"float"},{name:"y",type:"float"}]}),CB=R(([r,e,t,s])=>{const i=T(s).toVar(),n=T(t).toVar(),a=T(e).toVar(),o=Ar(r).toVar();return E(Mt(o.x,a,n,i),Mt(o.y,a,n,i),Mt(o.z,a,n,i))}).setLayout({name:"mx_gradient_vec3_1",type:"vec3",inputs:[{name:"hash",type:"uvec3"},{name:"x",type:"float"},{name:"y",type:"float"},{name:"z",type:"float"}]}),ws=Pt([wB,CB]),AB=R(([r])=>{const e=T(r).toVar();return ae(.6616,e)}).setLayout({name:"mx_gradient_scale2d_0",type:"float",inputs:[{name:"v",type:"float"}]}),EB=R(([r])=>{const e=T(r).toVar();return ae(.982,e)}).setLayout({name:"mx_gradient_scale3d_0",type:"float",inputs:[{name:"v",type:"float"}]}),NB=R(([r])=>{const e=E(r).toVar();return ae(.6616,e)}).setLayout({name:"mx_gradient_scale2d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]}),_S=Pt([AB,NB]),RB=R(([r])=>{const e=E(r).toVar();return ae(.982,e)}).setLayout({name:"mx_gradient_scale3d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]}),bS=Pt([EB,RB]),ps=R(([r,e])=>{const t=w(e).toVar(),s=k(r).toVar();return s.shiftLeft(t).bitOr(s.shiftRight(w(32).sub(t)))}).setLayout({name:"mx_rotl32",type:"uint",inputs:[{name:"x",type:"uint"},{name:"k",type:"int"}]}),TS=R(([r,e,t])=>{r.subAssign(t),r.bitXorAssign(ps(t,w(4))),t.addAssign(e),e.subAssign(r),e.bitXorAssign(ps(r,w(6))),r.addAssign(t),t.subAssign(e),t.bitXorAssign(ps(e,w(8))),e.addAssign(r),r.subAssign(t),r.bitXorAssign(ps(t,w(16))),t.addAssign(e),e.subAssign(r),e.bitXorAssign(ps(r,w(19))),r.addAssign(t),t.subAssign(e),t.bitXorAssign(ps(e,w(4))),e.addAssign(r)}),al=R(([r,e,t])=>{const s=k(t).toVar(),i=k(e).toVar(),n=k(r).toVar();return s.bitXorAssign(i),s.subAssign(ps(i,w(14))),n.bitXorAssign(s),n.subAssign(ps(s,w(11))),i.bitXorAssign(n),i.subAssign(ps(n,w(25))),s.bitXorAssign(i),s.subAssign(ps(i,w(16))),n.bitXorAssign(s),n.subAssign(ps(s,w(4))),i.bitXorAssign(n),i.subAssign(ps(n,w(14))),s.bitXorAssign(i),s.subAssign(ps(i,w(24))),s}).setLayout({name:"mx_bjfinal",type:"uint",inputs:[{name:"a",type:"uint"},{name:"b",type:"uint"},{name:"c",type:"uint"}]}),zt=R(([r])=>{const e=k(r).toVar();return T(e).div(T(k(w(4294967295))))}).setLayout({name:"mx_bits_to_01",type:"float",inputs:[{name:"bits",type:"uint"}]}),Ni=R(([r])=>{const e=T(r).toVar();return e.mul(e).mul(e).mul(e.mul(e.mul(6).sub(15)).add(10))}).setLayout({name:"mx_fade",type:"float",inputs:[{name:"t",type:"float"}]}),PB=R(([r])=>{const e=w(r).toVar(),t=k(k(1)).toVar(),s=k(k(w(3735928559)).add(t.shiftLeft(k(2))).add(k(13))).toVar();return al(s.add(k(e)),s,s)}).setLayout({name:"mx_hash_int_0",type:"uint",inputs:[{name:"x",type:"int"}]}),FB=R(([r,e])=>{const t=w(e).toVar(),s=w(r).toVar(),i=k(k(2)).toVar(),n=k().toVar(),a=k().toVar(),o=k().toVar();return n.assign(a.assign(o.assign(k(w(3735928559)).add(i.shiftLeft(k(2))).add(k(13))))),n.addAssign(k(s)),a.addAssign(k(t)),al(n,a,o)}).setLayout({name:"mx_hash_int_1",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),BB=R(([r,e,t])=>{const s=w(t).toVar(),i=w(e).toVar(),n=w(r).toVar(),a=k(k(3)).toVar(),o=k().toVar(),l=k().toVar(),c=k().toVar();return o.assign(l.assign(c.assign(k(w(3735928559)).add(a.shiftLeft(k(2))).add(k(13))))),o.addAssign(k(n)),l.addAssign(k(i)),c.addAssign(k(s)),al(o,l,c)}).setLayout({name:"mx_hash_int_2",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]}),DB=R(([r,e,t,s])=>{const i=w(s).toVar(),n=w(t).toVar(),a=w(e).toVar(),o=w(r).toVar(),l=k(k(4)).toVar(),c=k().toVar(),u=k().toVar(),h=k().toVar();return c.assign(u.assign(h.assign(k(w(3735928559)).add(l.shiftLeft(k(2))).add(k(13))))),c.addAssign(k(o)),u.addAssign(k(a)),h.addAssign(k(n)),TS(c,u,h),c.addAssign(k(i)),al(c,u,h)}).setLayout({name:"mx_hash_int_3",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"},{name:"xx",type:"int"}]}),OB=R(([r,e,t,s,i])=>{const n=w(i).toVar(),a=w(s).toVar(),o=w(t).toVar(),l=w(e).toVar(),c=w(r).toVar(),u=k(k(5)).toVar(),h=k().toVar(),d=k().toVar(),p=k().toVar();return h.assign(d.assign(p.assign(k(w(3735928559)).add(u.shiftLeft(k(2))).add(k(13))))),h.addAssign(k(c)),d.addAssign(k(l)),p.addAssign(k(o)),TS(h,d,p),h.addAssign(k(a)),d.addAssign(k(n)),al(h,d,p)}).setLayout({name:"mx_hash_int_4",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"},{name:"xx",type:"int"},{name:"yy",type:"int"}]}),ke=Pt([PB,FB,BB,DB,OB]),LB=R(([r,e])=>{const t=w(e).toVar(),s=w(r).toVar(),i=k(ke(s,t)).toVar(),n=Ar().toVar();return n.x.assign(i.bitAnd(w(255))),n.y.assign(i.shiftRight(w(8)).bitAnd(w(255))),n.z.assign(i.shiftRight(w(16)).bitAnd(w(255))),n}).setLayout({name:"mx_hash_vec3_0",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),IB=R(([r,e,t])=>{const s=w(t).toVar(),i=w(e).toVar(),n=w(r).toVar(),a=k(ke(n,i,s)).toVar(),o=Ar().toVar();return o.x.assign(a.bitAnd(w(255))),o.y.assign(a.shiftRight(w(8)).bitAnd(w(255))),o.z.assign(a.shiftRight(w(16)).bitAnd(w(255))),o}).setLayout({name:"mx_hash_vec3_1",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]}),Cs=Pt([LB,IB]),UB=R(([r])=>{const e=z(r).toVar(),t=w().toVar(),s=w().toVar(),i=T(Qe(e.x,t)).toVar(),n=T(Qe(e.y,s)).toVar(),a=T(Ni(i)).toVar(),o=T(Ni(n)).toVar(),l=T(yS(Mt(ke(t,s),i,n),Mt(ke(t.add(w(1)),s),i.sub(1),n),Mt(ke(t,s.add(w(1))),i,n.sub(1)),Mt(ke(t.add(w(1)),s.add(w(1))),i.sub(1),n.sub(1)),a,o)).toVar();return _S(l)}).setLayout({name:"mx_perlin_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"}]}),VB=R(([r])=>{const e=E(r).toVar(),t=w().toVar(),s=w().toVar(),i=w().toVar(),n=T(Qe(e.x,t)).toVar(),a=T(Qe(e.y,s)).toVar(),o=T(Qe(e.z,i)).toVar(),l=T(Ni(n)).toVar(),c=T(Ni(a)).toVar(),u=T(Ni(o)).toVar(),h=T(xS(Mt(ke(t,s,i),n,a,o),Mt(ke(t.add(w(1)),s,i),n.sub(1),a,o),Mt(ke(t,s.add(w(1)),i),n,a.sub(1),o),Mt(ke(t.add(w(1)),s.add(w(1)),i),n.sub(1),a.sub(1),o),Mt(ke(t,s,i.add(w(1))),n,a,o.sub(1)),Mt(ke(t.add(w(1)),s,i.add(w(1))),n.sub(1),a,o.sub(1)),Mt(ke(t,s.add(w(1)),i.add(w(1))),n,a.sub(1),o.sub(1)),Mt(ke(t.add(w(1)),s.add(w(1)),i.add(w(1))),n.sub(1),a.sub(1),o.sub(1)),l,c,u)).toVar();return bS(h)}).setLayout({name:"mx_perlin_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"}]}),Nm=Pt([UB,VB]),kB=R(([r])=>{const e=z(r).toVar(),t=w().toVar(),s=w().toVar(),i=T(Qe(e.x,t)).toVar(),n=T(Qe(e.y,s)).toVar(),a=T(Ni(i)).toVar(),o=T(Ni(n)).toVar(),l=E(yS(ws(Cs(t,s),i,n),ws(Cs(t.add(w(1)),s),i.sub(1),n),ws(Cs(t,s.add(w(1))),i,n.sub(1)),ws(Cs(t.add(w(1)),s.add(w(1))),i.sub(1),n.sub(1)),a,o)).toVar();return _S(l)}).setLayout({name:"mx_perlin_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),zB=R(([r])=>{const e=E(r).toVar(),t=w().toVar(),s=w().toVar(),i=w().toVar(),n=T(Qe(e.x,t)).toVar(),a=T(Qe(e.y,s)).toVar(),o=T(Qe(e.z,i)).toVar(),l=T(Ni(n)).toVar(),c=T(Ni(a)).toVar(),u=T(Ni(o)).toVar(),h=E(xS(ws(Cs(t,s,i),n,a,o),ws(Cs(t.add(w(1)),s,i),n.sub(1),a,o),ws(Cs(t,s.add(w(1)),i),n,a.sub(1),o),ws(Cs(t.add(w(1)),s.add(w(1)),i),n.sub(1),a.sub(1),o),ws(Cs(t,s,i.add(w(1))),n,a,o.sub(1)),ws(Cs(t.add(w(1)),s,i.add(w(1))),n.sub(1),a,o.sub(1)),ws(Cs(t,s.add(w(1)),i.add(w(1))),n,a.sub(1),o.sub(1)),ws(Cs(t.add(w(1)),s.add(w(1)),i.add(w(1))),n.sub(1),a.sub(1),o.sub(1)),l,c,u)).toVar();return bS(h)}).setLayout({name:"mx_perlin_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),ol=Pt([kB,zB]),GB=R(([r])=>{const e=T(r).toVar(),t=w(ht(e)).toVar();return zt(ke(t))}).setLayout({name:"mx_cell_noise_float_0",type:"float",inputs:[{name:"p",type:"float"}]}),$B=R(([r])=>{const e=z(r).toVar(),t=w(ht(e.x)).toVar(),s=w(ht(e.y)).toVar();return zt(ke(t,s))}).setLayout({name:"mx_cell_noise_float_1",type:"float",inputs:[{name:"p",type:"vec2"}]}),WB=R(([r])=>{const e=E(r).toVar(),t=w(ht(e.x)).toVar(),s=w(ht(e.y)).toVar(),i=w(ht(e.z)).toVar();return zt(ke(t,s,i))}).setLayout({name:"mx_cell_noise_float_2",type:"float",inputs:[{name:"p",type:"vec3"}]}),HB=R(([r])=>{const e=ie(r).toVar(),t=w(ht(e.x)).toVar(),s=w(ht(e.y)).toVar(),i=w(ht(e.z)).toVar(),n=w(ht(e.w)).toVar();return zt(ke(t,s,i,n))}).setLayout({name:"mx_cell_noise_float_3",type:"float",inputs:[{name:"p",type:"vec4"}]}),jB=Pt([GB,$B,WB,HB]),qB=R(([r])=>{const e=T(r).toVar(),t=w(ht(e)).toVar();return E(zt(ke(t,w(0))),zt(ke(t,w(1))),zt(ke(t,w(2))))}).setLayout({name:"mx_cell_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"float"}]}),XB=R(([r])=>{const e=z(r).toVar(),t=w(ht(e.x)).toVar(),s=w(ht(e.y)).toVar();return E(zt(ke(t,s,w(0))),zt(ke(t,s,w(1))),zt(ke(t,s,w(2))))}).setLayout({name:"mx_cell_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),YB=R(([r])=>{const e=E(r).toVar(),t=w(ht(e.x)).toVar(),s=w(ht(e.y)).toVar(),i=w(ht(e.z)).toVar();return E(zt(ke(t,s,i,w(0))),zt(ke(t,s,i,w(1))),zt(ke(t,s,i,w(2))))}).setLayout({name:"mx_cell_noise_vec3_2",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),ZB=R(([r])=>{const e=ie(r).toVar(),t=w(ht(e.x)).toVar(),s=w(ht(e.y)).toVar(),i=w(ht(e.z)).toVar(),n=w(ht(e.w)).toVar();return E(zt(ke(t,s,i,n,w(0))),zt(ke(t,s,i,n,w(1))),zt(ke(t,s,i,n,w(2))))}).setLayout({name:"mx_cell_noise_vec3_3",type:"vec3",inputs:[{name:"p",type:"vec4"}]}),fh=Pt([qB,XB,YB,ZB]),Su=R(([r,e,t,s])=>{const i=T(s).toVar(),n=T(t).toVar(),a=w(e).toVar(),o=E(r).toVar(),l=T(0).toVar(),c=T(1).toVar();return Ie(a,()=>{l.addAssign(c.mul(Nm(o))),c.mulAssign(i),o.mulAssign(n)}),l}).setLayout({name:"mx_fractal_noise_float",type:"float",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),mh=R(([r,e,t,s])=>{const i=T(s).toVar(),n=T(t).toVar(),a=w(e).toVar(),o=E(r).toVar(),l=E(0).toVar(),c=T(1).toVar();return Ie(a,()=>{l.addAssign(c.mul(ol(o))),c.mulAssign(i),o.mulAssign(n)}),l}).setLayout({name:"mx_fractal_noise_vec3",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),QB=R(([r,e,t,s])=>{const i=T(s).toVar(),n=T(t).toVar(),a=w(e).toVar(),o=E(r).toVar();return z(Su(o,a,n,i),Su(o.add(E(w(19),w(193),w(17))),a,n,i))}).setLayout({name:"mx_fractal_noise_vec2",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),KB=R(([r,e,t,s])=>{const i=T(s).toVar(),n=T(t).toVar(),a=w(e).toVar(),o=E(r).toVar(),l=E(mh(o,a,n,i)).toVar(),c=T(Su(o.add(E(w(19),w(193),w(17))),a,n,i)).toVar();return ie(l,c)}).setLayout({name:"mx_fractal_noise_vec4",type:"vec4",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),JB=R(([r,e,t,s,i,n,a])=>{const o=w(a).toVar(),l=T(n).toVar(),c=w(i).toVar(),u=w(s).toVar(),h=w(t).toVar(),d=w(e).toVar(),p=z(r).toVar(),f=E(fh(z(d.add(u),h.add(c)))).toVar(),m=z(f.x,f.y).toVar();m.subAssign(.5),m.mulAssign(l),m.addAssign(.5);const x=z(z(T(d),T(h)).add(m)).toVar(),y=z(x.sub(p)).toVar();return ne(o.equal(w(2)),()=>We(y.x).add(We(y.y))),ne(o.equal(w(3)),()=>tt(We(y.x),We(y.y))),Vs(y,y)}).setLayout({name:"mx_worley_distance_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"x",type:"int"},{name:"y",type:"int"},{name:"xoff",type:"int"},{name:"yoff",type:"int"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),eD=R(([r,e,t,s,i,n,a,o,l])=>{const c=w(l).toVar(),u=T(o).toVar(),h=w(a).toVar(),d=w(n).toVar(),p=w(i).toVar(),f=w(s).toVar(),m=w(t).toVar(),x=w(e).toVar(),y=E(r).toVar(),b=E(fh(E(x.add(p),m.add(d),f.add(h)))).toVar();b.subAssign(.5),b.mulAssign(u),b.addAssign(.5);const v=E(E(T(x),T(m),T(f)).add(b)).toVar(),S=E(v.sub(y)).toVar();return ne(c.equal(w(2)),()=>We(S.x).add(We(S.y)).add(We(S.z))),ne(c.equal(w(3)),()=>tt(We(S.x),We(S.y),We(S.z))),Vs(S,S)}).setLayout({name:"mx_worley_distance_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"},{name:"xoff",type:"int"},{name:"yoff",type:"int"},{name:"zoff",type:"int"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),za=Pt([JB,eD]),tD=R(([r,e,t])=>{const s=w(t).toVar(),i=T(e).toVar(),n=z(r).toVar(),a=w().toVar(),o=w().toVar(),l=z(Qe(n.x,a),Qe(n.y,o)).toVar(),c=T(1e6).toVar();return Ie({start:-1,end:w(1),name:"x",condition:"<="},({x:u})=>{Ie({start:-1,end:w(1),name:"y",condition:"<="},({y:h})=>{const d=T(za(l,u,h,a,o,i,s)).toVar();c.assign(ns(c,d))})}),ne(s.equal(w(0)),()=>{c.assign(Zt(c))}),c}).setLayout({name:"mx_worley_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),sD=R(([r,e,t])=>{const s=w(t).toVar(),i=T(e).toVar(),n=z(r).toVar(),a=w().toVar(),o=w().toVar(),l=z(Qe(n.x,a),Qe(n.y,o)).toVar(),c=z(1e6,1e6).toVar();return Ie({start:-1,end:w(1),name:"x",condition:"<="},({x:u})=>{Ie({start:-1,end:w(1),name:"y",condition:"<="},({y:h})=>{const d=T(za(l,u,h,a,o,i,s)).toVar();ne(d.lessThan(c.x),()=>{c.y.assign(c.x),c.x.assign(d)}).ElseIf(d.lessThan(c.y),()=>{c.y.assign(d)})})}),ne(s.equal(w(0)),()=>{c.assign(Zt(c))}),c}).setLayout({name:"mx_worley_noise_vec2_0",type:"vec2",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),iD=R(([r,e,t])=>{const s=w(t).toVar(),i=T(e).toVar(),n=z(r).toVar(),a=w().toVar(),o=w().toVar(),l=z(Qe(n.x,a),Qe(n.y,o)).toVar(),c=E(1e6,1e6,1e6).toVar();return Ie({start:-1,end:w(1),name:"x",condition:"<="},({x:u})=>{Ie({start:-1,end:w(1),name:"y",condition:"<="},({y:h})=>{const d=T(za(l,u,h,a,o,i,s)).toVar();ne(d.lessThan(c.x),()=>{c.z.assign(c.y),c.y.assign(c.x),c.x.assign(d)}).ElseIf(d.lessThan(c.y),()=>{c.z.assign(c.y),c.y.assign(d)}).ElseIf(d.lessThan(c.z),()=>{c.z.assign(d)})})}),ne(s.equal(w(0)),()=>{c.assign(Zt(c))}),c}).setLayout({name:"mx_worley_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),nD=R(([r,e,t])=>{const s=w(t).toVar(),i=T(e).toVar(),n=E(r).toVar(),a=w().toVar(),o=w().toVar(),l=w().toVar(),c=E(Qe(n.x,a),Qe(n.y,o),Qe(n.z,l)).toVar(),u=T(1e6).toVar();return Ie({start:-1,end:w(1),name:"x",condition:"<="},({x:h})=>{Ie({start:-1,end:w(1),name:"y",condition:"<="},({y:d})=>{Ie({start:-1,end:w(1),name:"z",condition:"<="},({z:p})=>{const f=T(za(c,h,d,p,a,o,l,i,s)).toVar();u.assign(ns(u,f))})})}),ne(s.equal(w(0)),()=>{u.assign(Zt(u))}),u}).setLayout({name:"mx_worley_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),rD=Pt([tD,nD]),aD=R(([r,e,t])=>{const s=w(t).toVar(),i=T(e).toVar(),n=E(r).toVar(),a=w().toVar(),o=w().toVar(),l=w().toVar(),c=E(Qe(n.x,a),Qe(n.y,o),Qe(n.z,l)).toVar(),u=z(1e6,1e6).toVar();return Ie({start:-1,end:w(1),name:"x",condition:"<="},({x:h})=>{Ie({start:-1,end:w(1),name:"y",condition:"<="},({y:d})=>{Ie({start:-1,end:w(1),name:"z",condition:"<="},({z:p})=>{const f=T(za(c,h,d,p,a,o,l,i,s)).toVar();ne(f.lessThan(u.x),()=>{u.y.assign(u.x),u.x.assign(f)}).ElseIf(f.lessThan(u.y),()=>{u.y.assign(f)})})})}),ne(s.equal(w(0)),()=>{u.assign(Zt(u))}),u}).setLayout({name:"mx_worley_noise_vec2_1",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),oD=Pt([sD,aD]),lD=R(([r,e,t])=>{const s=w(t).toVar(),i=T(e).toVar(),n=E(r).toVar(),a=w().toVar(),o=w().toVar(),l=w().toVar(),c=E(Qe(n.x,a),Qe(n.y,o),Qe(n.z,l)).toVar(),u=E(1e6,1e6,1e6).toVar();return Ie({start:-1,end:w(1),name:"x",condition:"<="},({x:h})=>{Ie({start:-1,end:w(1),name:"y",condition:"<="},({y:d})=>{Ie({start:-1,end:w(1),name:"z",condition:"<="},({z:p})=>{const f=T(za(c,h,d,p,a,o,l,i,s)).toVar();ne(f.lessThan(u.x),()=>{u.z.assign(u.y),u.y.assign(u.x),u.x.assign(f)}).ElseIf(f.lessThan(u.y),()=>{u.z.assign(u.y),u.y.assign(f)}).ElseIf(f.lessThan(u.z),()=>{u.z.assign(f)})})})}),ne(s.equal(w(0)),()=>{u.assign(Zt(u))}),u}).setLayout({name:"mx_worley_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),Rm=Pt([iD,lD]),cD=R(([r,e,t,s,i,n,a,o,l,c,u])=>{const h=w(r).toVar(),d=z(e).toVar(),p=z(t).toVar(),f=z(s).toVar(),m=T(i).toVar(),x=T(n).toVar(),y=T(a).toVar(),b=Us(o).toVar(),v=w(l).toVar(),S=T(c).toVar(),M=T(u).toVar(),A=d.mul(p).add(f),C=T(0).toVar();return ne(h.equal(w(0)),()=>{C.assign(ol(A))}),ne(h.equal(w(1)),()=>{C.assign(fh(A))}),ne(h.equal(w(2)),()=>{C.assign(Rm(A,m,w(0)))}),ne(h.equal(w(3)),()=>{C.assign(mh(E(A,0),v,S,M))}),C.assign(C.mul(y.sub(x)).add(x)),ne(b,()=>{C.assign(ei(C,x,y))}),C}).setLayout({name:"mx_unifiednoise2d",type:"float",inputs:[{name:"noiseType",type:"int"},{name:"texcoord",type:"vec2"},{name:"freq",type:"vec2"},{name:"offset",type:"vec2"},{name:"jitter",type:"float"},{name:"outmin",type:"float"},{name:"outmax",type:"float"},{name:"clampoutput",type:"bool"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),uD=R(([r,e,t,s,i,n,a,o,l,c,u])=>{const h=w(r).toVar(),d=E(e).toVar(),p=E(t).toVar(),f=E(s).toVar(),m=T(i).toVar(),x=T(n).toVar(),y=T(a).toVar(),b=Us(o).toVar(),v=w(l).toVar(),S=T(c).toVar(),M=T(u).toVar(),A=d.mul(p).add(f),C=T(0).toVar();return ne(h.equal(w(0)),()=>{C.assign(ol(A))}),ne(h.equal(w(1)),()=>{C.assign(fh(A))}),ne(h.equal(w(2)),()=>{C.assign(Rm(A,m,w(0)))}),ne(h.equal(w(3)),()=>{C.assign(mh(A,v,S,M))}),C.assign(C.mul(y.sub(x)).add(x)),ne(b,()=>{C.assign(ei(C,x,y))}),C}).setLayout({name:"mx_unifiednoise3d",type:"float",inputs:[{name:"noiseType",type:"int"},{name:"position",type:"vec3"},{name:"freq",type:"vec3"},{name:"offset",type:"vec3"},{name:"jitter",type:"float"},{name:"outmin",type:"float"},{name:"outmax",type:"float"},{name:"clampoutput",type:"bool"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),hD=R(([r])=>{const e=r.y,t=r.z,s=E().toVar();return ne(e.lessThan(1e-4),()=>{s.assign(E(t,t,t))}).Else(()=>{let i=r.x;i=i.sub(Mi(i)).mul(6).toVar();const n=w(Rf(i)),a=i.sub(T(n)),o=t.mul(e.oneMinus()),l=t.mul(e.mul(a).oneMinus()),c=t.mul(e.mul(a.oneMinus()).oneMinus());ne(n.equal(w(0)),()=>{s.assign(E(t,c,o))}).ElseIf(n.equal(w(1)),()=>{s.assign(E(l,t,o))}).ElseIf(n.equal(w(2)),()=>{s.assign(E(o,t,c))}).ElseIf(n.equal(w(3)),()=>{s.assign(E(o,l,t))}).ElseIf(n.equal(w(4)),()=>{s.assign(E(c,o,t))}).Else(()=>{s.assign(E(t,o,l))})}),s}).setLayout({name:"mx_hsvtorgb",type:"vec3",inputs:[{name:"hsv",type:"vec3"}]}),dD=R(([r])=>{const e=E(r).toVar(),t=T(e.x).toVar(),s=T(e.y).toVar(),i=T(e.z).toVar(),n=T(ns(t,ns(s,i))).toVar(),a=T(tt(t,tt(s,i))).toVar(),o=T(a.sub(n)).toVar(),l=T().toVar(),c=T().toVar(),u=T().toVar();return u.assign(a),ne(a.greaterThan(0),()=>{c.assign(o.div(a))}).Else(()=>{c.assign(0)}),ne(c.lessThanEqual(0),()=>{l.assign(0)}).Else(()=>{ne(t.greaterThanEqual(a),()=>{l.assign(s.sub(i).div(o))}).ElseIf(s.greaterThanEqual(a),()=>{l.assign(dt(2,i.sub(t).div(o)))}).Else(()=>{l.assign(dt(4,t.sub(s).div(o)))}),l.mulAssign(1/6),ne(l.lessThan(0),()=>{l.addAssign(1)})}),E(l,c,u)}).setLayout({name:"mx_rgbtohsv",type:"vec3",inputs:[{name:"c",type:"vec3"}]}),pD=R(([r])=>{const e=E(r).toVar(),t=df(bf(e,E(.04045))).toVar(),s=E(e.div(12.92)).toVar(),i=E(Rs(tt(e.add(E(.055)),E(0)).div(1.055),E(2.4))).toVar();return ye(s,i,t)}).setLayout({name:"mx_srgb_texture_to_lin_rec709",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),SS=(r,e)=>{r=T(r),e=T(e);const t=z(e.dFdx(),e.dFdy()).length().mul(.7071067811865476);return ti(r.sub(t),r.add(t),e)},vS=(r,e,t,s)=>ye(r,e,t[s].clamp()),fD=(r,e,t=ze())=>vS(r,e,t,"x"),mD=(r,e,t=ze())=>vS(r,e,t,"y"),gD=(r,e,t,s,i=ze())=>{const n=i.x.clamp(),a=i.y.clamp(),o=ye(r,e,n),l=ye(t,s,n);return ye(o,l,a)},MS=(r,e,t,s,i)=>ye(r,e,SS(t,s[i])),yD=(r,e,t,s=ze())=>MS(r,e,t,s,"x"),xD=(r,e,t,s=ze())=>MS(r,e,t,s,"y"),_D=(r=1,e=0,t=ze())=>t.mul(r).add(e),bD=(r,e=1)=>(r=T(r),r.abs().pow(e).mul(r.sign())),TD=(r,e=1,t=.5)=>T(r).sub(t).mul(e).add(t),SD=(r=ze(),e=1,t=0)=>Nm(r.convert("vec2|vec3")).mul(e).add(t),vD=(r=ze(),e=1,t=0)=>ol(r.convert("vec2|vec3")).mul(e).add(t),MD=(r=ze(),e=1,t=0)=>(r=r.convert("vec2|vec3"),ie(ol(r),Nm(r.add(z(19,73)))).mul(e).add(t)),wD=(r,e=ze(),t=z(1,1),s=z(0,0),i=1,n=0,a=1,o=!1,l=1,c=2,u=.5)=>cD(r,e.convert("vec2|vec3"),t,s,i,n,a,o,l,c,u),CD=(r,e=ze(),t=z(1,1),s=z(0,0),i=1,n=0,a=1,o=!1,l=1,c=2,u=.5)=>uD(r,e.convert("vec2|vec3"),t,s,i,n,a,o,l,c,u),AD=(r=ze(),e=1)=>rD(r.convert("vec2|vec3"),e,w(1)),ED=(r=ze(),e=1)=>oD(r.convert("vec2|vec3"),e,w(1)),ND=(r=ze(),e=1)=>Rm(r.convert("vec2|vec3"),e,w(1)),RD=(r=ze())=>jB(r.convert("vec2|vec3")),PD=(r=ze(),e=3,t=2,s=.5,i=1)=>Su(r,w(e),t,s).mul(i),FD=(r=ze(),e=3,t=2,s=.5,i=1)=>QB(r,w(e),t,s).mul(i),BD=(r=ze(),e=3,t=2,s=.5,i=1)=>mh(r,w(e),t,s).mul(i),DD=(r=ze(),e=3,t=2,s=.5,i=1)=>KB(r,w(e),t,s).mul(i),OD=(r,e=T(0))=>dt(r,e),LD=(r,e=T(0))=>Te(r,e),ID=(r,e=T(1))=>ae(r,e),UD=(r,e=T(1))=>bs(r,e),VD=(r,e=T(1))=>el(r,e),kD=(r,e=T(1))=>Rs(r,e),zD=(r=T(0),e=T(1))=>wf(r,e),GD=()=>ka,$D=()=>UT,WD=(r,e=T(1))=>Te(e,r),HD=(r,e,t,s)=>r.greaterThan(e).mix(t,s),jD=(r,e,t,s)=>r.greaterThanEqual(e).mix(t,s),qD=(r,e,t,s)=>r.equal(e).mix(t,s),XD=(r,e=null)=>{if(typeof e=="string"){const t={x:0,r:0,y:1,g:1,z:2,b:2,w:3,a:3},s=e.replace(/^out/,"").toLowerCase();if(t[s]!==void 0)return r.element(t[s])}if(typeof e=="number")return r.element(e);if(typeof e=="string"&&e.length===1){const t={x:0,r:0,y:1,g:1,z:2,b:2,w:3,a:3};if(t[e]!==void 0)return r.element(t[e])}return r},YD=(r,e=z(.5,.5),t=z(1,1),s=T(0),i=z(0,0))=>{let n=r;if(e&&(n=n.sub(e)),t&&(n=n.mul(t)),s){const a=s.mul(Math.PI/180),o=a.cos(),l=a.sin();n=z(n.x.mul(o).sub(n.y.mul(l)),n.x.mul(l).add(n.y.mul(o)))}return e&&(n=n.add(e)),i&&(n=n.add(i)),n},ZD=(r,e)=>{r=z(r),e=T(e);const t=e.mul(Math.PI/180);return il(r,t)},QD=(r,e,t)=>{r=E(r),e=T(e),t=E(t);const s=e.mul(Math.PI/180),i=t.normalize(),n=s.cos(),a=s.sin(),o=T(1).sub(n);return r.mul(n).add(i.cross(r).mul(a)).add(i.mul(i.dot(r)).mul(o))},KD=(r,e)=>(r=E(r),e=T(e),Jf(r,e)),JD=R(([r,e,t])=>{const s=is(r).toVar(),i=Te(T(.5).mul(e.sub(t)),Ai).div(s).toVar(),n=Te(T(-.5).mul(e.sub(t)),Ai).div(s).toVar(),a=E().toVar();a.x=s.x.greaterThan(T(0)).select(i.x,n.x),a.y=s.y.greaterThan(T(0)).select(i.y,n.y),a.z=s.z.greaterThan(T(0)).select(i.z,n.z);const o=ns(a.x,a.y,a.z).toVar();return Ai.add(s.mul(o)).toVar().sub(t)}),wS=R(([r,e])=>{const t=r.x,s=r.y,i=r.z;let n=e.element(0).mul(.886227);return n=n.add(e.element(1).mul(2*.511664).mul(s)),n=n.add(e.element(2).mul(2*.511664).mul(i)),n=n.add(e.element(3).mul(2*.511664).mul(t)),n=n.add(e.element(4).mul(2*.429043).mul(t).mul(s)),n=n.add(e.element(5).mul(2*.429043).mul(s).mul(i)),n=n.add(e.element(6).mul(i.mul(i).mul(.743125).sub(.247708))),n=n.add(e.element(7).mul(2*.429043).mul(t).mul(i)),n=n.add(e.element(8).mul(.429043).mul(ae(t,t).sub(ae(s,s)))),n});var g=Object.freeze({__proto__:null,BRDF_GGX:dm,BRDF_Lambert:Sr,BasicPointShadowFilter:pS,BasicShadowFilter:nS,Break:Jb,Const:g_,Continue:X1,DFGLUT:Xo,D_GGX:mT,Discard:F_,EPSILON:Tf,F_Schlick:La,Fn:R,HALF_PI:TA,INFINITY:xA,If:ne,Loop:Ie,NodeAccess:Nt,NodeShaderStage:xo,NodeType:zC,NodeUpdateType:re,OnBeforeMaterialUpdate:dP,OnBeforeObjectUpdate:hP,OnMaterialUpdate:uP,OnObjectUpdate:cP,PCFShadowFilter:rS,PCFSoftShadowFilter:aS,PI:mu,PI2:_A,PointShadowFilter:fS,Return:IA,Schlick_to_F0:Tp,ShaderNode:pa,Stack:$u,Switch:cA,TBNViewMatrix:gr,TWO_PI:bA,VSMShadowFilter:oS,V_GGX_SmithCorrelated:fT,Var:m_,VarIntent:y_,abs:We,acesFilmicToneMapping:YT,acos:Mf,add:dt,addMethodChaining:I,addNodeElement:zA,agxToneMapping:ZT,all:G0,alphaT:du,and:A0,anisotropy:Sn,anisotropyB:_r,anisotropyT:Fo,any:$0,append:pA,array:_0,arrayBuffer:hA,asin:q0,assign:b0,atan:wf,atomicAdd:gF,atomicAnd:bF,atomicFunc:Di,atomicLoad:fF,atomicMax:xF,atomicMin:_F,atomicOr:TF,atomicStore:mF,atomicSub:yF,atomicXor:SF,attenuationColor:yf,attenuationDistance:gf,attribute:sn,attributeArray:mP,backgroundBlurriness:zT,backgroundIntensity:Cp,backgroundRotation:GT,batch:Zb,bentNormalView:db,billboarding:qR,bitAnd:P0,bitNot:F0,bitOr:B0,bitXor:D0,bitangentGeometry:A1,bitangentLocal:E1,bitangentView:ub,bitangentWorld:N1,bitcast:LT,blendBurn:pE,blendColor:yE,blendDodge:fE,blendOverlay:gE,blendScreen:mE,blur:ST,bool:Us,buffer:tl,bufferAttribute:zf,builtin:an,builtinAOContext:p_,builtinShadowContext:d_,bumpMap:Jf,bvec2:d0,bvec3:df,bvec4:p0,bypass:E_,cache:A_,call:T0,cameraFar:Cn,cameraIndex:Wn,cameraNear:wn,cameraNormalMatrix:t1,cameraPosition:G_,cameraProjectionMatrix:en,cameraProjectionMatrixInverse:z_,cameraViewMatrix:Gs,cameraViewport:s1,cameraWorldMatrix:e1,cbrt:r_,cdl:BP,ceil:Xu,checker:yB,cineonToneMapping:XT,clamp:ei,clearcoat:cu,clearcoatNormalView:An,clearcoatRoughness:ba,clipSpace:H_,code:hh,color:h0,colorSpaceToWorking:Zu,colorToDirection:P1,compute:C_,computeKernel:Gf,computeSkinning:j1,context:rn,convert:m0,convertColorSpace:EA,convertToTexture:nP,cos:Xs,countLeadingZeros:vR,countOneBits:MR,countTrailingZeros:SR,cross:tn,cubeTexture:Xt,cubeTextureBase:Kf,dFdx:Ef,dFdy:Nf,dashSize:xc,debug:D_,decrement:k0,decrementBefore:U0,defaultBuildStages:ap,defaultShaderStages:r0,defined:Ho,degrees:H0,deltaTime:VR,densityFogFactor:tS,depth:om,depthPass:VP,determinant:K0,difference:s_,diffuseColor:Oe,diffuseContribution:ur,directPointLight:gS,directionToColor:pb,directionToFaceDirection:Ua,dispersion:xf,disposeShadowMaterial:cS,distance:t_,div:bs,dot:Vs,drawIndex:qb,dynamicBufferAttribute:BA,element:f0,emissive:up,equal:S0,equirectUV:lm,exp:Sf,exp2:Pa,exponentialHeightFogFactor:QP,expression:Ks,faceDirection:Yf,faceForward:Lf,faceforward:SA,float:T,floatBitsToInt:_R,floatBitsToUint:IT,floor:Mi,fog:Ap,fract:Js,frameGroup:x0,frameId:UT,frontFacing:j_,fwidth:Pf,gain:CR,gapSize:hp,getConstNodeType:u0,getCurrentStack:cf,getDirection:bT,getDistanceAttenuation:Em,getGeometryRoughness:pT,getNormalFromDepth:aP,getParallaxCorrectNormal:JD,getRoughness:hm,getScreenPosition:rP,getShIrradianceAt:wS,getShadowMaterial:lS,getShadowRenderObjectFunction:uS,getTextureIndex:DT,getViewPosition:la,ggxConvolution:vT,globalId:iF,glsl:XP,glslFn:YP,grayscale:NP,greaterThan:bf,greaterThanEqual:C0,hash:wR,highpModelNormalViewMatrix:fp,highpModelViewMatrix:pp,hue:FP,increment:V0,incrementBefore:I0,inspector:L_,instance:$1,instanceIndex:Ei,instancedArray:gP,instancedBufferAttribute:gu,instancedDynamicBufferAttribute:dp,instancedMesh:Yb,int:w,intBitsToFloat:bR,interleavedGradientNoise:_m,inverse:J0,inverseSqrt:vf,inversesqrt:vA,invocationLocalIndex:G1,invocationSubgroupIndex:z1,ior:Bo,iridescence:Hu,iridescenceIOR:uu,iridescenceThickness:hu,isolate:Sa,ivec2:ft,ivec3:hf,ivec4:pf,js:jP,label:f_,length:wi,lengthSq:Df,lessThan:M0,lessThanEqual:w0,lightPosition:vm,lightProjectionUV:sS,lightShadowMatrix:ph,lightTargetDirection:wm,lightTargetPosition:iS,lightViewPosition:Mm,lightingContext:tT,lights:ZF,linearDepth:yu,linearToneMapping:jT,localId:nF,log:qu,log2:vi,logarithmicDepthToViewZ:rE,luminance:bm,mat2:Wu,mat3:wt,mat4:Dn,matcapUV:wT,materialAO:Wb,materialAlphaTest:fb,materialAnisotropy:Nb,materialAnisotropyVector:oa,materialAttenuationColor:Ib,materialAttenuationDistance:Lb,materialClearcoat:vb,materialClearcoatNormal:wb,materialClearcoatRoughness:Mb,materialColor:mb,materialDispersion:$b,materialEmissive:yb,materialEnvIntensity:Tc,materialEnvRotation:Qf,materialIOR:Ob,materialIridescence:Rb,materialIridescenceIOR:Pb,materialIridescenceThickness:Fb,materialLightMap:tm,materialLineDashOffset:zb,materialLineDashSize:Vb,materialLineGapSize:kb,materialLineScale:Ub,materialLineWidth:L1,materialMetalness:Tb,materialNormal:Sb,materialOpacity:em,materialPointSize:Gb,materialReference:Wi,materialReflectivity:Sc,materialRefractionRatio:Z_,materialRotation:Cb,materialRoughness:bb,materialSheen:Ab,materialSheenRoughness:Eb,materialShininess:gb,materialSpecular:xb,materialSpecularColor:_b,materialSpecularIntensity:bp,materialSpecularStrength:Do,materialThickness:Db,materialTransmission:Bb,max:tt,maxMipLevel:$f,mediumpModelViewMatrix:W_,metalness:ji,min:ns,mix:ye,mixElement:o_,mod:el,modInt:z0,modelDirection:c1,modelNormalMatrix:$_,modelPosition:u1,modelRadius:p1,modelScale:h1,modelViewMatrix:Hn,modelViewPosition:d1,modelViewProjection:Hb,modelWorldMatrix:Ps,modelWorldMatrixInverse:f1,morphReference:eT,mrt:OT,mul:ae,mx_aastep:SS,mx_add:OD,mx_atan2:zD,mx_cell_noise_float:RD,mx_contrast:TD,mx_divide:UD,mx_fractal_noise_float:PD,mx_fractal_noise_vec2:FD,mx_fractal_noise_vec3:BD,mx_fractal_noise_vec4:DD,mx_frame:$D,mx_heighttonormal:KD,mx_hsvtorgb:hD,mx_ifequal:qD,mx_ifgreater:HD,mx_ifgreatereq:jD,mx_invert:WD,mx_modulo:VD,mx_multiply:ID,mx_noise_float:SD,mx_noise_vec3:vD,mx_noise_vec4:MD,mx_place2d:YD,mx_power:kD,mx_ramp4:gD,mx_ramplr:fD,mx_ramptb:mD,mx_rgbtohsv:dD,mx_rotate2d:ZD,mx_rotate3d:QD,mx_safepower:bD,mx_separate:XD,mx_splitlr:yD,mx_splittb:xD,mx_srgb_texture_to_lin_rec709:pD,mx_subtract:LD,mx_timer:GD,mx_transform_uv:_D,mx_unifiednoise2d:wD,mx_unifiednoise3d:CD,mx_worley_noise_float:AD,mx_worley_noise_vec2:ED,mx_worley_noise_vec3:ND,negate:Af,neutralToneMapping:QT,nodeArray:xr,nodeImmutable:H,nodeObject:Z,nodeObjectIntent:_o,nodeObjects:Gu,nodeProxy:ue,nodeProxyIntent:G,normalFlat:q_,normalGeometry:Ku,normalLocal:rs,normalMap:_p,normalView:Me,normalViewGeometry:Da,normalWorld:jn,normalWorldGeometry:X_,normalize:is,not:N0,notEqual:v0,numWorkgroups:tF,objectDirection:i1,objectGroup:_f,objectPosition:r1,objectRadius:l1,objectScale:a1,objectViewPosition:o1,objectWorldMatrix:n1,oneMinus:X0,or:E0,orthographicDepthToViewZ:nE,oscSawtooth:$R,oscSine:kR,oscSquare:zR,oscTriangle:GR,output:Ta,outputStruct:mR,overloadingFn:Pt,packHalf2x16:PR,packSnorm2x16:NR,packUnorm2x16:RR,parabola:wp,parallaxDirection:hb,parallaxUV:R1,parameter:cR,pass:IP,passTexture:UP,pcurve:AR,perspectiveDepthToViewZ:rm,pmremTexture:fm,pointShadow:mS,pointUV:xP,pointWidth:fA,positionGeometry:sl,positionLocal:Je,positionPrevious:Ba,positionView:lt,positionViewDirection:Ge,positionWorld:Ai,positionWorldDirection:Xf,posterize:DP,pow:Rs,pow2:Ff,pow3:i_,pow4:Bf,premultiplyAlpha:aT,property:Ji,quadBroadcast:qF,quadSwapDiagonal:zF,quadSwapX:VF,quadSwapY:kF,radians:W0,rand:a_,range:JP,rangeFogFactor:eS,reciprocal:Z0,reference:Ye,referenceBuffer:mp,reflect:e_,reflectVector:J_,reflectView:Q_,reflector:JR,refract:Of,refractVector:eb,refractView:K_,reinhardToneMapping:qT,remap:R_,remapClamp:P_,renderGroup:se,renderOutput:B_,rendererReference:v_,replaceDefaultUV:WR,rotate:il,rotateUV:HR,roughness:yi,round:Y0,rtt:kT,sRGBTransferEOTF:__,sRGBTransferOETF:b_,sample:lP,sampler:qA,samplerComparison:XA,saturate:Yu,saturation:RP,screenCoordinate:Er,screenDPR:V_,screenSize:Tr,screenUV:Ci,select:Vt,setCurrentStack:jo,setName:If,shaderStages:op,shadow:dS,shadowPositionWorld:Am,shapeCircle:xB,sharedUniformGroup:ju,sheen:hs,sheenRoughness:Mn,shiftLeft:O0,shiftRight:L0,shininess:pu,sign:Cf,sin:jt,sinc:ER,skinning:Kb,smoothstep:ti,smoothstepElement:l_,specularColor:kn,specularColorBlended:fr,specularF90:mr,spherizeUV:jR,split:dA,spritesheetUV:YR,sqrt:Zt,stack:vc,step:Fa,stepElement:c_,storage:Ln,storageBarrier:lF,storageTexture:$T,string:uA,struct:fR,sub:Te,subBuild:br,subgroupAdd:wF,subgroupAll:LF,subgroupAnd:PF,subgroupAny:IF,subgroupBallot:MF,subgroupBroadcast:GF,subgroupBroadcastFirst:UF,subgroupElect:vF,subgroupExclusiveAdd:AF,subgroupExclusiveMul:RF,subgroupInclusiveAdd:CF,subgroupInclusiveMul:NF,subgroupIndex:k1,subgroupMax:OF,subgroupMin:DF,subgroupMul:EF,subgroupOr:FF,subgroupShuffle:$F,subgroupShuffleDown:jF,subgroupShuffleUp:HF,subgroupShuffleXor:WF,subgroupSize:rF,subgroupXor:BF,tan:j0,tangentGeometry:eh,tangentLocal:Oa,tangentView:th,tangentWorld:cb,texture:we,texture3D:uh,texture3DLevel:MP,texture3DLoad:vP,textureBarrier:cF,textureBicubic:WE,textureBicubicLevel:pm,textureCubeUV:TT,textureLevel:jA,textureLoad:nt,textureSize:On,textureStore:bP,thickness:mf,time:ka,toneMapping:M_,toneMappingExposure:w_,toonOutlinePass:zP,transformDirection:n_,transformNormal:Y_,transformNormalToView:Zf,transformedClearcoatNormalView:x1,transformedNormalView:g1,transformedNormalWorld:y1,transmission:fu,transpose:Q0,triNoise3D:LR,triplanarTexture:ZR,triplanarTextures:VT,trunc:Rf,uint:k,uintBitsToFloat:TR,uniform:ee,uniformArray:It,uniformCubeTexture:b1,uniformFlow:h_,uniformGroup:y0,uniformTexture:HA,unpackHalf2x16:DR,unpackNormal:xp,unpackSnorm2x16:FR,unpackUnorm2x16:BR,unpremultiplyAlpha:xE,userData:CP,uv:ze,uvec2:uf,uvec3:Ar,uvec4:ff,varying:$n,varyingProperty:qo,vec2:z,vec3:E,vec4:ie,vectorComponents:wr,velocity:EP,vertexColor:rT,vertexIndex:jb,vertexStage:x_,vibrance:PP,viewZToLogarithmicDepth:am,viewZToOrthographicDepth:va,viewZToPerspectiveDepth:nm,viewZToReversedOrthographicDepth:iE,viewZToReversedPerspectiveDepth:iT,viewport:jf,viewportCoordinate:k_,viewportDepthTexture:im,viewportLinearDepth:aE,viewportMipTexture:sm,viewportOpaqueMipTexture:sT,viewportResolution:JA,viewportSafeUV:XR,viewportSharedTexture:LP,viewportSize:qf,viewportTexture:eE,viewportUV:KA,vogelDiskSample:Zs,wgsl:qP,wgslFn:ZP,workgroupArray:dF,workgroupBarrier:oF,workgroupId:sF,workingToColorSpace:T_,xor:R0});const js=new mm;class eO extends qn{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,s){const i=this.renderer,n=this.nodes.getBackgroundNode(e)||e.background;let a=!1;if(n===null)i._clearColor.getRGB(js),js.a=i._clearColor.a;else if(n.isColor===!0)n.getRGB(js),js.a=1,a=!0;else if(n.isNode===!0){const l=this.get(e),c=n;js.copy(i._clearColor);let u=l.backgroundMesh;if(u===void 0){let v=function(){n.removeEventListener("dispose",v),u.material.dispose(),u.geometry.dispose()};const d=ie(c).mul(Cp).context({getUV:()=>GT.mul(X_),getTextureLevel:()=>zT}),p=en.element(3).element(3).equal(1),f=bs(1,en.element(1).element(1)).mul(3),m=p.select(Je.mul(f),Je),x=Hn.mul(ie(m,0));let y=en.mul(ie(x.xyz,1));y=y.setZ(y.w);const b=new st;b.name="Background.material",b.side=Rt,b.depthTest=!1,b.depthWrite=!1,b.allowOverride=!1,b.fog=!1,b.lights=!1,b.vertexNode=y,b.colorNode=d,l.backgroundMeshNode=d,l.backgroundMesh=u=new Un(new Kp(1,32,32),b),u.frustumCulled=!1,u.name="Background.mesh",n.addEventListener("dispose",v)}const h=c.getCacheKey();l.backgroundCacheKey!==h&&(l.backgroundMeshNode.node=ie(c).mul(Cp),l.backgroundMeshNode.needsUpdate=!0,u.material.needsUpdate=!0,l.backgroundCacheKey=h),t.unshift(u,u.geometry,u.material,0,0,null,null)}else $("Renderer: Unsupported background configuration.",n);const o=i.xr.getEnvironmentBlendMode();if(o==="additive"?js.set(0,0,0,1):o==="alpha-blend"&&js.set(0,0,0,0),i.autoClear===!0||a===!0){const l=s.clearColorValue;l.r=js.r,l.g=js.g,l.b=js.b,l.a=js.a,(i.backend.isWebGLBackend===!0||i.alpha===!0)&&(l.r*=l.a,l.g*=l.a,l.b*=l.a),s.depthClearValue=i.getClearDepth(),s.stencilClearValue=i.getClearStencil(),s.clearColor=i.autoClearColor===!0,s.clearDepth=i.autoClearDepth===!0,s.clearStencil=i.autoClearStencil===!0}else s.clearColor=!1,s.clearDepth=!1,s.clearStencil=!1}}let tO=0;class Ep{constructor(e="",t=[],s=0){this.name=e,this.bindings=t,this.index=s,this.id=tO++}}class sO{constructor(e,t,s,i,n,a,o,l,c,u=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=s,this.transforms=u,this.nodeAttributes=i,this.bindings=n,this.updateNodes=a,this.updateBeforeNodes=o,this.updateAfterNodes=l,this.observer=c,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings)if(t.bindings[0].groupNode.shared!==!0){const i=new Ep(t.name,[],t.index);e.push(i);for(const n of t.bindings)i.bindings.push(n.clone())}else e.push(t);return e}}class ry{constructor(e,t,s=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=s}}class iO{constructor(e,t,s){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=s}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 CS{constructor(e,t,s=!1,i=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=s,this.count=i}}class nO extends CS{constructor(e,t,s=null,i=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=s,this.interpolationSampling=i}}class rO{constructor(e,t,s=""){this.name=e,this.type=t,this.code=s,Object.defineProperty(this,"isNodeCode",{value:!0})}}let aO=0;class xd{constructor(e=null){this.id=aO++,this.nodesData=new WeakMap,this.parent=e}getData(e){let t=this.nodesData.get(e);return t===void 0&&this.parent!==null&&(t=this.parent.getData(e)),t}setData(e,t){this.nodesData.set(e,t)}}class oO{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class Xn{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 lO extends Xn{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class cO extends Xn{constructor(e,t=new xe){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class uO extends Xn{constructor(e,t=new D){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class hO extends Xn{constructor(e,t=new Ee){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class dO extends Xn{constructor(e,t=new Ne){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class pO extends Xn{constructor(e,t=new Vu){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class fO extends Xn{constructor(e,t=new as){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class mO extends Xn{constructor(e,t=new ve){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class gO extends lO{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class yO extends cO{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class xO extends uO{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class _O extends hO{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class bO extends dO{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class TO extends pO{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class SO extends fO{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class vO extends mO{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}let MO=0;const ay=new WeakMap,wO=new WeakMap,CO=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),Jl=r=>/e/g.test(r)?String(r).replace(/\+/g,""):(r=Number(r),r+(r%1?"":".0"));class AS{constructor(e,t,s){this.object=e,this.material=e&&e.material||null,this.geometry=e&&e.geometry||null,this.renderer=t,this.parser=s,this.scene=null,this.camera=null,this.nodes=[],this.sequentialNodes=[],this.updateNodes=[],this.updateBeforeNodes=[],this.updateAfterNodes=[],this.hashNodes={},this.observer=null,this.lightsNode=null,this.environmentNode=null,this.fogNode=null,this.clippingContext=null,this.vertexShader=null,this.fragmentShader=null,this.computeShader=null,this.flowNodes={vertex:[],fragment:[],compute:[]},this.flowCode={vertex:"",fragment:"",compute:""},this.uniforms={vertex:[],fragment:[],compute:[],index:0},this.structs={vertex:[],fragment:[],compute:[],index:0},this.types={vertex:[],fragment:[],compute:[],index:0},this.bindings={vertex:{},fragment:{},compute:{}},this.bindingsIndexes={},this.bindGroups=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.declarations={},this.flow={code:""},this.chaining=[],this.stack=vc(),this.stacks=[],this.tab=" ",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new xd,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null,this.subBuildLayers=[],this.activeStacks=[],this.subBuildFn=null,this.fnCall=null,Object.defineProperty(this,"id",{value:MO++})}isFlatShading(){return this.material.flatShading===!0||this.geometry.hasAttribute("normal")===!1}isOpaque(){const e=this.material;return e.transparent===!1&&e.blending===Es&&e.alphaToCoverage===!1}createRenderTarget(e,t,s){return new nn(e,t,s)}createCubeRenderTarget(e,t){return new lT(e,t)}includes(e){return this.nodes.includes(e)}getOutputStructName(){}_getBindGroup(e,t){const s=t[0].groupNode;let i=s.shared;if(i)for(let a=1;a<t.length;a++)s!==t[a].groupNode&&(i=!1);let n;if(i){let a="";for(const u of t)if(u.isNodeUniformsGroup){u.uniforms.sort((h,d)=>h.nodeUniform.node.id-d.nodeUniform.node.id);for(const h of u.uniforms)a+=h.nodeUniform.node.id}else a+=u.nodeUniform.id;const o=this.renderer._currentRenderContext||this.renderer;let l=ay.get(o);l===void 0&&(l=new Map,ay.set(o,l));const c=Ia(a);n=l.get(c),n===void 0&&(n=new Ep(e,t,this.bindingsIndexes[e].group),l.set(c,n))}else n=new Ep(e,t,this.bindingsIndexes[e].group);return n}getBindGroupArray(e,t){const s=this.bindings[t];let i=s[e];return i===void 0&&(this.bindingsIndexes[e]===void 0&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),s[e]=i=[]),i}getBindings(){let e=this.bindGroups;if(e===null){const t={},s=this.bindings;for(const i of op)for(const n in s[i]){const a=s[i][n],o=t[n]||(t[n]=[]);for(const l of a)o.includes(l)===!1&&o.push(l)}e=[];for(const i in t){const n=t[i],a=this._getBindGroup(i,n);e.push(a)}this.bindGroups=e}return e}sortBindingGroups(){const e=this.getBindings();e.sort((t,s)=>t.bindings[0].groupNode.order-s.bindings[0].groupNode.order);for(let t=0;t<e.length;t++){const s=e[t];this.bindingsIndexes[s.name].group=t,s.index=t}}setHashNode(e,t){this.hashNodes[t]=e}addNode(e){this.nodes.includes(e)===!1&&(this.nodes.push(e),this.setHashNode(e,e.getHash(this)))}addSequentialNode(e){const t=e.getUpdateBeforeType(),s=e.getUpdateAfterType();(t!==re.NONE||s!==re.NONE)&&this.sequentialNodes.includes(e)===!1&&this.sequentialNodes.push(e)}buildUpdateNodes(){for(const e of this.nodes)e.getUpdateType()!==re.NONE&&this.updateNodes.push(e);for(const e of this.sequentialNodes){const t=e.getUpdateBeforeType(),s=e.getUpdateAfterType();t!==re.NONE&&this.updateBeforeNodes.push(e),s!==re.NONE&&this.updateAfterNodes.push(e)}}get currentNode(){return this.chaining[this.chaining.length-1]}isFilteredTexture(e){return e.magFilter===Gt||e.magFilter===Kd||e.magFilter===zo||e.magFilter===Pn||e.minFilter===Gt||e.minFilter===Kd||e.minFilter===zo||e.minFilter===Pn}getUniformBufferLimit(){return 16384}addChain(e){this.chaining.push(e)}removeChain(e){if(this.chaining.pop()!==e)throw new Error("NodeBuilder: Invalid node chaining!")}getMethod(e){return e}getTernary(){return null}getNodeFromHash(e){return this.hashNodes[e]}addFlow(e,t){return this.flowNodes[e].push(t),t}setContext(e){this.context=e}getContext(){return this.context}addContext(e){const t=this.getContext();return this.setContext({...this.context,...e}),t}getSharedContext(){const e={...this.context};return delete e.material,delete e.getUV,delete e.getOutput,delete e.getTextureLevel,delete e.getAO,delete e.getShadow,e}setCache(e){this.cache=e}getCache(){return this.cache}getCacheFromNode(e,t=!0){const s=this.getDataFromNode(e);return s.cache===void 0&&(s.cache=new xd(t?this.getCache():null)),s.cache}isAvailable(){return!1}getVertexIndex(){W("Abstract function.")}getInstanceIndex(){W("Abstract function.")}getDrawIndex(){W("Abstract function.")}getFrontFacing(){W("Abstract function.")}getFragCoord(){W("Abstract function.")}isFlipY(){return!1}increaseUsage(e){const t=this.getDataFromNode(e);return t.usageCount=t.usageCount===void 0?1:t.usageCount+1,t.usageCount}generateTexture(){W("Abstract function.")}generateTextureLod(){W("Abstract function.")}generateArrayDeclaration(e,t){return this.getType(e)+"[ "+t+" ]"}generateArray(e,t,s=null){let i=this.generateArrayDeclaration(e,t)+"( ";for(let n=0;n<t;n++){const a=s?s[n]:null;a!==null?i+=a.build(this,e):i+=this.generateConst(e),n<t-1&&(i+=", ")}return i+=" )",i}generateStruct(e,t,s=null){const i=[];for(const n of t){const{name:a,type:o}=n;s&&s[a]&&s[a].isNode?i.push(s[a].build(this,o)):i.push(this.generateConst(o))}return e+"( "+i.join(", ")+" )"}generateConst(e,t=null){if(t===null&&(e==="float"||e==="int"||e==="uint"?t=0:e==="bool"?t=!1:e==="color"?t=new Ne:e==="vec2"||e==="uvec2"||e==="ivec2"?t=new xe:e==="vec3"||e==="uvec3"||e==="ivec3"?t=new D:(e==="vec4"||e==="uvec4"||e==="ivec4")&&(t=new Ee)),e==="float")return Jl(t);if(e==="int")return`${Math.round(t)}`;if(e==="uint")return t>=0?`${Math.round(t)}u`:"0u";if(e==="bool")return t?"true":"false";if(e==="color")return`${this.getType("vec3")}( ${Jl(t.r)}, ${Jl(t.g)}, ${Jl(t.b)} )`;const s=this.getTypeLength(e),i=this.getComponentType(e),n=a=>this.generateConst(i,a);if(s===2)return`${this.getType(e)}( ${n(t.x)}, ${n(t.y)} )`;if(s===3)return`${this.getType(e)}( ${n(t.x)}, ${n(t.y)}, ${n(t.z)} )`;if(s===4&&e!=="mat2")return`${this.getType(e)}( ${n(t.x)}, ${n(t.y)}, ${n(t.z)}, ${n(t.w)} )`;if(s>=4&&t&&(t.isMatrix2||t.isMatrix3||t.isMatrix4))return`${this.getType(e)}( ${t.elements.map(n).join(", ")} )`;if(s>4)return`${this.getType(e)}()`;throw new Error(`NodeBuilder: Type '${e}' not found in generate constant attempt.`)}getType(e){return e==="color"?"vec3":e}hasGeometryAttribute(e){return this.geometry&&this.geometry.getAttribute(e)!==void 0}getAttribute(e,t){const s=this.attributes;for(const n of s)if(n.name===e)return n;const i=new ry(e,t);return this.registerDeclaration(i),s.push(i),i}getPropertyName(e){return e.name}isVector(e){return/vec\d/.test(e)}isMatrix(e){return/mat\d/.test(e)}isReference(e){return e==="void"||e==="property"||e==="sampler"||e==="samplerComparison"||e==="texture"||e==="cubeTexture"||e==="storageTexture"||e==="depthTexture"||e==="texture3D"}needsToWorkingColorSpace(){return!1}getComponentTypeFromTexture(e){const t=e.type;if(e.isDataTexture){if(t===Lt)return"int";if(t===rt)return"uint"}return"float"}getElementType(e){return e==="mat2"?"vec2":e==="mat3"?"vec3":e==="mat4"?"vec4":this.getComponentType(e)}getComponentType(e){if(e=this.getVectorType(e),e==="float"||e==="bool"||e==="int"||e==="uint")return e;const t=/(b|i|u|)(vec|mat)([2-4])/.exec(e);return t===null?null:t[1]==="b"?"bool":t[1]==="i"?"int":t[1]==="u"?"uint":"float"}getVectorType(e){return e==="color"?"vec3":e==="texture"||e==="cubeTexture"||e==="storageTexture"||e==="texture3D"?"vec4":e}getTypeFromLength(e,t="float"){if(e===1)return t;let s=s0(e);const i=t==="float"?"":t[0];return/mat2/.test(t)===!0&&(s=s.replace("vec","mat")),i+s}getTypeFromArray(e){return CO.get(e.constructor)}isInteger(e){return/int|uint|(i|u)vec/.test(e)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const s=t.array,i=e.itemSize,n=e.normalized;let a;return!(e instanceof Zx)&&n!==!0&&(a=this.getTypeFromArray(s)),this.getTypeFromLength(i,a)}getTypeLength(e){const t=this.getVectorType(e),s=/vec([2-4])/.exec(t);return s!==null?Number(s[1]):t==="float"||t==="bool"||t==="int"||t==="uint"?1:/mat2/.test(e)===!0?4:/mat3/.test(e)===!0?9:/mat4/.test(e)===!0?16:0}getVectorFromMatrix(e){return e.replace("mat","vec")}changeComponentType(e,t){return this.getTypeFromLength(this.getTypeLength(e),t)}getIntegerType(e){const t=this.getComponentType(e);return t==="int"||t==="uint"?e:this.changeComponentType(e,"int")}setActiveStack(e){this.activeStacks.push(e)}removeActiveStack(e){if(this.activeStacks[this.activeStacks.length-1]===e)this.activeStacks.pop();else throw new Error("NodeBuilder: Invalid active stack removal.")}getActiveStack(){return this.activeStacks[this.activeStacks.length-1]}getBaseStack(){return this.activeStacks[0]}addStack(){this.stack=vc(this.stack);const e=cf();return this.stacks.push(e),jo(this.stack),this.stack}removeStack(){const e=this.stack;for(const t of e.nodes){const s=this.getDataFromNode(t);s.stack=e}return this.stack=e.parent,jo(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,s=null){s=s===null?e.isGlobal(this)?this.globalCache:this.cache:s;let i=s.getData(e);i===void 0&&(i={},s.setData(e,i)),i[t]===void 0&&(i[t]={});let n=i[t];const a=i.any?i.any.subBuilds:null,o=this.getClosestSubBuild(a);return o&&(n.subBuildsCache===void 0&&(n.subBuildsCache={}),n=n.subBuildsCache[o]||(n.subBuildsCache[o]={}),n.subBuilds=a),n}getNodeProperties(e,t="any"){const s=this.getDataFromNode(e,t);return s.properties||(s.properties={outputNode:null})}getBufferAttributeFromNode(e,t){const s=this.getDataFromNode(e,"vertex");let i=s.bufferAttribute;if(i===void 0){const n=this.uniforms.index++;i=new ry("nodeAttribute"+n,t,e),this.bufferAttributes.push(i),s.bufferAttribute=i}return i}getStructTypeNode(e,t=this.shaderStage){return this.types[t][e]||null}getStructTypeFromNode(e,t,s=null,i=this.shaderStage){const n=this.getDataFromNode(e,i,this.globalCache);let a=n.structType;if(a===void 0){const o=this.structs.index++;s===null&&(s="StructType"+o),a=new oO(s,t),this.structs[i].push(a),this.types[i][s]=e,n.structType=a}return a}getOutputStructTypeFromNode(e,t){const s=this.getStructTypeFromNode(e,t,"OutputType","fragment");return s.output=!0,s}getUniformFromNode(e,t,s=this.shaderStage,i=null){const n=this.getDataFromNode(e,s,this.globalCache);let a=n.uniform;if(a===void 0){const o=this.uniforms.index++;a=new iO(i||"nodeUniform"+o,t,e),this.uniforms[s].push(a),this.registerDeclaration(a),n.uniform=a}return a}getVarFromNode(e,t=null,s=e.getNodeType(this),i=this.shaderStage,n=!1){const a=this.getDataFromNode(e,i),o=this.getSubBuildProperty("variable",a.subBuilds);let l=a[o];if(l===void 0){const c=n?"_const":"_var",u=this.vars[i]||(this.vars[i]=[]),h=this.vars[c]||(this.vars[c]=0);t===null&&(t=(n?"nodeConst":"nodeVar")+h,this.vars[c]++),o!=="variable"&&(t=this.getSubBuildProperty(t,a.subBuilds));const d=e.getArrayCount(this);l=new CS(t,s,n,d),n||u.push(l),this.registerDeclaration(l),a[o]=l}return l}isDeterministic(e){if(e.isMathNode)return this.isDeterministic(e.aNode)&&(e.bNode?this.isDeterministic(e.bNode):!0)&&(e.cNode?this.isDeterministic(e.cNode):!0);if(e.isOperatorNode)return this.isDeterministic(e.aNode)&&(e.bNode?this.isDeterministic(e.bNode):!0);if(e.isArrayNode){if(e.values!==null){for(const t of e.values)if(!this.isDeterministic(t))return!1}return!0}else if(e.isConstNode)return!0;return!1}getVaryingFromNode(e,t=null,s=e.getNodeType(this),i=null,n=null){const a=this.getDataFromNode(e,"any"),o=this.getSubBuildProperty("varying",a.subBuilds);let l=a[o];if(l===void 0){const c=this.varyings,u=c.length;t===null&&(t="nodeVarying"+u),o!=="varying"&&(t=this.getSubBuildProperty(t,a.subBuilds)),l=new nO(t,s,i,n),c.push(l),this.registerDeclaration(l),a[o]=l}return l}registerDeclaration(e){const t=this.shaderStage,s=this.declarations[t]||(this.declarations[t]={}),i=this.getPropertyName(e);let n=1,a=i;for(;s[a]!==void 0;)a=i+"_"+n++;n>1&&(e.name=a,W(`TSL: Declaration name '${i}' of '${e.type}' already in use. Renamed to '${a}'.`)),s[a]=e}getCodeFromNode(e,t,s=this.shaderStage){const i=this.getDataFromNode(e);let n=i.code;if(n===void 0){const a=this.codes[s]||(this.codes[s]=[]),o=a.length;n=new rO("nodeCode"+o,t),a.push(n),i.code=n}return n}addFlowCodeHierarchy(e,t){const{flowCodes:s,flowCodeBlock:i}=this.getDataFromNode(e);let n=!0,a=t;for(;a;){if(i.get(a)===!0){n=!1;break}a=this.getDataFromNode(a).parentNodeBlock}if(n)for(const o of s)this.addLineFlowCode(o)}addLineFlowCodeBlock(e,t,s){const i=this.getDataFromNode(e),n=i.flowCodes||(i.flowCodes=[]),a=i.flowCodeBlock||(i.flowCodeBlock=new WeakMap);n.push(t),a.set(s,!0)}addLineFlowCode(e,t=null){return e===""?this:(t!==null&&this.context.nodeBlock&&this.addLineFlowCodeBlock(t,e,this.context.nodeBlock),e=this.tab+e,/;\s*$/.test(e)||(e=e+`;
58
- `),this.flow.code+=e,this)}addFlowCode(e){return this.flow.code+=e,this}addFlowTab(){return this.tab+=" ",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),s=this.flowChildNode(e,t);return this.flowsData.set(e,s),s}addInclude(e){this.currentFunctionNode!==null&&this.currentFunctionNode.includes.push(e)}buildFunctionNode(e){const t=new KT,s=this.currentFunctionNode;return this.currentFunctionNode=t,t.code=this.buildFunctionCode(e),this.currentFunctionNode=s,t}flowShaderNode(e){const t=e.layout,s={[Symbol.iterator](){let a=0;const o=Object.values(this);return{next:()=>({value:o[a],done:a++>=o.length})}}};for(const a of t.inputs)s[a.name]=new PT(a.type,a.name);e.layout=null;const i=e.call(s),n=this.flowStagesNode(i,t.type);return e.layout=t,n}flowBuildStage(e,t,s=null){const i=this.getBuildStage();this.setBuildStage(t);const n=e.build(this,s);return this.setBuildStage(i),n}flowStagesNode(e,t=null){const s=this.flow,i=this.vars,n=this.declarations,a=this.cache,o=this.buildStage,l=this.stack,c={code:""};this.flow=c,this.vars={},this.declarations={},this.cache=new xd,this.stack=vc();for(const u of ap)this.setBuildStage(u),c.result=e.build(this,t);return c.vars=this.getVars(this.shaderStage),this.flow=s,this.vars=i,this.declarations=n,this.cache=a,this.stack=l,this.setBuildStage(o),c}getFunctionOperator(){return null}buildFunctionCode(){W("Abstract function.")}flowChildNode(e,t=null){const s=this.flow,i={code:""};return this.flow=i,i.result=e.build(this,t),this.flow=s,i}flowNodeFromShaderStage(e,t,s=null,i=null){const n=this.tab,a=this.cache,o=this.shaderStage,l=this.context;this.setShaderStage(e);const c={...this.context};delete c.nodeBlock,this.cache=this.globalCache,this.tab=" ",this.context=c;let u=null;if(this.buildStage==="generate"){const h=this.flowChildNode(t,s);i!==null&&(h.code+=`${this.tab+i} = ${h.result};
59
- `),this.flowCode[e]=this.flowCode[e]+h.code,u=h}else u=t.build(this);return this.setShaderStage(o),this.cache=a,this.tab=n,this.context=l,u}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){W("Abstract function.")}getVaryings(){W("Abstract function.")}getVar(e,t,s=null){return`${s!==null?this.generateArrayDeclaration(e,s):this.getType(e)} ${t}`}getVars(e){let t="";const s=this.vars[e];if(s!==void 0)for(const i of s)t+=`${this.getVar(i.type,i.name)}; `;return t}getUniforms(){W("Abstract function.")}getCodes(e){const t=this.codes[e];let s="";if(t!==void 0)for(const i of t)s+=i.code+`
60
- `;return s}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(){W("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(e&&e.isNode?e.isShaderCallNodeInternal?t=e.shaderNode.subBuilds:e.isStackNode?t=[e.subBuild]:t=this.getDataFromNode(e,"any").subBuilds:e instanceof Set?t=[...e]:t=e,!t)return null;const s=this.subBuildLayers;for(let i=t.length-1;i>=0;i--){const n=t[i];if(s.includes(n))return n}return null}getSubBuildOutput(e){return this.getSubBuildProperty("outputNode",e)}getSubBuildProperty(e="",t=null){let s;t!==null?s=this.getClosestSubBuild(t):s=this.subBuildFn;let i;return s?i=e?s+"_"+e:s:i=e,i}build(){const{object:e,material:t,renderer:s}=this;if(t!==null){let i=s.library.fromMaterial(t);i===null&&($(`NodeMaterial: Material "${t.type}" is not compatible.`),i=new st),i.build(this)}else this.addFlow("compute",e);for(const i of ap){this.setBuildStage(i),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(const n of op){this.setShaderStage(n);const a=this.flowNodes[n];for(const o of a)i==="generate"?this.flowNode(o):o.build(this)}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getSharedDataFromNode(e){let t=wO.get(e);return t===void 0&&(t={}),t}getNodeUniform(e,t){const s=this.getSharedDataFromNode(e);let i=s.cache;if(i===void 0){if(t==="float"||t==="int"||t==="uint")i=new gO(e);else if(t==="vec2"||t==="ivec2"||t==="uvec2")i=new yO(e);else if(t==="vec3"||t==="ivec3"||t==="uvec3")i=new xO(e);else if(t==="vec4"||t==="ivec4"||t==="uvec4")i=new _O(e);else if(t==="color")i=new bO(e);else if(t==="mat2")i=new TO(e);else if(t==="mat3")i=new SO(e);else if(t==="mat4")i=new vO(e);else throw new Error(`Uniform "${t}" not implemented.`);s.cache=i}return i}format(e,t,s){if(t=this.getVectorType(t),s=this.getVectorType(s),t===s||s===null||this.isReference(s))return e;const i=this.getTypeLength(t),n=this.getTypeLength(s);return i===16&&n===9?`${this.getType(s)}( ${e}[ 0 ].xyz, ${e}[ 1 ].xyz, ${e}[ 2 ].xyz )`:i===9&&n===4?`${this.getType(s)}( ${e}[ 0 ].xy, ${e}[ 1 ].xy )`:i>4||n>4||n===0?e:i===n?`${this.getType(s)}( ${e} )`:i>n?(e=s==="bool"?`all( ${e} )`:`${e}.${"xyz".slice(0,n)}`,this.format(e,this.getTypeFromLength(n,this.getComponentType(t)),s)):n===4&&i>1?`${this.getType(s)}( ${this.format(e,t,"vec3")}, 1.0 )`:i===2?`${this.getType(s)}( ${this.format(e,t,"vec2")}, 0.0 )`:(i===1&&n>1&&t!==this.getComponentType(s)&&(e=`${this.getType(this.getComponentType(s))}( ${e} )`),`${this.getType(s)}( ${e} )`)}getSignature(){return`// Three.js r${Zo} - Node System
61
- `}needsPreviousData(){const e=this.renderer.getMRT();return e&&e.has("velocity")||n0(this.object).useVelocity===!0}}class oy{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.updateMap=new WeakMap,this.updateBeforeMap=new WeakMap,this.updateAfterMap=new WeakMap,this.renderer=null,this.material=null,this.camera=null,this.object=null,this.scene=null}_getMaps(e,t){let s=e.get(t);return s===void 0&&(s={renderId:0,frameId:0},e.set(t,s)),s}updateBeforeNode(e){const t=e.getUpdateBeforeType(),s=e.updateReference(this);if(t===re.FRAME){const i=this._getMaps(this.updateBeforeMap,s);if(i.frameId!==this.frameId){const n=i.frameId;i.frameId=this.frameId,e.updateBefore(this)===!1&&(i.frameId=n)}}else if(t===re.RENDER){const i=this._getMaps(this.updateBeforeMap,s);if(i.renderId!==this.renderId){const n=i.renderId;i.renderId=this.renderId,e.updateBefore(this)===!1&&(i.renderId=n)}}else t===re.OBJECT&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),s=e.updateReference(this);if(t===re.FRAME){const i=this._getMaps(this.updateAfterMap,s);i.frameId!==this.frameId&&e.updateAfter(this)!==!1&&(i.frameId=this.frameId)}else if(t===re.RENDER){const i=this._getMaps(this.updateAfterMap,s);i.renderId!==this.renderId&&e.updateAfter(this)!==!1&&(i.renderId=this.renderId)}else t===re.OBJECT&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),s=e.updateReference(this);if(t===re.FRAME){const i=this._getMaps(this.updateMap,s);i.frameId!==this.frameId&&e.update(this)!==!1&&(i.frameId=this.frameId)}else if(t===re.RENDER){const i=this._getMaps(this.updateMap,s);i.renderId!==this.renderId&&e.update(this)!==!1&&(i.renderId=this.renderId)}else t===re.OBJECT&&e.update(this)}update(){this.frameId++,this.lastTime===void 0&&(this.lastTime=performance.now()),this.deltaTime=(performance.now()-this.lastTime)/1e3,this.lastTime=performance.now(),this.time+=this.deltaTime}}class Pm{constructor(e,t,s=null,i="",n=!1){this.type=e,this.name=t,this.count=s,this.qualifier=i,this.isConst=n}}Pm.isNodeFunctionInput=!0;class AO extends Nr{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class EO extends Nr{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:wm(this.light),lightColor:e}}}class NO extends Nr{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=vm(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=ee(new Ne).setGroup(se)}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:s,lightDirectionNode:i}=this,a=jn.dot(i).mul(.5).add(.5),o=ye(s,t,a);e.context.irradiance.addAssign(o)}}class Fm extends Nr{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=ee(0).setGroup(se),this.penumbraCosNode=ee(0).setGroup(se),this.cutoffDistanceNode=ee(0).setGroup(se),this.decayExponentNode=ee(0).setGroup(se),this.colorNode=ee(this.color).setGroup(se)}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:s,penumbraCosNode:i}=this;return ti(s,i,t)}getLightCoord(e){const t=e.getNodeProperties(this);let s=t.projectionUV;return s===void 0&&(s=sS(this.light,e.context.positionWorld),t.projectionUV=s),s}setupDirect(e){const{colorNode:t,cutoffDistanceNode:s,decayExponentNode:i,light:n}=this,a=this.getLightVector(e),o=a.normalize(),l=o.dot(wm(n)),c=this.getSpotAttenuation(e,l),u=a.length(),h=Em({lightDistance:u,cutoffDistance:s,decayExponent:i});let d=t.mul(c).mul(h),p,f;return n.colorNode?(f=this.getLightCoord(e),p=n.colorNode(f)):n.map&&(f=this.getLightCoord(e),p=we(n.map,f.xy).onRenderUpdate(()=>n.map)),p&&(d=f.mul(2).sub(1).abs().lessThan(1).all().select(d.mul(p),d)),{lightColor:d,lightDirection:o}}}class RO extends Fm{static get type(){return"IESSpotLightNode"}getSpotAttenuation(e,t){const s=this.light.iesMap;let i=null;if(s&&s.isTexture===!0){const n=t.acos().mul(1/Math.PI);i=we(s,z(n,0),0).r}else i=super.getSpotAttenuation(t);return i}}class PO extends Nr{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let s=0;s<9;s++)t.push(new D);this.lightProbe=It(t)}update(e){const{light:t}=this;super.update(e);for(let s=0;s<9;s++)this.lightProbe.array[s].copy(t.sh.coefficients[s]).multiplyScalar(t.intensity)}setup(e){const t=wS(jn,this.lightProbe);e.context.irradiance.addAssign(t)}}const FO=R(([r,e])=>{const t=r.abs().sub(e);return wi(tt(t,0)).add(ns(tt(t.x,t.y),0))});class BO extends Fm{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),t.aspect===null){let s=1;t.map!==null&&(s=t.map.width/t.map.height),t.shadow.aspect=s}else t.shadow.aspect=t.aspect}getSpotAttenuation(e){const t=T(0),s=this.penumbraCosNode,i=ph(this.light).mul(e.context.positionWorld||Ai);return ne(i.w.greaterThan(0),()=>{const n=i.xyz.div(i.w),a=FO(n.xy.sub(z(.5)),z(.5)),o=bs(-1,Te(1,Mf(s)).sub(1));t.assign(Yu(a.mul(-2).mul(o)))}),t}}const _d=new ve,ec=new ve;let no=null;class DO extends Nr{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=ee(new D).setGroup(se),this.halfWidth=ee(new D).setGroup(se),this.updateType=re.RENDER}update(e){super.update(e);const{light:t}=this,s=e.camera.matrixWorldInverse;ec.identity(),_d.copy(t.matrixWorld),_d.premultiply(s),ec.extractRotation(_d),this.halfWidth.value.set(t.width*.5,0,0),this.halfHeight.value.set(0,t.height*.5,0),this.halfWidth.value.applyMatrix4(ec),this.halfHeight.value.applyMatrix4(ec)}setupDirectRectArea(e){let t,s;e.isAvailable("float32Filterable")?(t=we(no.LTC_FLOAT_1),s=we(no.LTC_FLOAT_2)):(t=we(no.LTC_HALF_1),s=we(no.LTC_HALF_2));const{colorNode:i,light:n}=this,a=Mm(n);return{lightColor:i,lightPosition:a,halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:s}}static setLTC(e){no=e}}class ES{parseFunction(){W("Abstract function.")}}class Bm{constructor(e,t,s="",i=""){this.type=e,this.inputs=t,this.name=s,this.precision=i}getCode(){W("Abstract function.")}}Bm.isNodeFunction=!0;const OO=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,LO=/[a-z_0-9]+/ig,ly="#pragma main",IO=r=>{r=r.trim();const e=r.indexOf(ly),t=e!==-1?r.slice(e+ly.length):r,s=t.match(OO);if(s!==null&&s.length===5){const i=s[4],n=[];let a=null;for(;(a=LO.exec(i))!==null;)n.push(a);const o=[];let l=0;for(;l<n.length;){const f=n[l][0]==="const";f===!0&&l++;let m=n[l][0];m==="in"||m==="out"||m==="inout"?l++:m="";const x=n[l++][0];let y=Number.parseInt(n[l][0]);Number.isNaN(y)===!1?l++:y=null;const b=n[l++][0];o.push(new Pm(x,b,y,m,f))}const c=t.substring(s[0].length),u=s[3]!==void 0?s[3]:"",h=s[2],d=s[1]!==void 0?s[1]:"",p=e!==-1?r.slice(0,e):"";return{type:h,inputs:o,name:u,precision:d,inputsCode:i,blockCode:c,headerCode:p}}else throw new Error("FunctionNode: Function is not a GLSL code.")};class UO extends Bm{constructor(e){const{type:t,inputs:s,name:i,precision:n,inputsCode:a,blockCode:o,headerCode:l}=IO(e);super(t,s,i,n),this.inputsCode=a,this.blockCode=o,this.headerCode=l}getCode(e=this.name){let t;const s=this.blockCode;if(s!==""){const{type:i,inputsCode:n,headerCode:a,precision:o}=this;let l=`${i} ${e} ( ${n.trim()} )`;o!==""&&(l=`${o} ${l}`),t=a+l+s}else t="";return t}}class VO extends ES{parseFunction(e){return new UO(e)}}const cy=new WeakMap,vs=[],fn=[];class kO extends qn{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new oy,this.nodeBuilderCache=new Map,this.callHashCache=new zn,this.groupsData=new zn,this.cacheLib={}}updateGroup(e){const t=e.groupNode,s=t.name;if(s===_f.name)return!0;if(s===se.name){const n=this.get(e),a=this.nodeFrame.renderId;return n.renderId!==a?(n.renderId=a,!0):!1}if(s===x0.name){const n=this.get(e),a=this.nodeFrame.frameId;return n.frameId!==a?(n.frameId=a,!0):!1}vs[0]=t,vs[1]=e;let i=this.groupsData.get(vs);return i===void 0&&this.groupsData.set(vs,i={}),vs[0]=null,vs[1]=null,i.version!==t.version?(i.version=t.version,!0):!1}getForRenderCacheKey(e){return e.initialCacheKey}getForRender(e){const t=this.get(e);let s=t.nodeBuilderState;if(s===void 0){const{nodeBuilderCache:i}=this,n=this.getForRenderCacheKey(e);if(s=i.get(n),s===void 0){const a=l=>{const c=this.backend.createNodeBuilder(e.object,this.renderer);return c.scene=e.scene,c.material=l,c.camera=e.camera,c.context.material=l,c.lightsNode=e.lightsNode,c.environmentNode=this.getEnvironmentNode(e.scene),c.fogNode=this.getFogNode(e.scene),c.clippingContext=e.clippingContext,this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview&&c.enableMultiview(),c};let o=a(e.material);try{o.build()}catch(l){o=a(new st),o.build();let c=l.stackTrace;!c&&l.stack&&(c=new ct(l.stack)),$("TSL: "+l,c)}s=this._createNodeBuilderState(o),i.set(n,s)}s.usedTimes++,t.nodeBuilderState=s}return s}delete(e){if(e.isRenderObject){const t=this.get(e).nodeBuilderState;t.usedTimes--,t.usedTimes===0&&this.nodeBuilderCache.delete(this.getForRenderCacheKey(e))}return super.delete(e)}getForCompute(e){const t=this.get(e);let s=t.nodeBuilderState;if(s===void 0){const i=this.backend.createNodeBuilder(e,this.renderer);i.build(),s=this._createNodeBuilderState(i),t.nodeBuilderState=s}return s}_createNodeBuilderState(e){return new sO(e.vertexShader,e.fragmentShader,e.computeShader,e.getAttributesArray(),e.getBindings(),e.updateNodes,e.updateBeforeNodes,e.updateAfterNodes,e.observer,e.transforms)}getEnvironmentNode(e){this.updateEnvironment(e);let t=null;if(e.environmentNode&&e.environmentNode.isNode)t=e.environmentNode;else{const s=this.get(e);s.environmentNode&&(t=s.environmentNode)}return t}getBackgroundNode(e){this.updateBackground(e);let t=null;if(e.backgroundNode&&e.backgroundNode.isNode)t=e.backgroundNode;else{const s=this.get(e);s.backgroundNode&&(t=s.backgroundNode)}return t}getFogNode(e){return this.updateFog(e),e.fogNode||this.get(e).fogNode||null}getCacheKey(e,t){vs[0]=e,vs[1]=t;const s=this.renderer.info.calls,i=this.callHashCache.get(vs)||{};if(i.callId!==s){const n=this.getEnvironmentNode(e),a=this.getFogNode(e);t&&fn.push(t.getCacheKey(!0)),n&&fn.push(n.getCacheKey()),a&&fn.push(a.getCacheKey()),fn.push(this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview?1:0),fn.push(this.renderer.shadowMap.enabled?1:0),fn.push(this.renderer.shadowMap.type),i.callId=s,i.cacheKey=Ko(fn),this.callHashCache.set(vs,i),fn.length=0}return vs[0]=null,vs[1]=null,i.cacheKey}get isToneMappingState(){return!this.renderer.getRenderTarget()}updateBackground(e){const t=this.get(e),s=e.background;if(s){const i=e.backgroundBlurriness===0&&t.backgroundBlurriness>0||e.backgroundBlurriness>0&&t.backgroundBlurriness===0;if(t.background!==s||i){const n=this.getCacheNode("background",s,()=>{if(s.isCubeTexture===!0||s.mapping===Vp||s.mapping===kp||s.mapping===Qd){if(e.backgroundBlurriness>0||s.mapping===Qd)return fm(s);{let a;return s.isCubeTexture===!0?a=Xt(s):a=we(s),uT(a)}}else{if(s.isTexture===!0)return we(s,Ci.flipY()).setUpdateMatrix(!0);s.isColor!==!0&&$("WebGPUNodes: Unsupported background configuration.",s)}},i);t.backgroundNode=n,t.background=s,t.backgroundBlurriness=e.backgroundBlurriness}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}getCacheNode(e,t,s,i=!1){const n=this.cacheLib[e]||(this.cacheLib[e]=new WeakMap);let a=n.get(t);return(a===void 0||i)&&(a=s(),n.set(t,a)),a}updateFog(e){const t=this.get(e),s=e.fog;if(s){if(t.fog!==s){const i=this.getCacheNode("fog",s,()=>{if(s.isFogExp2){const n=Ye("color","color",s).setGroup(se),a=Ye("density","float",s).setGroup(se);return Ap(n,tS(a))}else if(s.isFog){const n=Ye("color","color",s).setGroup(se),a=Ye("near","float",s).setGroup(se),o=Ye("far","float",s).setGroup(se);return Ap(n,eS(a,o))}else $("Renderer: Unsupported fog configuration.",s)});t.fogNode=i,t.fog=s}}else delete t.fogNode,delete t.fog}updateEnvironment(e){const t=this.get(e),s=e.environment;if(s){if(t.environment!==s){const i=this.getCacheNode("environment",s,()=>{if(s.isCubeTexture===!0)return Xt(s);if(s.isTexture===!0)return we(s);$("Nodes: Unsupported environment configuration.",s)});t.environmentNode=i,t.environment=s}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,s=null,i=null,n=null){const a=this.nodeFrame;return a.renderer=e,a.scene=t,a.object=s,a.camera=i,a.material=n,a}getNodeFrameForRender(e){return this.getNodeFrame(e.renderer,e.scene,e.object,e.camera,e.material)}getOutputCacheKey(){const e=this.renderer;return e.toneMapping+","+e.currentColorSpace+","+e.xr.isPresenting}hasOutputChange(e){return cy.get(e)!==this.getOutputCacheKey()}getOutputNode(e){const t=this.renderer,s=this.getOutputCacheKey(),i=e.isArrayTexture?uh(e,E(Ci,an("gl_ViewID_OVR"))).renderOutput(t.toneMapping,t.currentColorSpace):we(e,Ci).renderOutput(t.toneMapping,t.currentColorSpace);return cy.set(e,s),i}updateBefore(e){const t=e.getNodeBuilderState();for(const s of t.updateBeforeNodes)this.getNodeFrameForRender(e).updateBeforeNode(s)}updateAfter(e){const t=e.getNodeBuilderState();for(const s of t.updateAfterNodes)this.getNodeFrameForRender(e).updateAfterNode(s)}updateForCompute(e){const t=this.getNodeFrame(),s=this.getForCompute(e);for(const i of s.updateNodes)t.updateNode(i)}updateForRender(e){const t=this.getNodeFrameForRender(e),s=e.getNodeBuilderState();for(const i of s.updateNodes)t.updateNode(i)}needsRefresh(e){const t=this.getNodeFrameForRender(e);return e.getMonitor().needsRefresh(e,t)}dispose(){super.dispose(),this.nodeFrame=new oy,this.nodeBuilderCache=new Map,this.cacheLib={}}}const bd=new Tn;class vu{constructor(e=null){this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewNormalMatrix=new as,this.clippingGroupContexts=new WeakMap,this.intersectionPlanes=[],this.unionPlanes=[],this.parentVersion=null,e!==null&&(this.viewNormalMatrix=e.viewNormalMatrix,this.clippingGroupContexts=e.clippingGroupContexts,this.shadowPass=e.shadowPass,this.viewMatrix=e.viewMatrix)}projectPlanes(e,t,s){const i=e.length;for(let n=0;n<i;n++){bd.copy(e[n]).applyMatrix4(this.viewMatrix,this.viewNormalMatrix);const a=t[s+n],o=bd.normal;a.x=-o.x,a.y=-o.y,a.z=-o.z,a.w=bd.constant}}updateGlobal(e,t){this.shadowPass=e.overrideMaterial!==null&&e.overrideMaterial.isShadowPassMaterial,this.viewMatrix=t.matrixWorldInverse,this.viewNormalMatrix.getNormalMatrix(this.viewMatrix)}update(e,t){let s=!1;e.version!==this.parentVersion&&(this.intersectionPlanes=Array.from(e.intersectionPlanes),this.unionPlanes=Array.from(e.unionPlanes),this.parentVersion=e.version),this.clipIntersection!==t.clipIntersection&&(this.clipIntersection=t.clipIntersection,this.clipIntersection?this.unionPlanes.length=e.unionPlanes.length:this.intersectionPlanes.length=e.intersectionPlanes.length);const i=t.clippingPlanes,n=i.length;let a,o;if(this.clipIntersection?(a=this.intersectionPlanes,o=e.intersectionPlanes.length):(a=this.unionPlanes,o=e.unionPlanes.length),a.length!==o+n){a.length=o+n;for(let l=0;l<n;l++)a[o+l]=new Ee;s=!0}this.projectPlanes(i,a,o),s&&(this.version++,this.cacheKey=`${this.intersectionPlanes.length}:${this.unionPlanes.length}`)}getGroupContext(e){if(this.shadowPass&&!e.clipShadows)return this;let t=this.clippingGroupContexts.get(e);return t===void 0&&(t=new vu(this),this.clippingGroupContexts.set(e,t)),t.update(this,e),t}get unionClippingCount(){return this.unionPlanes.length}}class zO{constructor(e,t){this.bundleGroup=e,this.camera=t}}const Jr=[];class GO{constructor(){this.bundles=new zn}get(e,t){const s=this.bundles;Jr[0]=e,Jr[1]=t;let i=s.get(Jr);return i===void 0&&(i=new zO(e,t),s.set(Jr,i)),Jr[0]=null,Jr[1]=null,i}dispose(){this.bundles=new zn}}class NS{constructor(){this.lightNodes=new WeakMap,this.materialNodes=new Map,this.toneMappingNodes=new Map}fromMaterial(e){if(e.isNodeMaterial)return e;let t=null;const s=this.getMaterialNodeClass(e.type);if(s!==null){t=new s;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 this.lightNodes.get(e)||null}addLight(e,t){this.addClass(e,t,this.lightNodes)}addType(e,t,s){if(s.has(t)){W(`Redefinition of node ${t}`);return}if(typeof e!="function")throw new Error(`Node class ${e.name} is not a class.`);if(typeof t=="function"||typeof t=="object")throw new Error(`Base class ${t} is not a class.`);s.set(t,e)}addClass(e,t,s){if(s.has(t)){W(`Redefinition of node ${t.name}`);return}if(typeof e!="function")throw new Error(`Node class ${e.name} is not a class.`);if(typeof t!="function")throw new Error(`Base class ${t.name} is not a class.`);s.set(t,e)}}const $O=new Cm,uy=new WeakMap;class WO{createNode(e=[]){return new Cm().setLights(e)}getNode(e){if(e.isQuadMesh)return $O;let t=uy.get(e);return t===void 0&&(t=this.createNode(),uy.set(e,t)),t}}class bo extends nn{constructor(e=1,t=1,s={}){super(e,t,s),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 hy=new D,dy=new D;class HO extends Gn{constructor(e,t=!1){super(),this.enabled=!1,this.isPresenting=!1,this.cameraAutoUpdate=!0,this._renderer=e,this._cameraL=new fs,this._cameraL.viewport=new Ee,this._cameraR=new fs,this._cameraR.viewport=new Ee,this._cameras=[this._cameraL,this._cameraR],this._cameraXR=new EC,this._currentDepthNear=null,this._currentDepthFar=null,this._controllers=[],this._controllerInputSources=[],this._xrRenderTarget=null,this._layers=[],this._sessionUsesLayers=!1,this._supportsGlBinding=typeof XRWebGLBinding<"u",this._frameBufferTargets=null,this._createXRLayer=QO.bind(this),this._gl=null,this._currentAnimationContext=null,this._currentAnimationLoop=null,this._currentPixelRatio=null,this._currentSize=new xe,this._onSessionEvent=XO.bind(this),this._onSessionEnd=YO.bind(this),this._onInputSourcesChange=ZO.bind(this),this._onAnimationFrame=KO.bind(this),this._referenceSpace=null,this._referenceSpaceType="local-floor",this._customReferenceSpace=null,this._framebufferScaleFactor=1,this._foveation=1,this._session=null,this._glBaseLayer=null,this._glBinding=null,this._glProjLayer=null,this._xrFrame=null,this._supportsLayers=this._supportsGlBinding&&"createProjectionLayer"in XRWebGLBinding.prototype,this._useMultiviewIfPossible=t,this._useMultiview=!1}getController(e){return this._getController(e).getTargetRaySpace()}getControllerGrip(e){return this._getController(e).getGripSpace()}getHand(e){return this._getController(e).getHandSpace()}getFoveation(){if(!(this._glProjLayer===null&&this._glBaseLayer===null))return this._foveation}setFoveation(e){this._foveation=e,this._glProjLayer!==null&&(this._glProjLayer.fixedFoveation=e),this._glBaseLayer!==null&&this._glBaseLayer.fixedFoveation!==void 0&&(this._glBaseLayer.fixedFoveation=e)}getFramebufferScaleFactor(){return this._framebufferScaleFactor}setFramebufferScaleFactor(e){this._framebufferScaleFactor=e,this.isPresenting===!0&&W("XRManager: Cannot change framebuffer scale while presenting.")}getReferenceSpaceType(){return this._referenceSpaceType}setReferenceSpaceType(e){this._referenceSpaceType=e,this.isPresenting===!0&&W("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(this._session!==null)return this._session.environmentBlendMode}getBinding(){return this._glBinding===null&&this._supportsGlBinding&&(this._glBinding=new XRWebGLBinding(this._session,this._gl)),this._glBinding}getFrame(){return this._xrFrame}useMultiview(){return this._useMultiview}createQuadLayer(e,t,s,i,n,a,o,l={}){const c=new Qp(e,t),u=new bo(n,a,{format:ms,type:Ut,depthTexture:new Bs(n,a,l.stencil?Fn:rt,void 0,void 0,void 0,void 0,void 0,void 0,l.stencil?Yi:Qs),stencilBuffer:l.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});u._autoAllocateDepthBuffer=!0;const h=new vn({color:16777215,side:Si});h.map=u.texture,h.map.offset.y=1,h.map.repeat.y=-1;const d=new Un(c,h);d.position.copy(s),d.quaternion.copy(i);const p={type:"quad",width:e,height:t,translation:s,quaternion:i,pixelwidth:n,pixelheight:a,plane:d,material:h,rendercall:o,renderTarget:u};if(this._layers.push(p),this._session!==null){p.plane.material=new vn({color:16777215,side:Si}),p.plane.material.blending=ma,p.plane.material.blendEquation=Ns,p.plane.material.blendSrc=bn,p.plane.material.blendDst=bn,p.xrlayer=this._createXRLayer(p);const f=this._session.renderState.layers;f.unshift(p.xrlayer),this._session.updateRenderState({layers:f})}else u.isXRRenderTarget=!1;return d}createCylinderLayer(e,t,s,i,n,a,o,l,c={}){const u=new Zp(e,e,e*t/s,64,64,!0,Math.PI-t/2,t),h=new bo(a,o,{format:ms,type:Ut,depthTexture:new Bs(a,o,c.stencil?Fn:rt,void 0,void 0,void 0,void 0,void 0,void 0,c.stencil?Yi:Qs),stencilBuffer:c.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});h._autoAllocateDepthBuffer=!0;const d=new vn({color:16777215,side:Rt});d.map=h.texture,d.map.offset.y=1,d.map.repeat.y=-1;const p=new Un(u,d);p.position.copy(i),p.quaternion.copy(n);const f={type:"cylinder",radius:e,centralAngle:t,aspectratio:s,translation:i,quaternion:n,pixelwidth:a,pixelheight:o,plane:p,material:d,rendercall:l,renderTarget:h};if(this._layers.push(f),this._session!==null){f.plane.material=new vn({color:16777215,side:Rt}),f.plane.material.blending=ma,f.plane.material.blendEquation=Ns,f.plane.material.blendSrc=bn,f.plane.material.blendDst=bn,f.xrlayer=this._createXRLayer(f);const m=this._session.renderState.layers;m.unshift(f.xrlayer),this._session.updateRenderState({layers:m})}else h.isXRRenderTarget=!1;return p}renderLayers(){const e=new D,t=new vr,s=this._renderer,i=this.isPresenting,n=s.getOutputRenderTarget(),a=s._frameBufferTarget;this.isPresenting=!1;const o=new xe;s.getSize(o);const l=s._quad;for(const c of this._layers)if(c.renderTarget.isXRRenderTarget=this._session!==null,c.renderTarget._hasExternalTextures=c.renderTarget.isXRRenderTarget,c.renderTarget.isXRRenderTarget&&this._sessionUsesLayers){c.xrlayer.transform=new XRRigidTransform(c.plane.getWorldPosition(e),c.plane.getWorldQuaternion(t));const u=this._glBinding.getSubImage(c.xrlayer,this._xrFrame);s.backend.setXRRenderTargetTextures(c.renderTarget,u.colorTexture,void 0),s._setXRLayerSize(c.renderTarget.width,c.renderTarget.height),s.setOutputRenderTarget(c.renderTarget),s.setRenderTarget(null),s._frameBufferTarget=null,this._frameBufferTargets||(this._frameBufferTargets=new WeakMap);const{frameBufferTarget:h,quad:d}=this._frameBufferTargets.get(c.renderTarget)||{frameBufferTarget:null,quad:null};h?(s._frameBufferTarget=h,s._quad=d):(s._quad=new lh(new st),this._frameBufferTargets.set(c.renderTarget,{frameBufferTarget:s._getFrameBufferTarget(),quad:s._quad})),c.rendercall(),s._frameBufferTarget=null}else s.setRenderTarget(c.renderTarget),c.rendercall();s.setRenderTarget(null),s.setOutputRenderTarget(n),s._frameBufferTarget=a,s._setXRLayerSize(o.x,o.y),s._quad=l,this.isPresenting=i}getSession(){return this._session}async setSession(e){const t=this._renderer,s=t.backend;this._gl=t.getContext();const i=this._gl,n=i.getContextAttributes();if(this._session=e,e!==null){if(s.isWebGPUBackend===!0)throw new Error('THREE.XRManager: XR is currently not supported with a WebGPU backend. Use WebGL by passing "{ forceWebGL: true }" to the constructor of the renderer.');if(e.addEventListener("select",this._onSessionEvent),e.addEventListener("selectstart",this._onSessionEvent),e.addEventListener("selectend",this._onSessionEvent),e.addEventListener("squeeze",this._onSessionEvent),e.addEventListener("squeezestart",this._onSessionEvent),e.addEventListener("squeezeend",this._onSessionEvent),e.addEventListener("end",this._onSessionEnd),e.addEventListener("inputsourceschange",this._onInputSourcesChange),await s.makeXRCompatible(),this._currentPixelRatio=t.getPixelRatio(),t.getSize(this._currentSize),this._currentAnimationContext=t._animation.getContext(),this._currentAnimationLoop=t._animation.getAnimationLoop(),t._animation.stop(),this._supportsLayers===!0){let a=null,o=null,l=null;t.depth&&(l=t.stencil?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT24,a=t.stencil?Yi:Qs,o=t.stencil?Fn:rt);const c={colorFormat:i.RGBA8,depthFormat:l,scaleFactor:this._framebufferScaleFactor,clearOnAccess:!1};this._useMultiviewIfPossible&&t.hasFeature("OVR_multiview2")&&(c.textureType="texture-array",this._useMultiview=!0),this._glBinding=this.getBinding();const u=this._glBinding.createProjectionLayer(c),h=[u];this._glProjLayer=u,t.setPixelRatio(1),t._setXRLayerSize(u.textureWidth,u.textureHeight);const d=this._useMultiview?2:1,p=new Bs(u.textureWidth,u.textureHeight,o,void 0,void 0,void 0,void 0,void 0,void 0,a,d);if(this._xrRenderTarget=new bo(u.textureWidth,u.textureHeight,{format:ms,type:Ut,colorSpace:t.outputColorSpace,depthTexture:p,stencilBuffer:t.stencil,samples:n.antialias?4:0,resolveDepthBuffer:u.ignoreDepthValues===!1,resolveStencilBuffer:u.ignoreDepthValues===!1,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 f of this._layers)f.plane.material=new vn({color:16777215,side:f.type==="cylinder"?Rt:Si}),f.plane.material.blending=ma,f.plane.material.blendEquation=Ns,f.plane.material.blendSrc=bn,f.plane.material.blendDst=bn,f.xrlayer=this._createXRLayer(f),h.unshift(f.xrlayer);e.updateRenderState({layers:h})}else{const a={antialias:t.currentSamples>0,alpha:!0,depth:t.depth,stencil:t.stencil,framebufferScaleFactor:this.getFramebufferScaleFactor()},o=new XRWebGLLayer(e,i,a);this._glBaseLayer=o,e.updateRenderState({baseLayer:o}),t.setPixelRatio(1),t._setXRLayerSize(o.framebufferWidth,o.framebufferHeight),this._xrRenderTarget=new bo(o.framebufferWidth,o.framebufferHeight,{format:ms,type:Ut,colorSpace:t.outputColorSpace,stencilBuffer:t.stencil,resolveDepthBuffer:o.ignoreDepthValues===!1,resolveStencilBuffer:o.ignoreDepthValues===!1}),this._xrRenderTarget._isOpaqueFramebuffer=!0,this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType())}this.setFoveation(this.getFoveation()),t._animation.setAnimationLoop(this._onAnimationFrame),t._animation.setContext(e),t._animation.start(),this.isPresenting=!0,this.dispatchEvent({type:"sessionstart"})}}updateCamera(e){const t=this._session;if(t===null)return;const s=e.near,i=e.far,n=this._cameraXR,a=this._cameraL,o=this._cameraR;n.near=o.near=a.near=s,n.far=o.far=a.far=i,n.isMultiViewCamera=this._useMultiview,(this._currentDepthNear!==n.near||this._currentDepthFar!==n.far)&&(t.updateRenderState({depthNear:n.near,depthFar:n.far}),this._currentDepthNear=n.near,this._currentDepthFar=n.far),n.layers.mask=e.layers.mask|6,a.layers.mask=n.layers.mask&-5,o.layers.mask=n.layers.mask&-3;const l=e.parent,c=n.cameras;py(n,l);for(let u=0;u<c.length;u++)py(c[u],l);c.length===2?jO(n,a,o):n.projectionMatrix.copy(a.projectionMatrix),qO(e,n,l)}_getController(e){let t=this._controllers[e];return t===void 0&&(t=new Yw,this._controllers[e]=t),t}}function jO(r,e,t){hy.setFromMatrixPosition(e.matrixWorld),dy.setFromMatrixPosition(t.matrixWorld);const s=hy.distanceTo(dy),i=e.projectionMatrix.elements,n=t.projectionMatrix.elements,a=i[14]/(i[10]-1),o=i[14]/(i[10]+1),l=(i[9]+1)/i[5],c=(i[9]-1)/i[5],u=(i[8]-1)/i[0],h=(n[8]+1)/n[0],d=a*u,p=a*h,f=s/(-u+h),m=f*-u;if(e.matrixWorld.decompose(r.position,r.quaternion,r.scale),r.translateX(m),r.translateZ(f),r.matrixWorld.compose(r.position,r.quaternion,r.scale),r.matrixWorldInverse.copy(r.matrixWorld).invert(),i[10]===-1)r.projectionMatrix.copy(e.projectionMatrix),r.projectionMatrixInverse.copy(e.projectionMatrixInverse);else{const x=a+f,y=o+f,b=d-m,v=p+(s-m),S=l*o/y*x,M=c*o/y*x;r.projectionMatrix.makePerspective(b,v,S,M,x,y),r.projectionMatrixInverse.copy(r.projectionMatrix).invert()}}function py(r,e){e===null?r.matrixWorld.copy(r.matrix):r.matrixWorld.multiplyMatrices(e.matrixWorld,r.matrix),r.matrixWorldInverse.copy(r.matrixWorld).invert()}function qO(r,e,t){t===null?r.matrix.copy(e.matrixWorld):(r.matrix.copy(t.matrixWorld),r.matrix.invert(),r.matrix.multiply(e.matrixWorld)),r.matrix.decompose(r.position,r.quaternion,r.scale),r.updateMatrixWorld(!0),r.projectionMatrix.copy(e.projectionMatrix),r.projectionMatrixInverse.copy(e.projectionMatrixInverse),r.isPerspectiveCamera&&(r.fov=Ra*2*Math.atan(1/r.projectionMatrix.elements[5]),r.zoom=1)}function XO(r){const e=this._controllerInputSources.indexOf(r.inputSource);if(e===-1)return;const t=this._controllers[e];if(t!==void 0){const s=this.getReferenceSpace();t.update(r.inputSource,r.frame,s),t.dispatchEvent({type:r.type,data:r.inputSource})}}function YO(){const r=this._session,e=this._renderer;r.removeEventListener("select",this._onSessionEvent),r.removeEventListener("selectstart",this._onSessionEvent),r.removeEventListener("selectend",this._onSessionEvent),r.removeEventListener("squeeze",this._onSessionEvent),r.removeEventListener("squeezestart",this._onSessionEvent),r.removeEventListener("squeezeend",this._onSessionEvent),r.removeEventListener("end",this._onSessionEnd),r.removeEventListener("inputsourceschange",this._onInputSourcesChange);for(let t=0;t<this._controllers.length;t++){const s=this._controllerInputSources[t];s!==null&&(this._controllerInputSources[t]=null,this._controllers[t].disconnect(s))}if(this._currentDepthNear=null,this._currentDepthFar=null,e._resetXRState(),this._session=null,this._xrRenderTarget=null,this._glBinding=null,this._glBaseLayer=null,this._glProjLayer=null,this._sessionUsesLayers===!0)for(const t of this._layers)t.renderTarget=new bo(t.pixelwidth,t.pixelheight,{format:ms,type:Ut,depthTexture:new Bs(t.pixelwidth,t.pixelheight,t.stencilBuffer?Fn:rt,void 0,void 0,void 0,void 0,void 0,void 0,t.stencilBuffer?Yi:Qs),stencilBuffer:t.stencilBuffer,resolveDepthBuffer:!1,resolveStencilBuffer:!1}),t.renderTarget.isXRRenderTarget=!1,t.plane.material=t.material,t.material.map=t.renderTarget.texture,t.material.map.offset.y=1,t.material.map.repeat.y=-1,delete t.xrlayer;this.isPresenting=!1,this._useMultiview=!1,e._animation.stop(),e._animation.setAnimationLoop(this._currentAnimationLoop),e._animation.setContext(this._currentAnimationContext),e._animation.start(),e.setPixelRatio(this._currentPixelRatio),e.setSize(this._currentSize.width,this._currentSize.height,!1),this.dispatchEvent({type:"sessionend"})}function ZO(r){const e=this._controllers,t=this._controllerInputSources;for(let s=0;s<r.removed.length;s++){const i=r.removed[s],n=t.indexOf(i);n>=0&&(t[n]=null,e[n].disconnect(i))}for(let s=0;s<r.added.length;s++){const i=r.added[s];let n=t.indexOf(i);if(n===-1){for(let o=0;o<e.length;o++)if(o>=t.length){t.push(i),n=o;break}else if(t[o]===null){t[o]=i,n=o;break}if(n===-1)break}const a=e[n];a&&a.connect(i)}}function QO(r){return r.type==="quad"?this._glBinding.createQuadLayer({transform:new XRRigidTransform(r.translation,r.quaternion),width:r.width/2,height:r.height/2,space:this._referenceSpace,viewPixelWidth:r.pixelwidth,viewPixelHeight:r.pixelheight,clearOnAccess:!1}):this._glBinding.createCylinderLayer({transform:new XRRigidTransform(r.translation,r.quaternion),radius:r.radius,centralAngle:r.centralAngle,aspectRatio:r.aspectRatio,space:this._referenceSpace,viewPixelWidth:r.pixelwidth,viewPixelHeight:r.pixelheight,clearOnAccess:!1})}function KO(r,e){if(e===void 0)return;const t=this._cameraXR,s=this._renderer,i=s.backend,n=this._glBaseLayer,a=this.getReferenceSpace(),o=e.getViewerPose(a);if(this._xrFrame=e,o!==null){const l=o.views;this._glBaseLayer!==null&&i.setXRTarget(n.framebuffer);let c=!1;l.length!==t.cameras.length&&(t.cameras.length=0,c=!0);for(let u=0;u<l.length;u++){const h=l[u];let d;if(this._supportsLayers===!0){const f=this._glBinding.getViewSubImage(this._glProjLayer,h);d=f.viewport,u===0&&i.setXRRenderTargetTextures(this._xrRenderTarget,f.colorTexture,this._glProjLayer.ignoreDepthValues&&!this._useMultiview?void 0:f.depthStencilTexture)}else d=n.getViewport(h);let p=this._cameras[u];p===void 0&&(p=new fs,p.layers.enable(u),p.viewport=new Ee,this._cameras[u]=p),p.matrix.fromArray(h.transform.matrix),p.matrix.decompose(p.position,p.quaternion,p.scale),p.projectionMatrix.fromArray(h.projectionMatrix),p.projectionMatrixInverse.copy(p.projectionMatrix).invert(),p.viewport.set(d.x,d.y,d.width,d.height),u===0&&(t.matrix.copy(p.matrix),t.matrix.decompose(t.position,t.quaternion,t.scale)),c===!0&&t.cameras.push(p)}s.setOutputRenderTarget(this._xrRenderTarget)}for(let l=0;l<this._controllers.length;l++){const c=this._controllerInputSources[l],u=this._controllers[l];c!==null&&u!==void 0&&u.update(c,e,a)}this._currentAnimationLoop&&this._currentAnimationLoop(r,e),e.detectedPlanes&&this.dispatchEvent({type:"planesdetected",data:e}),this._xrFrame=null}class JO extends Gn{constructor(e){super(),this.domElement=e,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new Ee(0,0,this._width,this._height),this._scissor=new Ee(0,0,this._width,this._height),this._scissorTest=!1,this.colorTexture=new Yp,this.depthTexture=new Bs}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,s){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this._pixelRatio=s,this.domElement.width=Math.floor(e*s),this.domElement.height=Math.floor(t*s),this.setViewport(0,0,e,t),this._dispatchResize())}setSize(e,t,s=!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),s===!0&&(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,s,i){const n=this._scissor;e.isVector4?n.copy(e):n.set(e,t,s,i)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,s,i,n=0,a=1){const o=this._viewport;e.isVector4?o.copy(e):o.set(e,t,s,i),o.minDepth=n,o.maxDepth=a}_dispatchResize(){this.dispatchEvent({type:"resize"})}dispose(){this.dispatchEvent({type:"dispose"})}}const fy=new qx,ea=new xe,Td=new Ee,Sd=new qp,vd=new Xp,tc=new ve,ki=new Ee,eL={[Si]:Rt,[Rt]:Si,[qi]:qi};class tL{constructor(e,t={}){this.isRenderer=!0;const{logarithmicDepthBuffer:s=!1,reversedDepthBuffer:i=!1,alpha:n=!0,depth:a=!0,stencil:o=!1,antialias:l=!1,samples:c=0,getFallback:u=null,outputBufferType:h=Et,multiview:d=!1}=t;this.backend=e,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.alpha=n,this.logarithmicDepthBuffer=s,this.reversedDepthBuffer=i,this.outputColorSpace=ds,this.toneMapping=dr,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=a,this.stencil=o,this.info=new YN,this.contextNode=rn(),this.library=new NS,this.lighting=new WO,this._samples=c||l===!0?4:0,this._onCanvasTargetResize=this._onCanvasTargetResize.bind(this),this._canvasTarget=new JO(e.getDomElement()),this._canvasTarget.addEventListener("resize",this._onCanvasTargetResize),this._canvasTarget.isDefaultCanvasTarget=!0,this._inspector=new O_,this._inspector.setRenderer(this),this._getFallback=u,this._attributes=null,this._geometries=null,this._nodes=null,this._animation=null,this._bindings=null,this._objects=null,this._pipelines=null,this._bundles=null,this._renderLists=null,this._renderContexts=null,this._textures=null,this._background=null,this._quad=new lh(new st),this._quad.name="Output Color Transform",this._quad.material.name="outputColorTransform",this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null,this._frameBufferTarget=null;const p=this.alpha===!0?0:1;this._clearColor=new mm(0,0,0,p),this._clearDepth=1,this._clearStencil=0,this._renderTarget=null,this._activeCubeFace=0,this._activeMipmapLevel=0,this._outputRenderTarget=null,this._mrt=null,this._renderObjectFunction=null,this._currentRenderObjectFunction=null,this._currentRenderBundle=null,this._handleObjectFunction=this._renderObjectDirect,this._isDeviceLost=!1,this.onDeviceLost=this._onDeviceLost,this._outputBufferType=h,this._cacheShadowNodes=new WeakMap,this._initialized=!1,this._callDepth=-1,this._initPromise=null,this._compilationPromises=null,this.transparent=!0,this.opaque=!0,this.shadowMap={enabled:!1,transmitted:!1,type:Sx},this.xr=new HO(this,d),this.debug={checkShaderErrors:!0,onShaderError:null,getShaderAsync:async(f,m,x)=>{await this.compileAsync(f,m);const y=this._renderLists.get(f,m),b=this._renderContexts.get(this._renderTarget,this._mrt),v=f.overrideMaterial||x.material,S=this._objects.get(x,v,f,m,y.lightsNode,b,b.clippingContext),{fragmentShader:M,vertexShader:A}=S.getNodeBuilderState();return{fragmentShader:M,vertexShader:A}}}}async init(){return this._initPromise!==null?this._initPromise:(this._initPromise=new Promise(async(e,t)=>{let s=this.backend;try{await s.init(this)}catch(i){if(this._getFallback!==null)try{this.backend=s=this._getFallback(i),await s.init(this)}catch(n){t(n);return}else{t(i);return}}this._nodes=new kO(this,s),this._animation=new kN(this,this._nodes,this.info),this._attributes=new qN(s),this._background=new eO(this,this._nodes),this._geometries=new XN(this._attributes,this.info),this._textures=new lR(this,s,this.info),this._pipelines=new JN(s,this._nodes),this._bindings=new eR(s,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new WN(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new iR(this.lighting),this._bundles=new GO,this._renderContexts=new aR(this),this._animation.start(),this._initialized=!0,this._inspector.init(),e(this)}),this._initPromise)}get domElement(){return this._canvasTarget.domElement}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,s=null){if(this._isDeviceLost===!0)return;this._initialized===!1&&await this.init();const i=this._nodes.nodeFrame,n=i.renderId,a=this._currentRenderContext,o=this._currentRenderObjectFunction,l=this._handleObjectFunction,c=this._compilationPromises,u=e.isScene===!0?e:fy;s===null&&(s=e);const h=this._renderTarget,d=this._renderContexts.get(h,this._mrt),p=this._activeMipmapLevel,f=[];this._currentRenderContext=d,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=f,i.renderId++,i.update(),d.depth=this.depth,d.stencil=this.stencil,d.clippingContext||(d.clippingContext=new vu),d.clippingContext.updateGlobal(u,t),u.onBeforeRender(this,e,t,h);const m=this._renderLists.get(e,t);if(m.begin(),this._projectObject(e,t,0,m,d.clippingContext),s!==e&&s.traverseVisible(function(S){S.isLight&&S.layers.test(t.layers)&&m.pushLight(S)}),m.finish(),h!==null){this._textures.updateRenderTarget(h,p);const S=this._textures.get(h);d.textures=S.textures,d.depthTexture=S.depthTexture}else d.textures=null,d.depthTexture=null;s!==e?this._background.update(s,m,d):this._background.update(u,m,d);const x=m.opaque,y=m.transparent,b=m.transparentDoublePass,v=m.lightsNode;this.opaque===!0&&x.length>0&&this._renderObjects(x,t,u,v),this.transparent===!0&&y.length>0&&this._renderTransparents(y,b,t,u,v),i.renderId=n,this._currentRenderContext=a,this._currentRenderObjectFunction=o,this._handleObjectFunction=l,this._compilationPromises=c,await Promise.all(f)}async renderAsync(e,t){Le('Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.render(e,t)}async waitForGPU(){$("Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.")}set inspector(e){this._inspector!==null&&this._inspector.setRenderer(null),this._inspector=e,this._inspector.setRenderer(this)}get inspector(){return this._inspector}set highPrecision(e){const t=this.contextNode.value;e===!0?(t.modelViewMatrix=pp,t.modelNormalViewMatrix=fp):this.highPrecision&&(delete t.modelViewMatrix,delete t.modelNormalViewMatrix)}get highPrecision(){const e=this.contextNode.value;return e.modelViewMatrix===pp&&e.modelNormalViewMatrix===fp}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getOutputBufferType(){return this._outputBufferType}getColorBufferType(){return Le('Renderer: ".getColorBufferType()" has been renamed to ".getOutputBufferType()".'),this.getOutputBufferType()}_onDeviceLost(e){let t=`THREE.WebGPURenderer: ${e.api} Device Lost:
62
-
63
- Message: ${e.message}`;e.reason&&(t+=`
64
- Reason: ${e.reason}`),$(t),this._isDeviceLost=!0}_renderBundle(e,t,s){const{bundleGroup:i,camera:n,renderList:a}=e,o=this._currentRenderContext,l=this._bundles.get(i,n),c=this.backend.get(l);c.renderContexts===void 0&&(c.renderContexts=new Set);const u=i.version!==c.version,h=c.renderContexts.has(o)===!1||u;if(c.renderContexts.add(o),h){this.backend.beginBundle(o),(c.renderObjects===void 0||u)&&(c.renderObjects=[]),this._currentRenderBundle=l;const{transparentDoublePass:d,transparent:p,opaque:f}=a;this.opaque===!0&&f.length>0&&this._renderObjects(f,n,t,s),this.transparent===!0&&p.length>0&&this._renderTransparents(p,d,n,t,s),this._currentRenderBundle=null,this.backend.finishBundle(o,l),c.version=i.version}else{const{renderObjects:d}=c;for(let p=0,f=d.length;p<f;p++){const m=d[p];this._nodes.needsRefresh(m)&&(this._nodes.updateBefore(m),this._nodes.updateForRender(m),this._bindings.updateForRender(m),this._nodes.updateAfter(m))}}this.backend.addBundle(o,l)}render(e,t){if(this._initialized===!1)throw new Error('Renderer: .render() called before the backend is initialized. Use "await renderer.init();" before rendering.');this._renderScene(e,t)}get initialized(){return this._initialized}_getFrameBufferTarget(){const{currentToneMapping:e,currentColorSpace:t}=this,s=e!==dr,i=t!==Ae.workingColorSpace;if(s===!1&&i===!1)return null;const{width:n,height:a}=this.getDrawingBufferSize(ea),{depth:o,stencil:l}=this;let c=this._frameBufferTarget;c===null&&(c=new nn(n,a,{depthBuffer:o,stencilBuffer:l,type:this._outputBufferType,format:ms,colorSpace:Ae.workingColorSpace,generateMipmaps:!1,minFilter:Gt,magFilter:Gt,samples:this.samples}),c.isPostProcessingRenderTarget=!0,this._frameBufferTarget=c);const u=this.getOutputRenderTarget();c.depthBuffer=o,c.stencilBuffer=l,u!==null?c.setSize(u.width,u.height,u.depth):c.setSize(n,a,1);const h=this._canvasTarget;return c.viewport.copy(h._viewport),c.scissor.copy(h._scissor),c.viewport.multiplyScalar(h._pixelRatio),c.scissor.multiplyScalar(h._pixelRatio),c.scissorTest=h._scissorTest,c.multiview=u!==null?u.multiview:!1,c.resolveDepthBuffer=u!==null?u.resolveDepthBuffer:!0,c._autoAllocateDepthBuffer=u!==null?u._autoAllocateDepthBuffer:!1,c}_renderScene(e,t,s=!0){if(this._isDeviceLost===!0)return;const i=s?this._getFrameBufferTarget():null,n=this._nodes.nodeFrame,a=n.renderId,o=this._currentRenderContext,l=this._currentRenderObjectFunction,c=this._handleObjectFunction;this._callDepth++;const u=e.isScene===!0?e:fy,h=this._renderTarget||this._outputRenderTarget,d=this._activeCubeFace,p=this._activeMipmapLevel;let f;i!==null?(f=i,this.setRenderTarget(f)):f=h;const m=this._renderContexts.get(f,this._mrt,this._callDepth);this._currentRenderContext=m,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this._handleObjectFunction=this._renderObjectDirect,this.info.calls++,this.info.render.calls++,this.info.render.frameCalls++,n.renderId=this.info.calls,this.backend.updateTimeStampUID(m),this.inspector.beginRender(this.backend.getTimestampUID(m),e,t,f);const x=this.xr;if(x.isPresenting===!1){let te=!1;if(this.reversedDepthBuffer===!0&&t.reversedDepth!==!0){if(t._reversedDepth=!0,t.isArrayCamera)for(const oe of t.cameras)oe._reversedDepth=!0;te=!0}const q=this.coordinateSystem;if(t.coordinateSystem!==q){if(t.coordinateSystem=q,t.isArrayCamera)for(const oe of t.cameras)oe.coordinateSystem=q;te=!0}if(te===!0&&(t.updateProjectionMatrix(),t.isArrayCamera))for(const oe of t.cameras)oe.updateProjectionMatrix()}e.matrixWorldAutoUpdate===!0&&e.updateMatrixWorld(),t.parent===null&&t.matrixWorldAutoUpdate===!0&&t.updateMatrixWorld(),x.enabled===!0&&x.isPresenting===!0&&(x.cameraAutoUpdate===!0&&x.updateCamera(t),t=x.getCamera());const y=this._canvasTarget;let b=y._viewport,v=y._scissor,S=y._pixelRatio;f!==null&&(b=f.viewport,v=f.scissor,S=1),this.getDrawingBufferSize(ea),Td.set(0,0,ea.width,ea.height);const M=b.minDepth===void 0?0:b.minDepth,A=b.maxDepth===void 0?1:b.maxDepth;m.viewportValue.copy(b).multiplyScalar(S).floor(),m.viewportValue.width>>=p,m.viewportValue.height>>=p,m.viewportValue.minDepth=M,m.viewportValue.maxDepth=A,m.viewport=m.viewportValue.equals(Td)===!1,m.scissorValue.copy(v).multiplyScalar(S).floor(),m.scissor=y._scissorTest&&m.scissorValue.equals(Td)===!1,m.scissorValue.width>>=p,m.scissorValue.height>>=p,m.clippingContext||(m.clippingContext=new vu),m.clippingContext.updateGlobal(u,t),u.onBeforeRender(this,e,t,f);const C=t.isArrayCamera?vd:Sd;t.isArrayCamera||(tc.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),C.setFromProjectionMatrix(tc,t.coordinateSystem,t.reversedDepth));const P=this._renderLists.get(e,t);if(P.begin(),this._projectObject(e,t,0,P,m.clippingContext),P.finish(),this.sortObjects===!0&&P.sort(this._opaqueSort,this._transparentSort),f!==null){this._textures.updateRenderTarget(f,p);const te=this._textures.get(f);m.textures=te.textures,m.depthTexture=te.depthTexture,m.width=te.width,m.height=te.height,m.renderTarget=f,m.depth=f.depthBuffer,m.stencil=f.stencilBuffer}else m.textures=null,m.depthTexture=null,m.width=ea.width,m.height=ea.height,m.depth=this.depth,m.stencil=this.stencil;m.width>>=p,m.height>>=p,m.activeCubeFace=d,m.activeMipmapLevel=p,m.occlusionQueryCount=P.occlusionQueryCount,m.scissorValue.max(ki.set(0,0,0,0)),m.scissorValue.x+m.scissorValue.width>m.width&&(m.scissorValue.width=Math.max(m.width-m.scissorValue.x,0)),m.scissorValue.y+m.scissorValue.height>m.height&&(m.scissorValue.height=Math.max(m.height-m.scissorValue.y,0)),this._background.update(u,P,m),m.camera=t,this.backend.beginRender(m);const{bundles:B,lightsNode:V,transparentDoublePass:Y,transparent:J,opaque:K}=P;return B.length>0&&this._renderBundles(B,u,V),this.opaque===!0&&K.length>0&&this._renderObjects(K,t,u,V),this.transparent===!0&&J.length>0&&this._renderTransparents(J,Y,t,u,V),this.backend.finishRender(m),n.renderId=a,this._currentRenderContext=o,this._currentRenderObjectFunction=l,this._handleObjectFunction=c,this._callDepth--,i!==null&&(this.setRenderTarget(h,d,p),this._renderOutput(f)),u.onAfterRender(this,e,t,f),this.inspector.finishRender(this.backend.getTimestampUID(m)),m}_setXRLayerSize(e,t){this._canvasTarget._width=e,this._canvasTarget._height=t,this.setViewport(0,0,e,t)}_renderOutput(e){const t=this._quad;this._nodes.hasOutputChange(e.texture)&&(t.material.fragmentNode=this._nodes.getOutputNode(e.texture),t.material.needsUpdate=!0);const s=this.autoClear,i=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderScene(t,t.camera,!1),this.autoClear=s,this.xr.enabled=i}getMaxAnisotropy(){return this.backend.getMaxAnisotropy()}getActiveCubeFace(){return this._activeCubeFace}getActiveMipmapLevel(){return this._activeMipmapLevel}async setAnimationLoop(e){this._initialized===!1&&await this.init(),this._animation.setAnimationLoop(e)}getAnimationLoop(){return this._animation.getAnimationLoop()}async getArrayBufferAsync(e){return await this.backend.getArrayBufferAsync(e)}getContext(){return this.backend.getContext()}getPixelRatio(){return this._canvasTarget.getPixelRatio()}getDrawingBufferSize(e){return this._canvasTarget.getDrawingBufferSize(e)}getSize(e){return this._canvasTarget.getSize(e)}setPixelRatio(e=1){this._canvasTarget.setPixelRatio(e)}setDrawingBufferSize(e,t,s){this.xr&&this.xr.isPresenting||this._canvasTarget.setDrawingBufferSize(e,t,s)}setSize(e,t,s=!0){this.xr&&this.xr.isPresenting||this._canvasTarget.setSize(e,t,s)}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}getScissor(e){return this._canvasTarget.getScissor(e)}setScissor(e,t,s,i){this._canvasTarget.setScissor(e,t,s,i)}getScissorTest(){return this._canvasTarget.getScissorTest()}setScissorTest(e){this._canvasTarget.setScissorTest(e),this.backend.setScissorTest(e)}getViewport(e){return this._canvasTarget.getViewport(e)}setViewport(e,t,s,i,n=0,a=1){this._canvasTarget.setViewport(e,t,s,i,n,a)}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 this.reversedDepthBuffer===!0?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,s=!0){if(this._initialized===!1)throw new Error('Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before before using this method.');const i=this._renderTarget||this._getFrameBufferTarget();let n=null;if(i!==null){this._textures.updateRenderTarget(i);const a=this._textures.get(i);n=this._renderContexts.get(i),n.textures=a.textures,n.depthTexture=a.depthTexture,n.width=a.width,n.height=a.height,n.renderTarget=i,n.depth=i.depthBuffer,n.stencil=i.stencilBuffer;const o=this.backend.getClearColor();n.clearColorValue.r=o.r,n.clearColorValue.g=o.g,n.clearColorValue.b=o.b,n.clearColorValue.a=o.a,n.clearDepthValue=this.getClearDepth(),n.clearStencilValue=this.getClearStencil(),n.activeCubeFace=this.getActiveCubeFace(),n.activeMipmapLevel=this.getActiveMipmapLevel()}this.backend.clear(e,t,s,n),i!==null&&this._renderTarget===null&&this._renderOutput(i)}clearColor(){this.clear(!0,!1,!1)}clearDepth(){this.clear(!1,!0,!1)}clearStencil(){this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,s=!0){Le('Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.clear(e,t,s)}async clearColorAsync(){Le('Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.'),this.clear(!0,!1,!1)}async clearDepthAsync(){Le('Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!0,!1)}async clearStencilAsync(){Le('Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!1,!0)}get needsFrameBufferTarget(){const e=this.currentToneMapping!==dr,t=this.currentColorSpace!==Ae.workingColorSpace;return e||t}get samples(){return this._samples}get currentSamples(){let e=this._samples;return this._renderTarget!==null?e=this._renderTarget.samples:this.needsFrameBufferTarget&&(e=0),e}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:dr}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:Ae.workingColorSpace}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||this._renderTarget===null}dispose(){this._initialized===!0&&(this.info.dispose(),this.backend.dispose(),this._animation.dispose(),this._objects.dispose(),this._geometries.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose(),this._frameBufferTarget!==null&&this._frameBufferTarget.dispose(),Object.values(this.backend.timestampQueryPool).forEach(e=>{e!==null&&e.dispose()})),this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,s=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=s}getRenderTarget(){return this._renderTarget}setOutputRenderTarget(e){this._outputRenderTarget=e}getOutputRenderTarget(){return this._outputRenderTarget}setCanvasTarget(e){this._canvasTarget.removeEventListener("resize",this._onCanvasTargetResize),this._canvasTarget=e,this._canvasTarget.addEventListener("resize",this._onCanvasTargetResize)}getCanvasTarget(){return this._canvasTarget}_resetXRState(){this.backend.setXRTarget(null),this.setOutputRenderTarget(null),this.setRenderTarget(null),this._frameBufferTarget.dispose(),this._frameBufferTarget=null}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e,t=null){if(this._isDeviceLost===!0)return;if(this._initialized===!1)return W("Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e,t);const s=this._nodes.nodeFrame,i=s.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,s.renderId=this.info.calls,this.backend.updateTimeStampUID(e),this.inspector.beginCompute(this.backend.getTimestampUID(e),e);const n=this.backend,a=this._pipelines,o=this._bindings,l=this._nodes,c=Array.isArray(e)?e:[e];if(c[0]===void 0||c[0].isComputeNode!==!0)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");n.beginCompute(e);for(const u of c){if(a.has(u)===!1){const p=()=>{u.removeEventListener("dispose",p),a.delete(u),o.deleteForCompute(u),l.delete(u)};u.addEventListener("dispose",p);const f=u.onInitFunction;f!==null&&f.call(u,{renderer:this})}l.updateForCompute(u),o.updateForCompute(u);const h=o.getForCompute(u),d=a.getForCompute(u,h);n.compute(e,u,h,d,t)}n.finishCompute(e),s.renderId=i,this.inspector.finishCompute(this.backend.getTimestampUID(e))}async computeAsync(e,t=null){this._initialized===!1&&await this.init(),this.compute(e,t)}async hasFeatureAsync(e){return Le('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 this._initialized===!1&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){if(this._initialized===!1)throw new Error('Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before before using this method.');return this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){Le('Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.initTexture(e)}initTexture(e){if(this._initialized===!1)throw new Error('Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before before using this method.');this._textures.updateTexture(e)}initRenderTarget(e){if(this._initialized===!1)throw new Error('Renderer: .initRenderTarget() called before the backend is initialized. Use "await renderer.init();" before before using this method.');this._textures.updateRenderTarget(e);const t=this._textures.get(e),s=this._renderContexts.get(e);s.textures=t.textures,s.depthTexture=t.depthTexture,s.width=t.width,s.height=t.height,s.renderTarget=e,s.depth=e.depthBuffer,s.stencil=e.stencilBuffer,this.backend.initRenderTarget(s)}copyFramebufferToTexture(e,t=null){if(t!==null)if(t.isVector2)t=ki.set(t.x,t.y,e.image.width,e.image.height).floor();else if(t.isVector4)t=ki.copy(t).floor();else{$("Renderer.copyFramebufferToTexture: Invalid rectangle.");return}else t=ki.set(0,0,e.image.width,e.image.height);let s=this._currentRenderContext,i;s!==null?i=s.renderTarget:(i=this._renderTarget||this._getFrameBufferTarget(),i!==null&&(this._textures.updateRenderTarget(i),s=this._textures.get(i))),this._textures.updateTexture(e,{renderTarget:i}),this.backend.copyFramebufferToTexture(e,s,t),this._inspector.copyFramebufferToTexture(e)}copyTextureToTexture(e,t,s=null,i=null,n=0,a=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,s,i,n,a),this._inspector.copyTextureToTexture(e,t)}async readRenderTargetPixelsAsync(e,t,s,i,n,a=0,o=0){return this.backend.copyTextureToBuffer(e.textures[a],t,s,i,n,o)}_projectObject(e,t,s,i,n){if(e.visible===!1)return;if(e.layers.test(t.layers)){if(e.isGroup)s=e.renderOrder,e.isClippingGroup&&e.enabled&&(n=n.getGroupContext(e));else if(e.isLOD)e.autoUpdate===!0&&e.update(t);else if(e.isLight)i.pushLight(e);else if(e.isSprite){const l=t.isArrayCamera?vd:Sd;if(!e.frustumCulled||l.intersectsSprite(e,t)){this.sortObjects===!0&&ki.setFromMatrixPosition(e.matrixWorld).applyMatrix4(tc);const{geometry:c,material:u}=e;u.visible&&i.push(e,c,u,s,ki.z,null,n)}}else if(e.isLineLoop)$("Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.");else if(e.isMesh||e.isLine||e.isPoints){const l=t.isArrayCamera?vd:Sd;if(!e.frustumCulled||l.intersectsObject(e,t)){const{geometry:c,material:u}=e;if(this.sortObjects===!0&&(c.boundingSphere===null&&c.computeBoundingSphere(),ki.copy(c.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(tc)),Array.isArray(u)){const h=c.groups;for(let d=0,p=h.length;d<p;d++){const f=h[d],m=u[f.materialIndex];m&&m.visible&&i.push(e,c,m,s,ki.z,f,n)}}else u.visible&&i.push(e,c,u,s,ki.z,null,n)}}}if(e.isBundleGroup===!0&&this.backend.beginBundle!==void 0){const l=i;i=this._renderLists.get(e,t),i.begin(),l.pushBundle({bundleGroup:e,camera:t,renderList:i}),i.finish()}const o=e.children;for(let l=0,c=o.length;l<c;l++)this._projectObject(o[l],t,s,i,n)}_renderBundles(e,t,s){for(const i of e)this._renderBundle(i,t,s)}_renderTransparents(e,t,s,i,n){if(t.length>0){for(const{material:a}of t)a.side=Rt;this._renderObjects(t,s,i,n,"backSide");for(const{material:a}of t)a.side=Si;this._renderObjects(e,s,i,n);for(const{material:a}of t)a.side=qi}else this._renderObjects(e,s,i,n)}_renderObjects(e,t,s,i,n=null){for(let a=0,o=e.length;a<o;a++){const{object:l,geometry:c,material:u,group:h,clippingContext:d}=e[a];this._currentRenderObjectFunction(l,s,t,c,u,h,i,d,n)}}_getShadowNodes(e){const t=e.version;let s=this._cacheShadowNodes.get(e);if(s===void 0||s.version!==t){const i=e.map!==null,n=e.colorNode&&e.colorNode.isNode,a=e.castShadowNode&&e.castShadowNode.isNode,o=e.maskShadowNode&&e.maskShadowNode.isNode||e.maskNode&&e.maskNode.isNode;let l=null,c=null,u=null;if(i||n||a||o){let h,d;if(a?(h=e.castShadowNode.rgb,d=e.castShadowNode.a,this.shadowMap.transmitted!==!0&&Le("Renderer: `shadowMap.transmitted` needs to be set to `true` when using `material.castShadowNode`.")):(h=E(0),d=T(1)),i&&(d=d.mul(Ye("map","texture",e).a)),n&&(d=d.mul(e.colorNode.a)),c=ie(h,d),o){const p=e.maskShadowNode||e.maskNode;c=R(([f])=>(p.not().discard(),f))(c)}}e.depthNode&&e.depthNode.isNode&&(u=e.depthNode),e.castShadowPositionNode&&e.castShadowPositionNode.isNode?l=e.castShadowPositionNode:e.positionNode&&e.positionNode.isNode&&(l=e.positionNode),s={version:t,colorNode:c,depthNode:u,positionNode:l},this._cacheShadowNodes.set(e,s)}return s}renderObject(e,t,s,i,n,a,o,l=null,c=null){let u=!1,h,d,p,f;if(e.onBeforeRender(this,t,s,i,n,a),n.allowOverride===!0&&t.overrideMaterial!==null){const m=t.overrideMaterial;if(u=!0,h=m.isNodeMaterial?m.colorNode:null,d=m.isNodeMaterial?m.depthNode:null,p=m.isNodeMaterial?m.positionNode:null,f=t.overrideMaterial.side,n.positionNode&&n.positionNode.isNode&&(m.positionNode=n.positionNode),m.alphaTest=n.alphaTest,m.alphaMap=n.alphaMap,m.transparent=n.transparent||n.transmission>0||n.transmissionNode&&n.transmissionNode.isNode||n.backdropNode&&n.backdropNode.isNode,m.isShadowPassMaterial){const{colorNode:x,depthNode:y,positionNode:b}=this._getShadowNodes(n);this.shadowMap.type===vo?m.side=n.shadowSide!==null?n.shadowSide:n.side:m.side=n.shadowSide!==null?n.shadowSide:eL[n.side],x!==null&&(m.colorNode=x),y!==null&&(m.depthNode=y),b!==null&&(m.positionNode=b)}n=m}n.transparent===!0&&n.side===qi&&n.forceSinglePass===!1?(n.side=Rt,this._handleObjectFunction(e,n,t,s,o,a,l,"backSide"),n.side=Si,this._handleObjectFunction(e,n,t,s,o,a,l,c),n.side=qi):this._handleObjectFunction(e,n,t,s,o,a,l,c),u&&(t.overrideMaterial.colorNode=h,t.overrideMaterial.depthNode=d,t.overrideMaterial.positionNode=p,t.overrideMaterial.side=f),e.onAfterRender(this,t,s,i,n,a)}hasCompatibility(e){return this.backend.hasCompatibility(e)}_renderObjectDirect(e,t,s,i,n,a,o,l){const c=this._objects.get(e,t,s,i,n,this._currentRenderContext,o,l);c.drawRange=e.geometry.drawRange,c.group=a,this._currentRenderBundle!==null&&(this.backend.get(this._currentRenderBundle).renderObjects.push(c),c.bundle=this._currentRenderBundle.bundleGroup);const u=this._nodes.needsRefresh(c);u&&(this._nodes.updateBefore(c),this._geometries.updateForRender(c),this._nodes.updateForRender(c),this._bindings.updateForRender(c)),this._pipelines.updateForRender(c),this.backend.draw(c,this.info),u&&this._nodes.updateAfter(c)}_createObjectPipeline(e,t,s,i,n,a,o,l){const c=this._objects.get(e,t,s,i,n,this._currentRenderContext,o,l);c.drawRange=e.geometry.drawRange,c.group=a,this._nodes.updateBefore(c),this._geometries.updateForRender(c),this._nodes.updateForRender(c),this._bindings.updateForRender(c),this._pipelines.getForRender(c,this._compilationPromises),this._nodes.updateAfter(c)}_onCanvasTargetResize(){this._initialized&&this.backend.updateSize()}get compile(){return this.compileAsync}}class RS{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}getVisibility(){return this.visibility}clone(){return Object.assign(new this.constructor,this)}}function sL(r){return r+(En-r%En)%En}class PS extends RS{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 sL(this._buffer.byteLength)}get buffer(){return this._buffer}update(){return!0}}class FS extends PS{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let iL=0;class BS extends FS{constructor(e,t){super("UniformBuffer_"+iL++,e?e.value:null),this.nodeUniform=e,this.groupNode=t,this.isNodeUniformBuffer=!0}set updateRanges(e){this.nodeUniform.updateRanges=e}get updateRanges(){return this.nodeUniform.updateRanges}addUpdateRange(e,t){this.nodeUniform.addUpdateRange(e,t)}clearUpdateRanges(){this.nodeUniform.clearUpdateRanges()}get buffer(){return this.nodeUniform.value}}class nL extends FS{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[],this._updateRangeCache=new Map}addUniformUpdateRange(e){const t=e.index;if(this._updateRangeCache.has(t)!==!0){const s=this.updateRanges,i=e.offset,n=e.itemSize,a={start:i,count:n};s.push(a),this._updateRangeCache.set(t,a)}}clearUpdateRanges(){this._updateRangeCache.clear(),super.clearUpdateRanges()}addUniform(e){return this.uniforms.push(e),this}removeUniform(e){const t=this.uniforms.indexOf(e);return t!==-1&&this.uniforms.splice(t,1),this}get values(){return this._values===null&&(this._values=Array.from(this.buffer)),this._values}get buffer(){let e=this._buffer;if(e===null){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 s=0,i=this.uniforms.length;s<i;s++){const n=this.uniforms[s],a=n.boundary,o=n.itemSize*e,l=t%En,c=l%a,u=l+c;t+=c,u!==0&&En-u<o&&(t+=En-u),n.offset=t/e,n.index=s,t+=o}return Math.ceil(t/En)*En}update(){let e=!1;for(const t of this.uniforms)this.updateByType(t)===!0&&(e=!0);return e}updateByType(e){if(e.isNumberUniform)return this.updateNumber(e);if(e.isVector2Uniform)return this.updateVector2(e);if(e.isVector3Uniform)return this.updateVector3(e);if(e.isVector4Uniform)return this.updateVector4(e);if(e.isColorUniform)return this.updateColor(e);if(e.isMatrix3Uniform)return this.updateMatrix3(e);if(e.isMatrix4Uniform)return this.updateMatrix4(e);$("WebGPUUniformsGroup: Unsupported uniform type.",e)}updateNumber(e){let t=!1;const s=this.values,i=e.getValue(),n=e.offset,a=e.getType();if(s[n]!==i){const o=this._getBufferForType(a);o[n]=s[n]=i,t=!0,this.addUniformUpdateRange(e)}return t}updateVector2(e){let t=!1;const s=this.values,i=e.getValue(),n=e.offset,a=e.getType();if(s[n+0]!==i.x||s[n+1]!==i.y){const o=this._getBufferForType(a);o[n+0]=s[n+0]=i.x,o[n+1]=s[n+1]=i.y,t=!0,this.addUniformUpdateRange(e)}return t}updateVector3(e){let t=!1;const s=this.values,i=e.getValue(),n=e.offset,a=e.getType();if(s[n+0]!==i.x||s[n+1]!==i.y||s[n+2]!==i.z){const o=this._getBufferForType(a);o[n+0]=s[n+0]=i.x,o[n+1]=s[n+1]=i.y,o[n+2]=s[n+2]=i.z,t=!0,this.addUniformUpdateRange(e)}return t}updateVector4(e){let t=!1;const s=this.values,i=e.getValue(),n=e.offset,a=e.getType();if(s[n+0]!==i.x||s[n+1]!==i.y||s[n+2]!==i.z||s[n+4]!==i.w){const o=this._getBufferForType(a);o[n+0]=s[n+0]=i.x,o[n+1]=s[n+1]=i.y,o[n+2]=s[n+2]=i.z,o[n+3]=s[n+3]=i.w,t=!0,this.addUniformUpdateRange(e)}return t}updateColor(e){let t=!1;const s=this.values,i=e.getValue(),n=e.offset;if(s[n+0]!==i.r||s[n+1]!==i.g||s[n+2]!==i.b){const a=this.buffer;a[n+0]=s[n+0]=i.r,a[n+1]=s[n+1]=i.g,a[n+2]=s[n+2]=i.b,t=!0,this.addUniformUpdateRange(e)}return t}updateMatrix3(e){let t=!1;const s=this.values,i=e.getValue().elements,n=e.offset;if(s[n+0]!==i[0]||s[n+1]!==i[1]||s[n+2]!==i[2]||s[n+4]!==i[3]||s[n+5]!==i[4]||s[n+6]!==i[5]||s[n+8]!==i[6]||s[n+9]!==i[7]||s[n+10]!==i[8]){const a=this.buffer;a[n+0]=s[n+0]=i[0],a[n+1]=s[n+1]=i[1],a[n+2]=s[n+2]=i[2],a[n+4]=s[n+4]=i[3],a[n+5]=s[n+5]=i[4],a[n+6]=s[n+6]=i[5],a[n+8]=s[n+8]=i[6],a[n+9]=s[n+9]=i[7],a[n+10]=s[n+10]=i[8],t=!0,this.addUniformUpdateRange(e)}return t}updateMatrix4(e){let t=!1;const s=this.values,i=e.getValue().elements,n=e.offset;return aL(s,i,n)===!1&&(this.buffer.set(i,n),rL(s,i,n),t=!0,this.addUniformUpdateRange(e)),t}_getBufferForType(e){return e==="int"||e==="ivec2"||e==="ivec3"||e==="ivec4"?new Int32Array(this.buffer.buffer):e==="uint"||e==="uvec2"||e==="uvec3"||e==="uvec4"?new Uint32Array(this.buffer.buffer):this.buffer}}function rL(r,e,t){for(let s=0,i=e.length;s<i;s++)r[t+s]=e[s]}function aL(r,e,t){for(let s=0,i=e.length;s<i;s++)if(r[t+s]!==e[s])return!1;return!0}let oL=0;class DS extends nL{constructor(e,t){super(e),this.id=oL++,this.groupNode=t,this.isNodeUniformsGroup=!0}}class OS extends RS{constructor(e,t){super(e),this._texture=null,this._onTextureDispose=()=>{this.generation=null,this.version=-1},this.texture=t,this.version=t?t.version:-1,this.generation=null,this.samplerKey="",this.isSampler=!0}set texture(e){this._texture!==e&&(this._texture&&this._texture.removeEventListener("dispose",this._onTextureDispose),this._texture=e,this.generation=null,this.version=-1,this._texture&&this._texture.addEventListener("dispose",this._onTextureDispose))}get texture(){return this._texture}update(){const{texture:e,version:t}=this;return t!==e.version?(this.version=e.version,!0):!1}clone(){const e=super.clone();return e._texture=null,e._onTextureDispose=()=>{e.generation=null,e.version=-1},e.texture=this.texture,e}}let lL=0;class cL extends OS{constructor(e,t){super(e,t),this.id=lL++,this.store=!1,this.mipLevel=0,this.isSampledTexture=!0}}class gh extends cL{constructor(e,t,s,i=null){super(e,t?t.value:null),this.textureNode=t,this.groupNode=s,this.access=i}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class LS extends gh{constructor(e,t,s,i=null){super(e,t,s,i),this.isSampledCubeTexture=!0}}class Np extends gh{constructor(e,t,s,i=null){super(e,t,s,i),this.isSampledTexture3D=!0}}const my={bitcast_int_uint:new _t("uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }"),bitcast_uint_int:new _t("uint tsl_bitcast_uint_to_int ( uint x ) { return floatBitsToInt( uintBitsToFloat ( x ) ); }")},uL={textureDimensions:"textureSize",equals:"equal",bitcast_float_int:"floatBitsToInt",bitcast_int_float:"intBitsToFloat",bitcast_uint_float:"uintBitsToFloat",bitcast_float_uint:"floatBitsToUint",bitcast_uint_int:"tsl_bitcast_uint_to_int",bitcast_int_uint:"tsl_bitcast_int_to_uint",floatpack_snorm_2x16:"packSnorm2x16",floatpack_unorm_2x16:"packUnorm2x16",floatpack_float16_2x16:"packHalf2x16",floatunpack_snorm_2x16:"unpackSnorm2x16",floatunpack_unorm_2x16:"unpackUnorm2x16",floatunpack_float16_2x16:"unpackHalf2x16"},gy={low:"lowp",medium:"mediump",high:"highp"},yy={swizzleAssign:!0,storageBuffer:!1},xy={perspective:"smooth",linear:"noperspective"},_y={centroid:"centroid"},by=`
65
- precision highp float;
66
- precision highp int;
67
- precision highp sampler2D;
68
- precision highp sampler3D;
69
- precision highp samplerCube;
70
- precision highp sampler2DArray;
71
-
72
- precision highp usampler2D;
73
- precision highp usampler3D;
74
- precision highp usamplerCube;
75
- precision highp usampler2DArray;
76
-
77
- precision highp isampler2D;
78
- precision highp isampler3D;
79
- precision highp isamplerCube;
80
- precision highp isampler2DArray;
81
-
82
- precision highp sampler2DShadow;
83
- precision highp sampler2DArrayShadow;
84
- precision highp samplerCubeShadow;
85
- `;class hL extends AS{constructor(e,t){super(e,t,new VO),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return e.isVideoTexture===!0&&e.colorSpace!==In}_include(e){const t=my[e];return t.build(this),this.addInclude(t),t}getMethod(e){return my[e]!==void 0&&this._include(e),uL[e]||e}getBitcastMethod(e,t){return this.getMethod(`bitcast_${t}_${e}`)}getFloatPackingMethod(e){return this.getMethod(`floatpack_${e}_2x16`)}getFloatUnpackingMethod(e){return this.getMethod(`floatunpack_${e}_2x16`)}getTernary(e,t,s){return`${e} ? ${t} : ${s}`}getOutputStructName(){return""}buildFunctionCode(e){const t=e.layout,s=this.flowShaderNode(e),i=[];for(const a of t.inputs)i.push(this.getType(a.type)+" "+a.name);return`${this.getType(t.type)} ${t.name}( ${i.join(", ")} ) {
86
-
87
- ${s.vars}
88
-
89
- ${s.code}
90
- return ${s.result};
91
-
92
- }`}setupPBO(e){const t=e.value;if(t.pbo===void 0){const s=t.array,i=t.count*t.itemSize,{itemSize:n}=t,a=t.array.constructor.name.toLowerCase().includes("int");let o=a?Pu:Ru;n===2?o=a?Fu:_i:n===3?o=a?JM:Nu:n===4&&(o=a?Bu:ms);const l={Float32Array:es,Uint8Array:Ut,Uint16Array:pr,Uint32Array:rt,Int8Array:ga,Int16Array:ya,Int32Array:Lt,Uint8ClampedArray:Ut},c=Math.pow(2,Math.ceil(Math.log2(Math.sqrt(i/n))));let u=Math.ceil(i/n/c);c*u*n<i&&u++;const h=c*u*n,d=new s.constructor(h);d.set(s,0),t.array=d;const p=new Kx(t.array,c,u,o,l[t.array.constructor.name]||es);p.needsUpdate=!0,p.isPBOTexture=!0;const f=new Pi(p,null,null);f.setPrecision("high"),t.pboNode=f,t.pbo=f.value,this.getUniformFromNode(t.pboNode,"texture",this.shaderStage,this.context.nodeName)}}getPropertyName(e,t=this.shaderStage){return e.isNodeUniform&&e.node.isTextureNode!==!0&&e.node.isBufferNode!==!0?e.name:super.getPropertyName(e,t)}generatePBO(e){const{node:t,indexNode:s}=e,i=t.value;if(this.renderer.backend.has(i)){const u=this.renderer.backend.get(i);u.pbo=i.pbo}const n=this.getUniformFromNode(i.pboNode,"texture",this.shaderStage,this.context.nodeName),a=this.getPropertyName(n);this.increaseUsage(s);const o=s.build(this,"uint"),l=this.getDataFromNode(e);let c=l.propertyName;if(c===void 0){const u=this.getVarFromNode(e);c=this.getPropertyName(u);const h=this.getDataFromNode(t);let d=h.propertySizeName;d===void 0&&(d=c+"Size",this.getVarFromNode(t,d,"uint"),this.addLineFlowCode(`${d} = uint( textureSize( ${a}, 0 ).x )`,e),h.propertySizeName=d);const{itemSize:p}=i,f="."+wr.join("").slice(0,p),m=`ivec2(${o} % ${d}, ${o} / ${d})`,x=this.generateTextureLoad(null,a,m,"0",null,null);let y="vec4";i.pbo.type===rt?y="uvec4":i.pbo.type===Lt&&(y="ivec4"),this.addLineFlowCode(`${c} = ${y}(${x})${f}`,e),l.propertyName=c}return c}generateTextureLoad(e,t,s,i,n,a){i===null&&(i="0");let o;return n?a?o=`texelFetchOffset( ${t}, ivec3( ${s}, ${n} ), ${i}, ${a} )`:o=`texelFetch( ${t}, ivec3( ${s}, ${n} ), ${i} )`:a?o=`texelFetchOffset( ${t}, ${s}, ${i}, ${a} )`:o=`texelFetch( ${t}, ${s}, ${i} )`,e!==null&&e.isDepthTexture&&(o+=".x"),o}generateTexture(e,t,s,i,n){return i&&(s=`vec3( ${s}, ${i} )`),e.isDepthTexture?n?`textureOffset( ${t}, ${s}, ${n} ).x`:`texture( ${t}, ${s} ).x`:n?`textureOffset( ${t}, ${s}, ${n} )`:`texture( ${t}, ${s} )`}generateTextureLevel(e,t,s,i,n,a){return n&&(s=`vec3( ${s}, ${n} )`),a?`textureLodOffset( ${t}, ${s}, ${i}, ${a} )`:`textureLod( ${t}, ${s}, ${i} )`}generateTextureBias(e,t,s,i,n,a){return n&&(s=`vec3( ${s}, ${n} )`),a?`textureOffset( ${t}, ${s}, ${a}, ${i} )`:`texture( ${t}, ${s}, ${i} )`}generateTextureGrad(e,t,s,i,n,a){return n&&(s=`vec3( ${s}, ${n} )`),a?`textureGradOffset( ${t}, ${s}, ${i[0]}, ${i[1]}, ${a} )`:`textureGrad( ${t}, ${s}, ${i[0]}, ${i[1]} )`}generateTextureCompare(e,t,s,i,n,a,o=this.shaderStage){if(o==="fragment")return e.isCubeTexture?`texture( ${t}, vec4( ${s}, ${i} ) )`:n?a?`textureOffset( ${t}, vec4( ${s}, ${n}, ${i} ), ${a} )`:`texture( ${t}, vec4( ${s}, ${n}, ${i} ) )`:a?`textureOffset( ${t}, vec3( ${s}, ${i} ), ${a} )`:`texture( ${t}, vec3( ${s}, ${i} ) )`;$(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${o} shader.`)}getVars(e){const t=[],s=this.vars[e];if(s!==void 0)for(const i of s)t.push(`${this.getVar(i.type,i.name,i.count)};`);return t.join(`
93
- `)}getUniforms(e){const t=this.uniforms[e],s=[],i={};for(const a of t){let o=null,l=!1;if(a.type==="texture"||a.type==="texture3D"){const c=a.node.value;let u="";(c.isDataTexture===!0||c.isData3DTexture===!0)&&(c.type===rt?u="u":c.type===Lt&&(u="i")),a.type==="texture3D"&&c.isArrayTexture===!1?o=`${u}sampler3D ${a.name};`:c.compareFunction?c.isArrayTexture===!0?o=`sampler2DArrayShadow ${a.name};`:o=`sampler2DShadow ${a.name};`:c.isArrayTexture===!0||c.isDataArrayTexture===!0||c.isCompressedArrayTexture===!0?o=`${u}sampler2DArray ${a.name};`:o=`${u}sampler2D ${a.name};`}else if(a.type==="cubeTexture")o=`samplerCube ${a.name};`;else if(a.type==="cubeDepthTexture")a.node.value.compareFunction?o=`samplerCubeShadow ${a.name};`:o=`samplerCube ${a.name};`;else if(a.type==="buffer"){const c=a.node,u=this.getType(c.bufferType),h=c.bufferCount,d=h>0?h:"";o=`${c.name} {
94
- ${u} ${a.name}[${d}];
95
- };
96
- `}else{const c=a.groupNode.name;if(i[c]===void 0){const u=this.uniformGroups[c];if(u!==void 0){const h=[];for(const d of u.uniforms){const p=d.getType(),f=this.getVectorType(p),m=d.nodeUniform.node.precision;let x=`${f} ${d.name};`;m!==null&&(x=gy[m]+" "+x),h.push(" "+x)}i[c]=h}}l=!0}if(!l){const c=a.node.precision;c!==null&&(o=gy[c]+" "+o),o="uniform "+o,s.push(o)}}let n="";for(const a in i){const o=i[a];n+=this._getGLSLUniformStruct(a,o.join(`
97
- `))+`
98
- `}return n+=s.join(`
99
- `),n}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==Lt){let s=e;e.isInterleavedBufferAttribute&&(s=e.data);const i=s.array;i instanceof Uint32Array||i instanceof Int32Array||(t=t.slice(1))}return t}getAttributes(e){let t="";if(e==="vertex"||e==="compute"){const s=this.getAttributesArray();let i=0;for(const n of s)t+=`layout( location = ${i++} ) in ${n.type} ${n.name};
100
- `}return t}getStructMembers(e){const t=[];for(const s of e.members)t.push(` ${s.type} ${s.name};`);return t.join(`
101
- `)}getStructs(e){const t=[],s=this.structs[e],i=[];for(const n of s)if(n.output)for(const a of n.members)i.push(`layout( location = ${a.index} ) out ${a.type} ${a.name};`);else{let a="struct "+n.name+` {
102
- `;a+=this.getStructMembers(n),a+=`
103
- };
104
- `,t.push(a)}return i.length===0&&i.push("layout( location = 0 ) out vec4 fragColor;"),`
105
- `+i.join(`
106
- `)+`
107
-
108
- `+t.join(`
109
- `)}getVaryings(e){let t="";const s=this.varyings;if(e==="vertex"||e==="compute")for(const i of s){e==="compute"&&(i.needsInterpolation=!0);const n=this.getType(i.type);if(i.needsInterpolation)if(i.interpolationType){const a=xy[i.interpolationType]||i.interpolationType,o=_y[i.interpolationSampling]||"";t+=`${a} ${o} out ${n} ${i.name};
110
- `}else{const a=n.includes("int")||n.includes("uv")||n.includes("iv")?"flat ":"";t+=`${a}out ${n} ${i.name};
111
- `}else t+=`${n} ${i.name};
112
- `}else if(e==="fragment"){for(const i of s)if(i.needsInterpolation){const n=this.getType(i.type);if(i.interpolationType){const a=xy[i.interpolationType]||i.interpolationType,o=_y[i.interpolationSampling]||"";t+=`${a} ${o} in ${n} ${i.name};
113
- `}else{const a=n.includes("int")||n.includes("uv")||n.includes("iv")?"flat ":"";t+=`${a}in ${n} ${i.name};
114
- `}}}for(const i of this.builtins[e])t+=`${i};
115
- `;return t}getVertexIndex(){return"uint( gl_VertexID )"}getInstanceIndex(){return"uint( gl_InstanceID )"}getInvocationLocalIndex(){return`uint( gl_InstanceID ) % ${this.object.workgroupSize.reduce((s,i)=>s*i,1)}u`}getSubgroupSize(){$("GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node")}getInvocationSubgroupIndex(){$("GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node")}getSubgroupIndex(){$("GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node")}getDrawIndex(){return this.renderer.backend.extensions.has("WEBGL_multi_draw")?"uint( gl_DrawID )":null}getFrontFacing(){return"gl_FrontFacing"}getFragCoord(){return"gl_FragCoord.xy"}getFragDepth(){return"gl_FragDepth"}enableExtension(e,t,s=this.shaderStage){const i=this.extensions[s]||(this.extensions[s]=new Map);i.has(e)===!1&&i.set(e,{name:e,behavior:t})}getExtensions(e){const t=[];if(e==="vertex"){const i=this.renderer.backend.extensions;this.object.isBatchedMesh&&i.has("WEBGL_multi_draw")&&this.enableExtension("GL_ANGLE_multi_draw","require",e)}const s=this.extensions[e];if(s!==void 0)for(const{name:i,behavior:n}of s.values())t.push(`#extension ${i} : ${n}`);return t.join(`
116
- `)}getClipDistance(){return"gl_ClipDistance"}isAvailable(e){let t=yy[e];if(t===void 0){let s;switch(t=!1,e){case"float32Filterable":s="OES_texture_float_linear";break;case"clipDistance":s="WEBGL_clip_cull_distance";break}if(s!==void 0){const i=this.renderer.backend.extensions;i.has(s)&&(i.get(s),t=!0)}yy[e]=t}return t}isFlipY(){return!0}getUniformBufferLimit(){const e=this.renderer.backend.gl;return e.getParameter(e.MAX_UNIFORM_BLOCK_SIZE)}enableHardwareClipping(e){this.enableExtension("GL_ANGLE_clip_cull_distance","require"),this.builtins.vertex.push(`out float gl_ClipDistance[ ${e} ]`)}enableMultiview(){this.enableExtension("GL_OVR_multiview2","require","fragment"),this.enableExtension("GL_OVR_multiview2","require","vertex"),this.builtins.vertex.push("layout(num_views = 2) in")}registerTransform(e,t){this.transforms.push({varyingName:e,attributeNode:t})}getTransforms(){const e=this.transforms;let t="";for(let s=0;s<e.length;s++){const i=e[s],n=this.getPropertyName(i.attributeNode);n&&(t+=`${i.varyingName} = ${n};
117
- `)}return t}_getGLSLUniformStruct(e,t){return`
118
- layout( std140 ) uniform ${e} {
119
- ${t}
120
- };`}_getGLSLVertexCode(e){return`#version 300 es
121
-
122
- ${this.getSignature()}
123
-
124
- // extensions
125
- ${e.extensions}
126
-
127
- // precision
128
- ${by}
129
-
130
- // uniforms
131
- ${e.uniforms}
132
-
133
- // varyings
134
- ${e.varyings}
135
-
136
- // attributes
137
- ${e.attributes}
138
-
139
- // codes
140
- ${e.codes}
141
-
142
- void main() {
143
-
144
- // vars
145
- ${e.vars}
146
-
147
- // transforms
148
- ${e.transforms}
149
-
150
- // flow
151
- ${e.flow}
152
-
153
- gl_PointSize = 1.0;
154
-
155
- }
156
- `}_getGLSLFragmentCode(e){return`#version 300 es
157
-
158
- ${this.getSignature()}
159
-
160
- // extensions
161
- ${e.extensions}
162
-
163
- // precision
164
- ${by}
165
-
166
- // structs
167
- ${e.structs}
168
-
169
- // uniforms
170
- ${e.uniforms}
171
-
172
- // varyings
173
- ${e.varyings}
174
-
175
- // codes
176
- ${e.codes}
177
-
178
- void main() {
179
-
180
- // vars
181
- ${e.vars}
182
-
183
- // flow
184
- ${e.flow}
185
-
186
- }
187
- `}buildCode(){const e=this.material!==null?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){let s=`// code
188
-
189
- `;s+=this.flowCode[t];const i=this.flowNodes[t],n=i[i.length-1];for(const o of i){const l=this.getFlowData(o),c=o.name;c&&(s.length>0&&(s+=`
190
- `),s+=` // flow -> ${c}
191
- `),s+=`${l.code}
192
- `,o===n&&t!=="compute"&&(s+=`// result
193
- `,t==="vertex"?(s+="gl_Position = ",s+=`${l.result};`):t==="fragment"&&(o.outputNode.isOutputStructNode||(s+="fragColor = ",s+=`${l.result};`)))}const a=e[t];a.extensions=this.getExtensions(t),a.uniforms=this.getUniforms(t),a.attributes=this.getAttributes(t),a.varyings=this.getVaryings(t),a.vars=this.getVars(t),a.structs=this.getStructs(t),a.codes=this.getCodes(t),a.transforms=this.getTransforms(t),a.flow=s}this.material!==null?(this.vertexShader=this._getGLSLVertexCode(e.vertex),this.fragmentShader=this._getGLSLFragmentCode(e.fragment)):this.computeShader=this._getGLSLVertexCode(e.compute)}getUniformFromNode(e,t,s,i=null){const n=super.getUniformFromNode(e,t,s,i),a=this.getDataFromNode(e,s,this.globalCache);let o=a.uniformGPU;if(o===void 0){const l=e.groupNode,c=l.name,u=this.getBindGroupArray(c,s);if(t==="texture")o=new gh(n.name,n.node,l),u.push(o);else if(t==="cubeTexture"||t==="cubeDepthTexture")o=new LS(n.name,n.node,l),u.push(o);else if(t==="texture3D")o=new Np(n.name,n.node,l),u.push(o);else if(t==="buffer"){n.name=`buffer${e.id}`;const h=this.getSharedDataFromNode(e);let d=h.buffer;d===void 0&&(e.name=`NodeBuffer_${e.id}`,d=new BS(e,l),d.name=e.name,h.buffer=d),u.push(d),o=d}else{let h=this.uniformGroups[c];h===void 0?(h=new DS(c,l),this.uniformGroups[c]=h,u.push(h)):u.indexOf(h)===-1&&u.push(h),o=this.getNodeUniform(n,t);const d=o.name;h.uniforms.some(f=>f.name===d)||h.addUniform(o)}a.uniformGPU=o}return n}}let Md=null,ta=null;class IS{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={[bi.RENDER]:null,[bi.COMPUTE]:null},this.trackTimestamp=e.trackTimestamp===!0}async init(e){this.renderer=e}get coordinateSystem(){}beginRender(){}finishRender(){}beginCompute(){}finishCompute(){}draw(){}compute(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}updateBinding(){}createRenderPipeline(){}createComputePipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}updateSampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}updateTimeStampUID(e){const t=this.get(e),s=this.renderer.info.frame;let i;e.isComputeNode===!0?i="c:"+this.renderer.info.compute.frameCalls:i="r:"+this.renderer.info.render.frameCalls,t.timestampUID=i+":"+e.id+":f"+s}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:")?bi.COMPUTE:bi.RENDER;return this.timestampQueryPool[t]}getTimestamp(e){return this._getQueryPool(e).getTimestamp(e)}hasTimestamp(e){return this._getQueryPool(e).hasTimestamp(e)}isOccluded(){}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp){Le("WebGPURenderer: Timestamp tracking is disabled.");return}const t=this.timestampQueryPool[e];if(!t)return;const s=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=s,s}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getMaxAnisotropy(){}getDrawingBufferSize(){return Md=Md||new xe,this.renderer.getDrawingBufferSize(Md)}setScissorTest(){}getClearColor(){const e=this.renderer;return ta=ta||new mm,e.getClearColor(ta),ta.getRGB(ta),ta}getDomElement(){let e=this.domElement;return e===null&&(e=this.parameters.canvas!==void 0?this.parameters.canvas:_w(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${Zo} 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 t===void 0&&(t={},this.data.set(e,t)),t}has(e){return this.data.has(e)}delete(e){this.data.delete(e)}deleteBindGroupData(){}dispose(){}}let dL=0;class pL{constructor(e,t){this.buffers=[e.bufferGPU,t],this.type=e.type,this.bufferType=e.bufferType,this.pbo=e.pbo,this.byteLength=e.byteLength,this.bytesPerElement=e.BYTES_PER_ELEMENT,this.version=e.version,this.isInteger=e.isInteger,this.activeBufferIndex=0,this.baseId=e.id}get id(){return`${this.baseId}|${this.activeBufferIndex}`}get bufferGPU(){return this.buffers[this.activeBufferIndex]}get transformBuffer(){return this.buffers[this.activeBufferIndex^1]}switchBuffers(){this.activeBufferIndex^=1}}class fL{constructor(e){this.backend=e}createAttribute(e,t){const s=this.backend,{gl:i}=s,n=e.array,a=e.usage||i.STATIC_DRAW,o=e.isInterleavedBufferAttribute?e.data:e,l=s.get(o);let c=l.bufferGPU;c===void 0&&(c=this._createBuffer(i,t,n,a),l.bufferGPU=c,l.bufferType=t,l.version=o.version);let u;if(n instanceof Float32Array)u=i.FLOAT;else if(typeof Float16Array<"u"&&n instanceof Float16Array)u=i.HALF_FLOAT;else if(n instanceof Uint16Array)e.isFloat16BufferAttribute?u=i.HALF_FLOAT:u=i.UNSIGNED_SHORT;else if(n instanceof Int16Array)u=i.SHORT;else if(n instanceof Uint32Array)u=i.UNSIGNED_INT;else if(n instanceof Int32Array)u=i.INT;else if(n instanceof Int8Array)u=i.BYTE;else if(n instanceof Uint8Array)u=i.UNSIGNED_BYTE;else if(n instanceof Uint8ClampedArray)u=i.UNSIGNED_BYTE;else throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+n);let h={bufferGPU:c,bufferType:t,type:u,byteLength:n.byteLength,bytesPerElement:n.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:u===i.INT||u===i.UNSIGNED_INT||e.gpuType===Lt,id:dL++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const d=this._createBuffer(i,t,n,a);h=new pL(h,d)}s.set(e,h)}updateAttribute(e){const t=this.backend,{gl:s}=t,i=e.array,n=e.isInterleavedBufferAttribute?e.data:e,a=t.get(n),o=a.bufferType,l=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(s.bindBuffer(o,a.bufferGPU),l.length===0)s.bufferSubData(o,0,i);else{for(let c=0,u=l.length;c<u;c++){const h=l[c];s.bufferSubData(o,h.start*i.BYTES_PER_ELEMENT,i,h.start,h.count)}n.clearUpdateRanges()}s.bindBuffer(o,null),a.version=n.version}destroyAttribute(e){const t=this.backend,{gl:s}=t;e.isInterleavedBufferAttribute&&t.delete(e.data);const i=t.get(e);s.deleteBuffer(i.bufferGPU),t.delete(e)}async getArrayBufferAsync(e){const t=this.backend,{gl:s}=t,i=e.isInterleavedBufferAttribute?e.data:e,{bufferGPU:n}=t.get(i),a=e.array,o=a.byteLength;s.bindBuffer(s.COPY_READ_BUFFER,n);const l=s.createBuffer();s.bindBuffer(s.COPY_WRITE_BUFFER,l),s.bufferData(s.COPY_WRITE_BUFFER,o,s.STREAM_READ),s.copyBufferSubData(s.COPY_READ_BUFFER,s.COPY_WRITE_BUFFER,0,0,o),await t.utils._clientWaitAsync();const c=new e.array.constructor(a.length);return s.bindBuffer(s.COPY_WRITE_BUFFER,l),s.getBufferSubData(s.COPY_WRITE_BUFFER,0,c),s.deleteBuffer(l),s.bindBuffer(s.COPY_READ_BUFFER,null),s.bindBuffer(s.COPY_WRITE_BUFFER,null),c.buffer}_createBuffer(e,t,s,i){const n=e.createBuffer();return e.bindBuffer(t,n),e.bufferData(t,s,i),e.bindBuffer(t,null),n}}let ro,zi;class mL{constructor(e){this.backend=e,this.gl=this.backend.gl,this.enabled={},this.currentFlipSided=null,this.currentCullFace=null,this.currentProgram=null,this.currentBlendingEnabled=!1,this.currentBlending=null,this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentPremultipledAlpha=null,this.currentPolygonOffsetFactor=null,this.currentPolygonOffsetUnits=null,this.currentColorMask=null,this.currentDepthReversed=!1,this.currentDepthFunc=null,this.currentDepthMask=null,this.currentStencilFunc=null,this.currentStencilRef=null,this.currentStencilFuncMask=null,this.currentStencilFail=null,this.currentStencilZFail=null,this.currentStencilZPass=null,this.currentStencilMask=null,this.currentLineWidth=null,this.currentClippingPlanes=0,this.currentVAO=null,this.currentIndex=null,this.currentBoundFramebuffers={},this.currentDrawbuffers=new WeakMap,this.maxTextures=this.gl.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.currentTextureSlot=null,this.currentBoundTextures={},this.currentBoundBufferBases={},this._init()}_init(){const e=this.gl;ro={[Ns]:e.FUNC_ADD,[vx]:e.FUNC_SUBTRACT,[Mx]:e.FUNC_REVERSE_SUBTRACT},zi={[bn]:e.ZERO,[wx]:e.ONE,[Cx]:e.SRC_COLOR,[Vo]:e.SRC_ALPHA,[Fx]:e.SRC_ALPHA_SATURATE,[Rx]:e.DST_COLOR,[Ex]:e.DST_ALPHA,[Ax]:e.ONE_MINUS_SRC_COLOR,[ko]:e.ONE_MINUS_SRC_ALPHA,[Px]:e.ONE_MINUS_DST_COLOR,[Nx]:e.ONE_MINUS_DST_ALPHA};const t=e.getParameter(e.SCISSOR_BOX),s=e.getParameter(e.VIEWPORT);this.currentScissor=new Ee().fromArray(t),this.currentViewport=new Ee().fromArray(s),this._tempVec4=new Ee}enable(e){const{enabled:t}=this;t[e]!==!0&&(this.gl.enable(e),t[e]=!0)}disable(e){const{enabled:t}=this;t[e]!==!1&&(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;e!==IM?(this.enable(t.CULL_FACE),e!==this.currentCullFace&&(e===UM?t.cullFace(t.BACK):e===VM?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))):this.disable(t.CULL_FACE),this.currentCullFace=e}setLineWidth(e){const{currentLineWidth:t,gl:s}=this;e!==t&&(s.lineWidth(e),this.currentLineWidth=e)}setMRTBlending(e,t,s){const i=this.gl,n=this.backend.drawBuffersIndexedExt;if(!n){Le("WebGPURenderer: Multiple Render Targets (MRT) blending configuration is not fully supported in compatibility mode. The material blending will be used for all render targets.");return}for(let a=0;a<e.length;a++){const o=e[a];let l=null;if(t!==null){const c=t.getBlendMode(o.name);c.blending===Ip?l=s:c.blending!==Xi&&(l=c)}else l=s;l!==null?this._setMRTBlendingIndex(a,l):n.blendFuncSeparateiOES(a,i.ONE,i.ZERO,i.ONE,i.ZERO)}}_setMRTBlendingIndex(e,t){const{gl:s}=this,i=this.backend.drawBuffersIndexedExt,n=t.blending,a=t.blendSrc,o=t.blendDst,l=t.blendEquation,c=t.premultipliedAlpha;if(n===ma){const u=t.blendSrcAlpha!==null?t.blendSrcAlpha:a,h=t.blendDstAlpha!==null?t.blendDstAlpha:o,d=t.blendEquationAlpha!==null?t.blendEquationAlpha:l;i.blendEquationSeparateiOES(e,ro[l],ro[d]),i.blendFuncSeparateiOES(e,zi[a],zi[o],zi[u],zi[h])}else if(i.blendEquationSeparateiOES(e,s.FUNC_ADD,s.FUNC_ADD),c)switch(n){case Es:i.blendFuncSeparateiOES(e,s.ONE,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA);break;case ua:i.blendFuncSeparateiOES(e,s.ONE,s.ONE,s.ONE,s.ONE);break;case ha:i.blendFuncSeparateiOES(e,s.ZERO,s.ONE_MINUS_SRC_COLOR,s.ZERO,s.ONE);break;case da:i.blendFuncSeparateiOES(e,s.DST_COLOR,s.ONE_MINUS_SRC_ALPHA,s.ZERO,s.ONE);break;default:i.blendFuncSeparateiOES(e,s.ONE,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA);break}else switch(n){case Es:i.blendFuncSeparateiOES(e,s.SRC_ALPHA,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA);break;case ua:i.blendFuncSeparateiOES(e,s.SRC_ALPHA,s.ONE,s.ONE,s.ONE);break;case ha:i.blendFuncSeparateiOES(e,s.ZERO,s.ONE_MINUS_SRC_COLOR,s.ZERO,s.ONE);break;case da:i.blendFuncSeparateiOES(e,s.DST_COLOR,s.ONE_MINUS_SRC_ALPHA,s.ZERO,s.ONE);break;default:i.blendFuncSeparateiOES(e,s.SRC_ALPHA,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA);break}}setBlending(e,t,s,i,n,a,o,l){const{gl:c}=this;if(e===Xi){this.currentBlendingEnabled===!0&&(this.disable(c.BLEND),this.currentBlendingEnabled=!1);return}if(this.currentBlendingEnabled===!1&&(this.enable(c.BLEND),this.currentBlendingEnabled=!0),e!==ma){if(e!==this.currentBlending||l!==this.currentPremultipledAlpha){if((this.currentBlendEquation!==Ns||this.currentBlendEquationAlpha!==Ns)&&(c.blendEquation(c.FUNC_ADD),this.currentBlendEquation=Ns,this.currentBlendEquationAlpha=Ns),l)switch(e){case Es:c.blendFuncSeparate(c.ONE,c.ONE_MINUS_SRC_ALPHA,c.ONE,c.ONE_MINUS_SRC_ALPHA);break;case ua:c.blendFunc(c.ONE,c.ONE);break;case ha:c.blendFuncSeparate(c.ZERO,c.ONE_MINUS_SRC_COLOR,c.ZERO,c.ONE);break;case da:c.blendFuncSeparate(c.DST_COLOR,c.ONE_MINUS_SRC_ALPHA,c.ZERO,c.ONE);break;default:$("WebGLState: Invalid blending: ",e);break}else switch(e){case Es:c.blendFuncSeparate(c.SRC_ALPHA,c.ONE_MINUS_SRC_ALPHA,c.ONE,c.ONE_MINUS_SRC_ALPHA);break;case ua:c.blendFuncSeparate(c.SRC_ALPHA,c.ONE,c.ONE,c.ONE);break;case ha:$("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case da:$("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:$("WebGLState: Invalid blending: ",e);break}this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentBlending=e,this.currentPremultipledAlpha=l}return}n=n||t,a=a||s,o=o||i,(t!==this.currentBlendEquation||n!==this.currentBlendEquationAlpha)&&(c.blendEquationSeparate(ro[t],ro[n]),this.currentBlendEquation=t,this.currentBlendEquationAlpha=n),(s!==this.currentBlendSrc||i!==this.currentBlendDst||a!==this.currentBlendSrcAlpha||o!==this.currentBlendDstAlpha)&&(c.blendFuncSeparate(zi[s],zi[i],zi[a],zi[o]),this.currentBlendSrc=s,this.currentBlendDst=i,this.currentBlendSrcAlpha=a,this.currentBlendDstAlpha=o),this.currentBlending=e,this.currentPremultipledAlpha=!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=Wx[e]),this.currentDepthFunc!==e){const{gl:t}=this;switch(e){case Ac:t.depthFunc(t.NEVER);break;case Ec:t.depthFunc(t.ALWAYS);break;case Nc:t.depthFunc(t.LESS);break;case wa:t.depthFunc(t.LEQUAL);break;case Rc:t.depthFunc(t.EQUAL);break;case Pc:t.depthFunc(t.GEQUAL);break;case Fc:t.depthFunc(t.GREATER);break;case Bc:t.depthFunc(t.NOTEQUAL);break;default:t.depthFunc(t.LEQUAL)}this.currentDepthFunc=e}}scissor(e,t,s,i){const n=this._tempVec4.set(e,t,s,i);if(this.currentScissor.equals(n)===!1){const{gl:a}=this;a.scissor(n.x,n.y,n.z,n.w),this.currentScissor.copy(n)}}viewport(e,t,s,i){const n=this._tempVec4.set(e,t,s,i);if(this.currentViewport.equals(n)===!1){const{gl:a}=this;a.viewport(n.x,n.y,n.z,n.w),this.currentViewport.copy(n)}}setScissorTest(e){const t=this.gl;e?this.enable(t.SCISSOR_TEST):this.disable(t.SCISSOR_TEST)}setStencilTest(e){const{gl:t}=this;e?this.enable(t.STENCIL_TEST):this.disable(t.STENCIL_TEST)}setStencilMask(e){this.currentStencilMask!==e&&(this.gl.stencilMask(e),this.currentStencilMask=e)}setStencilFunc(e,t,s){(this.currentStencilFunc!==e||this.currentStencilRef!==t||this.currentStencilFuncMask!==s)&&(this.gl.stencilFunc(e,t,s),this.currentStencilFunc=e,this.currentStencilRef=t,this.currentStencilFuncMask=s)}setStencilOp(e,t,s){(this.currentStencilFail!==e||this.currentStencilZFail!==t||this.currentStencilZPass!==s)&&(this.gl.stencilOp(e,t,s),this.currentStencilFail=e,this.currentStencilZFail=t,this.currentStencilZPass=s)}setMaterial(e,t,s){const{gl:i}=this;e.side===qi?this.disable(i.CULL_FACE):this.enable(i.CULL_FACE);let n=e.side===Rt;t&&(n=!n),this.setFlipSided(n),e.blending===Es&&e.transparent===!1?this.setBlending(Xi):this.setBlending(e.blending,e.blendEquation,e.blendSrc,e.blendDst,e.blendEquationAlpha,e.blendSrcAlpha,e.blendDstAlpha,e.premultipliedAlpha),this.setDepthFunc(e.depthFunc),this.setDepthTest(e.depthTest),this.setDepthMask(e.depthWrite),this.setColorMask(e.colorWrite);const a=e.stencilWrite;if(this.setStencilTest(a),a&&(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),e.alphaToCoverage===!0&&this.backend.renderer.currentSamples>0?this.enable(i.SAMPLE_ALPHA_TO_COVERAGE):this.disable(i.SAMPLE_ALPHA_TO_COVERAGE),s>0&&this.currentClippingPlanes!==s)for(let l=0;l<8;l++)l<s?this.enable(12288+l):this.disable(12288+l)}setPolygonOffset(e,t,s){const{gl:i}=this;e?(this.enable(i.POLYGON_OFFSET_FILL),(this.currentPolygonOffsetFactor!==t||this.currentPolygonOffsetUnits!==s)&&(i.polygonOffset(t,s),this.currentPolygonOffsetFactor=t,this.currentPolygonOffsetUnits=s)):this.disable(i.POLYGON_OFFSET_FILL)}useProgram(e){return this.currentProgram!==e?(this.gl.useProgram(e),this.currentProgram=e,!0):!1}setVertexState(e,t=null){const s=this.gl;return this.currentVAO!==e||this.currentIndex!==t?(s.bindVertexArray(e),t!==null&&s.bindBuffer(s.ELEMENT_ARRAY_BUFFER,t),this.currentVAO=e,this.currentIndex=t,!0):!1}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:s,currentBoundFramebuffers:i}=this;return i[e]!==t?(s.bindFramebuffer(e,t),i[e]=t,e===s.DRAW_FRAMEBUFFER&&(i[s.FRAMEBUFFER]=t),e===s.FRAMEBUFFER&&(i[s.DRAW_FRAMEBUFFER]=t),!0):!1}drawBuffers(e,t){const{gl:s}=this;let i=[],n=!1;if(e.textures!==null){i=this.currentDrawbuffers.get(t),i===void 0&&(i=[],this.currentDrawbuffers.set(t,i));const a=e.textures;if(i.length!==a.length||i[0]!==s.COLOR_ATTACHMENT0){for(let o=0,l=a.length;o<l;o++)i[o]=s.COLOR_ATTACHMENT0+o;i.length=a.length,n=!0}}else i[0]!==s.BACK&&(i[0]=s.BACK,n=!0);n&&s.drawBuffers(i)}activeTexture(e){const{gl:t,currentTextureSlot:s,maxTextures:i}=this;e===void 0&&(e=t.TEXTURE0+i-1),s!==e&&(t.activeTexture(e),this.currentTextureSlot=e)}bindTexture(e,t,s){const{gl:i,currentTextureSlot:n,currentBoundTextures:a,maxTextures:o}=this;s===void 0&&(n===null?s=i.TEXTURE0+o-1:s=n);let l=a[s];l===void 0&&(l={type:void 0,texture:void 0},a[s]=l),(l.type!==e||l.texture!==t)&&(n!==s&&(i.activeTexture(s),this.currentTextureSlot=s),i.bindTexture(e,t),l.type=e,l.texture=t)}bindBufferBase(e,t,s){const{gl:i}=this,n=`${e}-${t}`;return this.currentBoundBufferBases[n]!==s?(i.bindBufferBase(e,t,s),this.currentBoundBufferBases[n]=s,!0):!1}unbindTexture(){const{gl:e,currentTextureSlot:t,currentBoundTextures:s}=this,i=s[t];i!==void 0&&i.type!==void 0&&(e.bindTexture(i.type,null),i.type=void 0,i.texture=void 0)}}class gL{constructor(e){this.backend=e,this.gl=this.backend.gl,this.extensions=e.extensions}convert(e,t=In){const{gl:s,extensions:i}=this;let n;const a=Ae.getTransfer(t);if(e===Ut)return s.UNSIGNED_BYTE;if(e===Dx)return s.UNSIGNED_SHORT_4_4_4_4;if(e===Ox)return s.UNSIGNED_SHORT_5_5_5_1;if(e===zp)return s.UNSIGNED_INT_5_9_9_9_REV;if(e===Gp)return s.UNSIGNED_INT_10F_11F_11F_REV;if(e===ga)return s.BYTE;if(e===ya)return s.SHORT;if(e===pr)return s.UNSIGNED_SHORT;if(e===Lt)return s.INT;if(e===rt)return s.UNSIGNED_INT;if(e===es)return s.FLOAT;if(e===Et)return s.HALF_FLOAT;if(e===Lx)return s.ALPHA;if(e===Nu)return s.RGB;if(e===ms)return s.RGBA;if(e===Qs)return s.DEPTH_COMPONENT;if(e===Yi)return s.DEPTH_STENCIL;if(e===Ru)return s.RED;if(e===Pu)return s.RED_INTEGER;if(e===_i)return s.RG;if(e===Fu)return s.RG_INTEGER;if(e===Bu)return s.RGBA_INTEGER;if(e===Mo||e===wo||e===Co||e===Ao)if(a===ce)if(n=i.get("WEBGL_compressed_texture_s3tc_srgb"),n!==null){if(e===Mo)return n.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(e===wo)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(e===Co)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(e===Ao)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(n=i.get("WEBGL_compressed_texture_s3tc"),n!==null){if(e===Mo)return n.COMPRESSED_RGB_S3TC_DXT1_EXT;if(e===wo)return n.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(e===Co)return n.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(e===Ao)return n.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(e===Jd||e===ep||e===tp||e===sp)if(n=i.get("WEBGL_compressed_texture_pvrtc"),n!==null){if(e===Jd)return n.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(e===ep)return n.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(e===tp)return n.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(e===sp)return n.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(e===Oc||e===Lc||e===Ic||e===Uc||e===Vc||e===Go||e===kc)if(n=i.get("WEBGL_compressed_texture_etc"),n!==null){if(e===Oc||e===Lc)return a===ce?n.COMPRESSED_SRGB8_ETC2:n.COMPRESSED_RGB8_ETC2;if(e===Ic)return a===ce?n.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:n.COMPRESSED_RGBA8_ETC2_EAC;if(e===Uc)return n.COMPRESSED_R11_EAC;if(e===Vc)return n.COMPRESSED_SIGNED_R11_EAC;if(e===Go)return n.COMPRESSED_RG11_EAC;if(e===kc)return n.COMPRESSED_SIGNED_RG11_EAC}else return null;if(e===zc||e===Gc||e===$c||e===Wc||e===Hc||e===jc||e===qc||e===Xc||e===Yc||e===Zc||e===Qc||e===Kc||e===Jc||e===eu)if(n=i.get("WEBGL_compressed_texture_astc"),n!==null){if(e===zc)return a===ce?n.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:n.COMPRESSED_RGBA_ASTC_4x4_KHR;if(e===Gc)return a===ce?n.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:n.COMPRESSED_RGBA_ASTC_5x4_KHR;if(e===$c)return a===ce?n.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:n.COMPRESSED_RGBA_ASTC_5x5_KHR;if(e===Wc)return a===ce?n.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:n.COMPRESSED_RGBA_ASTC_6x5_KHR;if(e===Hc)return a===ce?n.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:n.COMPRESSED_RGBA_ASTC_6x6_KHR;if(e===jc)return a===ce?n.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:n.COMPRESSED_RGBA_ASTC_8x5_KHR;if(e===qc)return a===ce?n.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:n.COMPRESSED_RGBA_ASTC_8x6_KHR;if(e===Xc)return a===ce?n.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:n.COMPRESSED_RGBA_ASTC_8x8_KHR;if(e===Yc)return a===ce?n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:n.COMPRESSED_RGBA_ASTC_10x5_KHR;if(e===Zc)return a===ce?n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:n.COMPRESSED_RGBA_ASTC_10x6_KHR;if(e===Qc)return a===ce?n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:n.COMPRESSED_RGBA_ASTC_10x8_KHR;if(e===Kc)return a===ce?n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:n.COMPRESSED_RGBA_ASTC_10x10_KHR;if(e===Jc)return a===ce?n.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:n.COMPRESSED_RGBA_ASTC_12x10_KHR;if(e===eu)return a===ce?n.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:n.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(e===tu)if(n=i.get("EXT_texture_compression_bptc"),n!==null){if(e===tu)return a===ce?n.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:n.COMPRESSED_RGBA_BPTC_UNORM_EXT}else return null;if(e===su||e===iu||e===$o||e===nu)if(n=i.get("EXT_texture_compression_rgtc"),n!==null){if(e===su)return n.COMPRESSED_RED_RGTC1_EXT;if(e===iu)return n.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(e===$o)return n.COMPRESSED_RED_GREEN_RGTC2_EXT;if(e===nu)return n.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return e===Fn?s.UNSIGNED_INT_24_8:s[e]!==void 0?s[e]:null}_clientWaitAsync(){const{gl:e}=this,t=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0);return e.flush(),new Promise((s,i)=>{function n(){const a=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(a===e.WAIT_FAILED){e.deleteSync(t),i();return}if(a===e.TIMEOUT_EXPIRED){requestAnimationFrame(n);return}e.deleteSync(t),s()}n()})}}let Ty=!1,sc,wd,Sy;class yL{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},this._srcFramebuffer=null,this._dstFramebuffer=null,Ty===!1&&(this._init(),Ty=!0)}_init(){const e=this.gl;sc={[Aa]:e.REPEAT,[xi]:e.CLAMP_TO_EDGE,[Ea]:e.MIRRORED_REPEAT},wd={[at]:e.NEAREST,[Bx]:e.NEAREST_MIPMAP_NEAREST,[zo]:e.NEAREST_MIPMAP_LINEAR,[Gt]:e.LINEAR,[Kd]:e.LINEAR_MIPMAP_NEAREST,[Pn]:e.LINEAR_MIPMAP_LINEAR},Sy={[Ux]:e.NEVER,[Gx]:e.ALWAYS,[$p]:e.LESS,[Du]:e.LEQUAL,[Vx]:e.EQUAL,[Ou]:e.GEQUAL,[kx]:e.GREATER,[zx]:e.NOTEQUAL}}getGLTextureType(e){const{gl:t}=this;let s;return e.isCubeTexture===!0?s=t.TEXTURE_CUBE_MAP:e.isArrayTexture===!0||e.isDataArrayTexture===!0||e.isCompressedArrayTexture===!0?s=t.TEXTURE_2D_ARRAY:e.isData3DTexture===!0?s=t.TEXTURE_3D:s=t.TEXTURE_2D,s}getInternalFormat(e,t,s,i,n=!1){const{gl:a,extensions:o}=this;if(e!==null){if(a[e]!==void 0)return a[e];W("WebGLBackend: Attempt to use non-existing WebGL internal format '"+e+"'")}let l=t;if(t===a.RED&&(s===a.FLOAT&&(l=a.R32F),s===a.HALF_FLOAT&&(l=a.R16F),s===a.UNSIGNED_BYTE&&(l=a.R8),s===a.UNSIGNED_SHORT&&(l=a.R16),s===a.UNSIGNED_INT&&(l=a.R32UI),s===a.BYTE&&(l=a.R8I),s===a.SHORT&&(l=a.R16I),s===a.INT&&(l=a.R32I)),t===a.RED_INTEGER&&(s===a.UNSIGNED_BYTE&&(l=a.R8UI),s===a.UNSIGNED_SHORT&&(l=a.R16UI),s===a.UNSIGNED_INT&&(l=a.R32UI),s===a.BYTE&&(l=a.R8I),s===a.SHORT&&(l=a.R16I),s===a.INT&&(l=a.R32I)),t===a.RG&&(s===a.FLOAT&&(l=a.RG32F),s===a.HALF_FLOAT&&(l=a.RG16F),s===a.UNSIGNED_BYTE&&(l=a.RG8),s===a.UNSIGNED_SHORT&&(l=a.RG16),s===a.UNSIGNED_INT&&(l=a.RG32UI),s===a.BYTE&&(l=a.RG8I),s===a.SHORT&&(l=a.RG16I),s===a.INT&&(l=a.RG32I)),t===a.RG_INTEGER&&(s===a.UNSIGNED_BYTE&&(l=a.RG8UI),s===a.UNSIGNED_SHORT&&(l=a.RG16UI),s===a.UNSIGNED_INT&&(l=a.RG32UI),s===a.BYTE&&(l=a.RG8I),s===a.SHORT&&(l=a.RG16I),s===a.INT&&(l=a.RG32I)),t===a.RGB){const c=n?au:Ae.getTransfer(i);s===a.FLOAT&&(l=a.RGB32F),s===a.HALF_FLOAT&&(l=a.RGB16F),s===a.UNSIGNED_BYTE&&(l=a.RGB8),s===a.UNSIGNED_SHORT&&(l=a.RGB16),s===a.UNSIGNED_INT&&(l=a.RGB32UI),s===a.BYTE&&(l=a.RGB8I),s===a.SHORT&&(l=a.RGB16I),s===a.INT&&(l=a.RGB32I),s===a.UNSIGNED_BYTE&&(l=c===ce?a.SRGB8:a.RGB8),s===a.UNSIGNED_SHORT_5_6_5&&(l=a.RGB565),s===a.UNSIGNED_SHORT_5_5_5_1&&(l=a.RGB5_A1),s===a.UNSIGNED_SHORT_4_4_4_4&&(l=a.RGB4),s===a.UNSIGNED_INT_5_9_9_9_REV&&(l=a.RGB9_E5),s===a.UNSIGNED_INT_10F_11F_11F_REV&&(l=a.R11F_G11F_B10F)}if(t===a.RGB_INTEGER&&(s===a.UNSIGNED_BYTE&&(l=a.RGB8UI),s===a.UNSIGNED_SHORT&&(l=a.RGB16UI),s===a.UNSIGNED_INT&&(l=a.RGB32UI),s===a.BYTE&&(l=a.RGB8I),s===a.SHORT&&(l=a.RGB16I),s===a.INT&&(l=a.RGB32I)),t===a.RGBA){const c=n?au:Ae.getTransfer(i);s===a.FLOAT&&(l=a.RGBA32F),s===a.HALF_FLOAT&&(l=a.RGBA16F),s===a.UNSIGNED_BYTE&&(l=a.RGBA8),s===a.UNSIGNED_SHORT&&(l=a.RGBA16),s===a.UNSIGNED_INT&&(l=a.RGBA32UI),s===a.BYTE&&(l=a.RGBA8I),s===a.SHORT&&(l=a.RGBA16I),s===a.INT&&(l=a.RGBA32I),s===a.UNSIGNED_BYTE&&(l=c===ce?a.SRGB8_ALPHA8:a.RGBA8),s===a.UNSIGNED_SHORT_4_4_4_4&&(l=a.RGBA4),s===a.UNSIGNED_SHORT_5_5_5_1&&(l=a.RGB5_A1)}return t===a.RGBA_INTEGER&&(s===a.UNSIGNED_BYTE&&(l=a.RGBA8UI),s===a.UNSIGNED_SHORT&&(l=a.RGBA16UI),s===a.UNSIGNED_INT&&(l=a.RGBA32UI),s===a.BYTE&&(l=a.RGBA8I),s===a.SHORT&&(l=a.RGBA16I),s===a.INT&&(l=a.RGBA32I)),t===a.DEPTH_COMPONENT&&(s===a.UNSIGNED_SHORT&&(l=a.DEPTH_COMPONENT16),s===a.UNSIGNED_INT&&(l=a.DEPTH_COMPONENT24),s===a.FLOAT&&(l=a.DEPTH_COMPONENT32F)),t===a.DEPTH_STENCIL&&s===a.UNSIGNED_INT_24_8&&(l=a.DEPTH24_STENCIL8),(l===a.R16F||l===a.R32F||l===a.RG16F||l===a.RG32F||l===a.RGBA16F||l===a.RGBA32F)&&o.get("EXT_color_buffer_float"),l}setTextureParameters(e,t){const{gl:s,extensions:i,backend:n}=this,a=Ae.getPrimaries(Ae.workingColorSpace),o=t.colorSpace===In?null:Ae.getPrimaries(t.colorSpace),l=t.colorSpace===In||a===o?s.NONE:s.BROWSER_DEFAULT_WEBGL;s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,t.flipY),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),s.pixelStorei(s.UNPACK_ALIGNMENT,t.unpackAlignment),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,l),s.texParameteri(e,s.TEXTURE_WRAP_S,sc[t.wrapS]),s.texParameteri(e,s.TEXTURE_WRAP_T,sc[t.wrapT]),(e===s.TEXTURE_3D||e===s.TEXTURE_2D_ARRAY)&&(t.isArrayTexture||s.texParameteri(e,s.TEXTURE_WRAP_R,sc[t.wrapR])),s.texParameteri(e,s.TEXTURE_MAG_FILTER,wd[t.magFilter]);const c=t.mipmaps!==void 0&&t.mipmaps.length>0,u=t.minFilter===Gt&&c?Pn:t.minFilter;if(s.texParameteri(e,s.TEXTURE_MIN_FILTER,wd[u]),t.compareFunction&&(s.texParameteri(e,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE),s.texParameteri(e,s.TEXTURE_COMPARE_FUNC,Sy[t.compareFunction])),i.has("EXT_texture_filter_anisotropic")===!0){if(t.magFilter===at||t.minFilter!==zo&&t.minFilter!==Pn||t.type===es&&i.has("OES_texture_float_linear")===!1)return;if(t.anisotropy>1){const h=i.get("EXT_texture_filter_anisotropic");s.texParameterf(e,h.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,n.getMaxAnisotropy()))}}}createDefaultTexture(e){const{gl:t,backend:s,defaultTextures:i}=this,n=this.getGLTextureType(e);let a=i[n];a===void 0&&(a=t.createTexture(),s.state.bindTexture(n,a),t.texParameteri(n,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(n,t.TEXTURE_MAG_FILTER,t.NEAREST),i[n]=a),s.set(e,{textureGPU:a,glTextureType:n})}createTexture(e,t){const{gl:s,backend:i}=this,{levels:n,width:a,height:o,depth:l}=t,c=i.utils.convert(e.format,e.colorSpace),u=i.utils.convert(e.type),h=this.getInternalFormat(e.internalFormat,c,u,e.colorSpace,e.isVideoTexture),d=s.createTexture(),p=this.getGLTextureType(e);i.state.bindTexture(p,d),this.setTextureParameters(p,e),e.isArrayTexture||e.isDataArrayTexture||e.isCompressedArrayTexture?s.texStorage3D(s.TEXTURE_2D_ARRAY,n,h,a,o,l):e.isData3DTexture?s.texStorage3D(s.TEXTURE_3D,n,h,a,o,l):e.isVideoTexture||s.texStorage2D(p,n,h,a,o),i.set(e,{textureGPU:d,glTextureType:p,glFormat:c,glType:u,glInternalFormat:h})}copyBufferToTexture(e,t){const{gl:s,backend:i}=this,{textureGPU:n,glTextureType:a,glFormat:o,glType:l}=i.get(t),{width:c,height:u}=t.source.data;s.bindBuffer(s.PIXEL_UNPACK_BUFFER,e),i.state.bindTexture(a,n),s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,!1),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),s.texSubImage2D(a,0,0,0,c,u,o,l,0),s.bindBuffer(s.PIXEL_UNPACK_BUFFER,null),i.state.unbindTexture()}updateTexture(e,t){const{gl:s}=this,{width:i,height:n}=t,{textureGPU:a,glTextureType:o,glFormat:l,glType:c,glInternalFormat:u}=this.backend.get(e);if(!(e.isRenderTargetTexture||a===void 0))if(this.backend.state.bindTexture(o,a),this.setTextureParameters(o,e),e.isCompressedTexture){const h=e.mipmaps,d=t.image;for(let p=0;p<h.length;p++){const f=h[p];e.isCompressedArrayTexture?e.format!==s.RGBA?l!==null?s.compressedTexSubImage3D(s.TEXTURE_2D_ARRAY,p,0,0,0,f.width,f.height,d.depth,l,f.data):W("WebGLBackend: Attempt to load unsupported compressed texture format in .uploadTexture()"):s.texSubImage3D(s.TEXTURE_2D_ARRAY,p,0,0,0,f.width,f.height,d.depth,l,c,f.data):l!==null?s.compressedTexSubImage2D(s.TEXTURE_2D,p,0,0,f.width,f.height,l,f.data):W("WebGLBackend: Unsupported compressed texture format")}}else if(e.isCubeTexture){const h=t.images,d=e.mipmaps;for(let p=0;p<6;p++){const f=ic(h[p]);s.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+p,0,0,0,i,n,l,c,f);for(let m=0;m<d.length;m++){const x=d[m],y=ic(x.images[p]);s.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+p,m+1,0,0,y.width,y.height,l,c,y)}}}else if(e.isDataArrayTexture||e.isArrayTexture){const h=t.image;if(e.layerUpdates.size>0){const d=RC(h.width,h.height,e.format,e.type);for(const p of e.layerUpdates){const f=h.data.subarray(p*d/h.data.BYTES_PER_ELEMENT,(p+1)*d/h.data.BYTES_PER_ELEMENT);s.texSubImage3D(s.TEXTURE_2D_ARRAY,0,0,0,p,h.width,h.height,1,l,c,f)}e.clearLayerUpdates()}else s.texSubImage3D(s.TEXTURE_2D_ARRAY,0,0,0,0,h.width,h.height,h.depth,l,c,h.data)}else if(e.isData3DTexture){const h=t.image;s.texSubImage3D(s.TEXTURE_3D,0,0,0,0,h.width,h.height,h.depth,l,c,h.data)}else if(e.isVideoTexture)e.update(),s.texImage2D(o,0,u,l,c,t.image);else{const h=e.mipmaps;if(h.length>0)for(let d=0,p=h.length;d<p;d++){const f=h[d],m=ic(f);s.texSubImage2D(o,d,0,0,f.width,f.height,l,c,m)}else{const d=ic(t.image);s.texSubImage2D(o,0,0,0,i,n,l,c,d)}}}generateMipmaps(e){const{gl:t,backend:s}=this,{textureGPU:i,glTextureType:n}=s.get(e);s.state.bindTexture(n,i),t.generateMipmap(n)}deallocateRenderBuffers(e){const{gl:t,backend:s}=this;if(e){const i=s.get(e);if(i.renderBufferStorageSetup=void 0,i.framebuffers){for(const n in i.framebuffers)t.deleteFramebuffer(i.framebuffers[n]);delete i.framebuffers}if(i.depthRenderbuffer&&(t.deleteRenderbuffer(i.depthRenderbuffer),delete i.depthRenderbuffer),i.stencilRenderbuffer&&(t.deleteRenderbuffer(i.stencilRenderbuffer),delete i.stencilRenderbuffer),i.msaaFrameBuffer&&(t.deleteFramebuffer(i.msaaFrameBuffer),delete i.msaaFrameBuffer),i.msaaRenderbuffers){for(let n=0;n<i.msaaRenderbuffers.length;n++)t.deleteRenderbuffer(i.msaaRenderbuffers[n]);delete i.msaaRenderbuffers}}}destroyTexture(e,t=!1){const{gl:s,backend:i}=this,{textureGPU:n,renderTarget:a}=i.get(e);this.deallocateRenderBuffers(a),t===!1&&s.deleteTexture(n),i.delete(e)}copyTextureToTexture(e,t,s=null,i=null,n=0,a=0){const{gl:o,backend:l}=this,{state:c}=this.backend,{textureGPU:u,glTextureType:h,glType:d,glFormat:p}=l.get(t);c.bindTexture(h,u);let f,m,x,y,b,v,S,M,A;const C=e.isCompressedTexture?e.mipmaps[a]:e.image;if(s!==null)f=s.max.x-s.min.x,m=s.max.y-s.min.y,x=s.isBox3?s.max.z-s.min.z:1,y=s.min.x,b=s.min.y,v=s.isBox3?s.min.z:0;else{const q=Math.pow(2,-n);f=Math.floor(C.width*q),m=Math.floor(C.height*q),e.isDataArrayTexture||e.isArrayTexture?x=C.depth:e.isData3DTexture?x=Math.floor(C.depth*q):x=1,y=0,b=0,v=0}i!==null?(S=i.x,M=i.y,A=i.z):(S=0,M=0,A=0),o.pixelStorei(o.UNPACK_FLIP_Y_WEBGL,t.flipY),o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),o.pixelStorei(o.UNPACK_ALIGNMENT,t.unpackAlignment);const P=o.getParameter(o.UNPACK_ROW_LENGTH),B=o.getParameter(o.UNPACK_IMAGE_HEIGHT),V=o.getParameter(o.UNPACK_SKIP_PIXELS),Y=o.getParameter(o.UNPACK_SKIP_ROWS),J=o.getParameter(o.UNPACK_SKIP_IMAGES);o.pixelStorei(o.UNPACK_ROW_LENGTH,C.width),o.pixelStorei(o.UNPACK_IMAGE_HEIGHT,C.height),o.pixelStorei(o.UNPACK_SKIP_PIXELS,y),o.pixelStorei(o.UNPACK_SKIP_ROWS,b),o.pixelStorei(o.UNPACK_SKIP_IMAGES,v);const K=e.isDataArrayTexture||e.isData3DTexture||t.isArrayTexture,te=t.isDataArrayTexture||t.isData3DTexture||t.isArrayTexture;if(e.isDepthTexture){const q=l.get(e),oe=l.get(t),Pe=l.get(q.renderTarget),ge=l.get(oe.renderTarget),le=Pe.framebuffers[q.cacheKey],Ue=ge.framebuffers[oe.cacheKey];c.bindFramebuffer(o.READ_FRAMEBUFFER,le),c.bindFramebuffer(o.DRAW_FRAMEBUFFER,Ue);for(let He=0;He<x;He++)K&&(o.framebufferTextureLayer(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,q.textureGPU,n,v+He),o.framebufferTextureLayer(o.DRAW_FRAMEBUFFER,o.COLOR_ATTACHMENT0,u,a,A+He)),o.blitFramebuffer(y,b,f,m,S,M,f,m,o.DEPTH_BUFFER_BIT,o.NEAREST);c.bindFramebuffer(o.READ_FRAMEBUFFER,null),c.bindFramebuffer(o.DRAW_FRAMEBUFFER,null)}else if(n!==0||e.isRenderTargetTexture||l.has(e)){const q=l.get(e);this._srcFramebuffer===null&&(this._srcFramebuffer=o.createFramebuffer()),this._dstFramebuffer===null&&(this._dstFramebuffer=o.createFramebuffer()),c.bindFramebuffer(o.READ_FRAMEBUFFER,this._srcFramebuffer),c.bindFramebuffer(o.DRAW_FRAMEBUFFER,this._dstFramebuffer);for(let oe=0;oe<x;oe++)K?o.framebufferTextureLayer(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,q.textureGPU,n,v+oe):o.framebufferTexture2D(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,q.textureGPU,n),te?o.framebufferTextureLayer(o.DRAW_FRAMEBUFFER,o.COLOR_ATTACHMENT0,u,a,A+oe):o.framebufferTexture2D(o.DRAW_FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,u,a),n!==0?o.blitFramebuffer(y,b,f,m,S,M,f,m,o.COLOR_BUFFER_BIT,o.NEAREST):te?o.copyTexSubImage3D(h,a,S,M,A+oe,y,b,f,m):o.copyTexSubImage2D(h,a,S,M,y,b,f,m);c.bindFramebuffer(o.READ_FRAMEBUFFER,null),c.bindFramebuffer(o.DRAW_FRAMEBUFFER,null)}else te?e.isDataTexture||e.isData3DTexture?o.texSubImage3D(h,a,S,M,A,f,m,x,p,d,C.data):t.isCompressedArrayTexture?o.compressedTexSubImage3D(h,a,S,M,A,f,m,x,p,C.data):o.texSubImage3D(h,a,S,M,A,f,m,x,p,d,C):e.isDataTexture?o.texSubImage2D(o.TEXTURE_2D,a,S,M,f,m,p,d,C.data):e.isCompressedTexture?o.compressedTexSubImage2D(o.TEXTURE_2D,a,S,M,C.width,C.height,p,C.data):o.texSubImage2D(o.TEXTURE_2D,a,S,M,f,m,p,d,C);o.pixelStorei(o.UNPACK_ROW_LENGTH,P),o.pixelStorei(o.UNPACK_IMAGE_HEIGHT,B),o.pixelStorei(o.UNPACK_SKIP_PIXELS,V),o.pixelStorei(o.UNPACK_SKIP_ROWS,Y),o.pixelStorei(o.UNPACK_SKIP_IMAGES,J),a===0&&t.generateMipmaps&&o.generateMipmap(h),c.unbindTexture()}copyFramebufferToTexture(e,t,s){const{gl:i}=this,{state:n}=this.backend,{textureGPU:a}=this.backend.get(e),{x:o,y:l,z:c,w:u}=s,h=e.isDepthTexture===!0||t.renderTarget&&t.renderTarget.samples>0,d=t.renderTarget?t.renderTarget.height:this.backend.getDrawingBufferSize().y;if(h){const p=o!==0||l!==0;let f,m;if(e.isDepthTexture===!0?(f=i.DEPTH_BUFFER_BIT,m=i.DEPTH_ATTACHMENT,t.stencil&&(f|=i.STENCIL_BUFFER_BIT)):(f=i.COLOR_BUFFER_BIT,m=i.COLOR_ATTACHMENT0),p){const x=this.backend.get(t.renderTarget),y=x.framebuffers[t.getCacheKey()],b=x.msaaFrameBuffer;n.bindFramebuffer(i.DRAW_FRAMEBUFFER,y),n.bindFramebuffer(i.READ_FRAMEBUFFER,b);const v=d-l-u;i.blitFramebuffer(o,v,o+c,v+u,o,v,o+c,v+u,f,i.NEAREST),n.bindFramebuffer(i.READ_FRAMEBUFFER,y),n.bindTexture(i.TEXTURE_2D,a),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,o,v,c,u),n.unbindTexture()}else{const x=i.createFramebuffer();n.bindFramebuffer(i.DRAW_FRAMEBUFFER,x),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,m,i.TEXTURE_2D,a,0),i.blitFramebuffer(0,0,c,u,0,0,c,u,f,i.NEAREST),i.deleteFramebuffer(x)}}else n.bindTexture(i.TEXTURE_2D,a),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,o,d-u-l,c,u),n.unbindTexture();e.generateMipmaps&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t,s,i=!1){const{gl:n}=this,a=t.renderTarget,{depthTexture:o,depthBuffer:l,stencilBuffer:c,width:u,height:h}=a;if(n.bindRenderbuffer(n.RENDERBUFFER,e),l&&!c){let d=n.DEPTH_COMPONENT24;i===!0?this.extensions.get("WEBGL_multisampled_render_to_texture").renderbufferStorageMultisampleEXT(n.RENDERBUFFER,a.samples,d,u,h):s>0?(o&&o.isDepthTexture&&o.type===n.FLOAT&&(d=n.DEPTH_COMPONENT32F),n.renderbufferStorageMultisample(n.RENDERBUFFER,s,d,u,h)):n.renderbufferStorage(n.RENDERBUFFER,d,u,h),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.DEPTH_ATTACHMENT,n.RENDERBUFFER,e)}else l&&c&&(s>0?n.renderbufferStorageMultisample(n.RENDERBUFFER,s,n.DEPTH24_STENCIL8,u,h):n.renderbufferStorage(n.RENDERBUFFER,n.DEPTH_STENCIL,u,h),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.DEPTH_STENCIL_ATTACHMENT,n.RENDERBUFFER,e));n.bindRenderbuffer(n.RENDERBUFFER,null)}async copyTextureToBuffer(e,t,s,i,n,a){const{backend:o,gl:l}=this,{textureGPU:c,glFormat:u,glType:h}=this.backend.get(e),d=l.createFramebuffer();o.state.bindFramebuffer(l.READ_FRAMEBUFFER,d);const p=e.isCubeTexture?l.TEXTURE_CUBE_MAP_POSITIVE_X+a:l.TEXTURE_2D;l.framebufferTexture2D(l.READ_FRAMEBUFFER,l.COLOR_ATTACHMENT0,p,c,0);const f=this._getTypedArrayType(h),m=this._getBytesPerTexel(h,u),y=i*n*m,b=l.createBuffer();l.bindBuffer(l.PIXEL_PACK_BUFFER,b),l.bufferData(l.PIXEL_PACK_BUFFER,y,l.STREAM_READ),l.readPixels(t,s,i,n,u,h,0),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),await o.utils._clientWaitAsync();const v=new f(y/f.BYTES_PER_ELEMENT);return l.bindBuffer(l.PIXEL_PACK_BUFFER,b),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,v),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),o.state.bindFramebuffer(l.READ_FRAMEBUFFER,null),l.deleteFramebuffer(d),v}_getTypedArrayType(e){const{gl:t}=this;if(e===t.UNSIGNED_BYTE)return Uint8Array;if(e===t.UNSIGNED_SHORT_4_4_4_4||e===t.UNSIGNED_SHORT_5_5_5_1||e===t.UNSIGNED_SHORT_5_6_5||e===t.UNSIGNED_SHORT)return Uint16Array;if(e===t.UNSIGNED_INT)return Uint32Array;if(e===t.HALF_FLOAT)return Uint16Array;if(e===t.FLOAT)return Float32Array;throw new Error(`Unsupported WebGL type: ${e}`)}_getBytesPerTexel(e,t){const{gl:s}=this;let i=0;if(e===s.UNSIGNED_BYTE&&(i=1),(e===s.UNSIGNED_SHORT_4_4_4_4||e===s.UNSIGNED_SHORT_5_5_5_1||e===s.UNSIGNED_SHORT_5_6_5||e===s.UNSIGNED_SHORT||e===s.HALF_FLOAT)&&(i=2),(e===s.UNSIGNED_INT||e===s.FLOAT)&&(i=4),t===s.RGBA)return i*4;if(t===s.RGB)return i*3;if(t===s.ALPHA)return i}dispose(){const{gl:e}=this;this._srcFramebuffer!==null&&e.deleteFramebuffer(this._srcFramebuffer),this._dstFramebuffer!==null&&e.deleteFramebuffer(this._dstFramebuffer)}}function ic(r){return r.isDataTexture?r.image.data:typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&r instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&r instanceof ImageBitmap||typeof OffscreenCanvas<"u"&&r instanceof OffscreenCanvas?r:r.data}class xL{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 t===void 0&&(t=this.gl.getExtension(e),this.extensions[e]=t),t}has(e){return this.availableExtensions.includes(e)}}class _L{constructor(e){this.backend=e,this.maxAnisotropy=null}getMaxAnisotropy(){if(this.maxAnisotropy!==null)return this.maxAnisotropy;const e=this.backend.gl,t=this.backend.extensions;if(t.has("EXT_texture_filter_anisotropic")===!0){const s=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(s.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}}const vy={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 bL{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:s,mode:i,object:n,type:a,info:o,index:l}=this;l!==0?s.drawElements(i,t,a,e):s.drawArrays(i,e,t),o.update(n,t,1)}renderInstances(e,t,s){const{gl:i,mode:n,type:a,index:o,object:l,info:c}=this;s!==0&&(o!==0?i.drawElementsInstanced(n,t,a,e,s):i.drawArraysInstanced(n,e,t,s),c.update(l,t,s))}renderMultiDraw(e,t,s){const{extensions:i,mode:n,object:a,info:o}=this;if(s===0)return;const l=i.get("WEBGL_multi_draw");if(l===null)for(let c=0;c<s;c++)this.render(e[c],t[c]);else{this.index!==0?l.multiDrawElementsWEBGL(n,t,0,this.type,e,0,s):l.multiDrawArraysWEBGL(n,e,0,t,0,s);let c=0;for(let u=0;u<s;u++)c+=t[u];o.update(a,c,1)}}renderMultiDrawInstances(e,t,s,i){const{extensions:n,mode:a,object:o,info:l}=this;if(s===0)return;const c=n.get("WEBGL_multi_draw");if(c===null)for(let u=0;u<s;u++)this.renderInstances(e[u],t[u],i[u]);else{this.index!==0?c.multiDrawElementsInstancedWEBGL(a,t,0,this.type,e,0,i,0,s):c.multiDrawArraysInstancedWEBGL(a,e,0,t,0,i,0,s);let u=0;for(let h=0;h<s;h++)u+=t[h]*i[h];l.update(o,u,1)}}}class US{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 t===void 0&&(W(`TimestampQueryPool: No timestamp available for uid ${e}.`),t=0),t}hasTimestamp(e){return this.timestamps.has(e)}allocateQueriesForContext(){}async resolveQueriesAsync(){}dispose(){}}class TL extends US{constructor(e,t,s=2048){if(super(s),this.gl=e,this.type=t,this.ext=e.getExtension("EXT_disjoint_timer_query_webgl2")||e.getExtension("EXT_disjoint_timer_query"),!this.ext){W("EXT_disjoint_timer_query not supported; timestamps will be disabled."),this.trackTimestamp=!1;return}this.queries=[];for(let i=0;i<this.maxQueries;i++)this.queries.push(e.createQuery());this.activeQuery=null,this.queryStates=new Map}allocateQueriesForContext(e){if(!this.trackTimestamp)return null;if(this.currentQueryIndex+2>this.maxQueries)return Le(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryStates.set(t,"inactive"),this.queryOffsets.set(e,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(t==null||this.activeQuery!==null)return;const s=this.queries[t];if(s)try{this.queryStates.get(t)==="inactive"&&(this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,s),this.activeQuery=t,this.queryStates.set(t,"started"))}catch(i){$("Error in beginQuery:",i),this.activeQuery=null,this.queryStates.set(t,"inactive")}}endQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(t!=null&&this.activeQuery===t)try{this.gl.endQuery(this.ext.TIME_ELAPSED_EXT),this.queryStates.set(t,"ended"),this.activeQuery=null}catch(s){$("Error in endQuery:",s),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[n,a]of this.queryOffsets)if(this.queryStates.get(a)==="ended"){const l=this.queries[a];e.set(n,this.resolveQuery(l))}if(e.size===0)return this.lastValue;const t={},s=[];for(const[n,a]of e){const o=n.match(/^(.*):f(\d+)$/),l=parseInt(o[2]);s.includes(l)===!1&&s.push(l),t[l]===void 0&&(t[l]=0);const c=await a;this.timestamps.set(n,c),t[l]+=c}const i=t[s[s.length-1]];return this.lastValue=i,this.frames=s,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,i}catch(e){return $("Error resolving queries:",e),this.lastValue}finally{this.pendingResolve=!1}}async resolveQuery(e){return new Promise(t=>{if(this.isDisposed){t(this.lastValue);return}let s,i=!1;const n=()=>{s&&(clearTimeout(s),s=null)},a=l=>{i||(i=!0,n(),t(l))},o=()=>{if(this.isDisposed){a(this.lastValue);return}try{if(this.gl.getParameter(this.ext.GPU_DISJOINT_EXT)){a(this.lastValue);return}if(!this.gl.getQueryParameter(e,this.gl.QUERY_RESULT_AVAILABLE)){s=setTimeout(o,1);return}const u=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT);t(Number(u)/1e6)}catch(l){$("Error checking query:",l),t(this.lastValue)}};o()})}dispose(){if(!this.isDisposed&&(this.isDisposed=!0,!!this.trackTimestamp)){for(const e of this.queries)this.gl.deleteQuery(e);this.queries=[],this.queryStates.clear(),this.queryOffsets.clear(),this.lastValue=0,this.activeQuery=null}}}class My extends IS{constructor(e={}){super(e),this.isWebGLBackend=!0,this.attributeUtils=null,this.extensions=null,this.capabilities=null,this.textureUtils=null,this.bufferRenderer=null,this.gl=null,this.state=null,this.utils=null,this.vaoCache={},this.transformFeedbackCache={},this.discard=!1,this.disjoint=null,this.parallel=null,this._currentContext=null,this._knownBindings=new WeakSet,this._supportsInvalidateFramebuffer=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),this._xrFramebuffer=null}init(e){super.init(e);const t=this.parameters,s={antialias:e.currentSamples>0,alpha:!0,depth:e.depth,stencil:e.stencil},i=t.context!==void 0?t.context:e.domElement.getContext("webgl2",s);function n(a){a.preventDefault();const o={api:"WebGL",message:a.statusMessage||"Unknown reason",reason:null,originalEvent:a};e.onDeviceLost(o)}this._onContextLost=n,e.domElement.addEventListener("webglcontextlost",n,!1),this.gl=i,this.extensions=new xL(this),this.capabilities=new _L(this),this.attributeUtils=new fL(this),this.textureUtils=new yL(this),this.bufferRenderer=new bL(this),this.state=new mL(this),this.utils=new gL(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===!0&&this.extensions.has("EXT_clip_control")&&this.state.setReversedDepth(!0)}get coordinateSystem(){return gs}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}async makeXRCompatible(){this.gl.getContextAttributes().xrCompatible!==!0&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,s=null){const i=this.gl;if(this.set(e.texture,{textureGPU:t,glInternalFormat:i.RGBA8}),s!==null){const n=e.stencilBuffer?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT24;this.set(e.depthTexture,{textureGPU:s,glInternalFormat:n}),this.extensions.has("WEBGL_multisampled_render_to_texture")===!0&&e._autoAllocateDepthBuffer===!0&&e.multiview===!1&&W("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 TL(this.gl,e,2048));const s=this.timestampQueryPool[e];s.allocateQueriesForContext(t)!==null&&s.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,s=this.get(e);if(e.viewport)this.updateViewport(e);else{const{width:n,height:a}=this.getDrawingBufferSize();t.viewport(0,0,n,a)}if(e.scissor)this.updateScissor(e);else{const{width:n,height:a}=this.getDrawingBufferSize();t.scissor(0,0,n,a)}this.initTimestampQuery(bi.RENDER,this.getTimestampUID(e)),s.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1);const i=e.occlusionQueryCount;i>0&&(s.currentOcclusionQueries=s.occlusionQueries,s.currentOcclusionQueryObjects=s.occlusionQueryObjects,s.lastOcclusionObject=null,s.occlusionQueries=new Array(i),s.occlusionQueryObjects=new Array(i),s.occlusionQueryIndex=0)}finishRender(e){const{gl:t,state:s}=this,i=this.get(e),n=i.previousContext;s.resetVertexState();const a=e.occlusionQueryCount;a>0&&(a>i.occlusionQueryIndex&&t.endQuery(t.ANY_SAMPLES_PASSED),this.resolveOccludedAsync(e));const o=e.textures;if(o!==null)for(let l=0;l<o.length;l++){const c=o[l];c.generateMipmaps&&this.generateMipmaps(c)}if(this._currentContext=n,this._resolveRenderTarget(e),n!==null){if(this._setFramebuffer(n),n.viewport)this.updateViewport(n);else{const{width:l,height:c}=this.getDrawingBufferSize();s.viewport(0,0,l,c)}if(n.scissor)this.updateScissor(n);else{const{width:l,height:c}=this.getDrawingBufferSize();s.scissor(0,0,l,c)}}this.prepareTimestampBuffer(bi.RENDER,this.getTimestampUID(e))}resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueries:s,currentOcclusionQueryObjects:i}=t;if(s&&i){const n=new WeakSet,{gl:a}=this;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueries=null;const o=()=>{let l=0;for(let c=0;c<s.length;c++){const u=s[c];u!==null&&a.getQueryParameter(u,a.QUERY_RESULT_AVAILABLE)&&(a.getQueryParameter(u,a.QUERY_RESULT)===0&&n.add(i[c]),s[c]=null,a.deleteQuery(u),l++)}l<s.length?requestAnimationFrame(o):t.occluded=n};o()}}isOccluded(e,t){const s=this.get(e);return s.occluded&&s.occluded.has(t)}updateViewport(e){const{state:t}=this,{x:s,y:i,width:n,height:a}=e.viewportValue;t.viewport(s,e.height-a-i,n,a)}updateScissor(e){const{state:t}=this,{x:s,y:i,width:n,height:a}=e.scissorValue;t.scissor(s,e.height-a-i,n,a)}setScissorTest(e){this.state.setScissorTest(e)}getClearColor(){const e=super.getClearColor();return e.r*=e.a,e.g*=e.a,e.b*=e.a,e}clear(e,t,s,i=null,n=!0,a=!0){const{gl:o,renderer:l}=this;i===null&&(i={textures:null,clearColorValue:this.getClearColor()});let c=0;if(e&&(c|=o.COLOR_BUFFER_BIT),t&&(c|=o.DEPTH_BUFFER_BIT),s&&(c|=o.STENCIL_BUFFER_BIT),c!==0){let u;i.clearColorValue?u=i.clearColorValue:u=this.getClearColor();const h=l.getClearDepth(),d=l.getClearStencil();if(t&&this.state.setDepthMask(!0),i.textures===null)o.clearColor(u.r,u.g,u.b,u.a),o.clear(c);else{if(n&&this._setFramebuffer(i),e)for(let p=0;p<i.textures.length;p++)p===0?o.clearBufferfv(o.COLOR,p,[u.r,u.g,u.b,u.a]):o.clearBufferfv(o.COLOR,p,[0,0,0,1]);t&&s?o.clearBufferfi(o.DEPTH_STENCIL,0,h,d):t?o.clearBufferfv(o.DEPTH,0,[h]):s&&o.clearBufferiv(o.STENCIL,0,[d]),n&&a&&this._resolveRenderTarget(i)}}}beginCompute(e){const{state:t,gl:s}=this;t.bindFramebuffer(s.FRAMEBUFFER,null),this.initTimestampQuery(bi.COMPUTE,this.getTimestampUID(e))}compute(e,t,s,i,n=null){const{state:a,gl:o}=this;this.discard===!1&&(a.enable(o.RASTERIZER_DISCARD),this.discard=!0);const{programGPU:l,transformBuffers:c,attributes:u}=this.get(i),h=this._getVaoKey(u),d=this.vaoCache[h];d===void 0?this.vaoCache[h]=this._createVao(u):a.setVertexState(d),a.useProgram(l),this._bindUniforms(s);const p=this._getTransformFeedback(c);o.bindTransformFeedback(o.TRANSFORM_FEEDBACK,p),o.beginTransformFeedback(o.POINTS),n=n!==null?n:t.count,Array.isArray(n)?(Le("WebGLBackend.compute(): The count parameter must be a single number, not an array."),n=n[0]):n&&typeof n=="object"&&n.isIndirectStorageBufferAttribute&&(Le("WebGLBackend.compute(): The count parameter must be a single number, not IndirectStorageBufferAttribute"),n=t.count),u[0].isStorageInstancedBufferAttribute?o.drawArraysInstanced(o.POINTS,0,1,n):o.drawArrays(o.POINTS,0,n),o.endTransformFeedback(),o.bindTransformFeedback(o.TRANSFORM_FEEDBACK,null);for(let f=0;f<c.length;f++){const m=c[f];m.pbo&&this.has(m.pbo)&&this.textureUtils.copyBufferToTexture(m.transformBuffer,m.pbo),m.switchBuffers()}}finishCompute(e){const{state:t,gl:s}=this;this.discard=!1,t.disable(s.RASTERIZER_DISCARD),this.prepareTimestampBuffer(bi.COMPUTE,this.getTimestampUID(e)),this._currentContext&&this._setFramebuffer(this._currentContext)}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.isArrayTexture&&e.camera.isArrayCamera}draw(e){const{object:t,pipeline:s,material:i,context:n,hardwareClippingPlanes:a}=e,{programGPU:o}=this.get(s),{gl:l,state:c}=this,u=this.get(n),h=e.getDrawParameters();if(h===null)return;this._bindUniforms(e.getBindings());const d=t.isMesh&&t.matrixWorld.determinant()<0;c.setMaterial(i,d,a),n.mrt!==null&&n.textures!==null&&c.setMRTBlending(n.textures,n.mrt,i),c.useProgram(o);const p=e.getAttributes(),f=this.get(p);let m=f.vaoGPU;if(m===void 0){const P=this._getVaoKey(p);m=this.vaoCache[P],m===void 0&&(m=this._createVao(p),this.vaoCache[P]=m,f.vaoGPU=m)}const x=e.getIndex(),y=x!==null?this.get(x).bufferGPU:null;c.setVertexState(m,y);const b=u.lastOcclusionObject;if(b!==t&&b!==void 0){if(b!==null&&b.occlusionTest===!0&&(l.endQuery(l.ANY_SAMPLES_PASSED),u.occlusionQueryIndex++),t.occlusionTest===!0){const P=l.createQuery();l.beginQuery(l.ANY_SAMPLES_PASSED,P),u.occlusionQueries[u.occlusionQueryIndex]=P,u.occlusionQueryObjects[u.occlusionQueryIndex]=t}u.lastOcclusionObject=t}const v=this.bufferRenderer;t.isPoints?v.mode=l.POINTS:t.isLineSegments?v.mode=l.LINES:t.isLine?v.mode=l.LINE_STRIP:t.isLineLoop?v.mode=l.LINE_LOOP:i.wireframe===!0?(c.setLineWidth(i.wireframeLinewidth*this.renderer.getPixelRatio()),v.mode=l.LINES):v.mode=l.TRIANGLES;const{vertexCount:S,instanceCount:M}=h;let{firstVertex:A}=h;if(v.object=t,x!==null){A*=x.array.BYTES_PER_ELEMENT;const P=this.get(x);v.index=x.count,v.type=P.type}else v.index=0;const C=()=>{t.isBatchedMesh?t._multiDrawInstances!==null?(Le("WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),v.renderMultiDrawInstances(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount,t._multiDrawInstances)):this.hasFeature("WEBGL_multi_draw")?v.renderMultiDraw(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount):Le("WebGLBackend: WEBGL_multi_draw not supported."):M>1?v.renderInstances(A,S,M):v.render(A,S)};if(e.camera.isArrayCamera===!0&&e.camera.cameras.length>0&&e.camera.isMultiViewCamera===!1){const P=this.get(e.camera),B=e.camera.cameras,V=e.getBindingGroup("cameraIndex").bindings[0];if(P.indexesGPU===void 0||P.indexesGPU.length!==B.length){const oe=new Uint32Array([0,0,0,0]),Pe=[];for(let ge=0,le=B.length;ge<le;ge++){const Ue=l.createBuffer();oe[0]=ge,l.bindBuffer(l.UNIFORM_BUFFER,Ue),l.bufferData(l.UNIFORM_BUFFER,oe,l.STATIC_DRAW),Pe.push(Ue)}P.indexesGPU=Pe}const Y=this.get(V),J=this.renderer.getPixelRatio(),K=this._currentContext.renderTarget,te=this._isRenderCameraDepthArray(this._currentContext),q=this._currentContext.activeCubeFace;if(te){const oe=this.get(K.depthTexture);if(oe.clearedRenderId!==this.renderer._nodes.nodeFrame.renderId){oe.clearedRenderId=this.renderer._nodes.nodeFrame.renderId;const{stencilBuffer:Pe}=K;for(let ge=0,le=B.length;ge<le;ge++)this.renderer._activeCubeFace=ge,this._currentContext.activeCubeFace=ge,this._setFramebuffer(this._currentContext),this.clear(!1,!0,Pe,this._currentContext,!1,!1);this.renderer._activeCubeFace=q,this._currentContext.activeCubeFace=q}}for(let oe=0,Pe=B.length;oe<Pe;oe++){const ge=B[oe];if(t.layers.test(ge.layers)){te&&(this.renderer._activeCubeFace=oe,this._currentContext.activeCubeFace=oe,this._setFramebuffer(this._currentContext));const le=ge.viewport;if(le!==void 0){const Ue=le.x*J,He=le.y*J,$t=le.width*J,Fe=le.height*J;c.viewport(Math.floor(Ue),Math.floor(e.context.height-Fe-He),Math.floor($t),Math.floor(Fe))}c.bindBufferBase(l.UNIFORM_BUFFER,Y.index,P.indexesGPU[oe]),C()}this._currentContext.activeCubeFace=q,this.renderer._activeCubeFace=q}}else C()}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,s,i,n,a){return this.textureUtils.copyTextureToBuffer(e,t,s,i,n,a)}updateSampler(){return""}createNodeBuilder(e,t){return new hL(e,t)}createProgram(e){const t=this.gl,{stage:s,code:i}=e,n=s==="fragment"?t.createShader(t.FRAGMENT_SHADER):t.createShader(t.VERTEX_SHADER);t.shaderSource(n,i),t.compileShader(n),this.set(e,{shaderGPU:n})}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){const s=this.gl,i=e.pipeline,{fragmentProgram:n,vertexProgram:a}=i,o=s.createProgram(),l=this.get(n).shaderGPU,c=this.get(a).shaderGPU;if(s.attachShader(o,l),s.attachShader(o,c),s.linkProgram(o),this.set(i,{programGPU:o,fragmentShader:l,vertexShader:c}),t!==null&&this.parallel){const u=new Promise(h=>{const d=this.parallel,p=()=>{s.getProgramParameter(o,d.COMPLETION_STATUS_KHR)?(this._completeCompile(e,i),h()):requestAnimationFrame(p)};p()});t.push(u);return}this._completeCompile(e,i)}_handleSource(e,t){const s=e.split(`
194
- `),i=[],n=Math.max(t-6,0),a=Math.min(t+6,s.length);for(let o=n;o<a;o++){const l=o+1;i.push(`${l===t?">":" "} ${l}: ${s[o]}`)}return i.join(`
195
- `)}_getShaderErrors(e,t,s){const i=e.getShaderParameter(t,e.COMPILE_STATUS),a=(e.getShaderInfoLog(t)||"").trim();if(i&&a==="")return"";const o=/ERROR: 0:(\d+)/.exec(a);if(o){const l=parseInt(o[1]);return s.toUpperCase()+`
196
-
197
- `+a+`
198
-
199
- `+this._handleSource(e.getShaderSource(t),l)}else return a}_logProgramError(e,t,s){if(this.renderer.debug.checkShaderErrors){const i=this.gl,a=(i.getProgramInfoLog(e)||"").trim();if(i.getProgramParameter(e,i.LINK_STATUS)===!1)if(typeof this.renderer.debug.onShaderError=="function")this.renderer.debug.onShaderError(i,e,s,t);else{const o=this._getShaderErrors(i,s,"vertex"),l=this._getShaderErrors(i,t,"fragment");$("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(e,i.VALIDATE_STATUS)+`
200
-
201
- Program Info Log: `+a+`
202
- `+o+`
203
- `+l)}else a!==""&&W("WebGLProgram: Program Info Log:",a)}}_completeCompile(e,t){const{state:s,gl:i}=this,n=this.get(t),{programGPU:a,fragmentShader:o,vertexShader:l}=n;i.getProgramParameter(a,i.LINK_STATUS)===!1&&this._logProgramError(a,o,l),s.useProgram(a);const c=e.getBindings();this._setupBindings(c,a),this.set(t,{programGPU:a})}createComputePipeline(e,t){const{state:s,gl:i}=this,n={stage:"fragment",code:`#version 300 es
204
- precision highp float;
205
- void main() {}`};this.createProgram(n);const{computeProgram:a}=e,o=i.createProgram(),l=this.get(n).shaderGPU,c=this.get(a).shaderGPU,u=a.transforms,h=[],d=[];for(let x=0;x<u.length;x++){const y=u[x];h.push(y.varyingName),d.push(y.attributeNode)}i.attachShader(o,l),i.attachShader(o,c),i.transformFeedbackVaryings(o,h,i.SEPARATE_ATTRIBS),i.linkProgram(o),i.getProgramParameter(o,i.LINK_STATUS)===!1&&this._logProgramError(o,l,c),s.useProgram(o),this._setupBindings(t,o);const p=a.attributes,f=[],m=[];for(let x=0;x<p.length;x++){const y=p[x].node.attribute;f.push(y),this.has(y)||this.attributeUtils.createAttribute(y,i.ARRAY_BUFFER)}for(let x=0;x<d.length;x++){const y=d[x].attribute;this.has(y)||this.attributeUtils.createAttribute(y,i.ARRAY_BUFFER);const b=this.get(y);m.push(b)}this.set(e,{programGPU:o,transformBuffers:m,attributes:f})}createBindings(e,t){if(this._knownBindings.has(t)===!1){this._knownBindings.add(t);let s=0,i=0;for(const n of t){this.set(n,{textures:i,uniformBuffers:s});for(const a of n.bindings)a.isUniformBuffer&&s++,a.isSampledTexture&&i++}}this.updateBindings(e,t)}updateBindings(e){const{gl:t}=this,s=this.get(e);let i=s.uniformBuffers,n=s.textures;for(const a of e.bindings){const o=this.get(a);if(a.isUniformsGroup||a.isUniformBuffer){const l=a.buffer;let{bufferGPU:c}=this.get(l);c===void 0?(c=t.createBuffer(),t.bindBuffer(t.UNIFORM_BUFFER,c),t.bufferData(t.UNIFORM_BUFFER,l.byteLength,t.DYNAMIC_DRAW),this.set(l,{bufferGPU:c})):t.bindBuffer(t.UNIFORM_BUFFER,c);const u=a.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,c),u.length===0)t.bufferData(t.UNIFORM_BUFFER,l,t.DYNAMIC_DRAW);else{const h=ou(l),d=h?1:l.BYTES_PER_ELEMENT;for(let p=0,f=u.length;p<f;p++){const m=u[p],x=m.start*d,y=m.count*d,b=x*(h?l.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,b,l,x,y)}}o.index=i++,o.bufferGPU=c,this.set(a,o)}else if(a.isSampledTexture){const{textureGPU:l,glTextureType:c}=this.get(a.texture);o.index=n++,o.textureGPU=l,o.glTextureType=c,this.set(a,o)}}}updateBinding(e){const t=this.gl;if(e.isUniformsGroup||e.isUniformBuffer){const i=this.get(e).bufferGPU,n=e.buffer,a=e.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,i),a.length===0)t.bufferData(t.UNIFORM_BUFFER,n,t.DYNAMIC_DRAW);else{const o=ou(n),l=o?1:n.BYTES_PER_ELEMENT;for(let c=0,u=a.length;c<u;c++){const h=a[c],d=h.start*l,p=h.count*l,f=d*(o?n.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,f,n,d,p)}}}}createIndexAttribute(e){const t=this.gl;this.attributeUtils.createAttribute(e,t.ELEMENT_ARRAY_BUFFER)}createAttribute(e){if(this.has(e))return;const t=this.gl;this.attributeUtils.createAttribute(e,t.ARRAY_BUFFER)}createStorageAttribute(e){if(this.has(e))return;const t=this.gl;this.attributeUtils.createAttribute(e,t.ARRAY_BUFFER)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}hasFeature(e){const t=Object.keys(vy).filter(i=>vy[i]===e),s=this.extensions;for(let i=0;i<t.length;i++)if(s.has(t[i]))return!0;return!1}getMaxAnisotropy(){return this.capabilities.getMaxAnisotropy()}copyTextureToTexture(e,t,s=null,i=null,n=0,a=0){this.textureUtils.copyTextureToTexture(e,t,s,i,n,a)}copyFramebufferToTexture(e,t,s){this.textureUtils.copyFramebufferToTexture(e,t,s)}hasCompatibility(e){return e===Bn.TEXTURE_COMPARE?!0:super.hasCompatibility(e)}initRenderTarget(e){const{gl:t,state:s}=this;this._setFramebuffer(e),s.bindFramebuffer(t.FRAMEBUFFER,null)}_setFramebuffer(e){const{gl:t,state:s}=this;let i=null;if(e.textures!==null){const n=e.renderTarget,a=this.get(n),{samples:o,depthBuffer:l,stencilBuffer:c}=n,u=n.isCubeRenderTarget===!0,h=n.isRenderTarget3D===!0,d=n.depth>1,p=n.isXRRenderTarget===!0,f=p===!0&&n._hasExternalTextures===!0;let m=a.msaaFrameBuffer,x=a.depthRenderbuffer;const y=this.extensions.get("WEBGL_multisampled_render_to_texture"),b=this.extensions.get("OVR_multiview2"),v=this._useMultisampledExtension(n),S=RT(e);let M;if(u?(a.cubeFramebuffers||(a.cubeFramebuffers={}),M=a.cubeFramebuffers[S]):p&&f===!1?M=this._xrFramebuffer:(a.framebuffers||(a.framebuffers={}),M=a.framebuffers[S]),M===void 0){M=t.createFramebuffer(),s.bindFramebuffer(t.FRAMEBUFFER,M);const A=e.textures,C=[];if(u){a.cubeFramebuffers[S]=M;const{textureGPU:B}=this.get(A[0]),V=this.renderer._activeCubeFace,Y=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+V,B,Y)}else{a.framebuffers[S]=M;for(let B=0;B<A.length;B++){const V=A[B],Y=this.get(V);Y.renderTarget=e.renderTarget,Y.cacheKey=S;const J=t.COLOR_ATTACHMENT0+B;if(n.multiview)b.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,J,Y.textureGPU,0,o,0,2);else if(h||d){const K=this.renderer._activeCubeFace,te=this.renderer._activeMipmapLevel;t.framebufferTextureLayer(t.FRAMEBUFFER,J,Y.textureGPU,te,K)}else if(v)y.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,J,t.TEXTURE_2D,Y.textureGPU,0,o);else{const K=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,J,t.TEXTURE_2D,Y.textureGPU,K)}}}const P=c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(n._autoAllocateDepthBuffer===!0){const B=t.createRenderbuffer();this.textureUtils.setupRenderBufferStorage(B,e,0,v),a.xrDepthRenderbuffer=B,C.push(c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT),t.bindRenderbuffer(t.RENDERBUFFER,B),t.framebufferRenderbuffer(t.FRAMEBUFFER,P,t.RENDERBUFFER,B)}else if(e.depthTexture!==null){C.push(c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT);const B=this.get(e.depthTexture);if(B.renderTarget=e.renderTarget,B.cacheKey=S,n.multiview)b.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,P,B.textureGPU,0,o,0,2);else if(f&&v)y.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,P,t.TEXTURE_2D,B.textureGPU,0,o);else if(e.depthTexture.isArrayTexture){const V=this.renderer._activeCubeFace;t.framebufferTextureLayer(t.FRAMEBUFFER,P,B.textureGPU,0,V)}else if(e.depthTexture.isCubeTexture){const V=this.renderer._activeCubeFace;t.framebufferTexture2D(t.FRAMEBUFFER,P,t.TEXTURE_CUBE_MAP_POSITIVE_X+V,B.textureGPU,0)}else t.framebufferTexture2D(t.FRAMEBUFFER,P,t.TEXTURE_2D,B.textureGPU,0)}a.depthInvalidationArray=C}else{if(this._isRenderCameraDepthArray(e)){s.bindFramebuffer(t.FRAMEBUFFER,M);const C=this.renderer._activeCubeFace,P=this.get(e.depthTexture),B=c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;t.framebufferTextureLayer(t.FRAMEBUFFER,B,P.textureGPU,0,C)}if((p||v||n.multiview)&&n._isOpaqueFramebuffer!==!0){s.bindFramebuffer(t.FRAMEBUFFER,M);const C=this.get(e.textures[0]);n.multiview?b.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,C.textureGPU,0,o,0,2):v?y.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,C.textureGPU,0,o):t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,C.textureGPU,0);const P=c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(n._autoAllocateDepthBuffer===!0){const B=a.xrDepthRenderbuffer;t.bindRenderbuffer(t.RENDERBUFFER,B),t.framebufferRenderbuffer(t.FRAMEBUFFER,P,t.RENDERBUFFER,B)}else{const B=this.get(e.depthTexture);n.multiview?b.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,P,B.textureGPU,0,o,0,2):v?y.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,P,t.TEXTURE_2D,B.textureGPU,0,o):t.framebufferTexture2D(t.FRAMEBUFFER,P,t.TEXTURE_2D,B.textureGPU,0)}}}if(o>0&&v===!1&&!n.multiview){if(m===void 0){const A=[];m=t.createFramebuffer(),s.bindFramebuffer(t.FRAMEBUFFER,m);const C=[],P=e.textures;for(let B=0;B<P.length;B++){C[B]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,C[B]),A.push(t.COLOR_ATTACHMENT0+B);const V=e.textures[B],Y=this.get(V);t.renderbufferStorageMultisample(t.RENDERBUFFER,o,Y.glInternalFormat,e.width,e.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+B,t.RENDERBUFFER,C[B])}if(t.bindRenderbuffer(t.RENDERBUFFER,null),a.msaaFrameBuffer=m,a.msaaRenderbuffers=C,l&&x===void 0){x=t.createRenderbuffer(),this.textureUtils.setupRenderBufferStorage(x,e,o),a.depthRenderbuffer=x;const B=c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;A.push(B)}a.invalidationArray=A}i=a.msaaFrameBuffer}else i=M;s.drawBuffers(e,M)}s.bindFramebuffer(t.FRAMEBUFFER,i)}_getVaoKey(e){let t="";for(let s=0;s<e.length;s++){const i=this.get(e[s]);t+=":"+i.id}return t}_createVao(e){const{gl:t}=this,s=t.createVertexArray();t.bindVertexArray(s);for(let i=0;i<e.length;i++){const n=e[i],a=this.get(n);t.bindBuffer(t.ARRAY_BUFFER,a.bufferGPU),t.enableVertexAttribArray(i);let o,l;n.isInterleavedBufferAttribute===!0?(o=n.data.stride*a.bytesPerElement,l=n.offset*a.bytesPerElement):(o=0,l=0),a.isInteger?t.vertexAttribIPointer(i,n.itemSize,a.type,o,l):t.vertexAttribPointer(i,n.itemSize,a.type,n.normalized,o,l),n.isInstancedBufferAttribute&&!n.isInterleavedBufferAttribute?t.vertexAttribDivisor(i,n.meshPerAttribute):n.isInterleavedBufferAttribute&&n.data.isInstancedInterleavedBuffer&&t.vertexAttribDivisor(i,n.data.meshPerAttribute)}return t.bindBuffer(t.ARRAY_BUFFER,null),s}_getTransformFeedback(e){let t="";for(let n=0;n<e.length;n++)t+=":"+e[n].id;let s=this.transformFeedbackCache[t];if(s!==void 0)return s;const{gl:i}=this;s=i.createTransformFeedback(),i.bindTransformFeedback(i.TRANSFORM_FEEDBACK,s);for(let n=0;n<e.length;n++){const a=e[n];i.bindBufferBase(i.TRANSFORM_FEEDBACK_BUFFER,n,a.transformBuffer)}return i.bindTransformFeedback(i.TRANSFORM_FEEDBACK,null),this.transformFeedbackCache[t]=s,s}_setupBindings(e,t){const s=this.gl;for(const i of e)for(const n of i.bindings){const o=this.get(n).index;if(n.isUniformsGroup||n.isUniformBuffer){const l=s.getUniformBlockIndex(t,n.name);s.uniformBlockBinding(t,l,o)}else if(n.isSampledTexture){const l=s.getUniformLocation(t,n.name);s.uniform1i(l,o)}}}_bindUniforms(e){const{gl:t,state:s}=this;for(const i of e)for(const n of i.bindings){const a=this.get(n),o=a.index;n.isUniformsGroup||n.isUniformBuffer?s.bindBufferBase(t.UNIFORM_BUFFER,o,a.bufferGPU):n.isSampledTexture&&s.bindTexture(a.glTextureType,a.textureGPU,t.TEXTURE0+o)}}_resolveRenderTarget(e){const{gl:t,state:s}=this,i=e.renderTarget;if(e.textures!==null&&i){const n=this.get(i);if(i.samples>0&&this._useMultisampledExtension(i)===!1){const a=n.framebuffers[e.getCacheKey()];let o=t.COLOR_BUFFER_BIT;i.resolveDepthBuffer&&(i.depthBuffer&&(o|=t.DEPTH_BUFFER_BIT),i.stencilBuffer&&i.resolveStencilBuffer&&(o|=t.STENCIL_BUFFER_BIT));const l=n.msaaFrameBuffer,c=n.msaaRenderbuffers,u=e.textures,h=u.length>1;if(s.bindFramebuffer(t.READ_FRAMEBUFFER,l),s.bindFramebuffer(t.DRAW_FRAMEBUFFER,a),h)for(let d=0;d<u.length;d++)t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0+d,t.RENDERBUFFER,null),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+d,t.TEXTURE_2D,null,0);for(let d=0;d<u.length;d++){if(h){const{textureGPU:p}=this.get(u[d]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,c[d]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,p,0)}if(e.scissor){const{x:p,y:f,width:m,height:x}=e.scissorValue,y=e.height-x-f;t.blitFramebuffer(p,y,p+m,y+x,p,y,p+m,y+x,o,t.NEAREST)}else t.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,o,t.NEAREST)}if(h)for(let d=0;d<u.length;d++){const{textureGPU:p}=this.get(u[d]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0+d,t.RENDERBUFFER,c[d]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+d,t.TEXTURE_2D,p,0)}this._supportsInvalidateFramebuffer===!0&&t.invalidateFramebuffer(t.READ_FRAMEBUFFER,n.invalidationArray)}else if(i.resolveDepthBuffer===!1&&n.framebuffers){const a=n.framebuffers[e.getCacheKey()];s.bindFramebuffer(t.DRAW_FRAMEBUFFER,a),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,n.depthInvalidationArray)}}}_useMultisampledExtension(e){return e.multiview===!0?!0:e.samples>0&&this.extensions.has("WEBGL_multisampled_render_to_texture")===!0&&e._autoAllocateDepthBuffer!==!1}dispose(){this.textureUtils!==null&&this.textureUtils.dispose();const e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext(),this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const nc={PointList:"point-list",LineList:"line-list",LineStrip:"line-strip",TriangleList:"triangle-list"},Ti=typeof self<"u"&&self.GPUShaderStage?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},At={Never:"never",Less:"less",Equal:"equal",LessEqual:"less-equal",Greater:"greater",NotEqual:"not-equal",GreaterEqual:"greater-equal",Always:"always"},Ht={Store:"store"},De={Load:"load",Clear:"clear"},wy={CCW:"ccw",CW:"cw"},Cy={None:"none",Back:"back"},Mu={Uint16:"uint16",Uint32:"uint32"},N={R8Unorm:"r8unorm",R8Snorm:"r8snorm",R8Uint:"r8uint",R8Sint:"r8sint",R16Uint:"r16uint",R16Sint:"r16sint",R16Float:"r16float",RG8Unorm:"rg8unorm",RG8Snorm:"rg8snorm",RG8Uint:"rg8uint",RG8Sint:"rg8sint",R32Uint:"r32uint",R32Sint:"r32sint",R32Float:"r32float",RG16Uint:"rg16uint",RG16Sint:"rg16sint",RG16Float:"rg16float",RGBA8Unorm:"rgba8unorm",RGBA8UnormSRGB:"rgba8unorm-srgb",RGBA8Snorm:"rgba8snorm",RGBA8Uint:"rgba8uint",RGBA8Sint:"rgba8sint",BGRA8Unorm:"bgra8unorm",BGRA8UnormSRGB:"bgra8unorm-srgb",RGB9E5UFloat:"rgb9e5ufloat",RGB10A2Unorm:"rgb10a2unorm",RG11B10UFloat:"rg11b10ufloat",RG32Uint:"rg32uint",RG32Sint:"rg32sint",RG32Float:"rg32float",RGBA16Uint:"rgba16uint",RGBA16Sint:"rgba16sint",RGBA16Float:"rgba16float",RGBA32Uint:"rgba32uint",RGBA32Sint:"rgba32sint",RGBA32Float:"rgba32float",Depth16Unorm:"depth16unorm",Depth24Plus:"depth24plus",Depth24PlusStencil8:"depth24plus-stencil8",Depth32Float:"depth32float",Depth32FloatStencil8:"depth32float-stencil8",BC1RGBAUnorm:"bc1-rgba-unorm",BC1RGBAUnormSRGB:"bc1-rgba-unorm-srgb",BC2RGBAUnorm:"bc2-rgba-unorm",BC2RGBAUnormSRGB:"bc2-rgba-unorm-srgb",BC3RGBAUnorm:"bc3-rgba-unorm",BC3RGBAUnormSRGB:"bc3-rgba-unorm-srgb",BC4RUnorm:"bc4-r-unorm",BC4RSnorm:"bc4-r-snorm",BC5RGUnorm:"bc5-rg-unorm",BC5RGSnorm:"bc5-rg-snorm",BC6HRGBUFloat:"bc6h-rgb-ufloat",BC6HRGBFloat:"bc6h-rgb-float",BC7RGBAUnorm:"bc7-rgba-unorm",BC7RGBAUnormSRGB:"bc7-rgba-unorm-srgb",ETC2RGB8Unorm:"etc2-rgb8unorm",ETC2RGB8UnormSRGB:"etc2-rgb8unorm-srgb",ETC2RGB8A1Unorm:"etc2-rgb8a1unorm",ETC2RGB8A1UnormSRGB:"etc2-rgb8a1unorm-srgb",ETC2RGBA8Unorm:"etc2-rgba8unorm",ETC2RGBA8UnormSRGB:"etc2-rgba8unorm-srgb",EACR11Unorm:"eac-r11unorm",EACR11Snorm:"eac-r11snorm",EACRG11Unorm:"eac-rg11unorm",EACRG11Snorm:"eac-rg11snorm",ASTC4x4Unorm:"astc-4x4-unorm",ASTC4x4UnormSRGB:"astc-4x4-unorm-srgb",ASTC5x4Unorm:"astc-5x4-unorm",ASTC5x4UnormSRGB:"astc-5x4-unorm-srgb",ASTC5x5Unorm:"astc-5x5-unorm",ASTC5x5UnormSRGB:"astc-5x5-unorm-srgb",ASTC6x5Unorm:"astc-6x5-unorm",ASTC6x5UnormSRGB:"astc-6x5-unorm-srgb",ASTC6x6Unorm:"astc-6x6-unorm",ASTC6x6UnormSRGB:"astc-6x6-unorm-srgb",ASTC8x5Unorm:"astc-8x5-unorm",ASTC8x5UnormSRGB:"astc-8x5-unorm-srgb",ASTC8x6Unorm:"astc-8x6-unorm",ASTC8x6UnormSRGB:"astc-8x6-unorm-srgb",ASTC8x8Unorm:"astc-8x8-unorm",ASTC8x8UnormSRGB:"astc-8x8-unorm-srgb",ASTC10x5Unorm:"astc-10x5-unorm",ASTC10x5UnormSRGB:"astc-10x5-unorm-srgb",ASTC10x6Unorm:"astc-10x6-unorm",ASTC10x6UnormSRGB:"astc-10x6-unorm-srgb",ASTC10x8Unorm:"astc-10x8-unorm",ASTC10x8UnormSRGB:"astc-10x8-unorm-srgb",ASTC10x10Unorm:"astc-10x10-unorm",ASTC10x10UnormSRGB:"astc-10x10-unorm-srgb",ASTC12x10Unorm:"astc-12x10-unorm",ASTC12x10UnormSRGB:"astc-12x10-unorm-srgb",ASTC12x12Unorm:"astc-12x12-unorm",ASTC12x12UnormSRGB:"astc-12x12-unorm-srgb"},Cd={ClampToEdge:"clamp-to-edge",Repeat:"repeat",MirrorRepeat:"mirror-repeat"},mi={Linear:"linear",Nearest:"nearest"},Se={Zero:"zero",One:"one",Src:"src",OneMinusSrc:"one-minus-src",SrcAlpha:"src-alpha",OneMinusSrcAlpha:"one-minus-src-alpha",Dst:"dst",OneMinusDst:"one-minus-dst",DstAlpha:"dst-alpha",OneMinusDstAlpha:"one-minus-dst-alpha",SrcAlphaSaturated:"src-alpha-saturated",Constant:"constant",OneMinusConstant:"one-minus-constant"},sr={Add:"add",Subtract:"subtract",ReverseSubtract:"reverse-subtract",Min:"min",Max:"max"},Ay={None:0,All:15},mn={Keep:"keep",Zero:"zero",Replace:"replace",Invert:"invert",IncrementClamp:"increment-clamp",DecrementClamp:"decrement-clamp",IncrementWrap:"increment-wrap",DecrementWrap:"decrement-wrap"},Ad={Storage:"storage",ReadOnlyStorage:"read-only-storage"},Ed={WriteOnly:"write-only",ReadOnly:"read-only",ReadWrite:"read-write"},Ey={NonFiltering:"non-filtering",Comparison:"comparison"},ir={Float:"float",UnfilterableFloat:"unfilterable-float",Depth:"depth",SInt:"sint",UInt:"uint"},Ny={TwoD:"2d",ThreeD:"3d"},Ot={TwoD:"2d",TwoDArray:"2d-array",Cube:"cube",ThreeD:"3d"},SL={All:"all"},rc={Vertex:"vertex",Instance:"instance"},Rp={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"},Ry={"texture-compression-s3tc":"texture-compression-bc","texture-compression-etc1":"texture-compression-etc2"};class vL extends OS{constructor(e,t,s){super(e,t?t.value:null),this.textureNode=t,this.groupNode=s}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class ML extends PS{constructor(e,t){super(e,t?t.array:null),this._attribute=t,this.isStorageBuffer=!0}get attribute(){return this._attribute}}let wL=0;class CL extends ML{constructor(e,t){super("StorageBuffer_"+wL++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:Nt.READ_WRITE,this.groupNode=t}get attribute(){return this.nodeUniform.value}get buffer(){return this.nodeUniform.value.array}}class AL extends qn{constructor(e){super(),this.device=e;const t=`
206
- struct VarysStruct {
207
- @builtin( position ) Position: vec4f,
208
- @location( 0 ) vTex : vec2f,
209
- @location( 1 ) @interpolate(flat, either) vBaseArrayLayer: u32,
210
- };
211
-
212
- @group( 0 ) @binding ( 2 )
213
- var<uniform> flipY: u32;
214
-
215
- @vertex
216
- fn mainVS(
217
- @builtin( vertex_index ) vertexIndex : u32,
218
- @builtin( instance_index ) instanceIndex : u32 ) -> VarysStruct {
219
-
220
- var Varys : VarysStruct;
221
-
222
- var pos = array(
223
- vec2f( -1, -1 ),
224
- vec2f( -1, 3 ),
225
- vec2f( 3, -1 ),
226
- );
227
-
228
- let p = pos[ vertexIndex ];
229
- let mult = select( vec2f( 0.5, -0.5 ), vec2f( 0.5, 0.5 ), flipY != 0 );
230
- Varys.vTex = p * mult + vec2f( 0.5 );
231
- Varys.Position = vec4f( p, 0, 1 );
232
- Varys.vBaseArrayLayer = instanceIndex;
233
-
234
- return Varys;
235
-
236
- }
237
-
238
- @group( 0 ) @binding( 0 )
239
- var imgSampler : sampler;
240
-
241
- @group( 0 ) @binding( 1 )
242
- var img2d : texture_2d<f32>;
243
-
244
- @fragment
245
- fn main_2d( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {
246
-
247
- return textureSample( img2d, imgSampler, Varys.vTex );
248
-
249
- }
250
-
251
- @group( 0 ) @binding( 1 )
252
- var img2dArray : texture_2d_array<f32>;
253
-
254
- @fragment
255
- fn main_2d_array( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {
256
-
257
- return textureSample( img2dArray, imgSampler, Varys.vTex, Varys.vBaseArrayLayer );
258
-
259
- }
260
-
261
- const faceMat = array(
262
- mat3x3f( 0, 0, -2, 0, -2, 0, 1, 1, 1 ), // pos-x
263
- mat3x3f( 0, 0, 2, 0, -2, 0, -1, 1, -1 ), // neg-x
264
- mat3x3f( 2, 0, 0, 0, 0, 2, -1, 1, -1 ), // pos-y
265
- mat3x3f( 2, 0, 0, 0, 0, -2, -1, -1, 1 ), // neg-y
266
- mat3x3f( 2, 0, 0, 0, -2, 0, -1, 1, 1 ), // pos-z
267
- mat3x3f( -2, 0, 0, 0, -2, 0, 1, 1, -1 ), // neg-z
268
- );
269
-
270
- @group( 0 ) @binding( 1 )
271
- var imgCube : texture_cube<f32>;
272
-
273
- @fragment
274
- fn main_cube( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {
275
-
276
- return textureSample( imgCube, imgSampler, faceMat[ Varys.vBaseArrayLayer ] * vec3f( fract( Varys.vTex ), 1 ) );
277
-
278
- }
279
- `;this.mipmapSampler=e.createSampler({minFilter:mi.Linear}),this.flipYSampler=e.createSampler({minFilter:mi.Nearest}),this.flipUniformBuffer=e.createBuffer({size:4,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),e.queue.writeBuffer(this.flipUniformBuffer,0,new Uint32Array([1])),this.noFlipUniformBuffer=e.createBuffer({size:4,usage:GPUBufferUsage.UNIFORM}),this.transferPipelines={},this.mipmapShaderModule=e.createShaderModule({label:"mipmap",code:t})}getTransferPipeline(e,t){t=t||"2d-array";const s=`${e}-${t}`;let i=this.transferPipelines[s];return i===void 0&&(i=this.device.createRenderPipeline({label:`mipmap-${e}-${t}`,vertex:{module:this.mipmapShaderModule},fragment:{module:this.mipmapShaderModule,entryPoint:`main_${t.replace("-","_")}`,targets:[{format:e}]},layout:"auto"}),this.transferPipelines[s]=i),i}flipY(e,t,s=0){const i=t.format,{width:n,height:a}=t.size,o=this.device.createTexture({size:{width:n,height:a},format:i,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),l=this.getTransferPipeline(i,e.textureBindingViewDimension),c=this.getTransferPipeline(i,o.textureBindingViewDimension),u=this.device.createCommandEncoder({}),h=(d,p,f,m,x,y)=>{const b=d.getBindGroupLayout(0),v=this.device.createBindGroup({layout:b,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:p.createView({dimension:p.textureBindingViewDimension||"2d-array",baseMipLevel:0,mipLevelCount:1})},{binding:2,resource:{buffer:y?this.flipUniformBuffer:this.noFlipUniformBuffer}}]}),S=u.beginRenderPass({colorAttachments:[{view:m.createView({dimension:"2d",baseMipLevel:0,mipLevelCount:1,baseArrayLayer:x,arrayLayerCount:1}),loadOp:De.Clear,storeOp:Ht.Store}]});S.setPipeline(d),S.setBindGroup(0,v),S.draw(3,1,0,f),S.end()};h(l,e,s,o,0,!1),h(c,o,0,e,s,!0),this.device.queue.submit([u.finish()]),o.destroy()}generateMipmaps(e,t=null){const s=this.get(e),i=s.layers||this._mipmapCreateBundles(e),n=t||this.device.createCommandEncoder({label:"mipmapEncoder"});this._mipmapRunBundles(n,i),t===null&&this.device.queue.submit([n.finish()]),s.layers=i}_mipmapCreateBundles(e){const t=e.textureBindingViewDimension||"2d-array",s=this.getTransferPipeline(e.format,t),i=s.getBindGroupLayout(0),n=[];for(let a=1;a<e.mipLevelCount;a++)for(let o=0;o<e.depthOrArrayLayers;o++){const l=this.device.createBindGroup({layout:i,entries:[{binding:0,resource:this.mipmapSampler},{binding:1,resource:e.createView({dimension:t,baseMipLevel:a-1,mipLevelCount:1})},{binding:2,resource:{buffer:this.noFlipUniformBuffer}}]}),c={colorAttachments:[{view:e.createView({dimension:"2d",baseMipLevel:a,mipLevelCount:1,baseArrayLayer:o,arrayLayerCount:1}),loadOp:De.Clear,storeOp:Ht.Store}]},u=this.device.createRenderBundleEncoder({colorFormats:[e.format]});u.setPipeline(s),u.setBindGroup(0,l),u.draw(3,1,0,o),n.push({renderBundles:[u.finish()],passDescriptor:c})}return n}_mipmapRunBundles(e,t){const s=t.length;for(let i=0;i<s;i++){const n=t[i],a=e.beginRenderPass(n.passDescriptor);a.executeBundles(n.renderBundles),a.end()}}}const EL={[Ux]:"never",[$p]:"less",[Vx]:"equal",[Du]:"less-equal",[kx]:"greater",[Ou]:"greater-equal",[Gx]:"always",[zx]:"not-equal"},NL=[0,1,3,2,4,5];class RL{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,s=e.minFilter+"-"+e.magFilter+"-"+e.wrapS+"-"+e.wrapT+"-"+(e.wrapR||"0")+"-"+e.anisotropy+"-"+(e.compareFunction||0);let i=this._samplerCache.get(s);if(i===void 0){const a={addressModeU:this._convertAddressMode(e.wrapS),addressModeV:this._convertAddressMode(e.wrapT),addressModeW:this._convertAddressMode(e.wrapR),magFilter:this._convertFilterMode(e.magFilter),minFilter:this._convertFilterMode(e.minFilter),mipmapFilter:this._convertFilterMode(e.minFilter),maxAnisotropy:1};e.isDepthTexture&&e.compareFunction===null&&(a.magFilter=mi.Nearest,a.minFilter=mi.Nearest,a.mipmapFilter=mi.Nearest),a.magFilter===mi.Linear&&a.minFilter===mi.Linear&&a.mipmapFilter===mi.Linear&&(a.maxAnisotropy=e.anisotropy),e.isDepthTexture&&e.compareFunction!==null&&t.hasCompatibility(Bn.TEXTURE_COMPARE)&&(a.compare=EL[e.compareFunction]),i={sampler:t.device.createSampler(a),usedTimes:0},this._samplerCache.set(s,i)}const n=t.get(e);if(n.sampler!==i.sampler){if(n.sampler!==void 0){const a=this._samplerCache.get(n.samplerKey);a.usedTimes--,a.usedTimes===0&&this._samplerCache.delete(n.samplerKey)}n.samplerKey=s,n.sampler=i.sampler,i.usedTimes++}return s}createDefaultTexture(e){let t;const s=Pp(e);e.isCubeTexture?t=this._getDefaultCubeTextureGPU(s):t=this._getDefaultTextureGPU(s),this.backend.get(e).texture=t}createTexture(e,t={}){const s=this.backend,i=s.get(e);if(i.initialized)throw new Error("WebGPUTextureUtils: Texture already initialized.");if(e.isExternalTexture){i.texture=e.sourceTexture,i.initialized=!0;return}t.needsMipmaps===void 0&&(t.needsMipmaps=!1),t.levels===void 0&&(t.levels=1),t.depth===void 0&&(t.depth=1);const{width:n,height:a,depth:o,levels:l}=t;e.isFramebufferTexture&&(t.renderTarget?t.format=this.backend.utils.getCurrentColorFormat(t.renderTarget):t.format=this.backend.utils.getPreferredCanvasFormat());const c=this._getDimension(e),u=e.internalFormat||t.format||Pp(e,s.device);i.format=u;const{samples:h,primarySamples:d,isMSAA:p}=s.utils.getTextureSampleData(e);let f=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC;e.isStorageTexture===!0&&(f|=GPUTextureUsage.STORAGE_BINDING),e.isCompressedTexture!==!0&&e.isCompressedArrayTexture!==!0&&u!==N.RGB9E5UFloat&&(f|=GPUTextureUsage.RENDER_ATTACHMENT);const m={label:e.name,size:{width:n,height:a,depthOrArrayLayers:o},mipLevelCount:l,sampleCount:d,dimension:c,format:u,usage:f};if(u===void 0){W("WebGPURenderer: Texture format not supported."),this.createDefaultTexture(e);return}e.isCubeTexture&&(m.textureBindingViewDimension=Ot.Cube);try{i.texture=s.device.createTexture(m)}catch{W("WebGPURenderer: Failed to create texture with descriptor:",m),this.createDefaultTexture(e);return}if(p){const x=Object.assign({},m);x.label=x.label+"-msaa",x.sampleCount=h,x.mipLevelCount=1,i.msaaTexture=s.device.createTexture(x)}i.initialized=!0,i.textureDescriptorGPU=m}destroyTexture(e,t=!1){const s=this.backend,i=s.get(e);i.texture!==void 0&&t===!1&&i.texture.destroy(),i.msaaTexture!==void 0&&i.msaaTexture.destroy(),s.delete(e)}generateMipmaps(e,t=null){const s=this.backend.get(e);this._generateMipmaps(s.texture,t)}getColorBuffer(){const e=this.backend,t=e.renderer.getCanvasTarget(),{width:s,height:i}=e.getDrawingBufferSize(),n=e.renderer.currentSamples,a=t.colorTexture,o=e.get(a);if(a.width===s&&a.height===i&&a.samples===n)return o.texture;let l=o.texture;return l&&l.destroy(),l=e.device.createTexture({label:"colorBuffer",size:{width:s,height:i,depthOrArrayLayers:1},sampleCount:e.utils.getSampleCount(e.renderer.currentSamples),format:e.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC}),a.source.width=s,a.source.height=i,a.samples=n,o.texture=l,l}getDepthBuffer(e=!0,t=!1){const s=this.backend,i=s.renderer.getCanvasTarget(),{width:n,height:a}=s.getDrawingBufferSize(),o=s.renderer.currentSamples,l=i.depthTexture;if(l.width===n&&l.height===a&&l.samples===o&&l.depth===e&&l.stencil===t)return s.get(l).texture;const c=s.get(l).texture;let u,h;if(t?(u=Yi,h=Fn):e&&(u=Qs,h=rt),c!==void 0){if(l.image.width===n&&l.image.height===a&&l.format===u&&l.type===h&&l.samples===o)return c;this.destroyTexture(l)}return l.name="depthBuffer",l.format=u,l.type=h,l.image.width=n,l.image.height=a,l.samples=o,this.createTexture(l,{width:n,height:a}),s.get(l).texture}updateTexture(e,t){const s=this.backend.get(e),i=e.mipmaps,{textureDescriptorGPU:n}=s;if(!(e.isRenderTargetTexture||n===void 0)){if(e.isDataTexture)if(i.length>0)for(let a=0,o=i.length;a<o;a++){const l=i[a];this._copyBufferToTexture(l,s.texture,n,0,e.flipY,0,a)}else this._copyBufferToTexture(t.image,s.texture,n,0,e.flipY);else if(e.isArrayTexture||e.isDataArrayTexture||e.isData3DTexture)for(let a=0;a<t.image.depth;a++)this._copyBufferToTexture(t.image,s.texture,n,a,e.flipY,a);else if(e.isCompressedTexture||e.isCompressedArrayTexture)this._copyCompressedBufferToTexture(e.mipmaps,s.texture,n);else if(e.isCubeTexture)this._copyCubeMapToTexture(e,s.texture,n);else if(i.length>0)for(let a=0,o=i.length;a<o;a++){const l=i[a];this._copyImageToTexture(l,s.texture,n,0,e.flipY,e.premultiplyAlpha,a)}else this._copyImageToTexture(t.image,s.texture,n,0,e.flipY,e.premultiplyAlpha);s.version=e.version}}async copyTextureToBuffer(e,t,s,i,n,a){const o=this.backend.device,l=this.backend.get(e),c=l.texture,u=l.textureDescriptorGPU.format,h=this._getBytesPerTexel(u);let d=i*h;d=Math.ceil(d/256)*256;const p=o.createBuffer({size:(n-1)*d+i*h,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),f=o.createCommandEncoder();f.copyTextureToBuffer({texture:c,origin:{x:t,y:s,z:a}},{buffer:p,bytesPerRow:d},{width:i,height:n});const m=this._getTypedArrayType(u);o.queue.submit([f.finish()]),await p.mapAsync(GPUMapMode.READ);const x=p.getMappedRange();return new m(x)}dispose(){this._samplerCache.clear()}_getDefaultTextureGPU(e){let t=this.defaultTexture[e];if(t===void 0){const s=new kt;s.minFilter=at,s.magFilter=at,this.createTexture(s,{width:1,height:1,format:e}),this.defaultTexture[e]=t=s}return this.backend.get(t).texture}_getDefaultCubeTextureGPU(e){let t=this.defaultCubeTexture[e];if(t===void 0){const s=new Iu;s.minFilter=at,s.magFilter=at,this.createTexture(s,{width:1,height:1,depth:6}),this.defaultCubeTexture[e]=t=s}return this.backend.get(t).texture}_copyCubeMapToTexture(e,t,s){const i=e.images,n=e.mipmaps;for(let a=0;a<6;a++){const o=i[a],l=e.flipY===!0?NL[a]:a;o.isDataTexture?this._copyBufferToTexture(o.image,t,s,l,e.flipY):this._copyImageToTexture(o,t,s,l,e.flipY,e.premultiplyAlpha);for(let c=0;c<n.length;c++){const h=n[c].images[a];h.isDataTexture?this._copyBufferToTexture(h.image,t,s,l,e.flipY,0,c+1):this._copyImageToTexture(h,t,s,l,e.flipY,e.premultiplyAlpha,c+1)}}}_copyImageToTexture(e,t,s,i,n,a,o=0){const l=this.backend.device,c=o>0?e.width:s.size.width,u=o>0?e.height:s.size.height;try{l.queue.copyExternalImageToTexture({source:e,flipY:n},{texture:t,mipLevel:o,origin:{x:0,y:0,z:i},premultipliedAlpha:a},{width:c,height:u,depthOrArrayLayers:1})}catch{}}_getPassUtils(){let e=this._passUtils;return e===null&&(this._passUtils=e=new AL(this.backend.device)),e}_generateMipmaps(e,t=null){this._getPassUtils().generateMipmaps(e,t)}_flipY(e,t,s=0){this._getPassUtils().flipY(e,t,s)}_copyBufferToTexture(e,t,s,i,n,a=0,o=0){const l=this.backend.device,c=e.data,u=this._getBytesPerTexel(s.format),h=e.width*u;l.queue.writeTexture({texture:t,mipLevel:o,origin:{x:0,y:0,z:i}},c,{offset:e.width*e.height*u*a,bytesPerRow:h},{width:e.width,height:e.height,depthOrArrayLayers:1}),n===!0&&this._flipY(t,s,i)}_copyCompressedBufferToTexture(e,t,s){const i=this.backend.device,n=this._getBlockData(s.format),a=s.size.depthOrArrayLayers>1;for(let o=0;o<e.length;o++){const l=e[o],c=l.width,u=l.height,h=a?s.size.depthOrArrayLayers:1,d=Math.ceil(c/n.width)*n.byteLength,p=d*Math.ceil(u/n.height);for(let f=0;f<h;f++)i.queue.writeTexture({texture:t,mipLevel:o,origin:{x:0,y:0,z:f}},l.data,{offset:f*p,bytesPerRow:d,rowsPerImage:Math.ceil(u/n.height)},{width:Math.ceil(c/n.width)*n.width,height:Math.ceil(u/n.height)*n.height,depthOrArrayLayers:1})}}_getBlockData(e){if(e===N.BC1RGBAUnorm||e===N.BC1RGBAUnormSRGB)return{byteLength:8,width:4,height:4};if(e===N.BC2RGBAUnorm||e===N.BC2RGBAUnormSRGB)return{byteLength:16,width:4,height:4};if(e===N.BC3RGBAUnorm||e===N.BC3RGBAUnormSRGB)return{byteLength:16,width:4,height:4};if(e===N.BC4RUnorm||e===N.BC4RSnorm)return{byteLength:8,width:4,height:4};if(e===N.BC5RGUnorm||e===N.BC5RGSnorm)return{byteLength:16,width:4,height:4};if(e===N.BC6HRGBUFloat||e===N.BC6HRGBFloat)return{byteLength:16,width:4,height:4};if(e===N.BC7RGBAUnorm||e===N.BC7RGBAUnormSRGB)return{byteLength:16,width:4,height:4};if(e===N.ETC2RGB8Unorm||e===N.ETC2RGB8UnormSRGB)return{byteLength:8,width:4,height:4};if(e===N.ETC2RGB8A1Unorm||e===N.ETC2RGB8A1UnormSRGB)return{byteLength:8,width:4,height:4};if(e===N.ETC2RGBA8Unorm||e===N.ETC2RGBA8UnormSRGB)return{byteLength:16,width:4,height:4};if(e===N.EACR11Unorm)return{byteLength:8,width:4,height:4};if(e===N.EACR11Snorm)return{byteLength:8,width:4,height:4};if(e===N.EACRG11Unorm)return{byteLength:16,width:4,height:4};if(e===N.EACRG11Snorm)return{byteLength:16,width:4,height:4};if(e===N.ASTC4x4Unorm||e===N.ASTC4x4UnormSRGB)return{byteLength:16,width:4,height:4};if(e===N.ASTC5x4Unorm||e===N.ASTC5x4UnormSRGB)return{byteLength:16,width:5,height:4};if(e===N.ASTC5x5Unorm||e===N.ASTC5x5UnormSRGB)return{byteLength:16,width:5,height:5};if(e===N.ASTC6x5Unorm||e===N.ASTC6x5UnormSRGB)return{byteLength:16,width:6,height:5};if(e===N.ASTC6x6Unorm||e===N.ASTC6x6UnormSRGB)return{byteLength:16,width:6,height:6};if(e===N.ASTC8x5Unorm||e===N.ASTC8x5UnormSRGB)return{byteLength:16,width:8,height:5};if(e===N.ASTC8x6Unorm||e===N.ASTC8x6UnormSRGB)return{byteLength:16,width:8,height:6};if(e===N.ASTC8x8Unorm||e===N.ASTC8x8UnormSRGB)return{byteLength:16,width:8,height:8};if(e===N.ASTC10x5Unorm||e===N.ASTC10x5UnormSRGB)return{byteLength:16,width:10,height:5};if(e===N.ASTC10x6Unorm||e===N.ASTC10x6UnormSRGB)return{byteLength:16,width:10,height:6};if(e===N.ASTC10x8Unorm||e===N.ASTC10x8UnormSRGB)return{byteLength:16,width:10,height:8};if(e===N.ASTC10x10Unorm||e===N.ASTC10x10UnormSRGB)return{byteLength:16,width:10,height:10};if(e===N.ASTC12x10Unorm||e===N.ASTC12x10UnormSRGB)return{byteLength:16,width:12,height:10};if(e===N.ASTC12x12Unorm||e===N.ASTC12x12UnormSRGB)return{byteLength:16,width:12,height:12}}_convertAddressMode(e){let t=Cd.ClampToEdge;return e===Aa?t=Cd.Repeat:e===Ea&&(t=Cd.MirrorRepeat),t}_convertFilterMode(e){let t=mi.Linear;return(e===at||e===Bx||e===zo)&&(t=mi.Nearest),t}_getBytesPerTexel(e){if(e===N.R8Unorm||e===N.R8Snorm||e===N.R8Uint||e===N.R8Sint)return 1;if(e===N.R16Uint||e===N.R16Sint||e===N.R16Float||e===N.RG8Unorm||e===N.RG8Snorm||e===N.RG8Uint||e===N.RG8Sint)return 2;if(e===N.R32Uint||e===N.R32Sint||e===N.R32Float||e===N.RG16Uint||e===N.RG16Sint||e===N.RG16Float||e===N.RGBA8Unorm||e===N.RGBA8UnormSRGB||e===N.RGBA8Snorm||e===N.RGBA8Uint||e===N.RGBA8Sint||e===N.BGRA8Unorm||e===N.BGRA8UnormSRGB||e===N.RGB9E5UFloat||e===N.RGB10A2Unorm||e===N.RG11B10UFloat||e===N.Depth32Float||e===N.Depth24Plus||e===N.Depth24PlusStencil8||e===N.Depth32FloatStencil8)return 4;if(e===N.RG32Uint||e===N.RG32Sint||e===N.RG32Float||e===N.RGBA16Uint||e===N.RGBA16Sint||e===N.RGBA16Float)return 8;if(e===N.RGBA32Uint||e===N.RGBA32Sint||e===N.RGBA32Float)return 16}_getTypedArrayType(e){if(e===N.R8Uint)return Uint8Array;if(e===N.R8Sint)return Int8Array;if(e===N.R8Unorm)return Uint8Array;if(e===N.R8Snorm)return Int8Array;if(e===N.RG8Uint)return Uint8Array;if(e===N.RG8Sint)return Int8Array;if(e===N.RG8Unorm)return Uint8Array;if(e===N.RG8Snorm)return Int8Array;if(e===N.RGBA8Uint)return Uint8Array;if(e===N.RGBA8Sint)return Int8Array;if(e===N.RGBA8Unorm||e===N.RGBA8UnormSRGB)return Uint8Array;if(e===N.RGBA8Snorm)return Int8Array;if(e===N.R16Uint)return Uint16Array;if(e===N.R16Sint)return Int16Array;if(e===N.RG16Uint)return Uint16Array;if(e===N.RG16Sint)return Int16Array;if(e===N.RGBA16Uint)return Uint16Array;if(e===N.RGBA16Sint)return Int16Array;if(e===N.R16Float||e===N.RG16Float||e===N.RGBA16Float)return Uint16Array;if(e===N.R32Uint)return Uint32Array;if(e===N.R32Sint)return Int32Array;if(e===N.R32Float)return Float32Array;if(e===N.RG32Uint)return Uint32Array;if(e===N.RG32Sint)return Int32Array;if(e===N.RG32Float)return Float32Array;if(e===N.RGBA32Uint)return Uint32Array;if(e===N.RGBA32Sint)return Int32Array;if(e===N.RGBA32Float)return Float32Array;if(e===N.BGRA8Unorm||e===N.BGRA8UnormSRGB)return Uint8Array;if(e===N.RGB10A2Unorm||e===N.RGB9E5UFloat||e===N.RG11B10UFloat)return Uint32Array;if(e===N.Depth32Float)return Float32Array;if(e===N.Depth24Plus||e===N.Depth24PlusStencil8)return Uint32Array;if(e===N.Depth32FloatStencil8)return Float32Array}_getDimension(e){let t;return e.is3DTexture||e.isData3DTexture?t=Ny.ThreeD:t=Ny.TwoD,t}}function Pp(r,e=null){const t=r.format,s=r.type,i=r.colorSpace,n=Ae.getTransfer(i);let a;if(r.isCompressedTexture===!0||r.isCompressedArrayTexture===!0)switch(t){case Mo:case wo:a=n===ce?N.BC1RGBAUnormSRGB:N.BC1RGBAUnorm;break;case Co:a=n===ce?N.BC2RGBAUnormSRGB:N.BC2RGBAUnorm;break;case Ao:a=n===ce?N.BC3RGBAUnormSRGB:N.BC3RGBAUnorm;break;case su:a=N.BC4RUnorm;break;case iu:a=N.BC4RSnorm;break;case $o:a=N.BC5RGUnorm;break;case nu:a=N.BC5RGSnorm;break;case tu:a=n===ce?N.BC7RGBAUnormSRGB:N.BC7RGBAUnorm;break;case Lc:case Oc:a=n===ce?N.ETC2RGB8UnormSRGB:N.ETC2RGB8Unorm;break;case Ic:a=n===ce?N.ETC2RGBA8UnormSRGB:N.ETC2RGBA8Unorm;break;case Uc:a=N.EACR11Unorm;break;case Vc:a=N.EACR11Snorm;break;case Go:a=N.EACRG11Unorm;break;case kc:a=N.EACRG11Snorm;break;case zc:a=n===ce?N.ASTC4x4UnormSRGB:N.ASTC4x4Unorm;break;case Gc:a=n===ce?N.ASTC5x4UnormSRGB:N.ASTC5x4Unorm;break;case $c:a=n===ce?N.ASTC5x5UnormSRGB:N.ASTC5x5Unorm;break;case Wc:a=n===ce?N.ASTC6x5UnormSRGB:N.ASTC6x5Unorm;break;case Hc:a=n===ce?N.ASTC6x6UnormSRGB:N.ASTC6x6Unorm;break;case jc:a=n===ce?N.ASTC8x5UnormSRGB:N.ASTC8x5Unorm;break;case qc:a=n===ce?N.ASTC8x6UnormSRGB:N.ASTC8x6Unorm;break;case Xc:a=n===ce?N.ASTC8x8UnormSRGB:N.ASTC8x8Unorm;break;case Yc:a=n===ce?N.ASTC10x5UnormSRGB:N.ASTC10x5Unorm;break;case Zc:a=n===ce?N.ASTC10x6UnormSRGB:N.ASTC10x6Unorm;break;case Qc:a=n===ce?N.ASTC10x8UnormSRGB:N.ASTC10x8Unorm;break;case Kc:a=n===ce?N.ASTC10x10UnormSRGB:N.ASTC10x10Unorm;break;case Jc:a=n===ce?N.ASTC12x10UnormSRGB:N.ASTC12x10Unorm;break;case eu:a=n===ce?N.ASTC12x12UnormSRGB:N.ASTC12x12Unorm;break;case ms:a=n===ce?N.RGBA8UnormSRGB:N.RGBA8Unorm;break;default:$("WebGPURenderer: Unsupported texture format.",t)}else switch(t){case ms:switch(s){case ga:a=N.RGBA8Snorm;break;case ya:a=N.RGBA16Sint;break;case pr:a=N.RGBA16Uint;break;case rt:a=N.RGBA32Uint;break;case Lt:a=N.RGBA32Sint;break;case Ut:a=n===ce?N.RGBA8UnormSRGB:N.RGBA8Unorm;break;case Et:a=N.RGBA16Float;break;case es:a=N.RGBA32Float;break;default:$("WebGPURenderer: Unsupported texture type with RGBAFormat.",s)}break;case Nu:switch(s){case zp:a=N.RGB9E5UFloat;break;case Gp:a=N.RG11B10UFloat;break;default:$("WebGPURenderer: Unsupported texture type with RGBFormat.",s)}break;case Ru:switch(s){case ga:a=N.R8Snorm;break;case ya:a=N.R16Sint;break;case pr:a=N.R16Uint;break;case rt:a=N.R32Uint;break;case Lt:a=N.R32Sint;break;case Ut:a=N.R8Unorm;break;case Et:a=N.R16Float;break;case es:a=N.R32Float;break;default:$("WebGPURenderer: Unsupported texture type with RedFormat.",s)}break;case _i:switch(s){case ga:a=N.RG8Snorm;break;case ya:a=N.RG16Sint;break;case pr:a=N.RG16Uint;break;case rt:a=N.RG32Uint;break;case Lt:a=N.RG32Sint;break;case Ut:a=N.RG8Unorm;break;case Et:a=N.RG16Float;break;case es:a=N.RG32Float;break;default:$("WebGPURenderer: Unsupported texture type with RGFormat.",s)}break;case Qs:switch(s){case pr:a=N.Depth16Unorm;break;case rt:a=N.Depth24Plus;break;case es:a=N.Depth32Float;break;default:$("WebGPURenderer: Unsupported texture type with DepthFormat.",s)}break;case Yi:switch(s){case Fn:a=N.Depth24PlusStencil8;break;case es:e&&e.features.has(Rp.Depth32FloatStencil8)===!1&&$('WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.'),a=N.Depth32FloatStencil8;break;default:$("WebGPURenderer: Unsupported texture type with DepthStencilFormat.",s)}break;case Pu:switch(s){case Lt:a=N.R32Sint;break;case rt:a=N.R32Uint;break;default:$("WebGPURenderer: Unsupported texture type with RedIntegerFormat.",s)}break;case Fu:switch(s){case Lt:a=N.RG32Sint;break;case rt:a=N.RG32Uint;break;default:$("WebGPURenderer: Unsupported texture type with RGIntegerFormat.",s)}break;case Bu:switch(s){case Lt:a=N.RGBA32Sint;break;case rt:a=N.RGBA32Uint;break;default:$("WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.",s)}break;default:$("WebGPURenderer: Unsupported texture format.",t)}return a}const PL=/^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,FL=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig,Py={f32:"float",i32:"int",u32:"uint",bool:"bool","vec2<f32>":"vec2","vec2<i32>":"ivec2","vec2<u32>":"uvec2","vec2<bool>":"bvec2",vec2f:"vec2",vec2i:"ivec2",vec2u:"uvec2",vec2b:"bvec2","vec3<f32>":"vec3","vec3<i32>":"ivec3","vec3<u32>":"uvec3","vec3<bool>":"bvec3",vec3f:"vec3",vec3i:"ivec3",vec3u:"uvec3",vec3b:"bvec3","vec4<f32>":"vec4","vec4<i32>":"ivec4","vec4<u32>":"uvec4","vec4<bool>":"bvec4",vec4f:"vec4",vec4i:"ivec4",vec4u:"uvec4",vec4b:"bvec4","mat2x2<f32>":"mat2",mat2x2f:"mat2","mat3x3<f32>":"mat3",mat3x3f:"mat3","mat4x4<f32>":"mat4",mat4x4f:"mat4",sampler:"sampler",texture_1d:"texture",texture_2d:"texture",texture_2d_array:"texture",texture_multisampled_2d:"cubeTexture",texture_depth_2d:"depthTexture",texture_depth_2d_array:"depthTexture",texture_depth_multisampled_2d:"depthTexture",texture_depth_cube:"depthTexture",texture_depth_cube_array:"depthTexture",texture_3d:"texture3D",texture_cube:"cubeTexture",texture_cube_array:"cubeTexture",texture_storage_1d:"storageTexture",texture_storage_2d:"storageTexture",texture_storage_2d_array:"storageTexture",texture_storage_3d:"storageTexture"},BL=r=>{r=r.trim();const e=r.match(PL);if(e!==null&&e.length===4){const t=e[2],s=[];let i=null;for(;(i=FL.exec(t))!==null;)s.push({name:i[1],type:i[2]});const n=[];for(let u=0;u<s.length;u++){const{name:h,type:d}=s[u];let p=d;p.startsWith("ptr")?p="pointer":(p.startsWith("texture")&&(p=d.split("<")[0]),p=Py[p]),n.push(new Pm(p,h))}const a=r.substring(e[0].length),o=e[3]||"void",l=e[1]!==void 0?e[1]:"";return{type:Py[o]||o,inputs:n,name:l,inputsCode:t,blockCode:a,outputType:o}}else throw new Error("FunctionNode: Function is not a WGSL code.")};class DL extends Bm{constructor(e){const{type:t,inputs:s,name:i,inputsCode:n,blockCode:a,outputType:o}=BL(e);super(t,s,i),this.inputsCode=n,this.blockCode=a,this.outputType=o}getCode(e=this.name){const t=this.outputType!=="void"?"-> "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class OL extends ES{parseFunction(e){return new DL(e)}}const LL={[Nt.READ_ONLY]:"read",[Nt.WRITE_ONLY]:"write",[Nt.READ_WRITE]:"read_write"},Fy={[Aa]:"repeat",[xi]:"clamp",[Ea]:"mirror"},Nd={vertex:Ti.VERTEX,fragment:Ti.FRAGMENT,compute:Ti.COMPUTE},By={instance:!0,swizzleAssign:!1,storageBuffer:!0},IL={"^^":"tsl_xor"},UL={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>"},Dy={},ao={tsl_xor:new _t("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new _t("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new _t("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new _t("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new _t("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new _t("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new _t("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new _t("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 _t("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 _t("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new _t("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 _t("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new _t(`
280
- fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
281
-
282
- let res = vec2f( iRes );
283
-
284
- let uvScaled = coord * res;
285
- let uvWrapping = ( ( uvScaled % res ) + res ) % res;
286
-
287
- // https://www.shadertoy.com/view/WtyXRy
288
-
289
- let uv = uvWrapping - 0.5;
290
- let iuv = floor( uv );
291
- let f = fract( uv );
292
-
293
- let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
294
- let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
295
- let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
296
- let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
297
-
298
- return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
299
-
300
- }
301
- `),biquadraticTextureArray:new _t(`
302
- fn tsl_biquadraticTexture_array( map : texture_2d_array<f32>, coord : vec2f, iRes : vec2u, layer : u32, level : u32 ) -> vec4f {
303
-
304
- let res = vec2f( iRes );
305
-
306
- let uvScaled = coord * res;
307
- let uvWrapping = ( ( uvScaled % res ) + res ) % res;
308
-
309
- // https://www.shadertoy.com/view/WtyXRy
310
-
311
- let uv = uvWrapping - 0.5;
312
- let iuv = floor( uv );
313
- let f = fract( uv );
314
-
315
- let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, layer, level );
316
- let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, layer, level );
317
- let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, layer, level );
318
- let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, layer, level );
319
-
320
- return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
321
-
322
- }
323
- `)},VL={dFdx:"dpdx",dFdy:"- dpdy",mod_float:"tsl_mod_float",mod_vec2:"tsl_mod_vec2",mod_vec3:"tsl_mod_vec3",mod_vec4:"tsl_mod_vec4",equals_bool:"tsl_equals_bool",equals_bvec2:"tsl_equals_bvec2",equals_bvec3:"tsl_equals_bvec3",equals_bvec4:"tsl_equals_bvec4",inversesqrt:"inverseSqrt",bitcast:"bitcast<f32>",floatpack_snorm_2x16:"pack2x16snorm",floatpack_unorm_2x16:"pack2x16unorm",floatpack_float16_2x16:"pack2x16float",floatunpack_snorm_2x16:"unpack2x16snorm",floatunpack_unorm_2x16:"unpack2x16unorm",floatunpack_float16_2x16:"unpack2x16float"};let VS="";(typeof navigator<"u"&&/Firefox|Deno/g.test(navigator.userAgent))!==!0&&(VS+=`diagnostic( off, derivative_uniformity );
324
- `);class kL extends AS{constructor(e,t){super(e,t,new OL),this.uniformGroups={},this.uniformGroupsBindings={},this.builtins={},this.directives={},this.scopedArrays=new Map}_generateTextureSample(e,t,s,i,n,a=this.shaderStage){return a==="fragment"?i?n?`textureSample( ${t}, ${t}_sampler, ${s}, ${i}, ${n} )`:`textureSample( ${t}, ${t}_sampler, ${s}, ${i} )`:n?`textureSample( ${t}, ${t}_sampler, ${s}, ${n} )`:`textureSample( ${t}, ${t}_sampler, ${s} )`:this.generateTextureSampleLevel(e,t,s,"0",i)}generateTextureSampleLevel(e,t,s,i,n,a){return this.isUnfilterable(e)===!1?n?a?`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${n}, ${i}, ${a} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${n}, ${i} )`:a?`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i}, ${a} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,s,a,i,n):this.generateTextureLod(e,t,s,n,a,i)}generateWrapFunction(e){const t=`tsl_coord_${Fy[e.wrapS]}S_${Fy[e.wrapT]}_${e.is3DTexture||e.isData3DTexture?"3d":"2d"}T`;let s=Dy[t];if(s===void 0){const i=[],n=e.is3DTexture||e.isData3DTexture?"vec3f":"vec2f";let a=`fn ${t}( coord : ${n} ) -> ${n} {
325
-
326
- return ${n}(
327
- `;const o=(l,c)=>{l===Aa?(i.push(ao.repeatWrapping_float),a+=` tsl_repeatWrapping_float( coord.${c} )`):l===xi?(i.push(ao.clampWrapping_float),a+=` tsl_clampWrapping_float( coord.${c} )`):l===Ea?(i.push(ao.mirrorWrapping_float),a+=` tsl_mirrorWrapping_float( coord.${c} )`):(a+=` coord.${c}`,W(`WebGPURenderer: Unsupported texture wrap type "${l}" for vertex shader.`))};o(e.wrapS,"x"),a+=`,
328
- `,o(e.wrapT,"y"),(e.is3DTexture||e.isData3DTexture)&&(a+=`,
329
- `,o(e.wrapR,"z")),a+=`
330
- );
331
-
332
- }
333
- `,Dy[t]=s=new _t(a,i)}return s.build(this),t}generateArrayDeclaration(e,t){return`array< ${this.getType(e)}, ${t} >`}generateTextureDimension(e,t,s){const i=this.getDataFromNode(e,this.shaderStage,this.globalCache);i.dimensionsSnippet===void 0&&(i.dimensionsSnippet={});let n=i.dimensionsSnippet[s];if(i.dimensionsSnippet[s]===void 0){let a,o;const{primarySamples:l}=this.renderer.backend.utils.getTextureSampleData(e),c=l>1;e.is3DTexture||e.isData3DTexture?o="vec3<u32>":o="vec2<u32>",c||e.isStorageTexture?a=t:a=`${t}${s?`, u32( ${s} )`:""}`,n=new _c(new bc(`textureDimensions( ${a} )`,o)),i.dimensionsSnippet[s]=n,(e.isArrayTexture||e.isDataArrayTexture||e.is3DTexture||e.isData3DTexture)&&(i.arrayLayerCount=new _c(new bc(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(i.cubeFaceCount=new _c(new bc("6u","u32")))}return n.build(this)}generateFilteredTexture(e,t,s,i,n="0u",a){const o=this.generateWrapFunction(e),l=this.generateTextureDimension(e,t,n);return i&&(s=`${s} + vec2<f32>(${i}) / ${l}`),a?(this._include("biquadraticTextureArray"),`tsl_biquadraticTexture_array( ${t}, ${o}( ${s} ), ${l}, u32( ${a} ), u32( ${n} ) )`):(this._include("biquadraticTexture"),`tsl_biquadraticTexture( ${t}, ${o}( ${s} ), ${l}, u32( ${n} ) )`)}generateTextureLod(e,t,s,i,n,a="0u"){if(e.isCubeTexture===!0){n&&(s=`${s} + vec3<f32>(${n})`);const p=e.isDepthTexture?"u32":"f32";return`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${p}( ${a} ) )`}const o=this.generateWrapFunction(e),l=this.generateTextureDimension(e,t,a),c=e.is3DTexture||e.isData3DTexture?"vec3":"vec2",u=c==="vec3"?"vec3<u32>( 1, 1, 1 )":"vec2<u32>( 1, 1 )";n&&(s=`${s} + ${c}<f32>(${n}) / ${c}<f32>( ${l} )`);const h=`${c}<f32>( 0 )`,d=`${c}<f32>( ${l} - ${u} )`;return s=`${c}<u32>( clamp( floor( ${o}( ${s} ) * ${c}<f32>( ${l} ) ), ${h}, ${d} ) )`,this.generateTextureLoad(e,t,s,a,i,null)}generateStorageTextureLoad(e,t,s,i,n,a){a&&(s=`${s} + ${a}`);let o;return n?o=`textureLoad( ${t}, ${s}, ${n} )`:o=`textureLoad( ${t}, ${s} )`,o}generateTextureLoad(e,t,s,i,n,a){i===null&&(i="0u"),a&&(s=`${s} + ${a}`);let o;return n?o=`textureLoad( ${t}, ${s}, ${n}, u32( ${i} ) )`:(o=`textureLoad( ${t}, ${s}, u32( ${i} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(o+=".x")),o}generateTextureStore(e,t,s,i,n){let a;return i?a=`textureStore( ${t}, ${s}, ${i}, ${n} )`:a=`textureStore( ${t}, ${s}, ${n} )`,a}isSampleCompare(e){return e.isDepthTexture===!0&&e.compareFunction!==null&&this.renderer.hasCompatibility(Bn.TEXTURE_COMPARE)}isUnfilterable(e){return this.getComponentTypeFromTexture(e)!=="float"||!this.isAvailable("float32Filterable")&&e.isDataTexture===!0&&e.type===es||this.isSampleCompare(e)===!1&&e.minFilter===at&&e.magFilter===at||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1}generateTexture(e,t,s,i,n,a=this.shaderStage){let o=null;return this.isUnfilterable(e)?o=this.generateTextureLod(e,t,s,i,n,"0",a):o=this._generateTextureSample(e,t,s,i,n,a),o}generateTextureGrad(e,t,s,i,n,a,o=this.shaderStage){if(o==="fragment")return n?a?`textureSampleGrad( ${t}, ${t}_sampler, ${s}, ${n}, ${i[0]}, ${i[1]}, ${a} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${s}, ${n}, ${i[0]}, ${i[1]} )`:a?`textureSampleGrad( ${t}, ${t}_sampler, ${s}, ${i[0]}, ${i[1]}, ${a} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${s}, ${i[0]}, ${i[1]} )`;$(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${o} shader.`)}generateTextureCompare(e,t,s,i,n,a,o=this.shaderStage){if(o==="fragment")return e.isDepthTexture===!0&&e.isArrayTexture===!0?a?`textureSampleCompare( ${t}, ${t}_sampler, ${s}, ${n}, ${i}, ${a} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${s}, ${n}, ${i} )`:a?`textureSampleCompare( ${t}, ${t}_sampler, ${s}, ${i}, ${a} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${s}, ${i} )`;$(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${o} shader.`)}generateTextureLevel(e,t,s,i,n,a){return this.isUnfilterable(e)===!1?n?a?`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${n}, ${i}, ${a} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${n}, ${i} )`:a?`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i}, ${a} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,s,a,i,n):this.generateTextureLod(e,t,s,n,a,i)}generateTextureBias(e,t,s,i,n,a,o=this.shaderStage){if(o==="fragment")return n?a?`textureSampleBias( ${t}, ${t}_sampler, ${s}, ${n}, ${i}, ${a} )`:`textureSampleBias( ${t}, ${t}_sampler, ${s}, ${n}, ${i} )`:a?`textureSampleBias( ${t}, ${t}_sampler, ${s}, ${i}, ${a} )`:`textureSampleBias( ${t}, ${t}_sampler, ${s}, ${i} )`;$(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${o} shader.`)}getPropertyName(e,t=this.shaderStage){if(e.isNodeVarying===!0&&e.needsInterpolation===!0){if(t==="vertex")return`varyings.${e.name}`}else if(e.isNodeUniform===!0){const s=e.name,i=e.type;return i==="texture"||i==="cubeTexture"||i==="cubeDepthTexture"||i==="storageTexture"||i==="texture3D"?s:i==="buffer"||i==="storageBuffer"||i==="indirectStorageBuffer"?this.isCustomStruct(e)?s:s+".value":e.groupNode.name+"."+s}return super.getPropertyName(e)}getOutputStructName(){return"output"}getFunctionOperator(e){const t=IL[e];return t!==void 0?(this._include(t),t):null}getNodeAccess(e,t){return t!=="compute"?e.isAtomic===!0?(W("WebGPURenderer: Atomic operations are only supported in compute shaders."),Nt.READ_WRITE):Nt.READ_ONLY:e.access}getStorageAccess(e,t){return LL[this.getNodeAccess(e,t)]}getUniformFromNode(e,t,s,i=null){const n=super.getUniformFromNode(e,t,s,i),a=this.getDataFromNode(e,s,this.globalCache);if(a.uniformGPU===void 0){let o;const l=e.groupNode,c=l.name,u=this.getBindGroupArray(c,s);if(t==="texture"||t==="cubeTexture"||t==="cubeDepthTexture"||t==="storageTexture"||t==="texture3D"){let h=null;const d=this.getNodeAccess(e,s);if(t==="texture"||t==="storageTexture"?e.value.is3DTexture===!0?h=new Np(n.name,n.node,l,d):h=new gh(n.name,n.node,l,d):t==="cubeTexture"||t==="cubeDepthTexture"?h=new LS(n.name,n.node,l,d):t==="texture3D"&&(h=new Np(n.name,n.node,l,d)),h.store=e.isStorageTextureNode===!0,h.mipLevel=h.store?e.mipLevel:0,h.setVisibility(Nd[s]),e.value.isCubeTexture===!0||this.isUnfilterable(e.value)===!1&&h.store===!1){const f=new vL(`${n.name}_sampler`,n.node,l);f.setVisibility(Nd[s]),u.push(f,h),o=[f,h]}else u.push(h),o=[h]}else if(t==="buffer"||t==="storageBuffer"||t==="indirectStorageBuffer"){const h=this.getSharedDataFromNode(e);let d=h.buffer;if(d===void 0){const p=t==="buffer"?BS:CL;d=new p(e,l),h.buffer=d}d.setVisibility(d.getVisibility()|Nd[s]),u.push(d),o=d,n.name=i||"NodeBuffer_"+n.id}else{let h=this.uniformGroups[c];h===void 0&&(h=new DS(c,l),h.setVisibility(Ti.VERTEX|Ti.FRAGMENT|Ti.COMPUTE),this.uniformGroups[c]=h),u.indexOf(h)===-1&&u.push(h),o=this.getNodeUniform(n,t);const d=o.name;h.uniforms.some(f=>f.name===d)||h.addUniform(o)}a.uniformGPU=o}return n}getBuiltin(e,t,s,i=this.shaderStage){const n=this.builtins[i]||(this.builtins[i]=new Map);return n.has(e)===!1&&n.set(e,{name:e,property:t,type:s}),t}hasBuiltin(e,t=this.shaderStage){return this.builtins[t]!==void 0&&this.builtins[t].has(e)}getVertexIndex(){return this.shaderStage==="vertex"?this.getBuiltin("vertex_index","vertexIndex","u32","attribute"):"vertexIndex"}buildFunctionCode(e){const t=e.layout,s=this.flowShaderNode(e),i=[];for(const a of t.inputs)i.push(a.name+" : "+this.getType(a.type));let n=`fn ${t.name}( ${i.join(", ")} ) -> ${this.getType(t.type)} {
334
- ${s.vars}
335
- ${s.code}
336
- `;return s.result&&(n+=` return ${s.result};
337
- `),n+=`
338
- }
339
- `,n}getInstanceIndex(){return this.shaderStage==="vertex"?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=[],s=this.directives[e];if(s!==void 0)for(const i of s)t.push(`enable ${i};`);return t.join(`
340
- `)}enableSubGroups(){this.enableDirective("subgroups")}enableSubgroupsF16(){this.enableDirective("subgroups-f16")}enableClipDistances(){this.enableDirective("clip_distances")}enableShaderF16(){this.enableDirective("f16")}enableDualSourceBlending(){this.enableDirective("dual_source_blending")}enableHardwareClipping(e){this.enableClipDistances(),this.getBuiltin("clip_distances","hw_clip_distances",`array<f32, ${e} >`,"vertex")}getBuiltins(e){const t=[],s=this.builtins[e];if(s!==void 0)for(const{name:i,property:n,type:a}of s.values())t.push(`@builtin( ${i} ) ${n} : ${a}`);return t.join(`,
341
- `)}getScopedArray(e,t,s,i){return this.scopedArrays.has(e)===!1&&this.scopedArrays.set(e,{name:e,scope:t,bufferType:s,bufferCount:i}),e}getScopedArrays(e){if(e!=="compute")return;const t=[];for(const{name:s,scope:i,bufferType:n,bufferCount:a}of this.scopedArrays.values()){const o=this.getType(n);t.push(`var<${i}> ${s}: array< ${o}, ${a} >;`)}return t.join(`
342
- `)}getAttributes(e){const t=[];if(e==="compute"&&(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"))),e==="vertex"||e==="compute"){const s=this.getBuiltins("attribute");s&&t.push(s);const i=this.getAttributesArray();for(let n=0,a=i.length;n<a;n++){const o=i[n],l=o.name,c=this.getType(o.type);t.push(`@location( ${n} ) ${l} : ${c}`)}}return t.join(`,
343
- `)}getStructMembers(e){const t=[];for(const s of e.members){const i=e.output?"@location( "+s.index+" ) ":"";let n=this.getType(s.type);s.atomic&&(n="atomic< "+n+" >"),t.push(` ${i+s.name} : ${n}`)}return e.output&&t.push(` ${this.getBuiltins("output")}`),t.join(`,
344
- `)}getStructs(e){let t="";const s=this.structs[e];if(s.length>0){const i=[];for(const n of s){let a=`struct ${n.name} {
345
- `;a+=this.getStructMembers(n),a+=`
346
- };`,i.push(a)}t=`
347
- `+i.join(`
348
-
349
- `)+`
350
- `}return t}getVar(e,t,s=null){let i=`var ${t} : `;return s!==null?i+=this.generateArrayDeclaration(e,s):i+=this.getType(e),i}getVars(e){const t=[],s=this.vars[e];if(s!==void 0)for(const i of s)t.push(` ${this.getVar(i.type,i.name,i.count)};`);return`
351
- ${t.join(`
352
- `)}
353
- `}getVaryings(e){const t=[];if(e==="vertex"&&this.getBuiltin("position","builtinClipSpace","vec4<f32>","vertex"),e==="vertex"||e==="fragment"){const n=this.varyings,a=this.vars[e];for(let o=0;o<n.length;o++){const l=n[o];if(l.needsInterpolation){let c=`@location( ${o} )`;if(l.interpolationType){const u=l.interpolationSampling!==null?`, ${l.interpolationSampling} )`:" )";c+=` @interpolate( ${l.interpolationType}${u}`}else/^(int|uint|ivec|uvec)/.test(l.type)&&(c+=" @interpolate(flat, either)");t.push(`${c} ${l.name} : ${this.getType(l.type)}`)}else e==="vertex"&&a.includes(l)===!1&&a.push(l)}}const s=this.getBuiltins(e);s&&t.push(s);const i=t.join(`,
354
- `);return e==="vertex"?this._getWGSLStruct("VaryingsStruct"," "+i):i}isCustomStruct(e){const t=e.value,s=e.node,i=(t.isBufferAttribute||t.isInstancedBufferAttribute)&&s.structTypeNode!==null,n=s.value&&s.value.array&&typeof s.value.itemSize=="number"&&s.value.array.length>s.value.itemSize;return i&&!n}getUniforms(e){const t=this.uniforms[e],s=[],i=[],n=[],a={};for(const l of t){const c=l.groupNode.name,u=this.bindingsIndexes[c];if(l.type==="texture"||l.type==="cubeTexture"||l.type==="cubeDepthTexture"||l.type==="storageTexture"||l.type==="texture3D"){const h=l.node.value;(h.isCubeTexture===!0||this.isUnfilterable(h)===!1&&l.node.isStorageTextureNode!==!0)&&(this.isSampleCompare(h)?s.push(`@binding( ${u.binding++} ) @group( ${u.group} ) var ${l.name}_sampler : sampler_comparison;`):s.push(`@binding( ${u.binding++} ) @group( ${u.group} ) var ${l.name}_sampler : sampler;`));let p,f="";const{primarySamples:m}=this.renderer.backend.utils.getTextureSampleData(h);if(m>1&&(f="_multisampled"),h.isCubeTexture===!0&&h.isDepthTexture===!0)p="texture_depth_cube";else if(h.isCubeTexture===!0)p="texture_cube<f32>";else if(h.isDepthTexture===!0)this.renderer.backend.compatibilityMode&&h.compareFunction===null?p=`texture${f}_2d<f32>`:p=`texture_depth${f}_2d${h.isArrayTexture===!0?"_array":""}`;else if(l.node.isStorageTextureNode===!0){const x=Pp(h),y=this.getStorageAccess(l.node,e),b=l.node.value.is3DTexture,v=l.node.value.isArrayTexture;p=`texture_storage_${b?"3d":`2d${v?"_array":""}`}<${x}, ${y}>`}else if(h.isArrayTexture===!0||h.isDataArrayTexture===!0||h.isCompressedArrayTexture===!0)p="texture_2d_array<f32>";else if(h.is3DTexture===!0||h.isData3DTexture===!0)p="texture_3d<f32>";else{const x=this.getComponentTypeFromTexture(h).charAt(0);p=`texture${f}_2d<${x}32>`}s.push(`@binding( ${u.binding++} ) @group( ${u.group} ) var ${l.name} : ${p};`)}else if(l.type==="buffer"||l.type==="storageBuffer"||l.type==="indirectStorageBuffer"){const h=l.node,d=this.getType(h.getNodeType(this)),p=h.bufferCount,f=p>0&&l.type==="buffer"?", "+p:"",m=h.isStorageBufferNode?`storage, ${this.getStorageAccess(h,e)}`:"uniform";if(this.isCustomStruct(l))i.push(`@binding( ${u.binding++} ) @group( ${u.group} ) var<${m}> ${l.name} : ${d};`);else{const y=` value : array< ${h.isAtomic?`atomic<${d}>`:`${d}`}${f} >`;i.push(this._getWGSLStructBinding(l.name,y,m,u.binding++,u.group))}}else{const h=l.groupNode.name;if(a[h]===void 0){const d=this.uniformGroups[h];if(d!==void 0){const p=[];for(const m of d.uniforms){const x=m.getType(),y=this.getType(this.getVectorType(x));p.push(` ${m.name} : ${y}`)}let f=this.uniformGroupsBindings[h];f===void 0&&(f={index:u.binding++,id:u.group},this.uniformGroupsBindings[h]=f),a[h]={index:f.index,id:f.id,snippets:p}}}}}for(const l in a){const c=a[l];n.push(this._getWGSLStructBinding(l,c.snippets.join(`,
355
- `),"uniform",c.index,c.id))}return[...s,...i,...n].join(`
356
- `)}buildCode(){const e=this.material!==null?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){this.shaderStage=t;const s=e[t];s.uniforms=this.getUniforms(t),s.attributes=this.getAttributes(t),s.varyings=this.getVaryings(t),s.structs=this.getStructs(t),s.vars=this.getVars(t),s.codes=this.getCodes(t),s.directives=this.getDirectives(t),s.scopedArrays=this.getScopedArrays(t);let i=`// code
357
-
358
- `;i+=this.flowCode[t];const n=this.flowNodes[t],a=n[n.length-1],o=a.outputNode,l=o!==void 0&&o.isOutputStructNode===!0;for(const c of n){const u=this.getFlowData(c),h=c.name;if(h&&(i.length>0&&(i+=`
359
- `),i+=` // flow -> ${h}
360
- `),i+=`${u.code}
361
- `,c===a&&t!=="compute"){if(i+=`// result
362
-
363
- `,t==="vertex")i+=`varyings.builtinClipSpace = ${u.result};`;else if(t==="fragment")if(l)s.returnType=o.getNodeType(this),s.structs+="var<private> output : "+s.returnType+";",i+=`return ${u.result};`;else{let d=" @location(0) color: vec4<f32>";const p=this.getBuiltins("output");p&&(d+=`,
364
- `+p),s.returnType="OutputStruct",s.structs+=this._getWGSLStruct("OutputStruct",d),s.structs+=`
365
- var<private> output : OutputStruct;`,i+=`output.color = ${u.result};
366
-
367
- return output;`}}}s.flow=i}if(this.shaderStage=null,this.material!==null)this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment);else{const t=this.object.workgroupSize;this.computeShader=this._getWGSLComputeCode(e.compute,t)}}getMethod(e,t=null){let s;return t!==null&&(s=this._getWGSLMethod(e+"_"+t)),s===void 0&&(s=this._getWGSLMethod(e)),s||e}getBitcastMethod(e){return`bitcast<${this.getType(e)}>`}getFloatPackingMethod(e){return this.getMethod(`floatpack_${e}_2x16`)}getFloatUnpackingMethod(e){return this.getMethod(`floatunpack_${e}_2x16`)}getTernary(e,t,s){return`select( ${s}, ${t}, ${e} )`}getType(e){return UL[e]||e}isAvailable(e){let t=By[e];return t===void 0&&(e==="float32Filterable"?t=this.renderer.hasFeature("float32-filterable"):e==="clipDistance"&&(t=this.renderer.hasFeature("clip-distances")),By[e]=t),t}getUniformBufferLimit(){return this.renderer.backend.device.limits.maxUniformBufferBindingSize}_getWGSLMethod(e){return ao[e]!==void 0&&this._include(e),VL[e]}_include(e){const t=ao[e];return t.build(this),this.addInclude(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}
368
- // directives
369
- ${e.directives}
370
-
371
- // structs
372
- ${e.structs}
373
-
374
- // uniforms
375
- ${e.uniforms}
376
-
377
- // varyings
378
- ${e.varyings}
379
- var<private> varyings : VaryingsStruct;
380
-
381
- // codes
382
- ${e.codes}
383
-
384
- @vertex
385
- fn main( ${e.attributes} ) -> VaryingsStruct {
386
-
387
- // vars
388
- ${e.vars}
389
-
390
- // flow
391
- ${e.flow}
392
-
393
- return varyings;
394
-
395
- }
396
- `}_getWGSLFragmentCode(e){return`${this.getSignature()}
397
- // global
398
- ${VS}
399
-
400
- // structs
401
- ${e.structs}
402
-
403
- // uniforms
404
- ${e.uniforms}
405
-
406
- // codes
407
- ${e.codes}
408
-
409
- @fragment
410
- fn main( ${e.varyings} ) -> ${e.returnType} {
411
-
412
- // vars
413
- ${e.vars}
414
-
415
- // flow
416
- ${e.flow}
417
-
418
- }
419
- `}_getWGSLComputeCode(e,t){const[s,i,n]=t;return`${this.getSignature()}
420
- // directives
421
- ${e.directives}
422
-
423
- // system
424
- var<private> instanceIndex : u32;
425
-
426
- // locals
427
- ${e.scopedArrays}
428
-
429
- // structs
430
- ${e.structs}
431
-
432
- // uniforms
433
- ${e.uniforms}
434
-
435
- // codes
436
- ${e.codes}
437
-
438
- @compute @workgroup_size( ${s}, ${i}, ${n} )
439
- fn main( ${e.attributes} ) {
440
-
441
- // system
442
- instanceIndex = globalId.x
443
- + globalId.y * ( ${s} * numWorkgroups.x )
444
- + globalId.z * ( ${s} * numWorkgroups.x ) * ( ${i} * numWorkgroups.y );
445
-
446
- // vars
447
- ${e.vars}
448
-
449
- // flow
450
- ${e.flow}
451
-
452
- }
453
- `}_getWGSLStruct(e,t){return`
454
- struct ${e} {
455
- ${t}
456
- };`}_getWGSLStructBinding(e,t,s,i=0,n=0){const a=e+"Struct";return`${this._getWGSLStruct(a,t)}
457
- @binding( ${i} ) @group( ${n} )
458
- var<${s}> ${e} : ${a};`}}class zL{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return e.depth&&(e.depthTexture!==null?t=this.getTextureFormatGPU(e.depthTexture):e.stencil?t=N.Depth24PlusStencil8:t=N.Depth24Plus),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 n=this.backend.renderer,a=n.getRenderTarget();t=a?a.samples:n.currentSamples}else e.renderTarget&&(t=e.renderTarget.samples);t=t||1;const s=t>1&&e.renderTarget!==null&&e.isDepthTexture!==!0&&e.isFramebufferTexture!==!0;return{samples:t,primarySamples:s?1:t,isMSAA:s}}getCurrentColorFormat(e){let t;return e.textures!==null?t=this.getTextureFormatGPU(e.textures[0]):t=this.getPreferredCanvasFormat(),t}getCurrentColorFormats(e){return e.textures!==null?e.textures.map(t=>this.getTextureFormatGPU(t)):[this.getPreferredCanvasFormat()]}getCurrentColorSpace(e){return e.textures!==null?e.textures[0].colorSpace:this.backend.renderer.outputColorSpace}getPrimitiveTopology(e,t){if(e.isPoints)return nc.PointList;if(e.isLineSegments||e.isMesh&&t.wireframe===!0)return nc.LineList;if(e.isLine)return nc.LineStrip;if(e.isMesh)return nc.TriangleList}getSampleCount(e){return e>=4?4:1}getSampleCountRenderContext(e){return e.textures!==null?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.currentSamples)}getPreferredCanvasFormat(){const t=this.backend.parameters.outputType;if(t===void 0)return navigator.gpu.getPreferredCanvasFormat();if(t===Ut)return N.BGRA8Unorm;if(t===Et)return N.RGBA16Float;throw new Error("Unsupported output buffer type.")}}const kS=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]);typeof Float16Array<"u"&&kS.set(Float16Array,["float16"]);const GL=new Map([[Zx,["float16"]]]),$L=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class WL{constructor(e){this.backend=e}createAttribute(e,t){const s=this._getBufferAttribute(e),i=this.backend,n=i.get(s);let a=n.buffer;if(a===void 0){const o=i.device;let l=s.array;if(e.normalized===!1){if(l.constructor===Int16Array||l.constructor===Int8Array)l=new Int32Array(l);else if((l.constructor===Uint16Array||l.constructor===Uint8Array)&&(l=new Uint32Array(l),t&GPUBufferUsage.INDEX))for(let h=0;h<l.length;h++)l[h]===65535&&(l[h]=4294967295)}if(s.array=l,(s.isStorageBufferAttribute||s.isStorageInstancedBufferAttribute)&&s.itemSize===3){l=new l.constructor(s.count*4);for(let h=0;h<s.count;h++)l.set(s.array.subarray(h*3,h*3+3),h*4);s.itemSize=4,s.array=l,n._force3to4BytesAlignment=!0}const c=l.byteLength,u=c+(4-c%4)%4;a=o.createBuffer({label:s.name,size:u,usage:t,mappedAtCreation:!0}),new l.constructor(a.getMappedRange()).set(l),a.unmap(),n.buffer=a}}updateAttribute(e){const t=this._getBufferAttribute(e),s=this.backend,i=s.device,n=s.get(t),a=s.get(t).buffer;let o=t.array;if(n._force3to4BytesAlignment===!0){o=new o.constructor(t.count*4);for(let c=0;c<t.count;c++)o.set(t.array.subarray(c*3,c*3+3),c*4);t.array=o}const l=t.updateRanges;if(l.length===0)i.queue.writeBuffer(a,0,o,0);else{const c=ou(o),u=c?1:o.BYTES_PER_ELEMENT;for(let h=0,d=l.length;h<d;h++){const p=l[h];let f,m;if(n._force3to4BytesAlignment===!0){const y=Math.floor(p.start/3),b=Math.ceil(p.count/3);f=y*4*u,m=b*4*u}else f=p.start*u,m=p.count*u;const x=f*(c?o.BYTES_PER_ELEMENT:1);i.queue.writeBuffer(a,x,o,f,m)}t.clearUpdateRanges()}}createShaderVertexBuffers(e){const t=e.getAttributes(),s=new Map;for(let i=0;i<t.length;i++){const n=t[i],a=n.array.BYTES_PER_ELEMENT,o=this._getBufferAttribute(n);let l=s.get(o);if(l===void 0){let h,d;n.isInterleavedBufferAttribute===!0?(h=n.data.stride*a,d=n.data.isInstancedInterleavedBuffer?rc.Instance:rc.Vertex):(h=n.itemSize*a,d=n.isInstancedBufferAttribute?rc.Instance:rc.Vertex),n.normalized===!1&&(n.array.constructor===Int16Array||n.array.constructor===Uint16Array)&&(h=4),l={arrayStride:h,attributes:[],stepMode:d},s.set(o,l)}const c=this._getVertexFormat(n),u=n.isInterleavedBufferAttribute===!0?n.offset*a:0;l.attributes.push({shaderLocation:i,offset:u,format:c})}return Array.from(s.values())}destroyAttribute(e){const t=this.backend;t.get(this._getBufferAttribute(e)).buffer.destroy(),t.delete(e)}async getArrayBufferAsync(e){const t=this.backend,s=t.device,n=t.get(this._getBufferAttribute(e)).buffer,a=n.size,o=s.createBuffer({label:`${e.name}_readback`,size:a,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),l=s.createCommandEncoder({label:`readback_encoder_${e.name}`});l.copyBufferToBuffer(n,0,o,0,a);const c=l.finish();s.queue.submit([c]),await o.mapAsync(GPUMapMode.READ);const u=o.getMappedRange(),h=new e.array.constructor(u.slice(0));return o.unmap(),h.buffer}_getVertexFormat(e){const{itemSize:t,normalized:s}=e,i=e.array.constructor,n=e.constructor;let a;if(t===1)a=$L.get(i);else{const l=(GL.get(n)||kS.get(i))[s?1:0];if(l){const c=i.BYTES_PER_ELEMENT*t,h=Math.floor((c+3)/4)*4/i.BYTES_PER_ELEMENT;if(h%1)throw new Error("THREE.WebGPUAttributeUtils: Bad vertex format item size.");a=`${l}x${h}`}}return a||$("WebGPUAttributeUtils: Vertex format not supported yet."),a}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}class HL{constructor(e){this.layoutGPU=e,this.usedTimes=0}}class jL{constructor(e){this.backend=e,this._bindGroupLayoutCache=new Map}createBindingsLayout(e){const t=this.backend,s=t.device,i=t.get(e);if(i.layout)return i.layout.layoutGPU;const n=this._createLayoutEntries(e),a=Ia(JSON.stringify(n));let o=this._bindGroupLayoutCache.get(a);return o===void 0&&(o=new HL(s.createBindGroupLayout({entries:n})),this._bindGroupLayoutCache.set(a,o)),o.usedTimes++,i.layout=o,i.layoutKey=a,o.layoutGPU}createBindings(e,t,s,i=0){const{backend:n}=this,a=n.get(e),o=this.createBindingsLayout(e);let l;s>0&&(a.groups===void 0&&(a.groups=[],a.versions=[]),a.versions[s]===i&&(l=a.groups[s])),l===void 0&&(l=this.createBindGroup(e,o),s>0&&(a.groups[s]=l,a.versions[s]=i)),a.group=l}updateBinding(e){const t=this.backend,s=t.device,i=e.buffer,n=t.get(e).buffer,a=e.updateRanges;if(a.length===0)s.queue.writeBuffer(n,0,i,0);else{const o=ou(i),l=o?1:i.BYTES_PER_ELEMENT;for(let c=0,u=a.length;c<u;c++){const h=a[c],d=h.start*l,p=h.count*l,f=d*(o?i.BYTES_PER_ELEMENT:1);s.queue.writeBuffer(n,f,i,d,p)}}}createBindGroupIndex(e,t){const i=this.backend.device,n=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,a=e[0],o=i.createBuffer({label:"bindingCameraIndex_"+a,size:16,usage:n});i.queue.writeBuffer(o,0,e,0);const l=[{binding:0,resource:{buffer:o}}];return i.createBindGroup({label:"bindGroupCameraIndex_"+a,layout:t,entries:l})}createBindGroup(e,t){const s=this.backend,i=s.device;let n=0;const a=[];for(const o of e.bindings){if(o.isUniformBuffer){const l=s.get(o);if(l.buffer===void 0){const c=o.byteLength,u=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,h=[];o.visibility&Ti.VERTEX&&h.push("vertex"),o.visibility&Ti.FRAGMENT&&h.push("fragment"),o.visibility&Ti.COMPUTE&&h.push("compute");const d=`(${h.join(",")})`,p=i.createBuffer({label:`bindingBuffer${o.id}_${o.name}_${d}`,size:c,usage:u});l.buffer=p}a.push({binding:n,resource:{buffer:l.buffer}})}else if(o.isStorageBuffer){const l=s.get(o.attribute).buffer;a.push({binding:n,resource:{buffer:l}})}else if(o.isSampledTexture){const l=s.get(o.texture);let c;if(l.externalTexture!==void 0)c=i.importExternalTexture({source:l.externalTexture});else{const u=o.store?1:l.texture.mipLevelCount,h=o.store?o.mipLevel:0;let d=`view-${l.texture.width}-${l.texture.height}`;if(l.texture.depthOrArrayLayers>1&&(d+=`-${l.texture.depthOrArrayLayers}`),d+=`-${u}-${h}`,c=l[d],c===void 0){const p=SL.All;let f;o.isSampledCubeTexture?f=Ot.Cube:o.isSampledTexture3D?f=Ot.ThreeD:o.texture.isArrayTexture||o.texture.isDataArrayTexture||o.texture.isCompressedArrayTexture?f=Ot.TwoDArray:f=Ot.TwoD,c=l[d]=l.texture.createView({aspect:p,dimension:f,mipLevelCount:u,baseMipLevel:h})}}a.push({binding:n,resource:c})}else if(o.isSampler){const l=s.get(o.texture);a.push({binding:n,resource:l.sampler})}n++}return i.createBindGroup({label:"bindGroup_"+e.name,layout:t,entries:a})}_createLayoutEntries(e){const t=[];let s=0;for(const i of e.bindings){const n=this.backend,a={binding:s,visibility:i.visibility};if(i.isUniformBuffer||i.isStorageBuffer){const o={};i.isStorageBuffer&&(i.visibility&Ti.COMPUTE&&(i.access===Nt.READ_WRITE||i.access===Nt.WRITE_ONLY)?o.type=Ad.Storage:o.type=Ad.ReadOnlyStorage),a.buffer=o}else if(i.isSampledTexture&&i.store){const o={};o.format=this.backend.get(i.texture).texture.format;const l=i.access;l===Nt.READ_WRITE?o.access=Ed.ReadWrite:l===Nt.WRITE_ONLY?o.access=Ed.WriteOnly:o.access=Ed.ReadOnly,i.texture.isArrayTexture?o.viewDimension=Ot.TwoDArray:i.texture.is3DTexture&&(o.viewDimension=Ot.ThreeD),a.storageTexture=o}else if(i.isSampledTexture){const o={},{primarySamples:l}=n.utils.getTextureSampleData(i.texture);if(l>1&&(o.multisampled=!0,i.texture.isDepthTexture||(o.sampleType=ir.UnfilterableFloat)),i.texture.isDepthTexture)n.compatibilityMode&&i.texture.compareFunction===null?o.sampleType=ir.UnfilterableFloat:o.sampleType=ir.Depth;else if(i.texture.isDataTexture||i.texture.isDataArrayTexture||i.texture.isData3DTexture){const c=i.texture.type;c===Lt?o.sampleType=ir.SInt:c===rt?o.sampleType=ir.UInt:c===es&&(this.backend.hasFeature("float32-filterable")?o.sampleType=ir.Float:o.sampleType=ir.UnfilterableFloat)}i.isSampledCubeTexture?o.viewDimension=Ot.Cube:i.texture.isArrayTexture||i.texture.isDataArrayTexture||i.texture.isCompressedArrayTexture?o.viewDimension=Ot.TwoDArray:i.isSampledTexture3D&&(o.viewDimension=Ot.ThreeD),a.texture=o}else if(i.isSampler){const o={};i.texture.isDepthTexture&&(i.texture.compareFunction!==null&&n.hasCompatibility(Bn.TEXTURE_COMPARE)?o.type=Ey.Comparison:o.type=Ey.NonFiltering),a.sampler=o}else $(`WebGPUBindingUtils: Unsupported binding "${i}".`);t.push(a),s++}return t}deleteBindGroupData(e){const{backend:t}=this,s=t.get(e);s.layout&&(s.layout.usedTimes--,s.layout.usedTimes===0&&this._bindGroupLayoutCache.delete(s.layoutKey),s.layout=void 0,s.layoutKey=void 0)}dispose(){this._bindGroupLayoutCache.clear()}}class qL{constructor(e){this.backend=e,this._activePipelines=new WeakMap}setPipeline(e,t){this._activePipelines.get(e)!==t&&(e.setPipeline(t),this._activePipelines.set(e,t))}_getSampleCount(e){return this.backend.utils.getSampleCountRenderContext(e)}createRenderPipeline(e,t){const{object:s,material:i,geometry:n,pipeline:a}=e,{vertexProgram:o,fragmentProgram:l}=a,c=this.backend,u=c.device,h=c.utils,d=c.get(a),p=[];for(const K of e.getBindings()){const te=c.get(K),{layoutGPU:q}=te.layout;p.push(q)}const f=c.attributeUtils.createShaderVertexBuffers(e);let m;i.blending!==Xi&&(i.blending!==Es||i.transparent!==!1)&&(m=this._getBlending(i));let x={};i.stencilWrite===!0&&(x={compare:this._getStencilCompare(i),failOp:this._getStencilOperation(i.stencilFail),depthFailOp:this._getStencilOperation(i.stencilZFail),passOp:this._getStencilOperation(i.stencilZPass)});const y=this._getColorWriteMask(i),b=[];if(e.context.textures!==null){const K=e.context.textures,te=e.context.mrt;for(let q=0;q<K.length;q++){const oe=K[q],Pe=h.getTextureFormatGPU(oe);let ge;if(te!==null)if(this.backend.compatibilityMode!==!0){const le=te.getBlendMode(oe.name);le.blending===Ip?ge=m:le.blending!==Xi&&(ge=this._getBlending(le))}else Le("WebGPURenderer: Multiple Render Targets (MRT) blending configuration is not fully supported in compatibility mode. The material blending will be used for all render targets."),ge=m;else ge=m;b.push({format:Pe,blend:ge,writeMask:y})}}else{const K=h.getCurrentColorFormat(e.context);b.push({format:K,blend:m,writeMask:y})}const v=c.get(o).module,S=c.get(l).module,M=this._getPrimitiveState(s,n,i),A=this._getDepthCompare(i),C=h.getCurrentDepthStencilFormat(e.context),P=this._getSampleCount(e.context),B={label:`renderPipeline_${i.name||i.type}_${i.id}`,vertex:Object.assign({},v,{buffers:f}),fragment:Object.assign({},S,{targets:b}),primitive:M,multisample:{count:P,alphaToCoverageEnabled:i.alphaToCoverage&&P>1},layout:u.createPipelineLayout({bindGroupLayouts:p})},V={},Y=e.context.depth,J=e.context.stencil;if((Y===!0||J===!0)&&(Y===!0&&(V.format=C,V.depthWriteEnabled=i.depthWrite,V.depthCompare=A),J===!0&&(V.stencilFront=x,V.stencilBack=x,V.stencilReadMask=i.stencilFuncMask,V.stencilWriteMask=i.stencilWriteMask),i.polygonOffset===!0&&(V.depthBias=i.polygonOffsetUnits,V.depthBiasSlopeScale=i.polygonOffsetFactor,V.depthBiasClamp=0),B.depthStencil=V),u.pushErrorScope("validation"),t===null)d.pipeline=u.createRenderPipeline(B),u.popErrorScope().then(K=>{K!==null&&(d.error=!0,$(K.message))});else{const K=new Promise(async te=>{try{d.pipeline=await u.createRenderPipelineAsync(B)}catch{}const q=await u.popErrorScope();q!==null&&(d.error=!0,$(q.message)),te()});t.push(K)}}createBundleEncoder(e,t="renderBundleEncoder"){const s=this.backend,{utils:i,device:n}=s,a=i.getCurrentDepthStencilFormat(e),o=i.getCurrentColorFormats(e),l=this._getSampleCount(e),c={label:t,colorFormats:o,depthStencilFormat:a,sampleCount:l};return n.createRenderBundleEncoder(c)}createComputePipeline(e,t){const s=this.backend,i=s.device,n=s.get(e.computeProgram).module,a=s.get(e),o=[];for(const l of t){const c=s.get(l),{layoutGPU:u}=c.layout;o.push(u)}a.pipeline=i.createComputePipeline({compute:n,layout:i.createPipelineLayout({bindGroupLayouts:o})})}_getBlending(e){let t,s;const i=e.blending,n=e.blendSrc,a=e.blendDst,o=e.blendEquation;if(i===ma){const l=e.blendSrcAlpha!==null?e.blendSrcAlpha:n,c=e.blendDstAlpha!==null?e.blendDstAlpha:a,u=e.blendEquationAlpha!==null?e.blendEquationAlpha:o;t={srcFactor:this._getBlendFactor(n),dstFactor:this._getBlendFactor(a),operation:this._getBlendOperation(o)},s={srcFactor:this._getBlendFactor(l),dstFactor:this._getBlendFactor(c),operation:this._getBlendOperation(u)}}else{const l=e.premultipliedAlpha,c=(u,h,d,p)=>{t={srcFactor:u,dstFactor:h,operation:sr.Add},s={srcFactor:d,dstFactor:p,operation:sr.Add}};if(l)switch(i){case Es:c(Se.One,Se.OneMinusSrcAlpha,Se.One,Se.OneMinusSrcAlpha);break;case ua:c(Se.One,Se.One,Se.One,Se.One);break;case ha:c(Se.Zero,Se.OneMinusSrc,Se.Zero,Se.One);break;case da:c(Se.Dst,Se.OneMinusSrcAlpha,Se.Zero,Se.One);break}else switch(i){case Es:c(Se.SrcAlpha,Se.OneMinusSrcAlpha,Se.One,Se.OneMinusSrcAlpha);break;case ua:c(Se.SrcAlpha,Se.One,Se.One,Se.One);break;case ha:$(`WebGPURenderer: "SubtractiveBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`);break;case da:$(`WebGPURenderer: "MultiplyBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`);break}}if(t!==void 0&&s!==void 0)return{color:t,alpha:s};$("WebGPURenderer: Invalid blending: ",i)}_getBlendFactor(e){let t;switch(e){case bn:t=Se.Zero;break;case wx:t=Se.One;break;case Cx:t=Se.Src;break;case Ax:t=Se.OneMinusSrc;break;case Vo:t=Se.SrcAlpha;break;case ko:t=Se.OneMinusSrcAlpha;break;case Rx:t=Se.Dst;break;case Px:t=Se.OneMinusDst;break;case Ex:t=Se.DstAlpha;break;case Nx:t=Se.OneMinusDstAlpha;break;case Fx:t=Se.SrcAlphaSaturated;break;case HN:t=Se.Constant;break;case jN:t=Se.OneMinusConstant;break;default:$("WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const s=e.stencilFunc;switch(s){case hw:t=At.Never;break;case ip:t=At.Always;break;case dw:t=At.Less;break;case fw:t=At.LessEqual;break;case pw:t=At.Equal;break;case yw:t=At.GreaterEqual;break;case mw:t=At.Greater;break;case gw:t=At.NotEqual;break;default:$("WebGPURenderer: Invalid stencil function.",s)}return t}_getStencilOperation(e){let t;switch(e){case lr:t=mn.Keep;break;case nw:t=mn.Zero;break;case rw:t=mn.Replace;break;case uw:t=mn.Invert;break;case aw:t=mn.IncrementClamp;break;case ow:t=mn.DecrementClamp;break;case lw:t=mn.IncrementWrap;break;case cw:t=mn.DecrementWrap;break;default:$("WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case Ns:t=sr.Add;break;case vx:t=sr.Subtract;break;case Mx:t=sr.ReverseSubtract;break;case GM:t=sr.Min;break;case $M:t=sr.Max;break;default:$("WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,s){const i={},n=this.backend.utils;i.topology=n.getPrimitiveTopology(e,s),t.index!==null&&e.isLine===!0&&e.isLineSegments!==!0&&(i.stripIndexFormat=t.index.array instanceof Uint16Array?Mu.Uint16:Mu.Uint32);let a=s.side===Rt;return e.isMesh&&e.matrixWorld.determinant()<0&&(a=!a),i.frontFace=a===!0?wy.CW:wy.CCW,i.cullMode=s.side===qi?Cy.None:Cy.Back,i}_getColorWriteMask(e){return e.colorWrite===!0?Ay.All:Ay.None}_getDepthCompare(e){let t;if(e.depthTest===!1)t=At.Always;else{const s=this.backend.parameters.reversedDepthBuffer?Wx[e.depthFunc]:e.depthFunc;switch(s){case Ac:t=At.Never;break;case Ec:t=At.Always;break;case Nc:t=At.Less;break;case wa:t=At.LessEqual;break;case Rc:t=At.Equal;break;case Pc:t=At.GreaterEqual;break;case Fc:t=At.Greater;break;case Bc:t=At.NotEqual;break;default:$("WebGPUPipelineUtils: Invalid depth function.",s)}}return t}}class XL extends US{constructor(e,t,s=2048){super(s),this.device=e,this.type=t,this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxQueries,label:`queryset_global_timestamp_${t}`});const i=this.maxQueries*8;this.resolveBuffer=this.device.createBuffer({label:`buffer_timestamp_resolve_${t}`,size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.resultBuffer=this.device.createBuffer({label:`buffer_timestamp_result_${t}`,size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})}allocateQueriesForContext(e){if(!this.trackTimestamp||this.isDisposed)return null;if(this.currentQueryIndex+2>this.maxQueries)return Le(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryOffsets.set(e,t),t}async resolveQueriesAsync(){if(!this.trackTimestamp||this.currentQueryIndex===0||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(this.resultBuffer.mapState!=="unmapped")return this.lastValue;const e=new Map(this.queryOffsets),t=this.currentQueryIndex,s=t*8;this.currentQueryIndex=0,this.queryOffsets.clear();const i=this.device.createCommandEncoder();i.resolveQuerySet(this.querySet,0,t,this.resolveBuffer,0),i.copyBufferToBuffer(this.resolveBuffer,0,this.resultBuffer,0,s);const n=i.finish();if(this.device.queue.submit([n]),this.resultBuffer.mapState!=="unmapped")return this.lastValue;if(await this.resultBuffer.mapAsync(GPUMapMode.READ,0,s),this.isDisposed)return this.resultBuffer.mapState==="mapped"&&this.resultBuffer.unmap(),this.lastValue;const a=new BigUint64Array(this.resultBuffer.getMappedRange(0,s)),o={},l=[];for(const[u,h]of e){const d=u.match(/^(.*):f(\d+)$/),p=parseInt(d[2]);l.includes(p)===!1&&l.push(p),o[p]===void 0&&(o[p]=0);const f=a[h],m=a[h+1],x=Number(m-f)/1e6;this.timestamps.set(u,x),o[p]+=x}const c=o[l[l.length-1]];return this.resultBuffer.unmap(),this.lastValue=c,this.frames=l,c}catch(e){return $("Error resolving queries:",e),this.resultBuffer.mapState==="mapped"&&this.resultBuffer.unmap(),this.lastValue}}async dispose(){if(!this.isDisposed){if(this.isDisposed=!0,this.pendingResolve)try{await this.pendingResolve}catch(e){$("Error waiting for pending resolve:",e)}if(this.resultBuffer&&this.resultBuffer.mapState==="mapped")try{this.resultBuffer.unmap()}catch(e){$("Error unmapping buffer:",e)}this.querySet&&(this.querySet.destroy(),this.querySet=null),this.resolveBuffer&&(this.resolveBuffer.destroy(),this.resolveBuffer=null),this.resultBuffer&&(this.resultBuffer.destroy(),this.resultBuffer=null),this.queryOffsets.clear(),this.pendingResolve=null}}}class YL extends IS{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=e.alpha===void 0?!0:e.alpha,this.parameters.requiredLimits=e.requiredLimits===void 0?{}:e.requiredLimits,this.compatibilityMode=null,this.device=null,this.defaultRenderPassdescriptor=null,this.utils=new zL(this),this.attributeUtils=new WL(this),this.bindingUtils=new jL(this),this.pipelineUtils=new qL(this),this.textureUtils=new RL(this),this.occludedResolveCache=new Map;const t=typeof navigator>"u"?!0:/Android/.test(navigator.userAgent)===!1;this._compatibility={[Bn.TEXTURE_COMPARE]:t}}async init(e){await super.init(e);const t=this.parameters;let s;if(t.device===void 0){const i={powerPreference:t.powerPreference,featureLevel:"compatibility"},n=typeof navigator<"u"?await navigator.gpu.requestAdapter(i):null;if(n===null)throw new Error("WebGPUBackend: Unable to create WebGPU adapter.");const a=Object.values(Rp),o=[];for(const c of a)n.features.has(c)&&o.push(c);const l={requiredFeatures:o,requiredLimits:t.requiredLimits};s=await n.requestDevice(l)}else s=t.device;this.compatibilityMode=!s.features.has("core-features-and-limits"),this.compatibilityMode&&(e._samples=0),s.lost.then(i=>{if(i.reason==="destroyed")return;const n={api:"WebGPU",message:i.message||"Unknown reason",reason:i.reason||null,originalEvent:i};e.onDeviceLost(n)}),this.device=s,this.trackTimestamp=this.trackTimestamp&&this.hasFeature(Rp.TimestampQuery),this.updateSize()}get context(){const e=this.renderer.getCanvasTarget(),t=this.get(e);let s=t.context;if(s===void 0){const i=this.parameters;e.isDefaultCanvasTarget===!0&&i.context!==void 0?s=i.context:s=e.domElement.getContext("webgpu"),"setAttribute"in e.domElement&&e.domElement.setAttribute("data-engine",`three.js r${Zo} webgpu`);const n=i.alpha?"premultiplied":"opaque",a=i.outputType===Et?"extended":"standard";s.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:n,toneMapping:{mode:a}}),t.context=s}return s}get coordinateSystem(){return Ls}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){const e=this.renderer,t=e.getCanvasTarget(),s=this.get(t),i=e.currentSamples;let n=s.descriptor;if(n===void 0||s.samples!==i){n={colorAttachments:[{view:null}]},(e.depth===!0||e.stencil===!0)&&(n.depthStencilAttachment={view:this.textureUtils.getDepthBuffer(e.depth,e.stencil).createView()});const o=n.colorAttachments[0];i>0?o.view=this.textureUtils.getColorBuffer().createView():o.resolveTarget=void 0,s.descriptor=n,s.samples=i}const a=n.colorAttachments[0];return i>0?a.resolveTarget=this.context.getCurrentTexture().createView():a.view=this.context.getCurrentTexture().createView(),n}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.image.depth>1&&e.camera.isArrayCamera}_getRenderPassDescriptor(e,t={}){const s=e.renderTarget,i=this.get(s);let n=i.descriptors;(n===void 0||i.width!==s.width||i.height!==s.height||i.samples!==s.samples)&&(n={},i.descriptors=n);const a=e.getCacheKey();let o=n[a];if(o===void 0){const c=e.textures,u=[];let h;const d=this._isRenderCameraDepthArray(e);for(let p=0;p<c.length;p++){const f=this.get(c[p]),m={label:`colorAttachment_${p}`,baseMipLevel:e.activeMipmapLevel,mipLevelCount:1,baseArrayLayer:e.activeCubeFace,arrayLayerCount:1,dimension:Ot.TwoD};if(s.isRenderTarget3D)h=e.activeCubeFace,m.baseArrayLayer=0,m.dimension=Ot.ThreeD,m.depthOrArrayLayers=c[p].image.depth;else if(s.isRenderTarget&&c[p].image.depth>1)if(d===!0){const x=e.camera.cameras;for(let y=0;y<x.length;y++){const b={...m,baseArrayLayer:y,arrayLayerCount:1,dimension:Ot.TwoD},v=f.texture.createView(b);u.push({view:v,resolveTarget:void 0,depthSlice:void 0})}}else m.dimension=Ot.TwoDArray,m.depthOrArrayLayers=c[p].image.depth;if(d!==!0){const x=f.texture.createView(m);let y,b;f.msaaTexture!==void 0?(y=f.msaaTexture.createView(),b=x):(y=x,b=void 0),u.push({view:y,resolveTarget:b,depthSlice:h})}}if(o={textureViews:u},e.depth){const p=this.get(e.depthTexture),f={};(e.depthTexture.isArrayTexture||e.depthTexture.isCubeTexture)&&(f.dimension=Ot.TwoD,f.arrayLayerCount=1,f.baseArrayLayer=e.activeCubeFace),o.depthStencilView=p.texture.createView(f)}n[a]=o,i.width=s.width,i.height=s.height,i.samples=s.samples,i.activeMipmapLevel=e.activeMipmapLevel,i.activeCubeFace=e.activeCubeFace}const l={colorAttachments:[]};for(let c=0;c<o.textureViews.length;c++){const u=o.textureViews[c];let h={r:0,g:0,b:0,a:1};c===0&&t.clearValue&&(h=t.clearValue),l.colorAttachments.push({view:u.view,depthSlice:u.depthSlice,resolveTarget:u.resolveTarget,loadOp:t.loadOp||De.Load,storeOp:t.storeOp||Ht.Store,clearValue:h})}return o.depthStencilView&&(l.depthStencilAttachment={view:o.depthStencilView}),l}beginRender(e){const t=this.get(e),s=this.device,i=e.occlusionQueryCount;let n;i>0&&(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,n=s.createQuerySet({type:"occlusion",count:i,label:`occlusionQuerySet_${e.id}`}),t.occlusionQuerySet=n,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(i),t.lastOcclusionObject=null);let a;e.textures===null?a=this._getDefaultRenderPassDescriptor():a=this._getRenderPassDescriptor(e,{loadOp:De.Load}),this.initTimestampQuery(bi.RENDER,this.getTimestampUID(e),a),a.occlusionQuerySet=n;const o=a.depthStencilAttachment;if(e.textures!==null){const c=a.colorAttachments;for(let u=0;u<c.length;u++){const h=c[u];e.clearColor?(h.clearValue=u===0?e.clearColorValue:{r:0,g:0,b:0,a:1},h.loadOp=De.Clear):h.loadOp=De.Load,h.storeOp=Ht.Store}}else{const c=a.colorAttachments[0];e.clearColor?(c.clearValue=e.clearColorValue,c.loadOp=De.Clear):c.loadOp=De.Load,c.storeOp=Ht.Store}e.depth&&(e.clearDepth?(o.depthClearValue=e.clearDepthValue,o.depthLoadOp=De.Clear):o.depthLoadOp=De.Load,o.depthStoreOp=Ht.Store),e.stencil&&(e.clearStencil?(o.stencilClearValue=e.clearStencilValue,o.stencilLoadOp=De.Clear):o.stencilLoadOp=De.Load,o.stencilStoreOp=Ht.Store);const l=s.createCommandEncoder({label:"renderContext_"+e.id});if(this._isRenderCameraDepthArray(e)===!0){const c=e.camera.cameras;!t.layerDescriptors||t.layerDescriptors.length!==c.length?this._createDepthLayerDescriptors(e,t,a,c):this._updateDepthLayerDescriptors(e,t,c),t.bundleEncoders=[],t.bundleSets=[];for(let u=0;u<c.length;u++){const h=this.pipelineUtils.createBundleEncoder(e,"renderBundleArrayCamera_"+u),d={attributes:{},bindingGroups:[],pipeline:null,index:null};t.bundleEncoders.push(h),t.bundleSets.push(d)}t.currentPass=null}else{const c=l.beginRenderPass(a);t.currentPass=c,e.viewport&&this.updateViewport(e),e.scissor&&this.updateScissor(e)}t.descriptor=a,t.encoder=l,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.renderBundles=[]}_createDepthLayerDescriptors(e,t,s,i){const n=s.depthStencilAttachment;t.layerDescriptors=[];const a=this.get(e.depthTexture);a.viewCache||(a.viewCache=[]);for(let o=0;o<i.length;o++){const l={...s,colorAttachments:[{...s.colorAttachments[0],view:s.colorAttachments[o].view}]};if(s.depthStencilAttachment){const c=o;a.viewCache[c]||(a.viewCache[c]=a.texture.createView({dimension:Ot.TwoD,baseArrayLayer:o,arrayLayerCount:1})),l.depthStencilAttachment={view:a.viewCache[c],depthLoadOp:n.depthLoadOp||De.Clear,depthStoreOp:n.depthStoreOp||Ht.Store,depthClearValue:n.depthClearValue||1},e.stencil&&(l.depthStencilAttachment.stencilLoadOp=n.stencilLoadOp,l.depthStencilAttachment.stencilStoreOp=n.stencilStoreOp,l.depthStencilAttachment.stencilClearValue=n.stencilClearValue)}else l.depthStencilAttachment={...n};t.layerDescriptors.push(l)}}_updateDepthLayerDescriptors(e,t,s){for(let i=0;i<s.length;i++){const n=t.layerDescriptors[i];if(n.depthStencilAttachment){const a=n.depthStencilAttachment;e.depth&&(e.clearDepth?(a.depthClearValue=e.clearDepthValue,a.depthLoadOp=De.Clear):a.depthLoadOp=De.Load),e.stencil&&(e.clearStencil?(a.stencilClearValue=e.clearStencilValue,a.stencilLoadOp=De.Clear):a.stencilLoadOp=De.Load)}}}finishRender(e){const t=this.get(e),s=e.occlusionQueryCount;t.renderBundles.length>0&&t.currentPass.executeBundles(t.renderBundles),s>t.occlusionQueryIndex&&t.currentPass.endOcclusionQuery();const i=t.encoder;if(this._isRenderCameraDepthArray(e)===!0){const n=[];for(let a=0;a<t.bundleEncoders.length;a++){const o=t.bundleEncoders[a];n.push(o.finish())}for(let a=0;a<t.layerDescriptors.length;a++)if(a<n.length){const o=t.layerDescriptors[a],l=i.beginRenderPass(o);if(e.viewport){const{x:c,y:u,width:h,height:d,minDepth:p,maxDepth:f}=e.viewportValue;l.setViewport(c,u,h,d,p,f)}if(e.scissor){const{x:c,y:u,width:h,height:d}=e.scissorValue;l.setScissorRect(c,u,h,d)}l.executeBundles([n[a]]),l.end()}}else t.currentPass&&t.currentPass.end();if(s>0){const n=s*8;let a=this.occludedResolveCache.get(n);a===void 0&&(a=this.device.createBuffer({size:n,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.occludedResolveCache.set(n,a));const o=this.device.createBuffer({size:n,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});t.encoder.resolveQuerySet(t.occlusionQuerySet,0,s,a,0),t.encoder.copyBufferToBuffer(a,0,o,0,n),t.occlusionQueryBuffer=o,this.resolveOccludedAsync(e)}if(this.device.queue.submit([t.encoder.finish()]),e.textures!==null){const n=e.textures;for(let a=0;a<n.length;a++){const o=n[a];o.generateMipmaps===!0&&this.textureUtils.generateMipmaps(o)}}}isOccluded(e,t){const s=this.get(e);return s.occluded&&s.occluded.has(t)}async resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueryBuffer:s,currentOcclusionQueryObjects:i}=t;if(s&&i){const n=new WeakSet;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueryBuffer=null,await s.mapAsync(GPUMapMode.READ);const a=s.getMappedRange(),o=new BigUint64Array(a);for(let l=0;l<i.length;l++)o[l]===BigInt(0)&&n.add(i[l]);s.destroy(),t.occluded=n}}updateViewport(e){const{currentPass:t}=this.get(e),{x:s,y:i,width:n,height:a,minDepth:o,maxDepth:l}=e.viewportValue;t.setViewport(s,i,n,a,o,l)}updateScissor(e){const{currentPass:t}=this.get(e),{x:s,y:i,width:n,height:a}=e.scissorValue;t.setScissorRect(s,i,n,a)}getClearColor(){const e=super.getClearColor();return this.renderer.alpha===!0&&(e.r*=e.a,e.g*=e.a,e.b*=e.a),e}clear(e,t,s,i=null){const n=this.device,a=this.renderer;let o=[],l,c,u,h;if(e){const f=this.getClearColor();c={r:f.r,g:f.g,b:f.b,a:f.a}}if(i===null){u=a.depth,h=a.stencil;const f=this._getDefaultRenderPassDescriptor();if(e){o=f.colorAttachments;const m=o[0];m.clearValue=c,m.loadOp=De.Clear,m.storeOp=Ht.Store}(u||h)&&(l=f.depthStencilAttachment)}else{u=i.depth,h=i.stencil;const f={loadOp:e?De.Clear:De.Load,clearValue:e?c:void 0};u&&(f.depthLoadOp=t?De.Clear:De.Load,f.depthClearValue=t?a.getClearDepth():void 0,f.depthStoreOp=Ht.Store),h&&(f.stencilLoadOp=s?De.Clear:De.Load,f.stencilClearValue=s?a.getClearStencil():void 0,f.stencilStoreOp=Ht.Store);const m=this._getRenderPassDescriptor(i,f);o=m.colorAttachments,l=m.depthStencilAttachment}u&&l&&(t?(l.depthLoadOp=De.Clear,l.depthClearValue=a.getClearDepth(),l.depthStoreOp=Ht.Store):(l.depthLoadOp=De.Load,l.depthStoreOp=Ht.Store)),h&&l&&(s?(l.stencilLoadOp=De.Clear,l.stencilClearValue=a.getClearStencil(),l.stencilStoreOp=Ht.Store):(l.stencilLoadOp=De.Load,l.stencilStoreOp=Ht.Store));const d=n.createCommandEncoder({label:"clear"});d.beginRenderPass({colorAttachments:o,depthStencilAttachment:l}).end(),n.queue.submit([d.finish()])}beginCompute(e){const t=this.get(e),s={label:"computeGroup_"+e.id};this.initTimestampQuery(bi.COMPUTE,this.getTimestampUID(e),s),t.cmdEncoderGPU=this.device.createCommandEncoder({label:"computeGroup_"+e.id}),t.passEncoderGPU=t.cmdEncoderGPU.beginComputePass(s)}compute(e,t,s,i,n=null){const a=this.get(t),{passEncoderGPU:o}=this.get(e),l=this.get(i).pipeline;this.pipelineUtils.setPipeline(o,l);for(let c=0,u=s.length;c<u;c++){const h=s[c],d=this.get(h);o.setBindGroup(c,d.group)}if(n===null&&(n=t.count),n&&typeof n=="object"&&n.isIndirectStorageBufferAttribute){const c=this.get(n).buffer;o.dispatchWorkgroupsIndirect(c,0);return}if(typeof n=="number"){const c=n;if(a.dispatchSize===void 0||a.count!==c){a.dispatchSize=[0,1,1],a.count=c;const u=t.workgroupSize;let h=u[0];for(let f=1;f<u.length;f++)h*=u[f];const d=Math.ceil(c/h),p=this.device.limits.maxComputeWorkgroupsPerDimension;n=[d,1,1],d>p&&(n[0]=Math.min(d,p),n[1]=Math.ceil(d/p)),a.dispatchSize=n}n=a.dispatchSize}o.dispatchWorkgroups(n[0],n[1]||1,n[2]||1)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.device.queue.submit([t.cmdEncoderGPU.finish()])}draw(e,t){const{object:s,material:i,context:n,pipeline:a}=e,o=e.getBindings(),l=this.get(n),c=this.get(a),u=c.pipeline;if(c.error===!0)return;const h=e.getIndex(),d=h!==null,p=e.getDrawParameters();if(p===null)return;const f=(x,y)=>{this.pipelineUtils.setPipeline(x,u),y.pipeline=u;const b=y.bindingGroups;for(let S=0,M=o.length;S<M;S++){const A=o[S],C=this.get(A);b[A.index]!==A.id&&(x.setBindGroup(A.index,C.group),b[A.index]=A.id)}if(d===!0&&y.index!==h){const S=this.get(h).buffer,M=h.array instanceof Uint16Array?Mu.Uint16:Mu.Uint32;x.setIndexBuffer(S,M),y.index=h}const v=e.getVertexBuffers();for(let S=0,M=v.length;S<M;S++){const A=v[S];if(y.attributes[S]!==A){const C=this.get(A).buffer;x.setVertexBuffer(S,C),y.attributes[S]=A}}n.stencil===!0&&i.stencilWrite===!0&&l.currentStencilRef!==i.stencilRef&&(x.setStencilReference(i.stencilRef),l.currentStencilRef=i.stencilRef)},m=(x,y)=>{if(f(x,y),s.isBatchedMesh===!0){const b=s._multiDrawStarts,v=s._multiDrawCounts,S=s._multiDrawCount,M=s._multiDrawInstances;M!==null&&Le("WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.");let A=d===!0?h.array.BYTES_PER_ELEMENT:1;i.wireframe&&(A=s.geometry.attributes.position.count>65535?4:2);for(let C=0;C<S;C++){const P=M?M[C]:1,B=P>1?0:C;d===!0?x.drawIndexed(v[C],P,b[C]/A,0,B):x.draw(v[C],P,b[C],B),t.update(s,v[C],P)}}else if(d===!0){const{vertexCount:b,instanceCount:v,firstVertex:S}=p,M=e.getIndirect();if(M!==null){const A=this.get(M).buffer,C=e.getIndirectOffset(),P=Array.isArray(C)?C:[C];for(let B=0;B<P.length;B++)x.drawIndexedIndirect(A,P[B])}else x.drawIndexed(b,v,S,0,0);t.update(s,b,v)}else{const{vertexCount:b,instanceCount:v,firstVertex:S}=p,M=e.getIndirect();if(M!==null){const A=this.get(M).buffer,C=e.getIndirectOffset(),P=Array.isArray(C)?C:[C];for(let B=0;B<P.length;B++)x.drawIndirect(A,P[B])}else x.draw(b,v,S,0);t.update(s,b,v)}};if(e.camera.isArrayCamera&&e.camera.cameras.length>0){const x=this.get(e.camera),y=e.camera.cameras,b=e.getBindingGroup("cameraIndex");if(x.indexesGPU===void 0||x.indexesGPU.length!==y.length){const S=this.get(b),M=[],A=new Uint32Array([0,0,0,0]);for(let C=0,P=y.length;C<P;C++){A[0]=C;const{layoutGPU:B}=S.layout,V=this.bindingUtils.createBindGroupIndex(A,B);M.push(V)}x.indexesGPU=M}const v=this.renderer.getPixelRatio();for(let S=0,M=y.length;S<M;S++){const A=y[S];if(s.layers.test(A.layers)){const C=A.viewport;let P=l.currentPass,B=l.currentSets;if(l.bundleEncoders){const V=l.bundleEncoders[S],Y=l.bundleSets[S];P=V,B=Y}C&&P.setViewport(Math.floor(C.x*v),Math.floor(C.y*v),Math.floor(C.width*v),Math.floor(C.height*v),n.viewportValue.minDepth,n.viewportValue.maxDepth),b&&x.indexesGPU&&(P.setBindGroup(b.index,x.indexesGPU[S]),B.bindingGroups[b.index]=b.id),m(P,B)}}}else if(l.currentPass){if(l.occlusionQuerySet!==void 0){const x=l.lastOcclusionObject;x!==s&&(x!==null&&x.occlusionTest===!0&&(l.currentPass.endOcclusionQuery(),l.occlusionQueryIndex++),s.occlusionTest===!0&&(l.currentPass.beginOcclusionQuery(l.occlusionQueryIndex),l.occlusionQueryObjects[l.occlusionQueryIndex]=s),l.lastOcclusionObject=s)}m(l.currentPass,l.currentSets)}}needsRenderUpdate(e){const t=this.get(e),{object:s,material:i}=e,n=this.utils,a=n.getSampleCountRenderContext(e.context),o=n.getCurrentColorSpace(e.context),l=n.getCurrentColorFormat(e.context),c=n.getCurrentDepthStencilFormat(e.context),u=n.getPrimitiveTopology(s,i);let h=!1;return(t.material!==i||t.materialVersion!==i.version||t.transparent!==i.transparent||t.blending!==i.blending||t.premultipliedAlpha!==i.premultipliedAlpha||t.blendSrc!==i.blendSrc||t.blendDst!==i.blendDst||t.blendEquation!==i.blendEquation||t.blendSrcAlpha!==i.blendSrcAlpha||t.blendDstAlpha!==i.blendDstAlpha||t.blendEquationAlpha!==i.blendEquationAlpha||t.colorWrite!==i.colorWrite||t.depthWrite!==i.depthWrite||t.depthTest!==i.depthTest||t.depthFunc!==i.depthFunc||t.stencilWrite!==i.stencilWrite||t.stencilFunc!==i.stencilFunc||t.stencilFail!==i.stencilFail||t.stencilZFail!==i.stencilZFail||t.stencilZPass!==i.stencilZPass||t.stencilFuncMask!==i.stencilFuncMask||t.stencilWriteMask!==i.stencilWriteMask||t.side!==i.side||t.alphaToCoverage!==i.alphaToCoverage||t.sampleCount!==a||t.colorSpace!==o||t.colorFormat!==l||t.depthStencilFormat!==c||t.primitiveTopology!==u||t.clippingContextCacheKey!==e.clippingContextCacheKey)&&(t.material=i,t.materialVersion=i.version,t.transparent=i.transparent,t.blending=i.blending,t.premultipliedAlpha=i.premultipliedAlpha,t.blendSrc=i.blendSrc,t.blendDst=i.blendDst,t.blendEquation=i.blendEquation,t.blendSrcAlpha=i.blendSrcAlpha,t.blendDstAlpha=i.blendDstAlpha,t.blendEquationAlpha=i.blendEquationAlpha,t.colorWrite=i.colorWrite,t.depthWrite=i.depthWrite,t.depthTest=i.depthTest,t.depthFunc=i.depthFunc,t.stencilWrite=i.stencilWrite,t.stencilFunc=i.stencilFunc,t.stencilFail=i.stencilFail,t.stencilZFail=i.stencilZFail,t.stencilZPass=i.stencilZPass,t.stencilFuncMask=i.stencilFuncMask,t.stencilWriteMask=i.stencilWriteMask,t.side=i.side,t.alphaToCoverage=i.alphaToCoverage,t.sampleCount=a,t.colorSpace=o,t.colorFormat=l,t.depthStencilFormat=c,t.primitiveTopology=u,t.clippingContextCacheKey=e.clippingContextCacheKey,h=!0),h}getRenderCacheKey(e){const{object:t,material:s}=e,i=this.utils,n=e.context,a=t.isMesh&&t.matrixWorld.determinant()<0;return[s.transparent,s.blending,s.premultipliedAlpha,s.blendSrc,s.blendDst,s.blendEquation,s.blendSrcAlpha,s.blendDstAlpha,s.blendEquationAlpha,s.colorWrite,s.depthWrite,s.depthTest,s.depthFunc,s.stencilWrite,s.stencilFunc,s.stencilFail,s.stencilZFail,s.stencilZPass,s.stencilFuncMask,s.stencilWriteMask,s.side,a,i.getSampleCountRenderContext(n),i.getCurrentColorSpace(n),i.getCurrentColorFormat(n),i.getCurrentDepthStencilFormat(n),i.getPrimitiveTopology(t,s),e.getGeometryCacheKey(),e.clippingContextCacheKey].join()}updateSampler(e){return this.textureUtils.updateSampler(e)}createDefaultTexture(e){return this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e,t=!1){this.textureUtils.destroyTexture(e,t)}async copyTextureToBuffer(e,t,s,i,n,a){return this.textureUtils.copyTextureToBuffer(e,t,s,i,n,a)}initTimestampQuery(e,t,s){if(!this.trackTimestamp)return;this.timestampQueryPool[e]||(this.timestampQueryPool[e]=new XL(this.device,e,2048));const i=this.timestampQueryPool[e],n=i.allocateQueriesForContext(t);s.timestampWrites={querySet:i.querySet,beginningOfPassWriteIndex:n,endOfPassWriteIndex:n+1}}createNodeBuilder(e,t){return new kL(e,t)}createProgram(e){const t=this.get(e);t.module={module:this.device.createShaderModule({code:e.code,label:e.stage+(e.name!==""?`_${e.name}`:"")}),entryPoint:"main"}}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){this.pipelineUtils.createRenderPipeline(e,t)}createComputePipeline(e,t){this.pipelineUtils.createComputePipeline(e,t)}beginBundle(e){const t=this.get(e);t._currentPass=t.currentPass,t._currentSets=t.currentSets,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.currentPass=this.pipelineUtils.createBundleEncoder(e)}finishBundle(e,t){const s=this.get(e),n=s.currentPass.finish();this.get(t).bundleGPU=n,s.currentSets=s._currentSets,s.currentPass=s._currentPass}addBundle(e,t){this.get(e).renderBundles.push(this.get(t).bundleGPU)}createBindings(e,t,s,i){this.bindingUtils.createBindings(e,t,s,i)}updateBindings(e,t,s,i){this.bindingUtils.createBindings(e,t,s,i)}updateBinding(e){this.bindingUtils.updateBinding(e)}deleteBindGroupData(e){this.bindingUtils.deleteBindGroupData(e)}createIndexAttribute(e){let t=GPUBufferUsage.INDEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST;(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(t|=GPUBufferUsage.STORAGE),this.attributeUtils.createAttribute(e,t)}createAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createIndirectStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.INDIRECT|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}updateSize(){this.delete(this.renderer.getCanvasTarget())}getMaxAnisotropy(){return 16}hasFeature(e){return Ry[e]!==void 0&&(e=Ry[e]),this.device.features.has(e)}copyTextureToTexture(e,t,s=null,i=null,n=0,a=0){let o=0,l=0,c=0,u=0,h=0,d=0,p=e.image.width,f=e.image.height,m=1;s!==null&&(s.isBox3===!0?(u=s.min.x,h=s.min.y,d=s.min.z,p=s.max.x-s.min.x,f=s.max.y-s.min.y,m=s.max.z-s.min.z):(u=s.min.x,h=s.min.y,p=s.max.x-s.min.x,f=s.max.y-s.min.y,m=1)),i!==null&&(o=i.x,l=i.y,c=i.z||0);const x=this.device.createCommandEncoder({label:"copyTextureToTexture_"+e.id+"_"+t.id}),y=this.get(e).texture,b=this.get(t).texture;x.copyTextureToTexture({texture:y,mipLevel:n,origin:{x:u,y:h,z:d}},{texture:b,mipLevel:a,origin:{x:o,y:l,z:c}},[p,f,m]),this.device.queue.submit([x.finish()]),a===0&&t.generateMipmaps&&this.textureUtils.generateMipmaps(t)}copyFramebufferToTexture(e,t,s){const i=this.get(t);let n=null;t.renderTarget?e.isDepthTexture?n=this.get(t.depthTexture).texture:n=this.get(t.textures[0]).texture:e.isDepthTexture?n=this.textureUtils.getDepthBuffer(t.depth,t.stencil):n=this.context.getCurrentTexture();const a=this.get(e).texture;if(n.format!==a.format){$("WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.",n.format,a.format);return}let o;if(i.currentPass?(i.currentPass.end(),o=i.encoder):o=this.device.createCommandEncoder({label:"copyFramebufferToTexture_"+e.id}),o.copyTextureToTexture({texture:n,origin:[s.x,s.y,0]},{texture:a},[s.z,s.w]),e.generateMipmaps&&this.textureUtils.generateMipmaps(e,o),i.currentPass){const{descriptor:l}=i;for(let c=0;c<l.colorAttachments.length;c++)l.colorAttachments[c].loadOp=De.Load;t.depth&&(l.depthStencilAttachment.depthLoadOp=De.Load),t.stencil&&(l.depthStencilAttachment.stencilLoadOp=De.Load),i.currentPass=o.beginRenderPass(l),i.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.viewport&&this.updateViewport(t),t.scissor&&this.updateScissor(t)}else this.device.queue.submit([o.finish()])}hasCompatibility(e){return this._compatibility[Bn.TEXTURE_COMPARE]!==void 0?this._compatibility[Bn.TEXTURE_COMPARE]:super.hasCompatibility(e)}dispose(){if(this.bindingUtils.dispose(),this.textureUtils.dispose(),this.occludedResolveCache){for(const e of this.occludedResolveCache.values())e.destroy();this.occludedResolveCache.clear()}if(this.timestampQueryPool)for(const e of Object.values(this.timestampQueryPool))e!==null&&e.dispose();this.parameters.device===void 0&&this.device!==null&&this.device.destroy()}}class ZL extends ef{constructor(e,t,s,i,n,a){super(e,t,s,i,n,a),this.iesMap=null}copy(e,t){return super.copy(e,t),this.iesMap=e.iesMap,this}}class QL extends ef{constructor(e,t,s,i,n,a){super(e,t,s,i,n,a),this.aspect=null}copy(e,t){return super.copy(e,t),this.aspect=e.aspect,this}}class KL extends NS{constructor(){super(),this.addMaterial(DE,"MeshPhongMaterial"),this.addMaterial(MT,"MeshStandardMaterial"),this.addMaterial(MN,"MeshPhysicalMaterial"),this.addMaterial(EN,"MeshToonMaterial"),this.addMaterial(um,"MeshBasicMaterial"),this.addMaterial(FE,"MeshLambertMaterial"),this.addMaterial(oT,"MeshNormalMaterial"),this.addMaterial(RN,"MeshMatcapMaterial"),this.addMaterial(bE,"LineBasicMaterial"),this.addMaterial(SE,"LineDashedMaterial"),this.addMaterial(ON,"PointsMaterial"),this.addMaterial(CT,"SpriteMaterial"),this.addMaterial(VN,"ShadowMaterial"),this.addLight(gB,bC),this.addLight(EO,SC),this.addLight(DO,MC),this.addLight(Fm,ef),this.addLight(AO,vC),this.addLight(NO,yC),this.addLight(PO,CC),this.addLight(RO,ZL),this.addLight(BO,QL),this.addToneMapping(jT,jM),this.addToneMapping(qT,qM),this.addToneMapping(XT,XM),this.addToneMapping(YT,YM),this.addToneMapping(ZT,ZM),this.addToneMapping(QT,QM)}}class Rd extends tL{constructor(e={}){let t;e.forceWebGL?t=My:(t=YL,e.getFallback=()=>(W("WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new My(e)));const s=new t(e);super(s,e),this.library=new KL,this.isWebGPURenderer=!0,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}class JL extends _.Line{constructor(e,t){const s=[1,1,0,-1,1,0,-1,-1,0,1,-1,0,1,1,0],i=new _.BufferGeometry;i.setAttribute("position",new _.Float32BufferAttribute(s,3)),i.computeBoundingSphere();const n=new _.LineBasicMaterial({fog:!1});super(i,n),this.light=e,this.color=t,this.type="RectAreaLightHelper";const a=[1,1,0,-1,1,0,-1,-1,0,1,1,0,-1,-1,0,1,-1,0],o=new _.BufferGeometry;o.setAttribute("position",new _.Float32BufferAttribute(a,3)),o.computeBoundingSphere(),this.add(new _.Mesh(o,new _.MeshBasicMaterial({side:_.BackSide,fog:!1})))}updateMatrixWorld(){if(this.scale.set(.5*this.light.width,.5*this.light.height,1),this.color!==void 0)this.material.color.set(this.color),this.children[0].material.color.set(this.color);else{this.material.color.copy(this.light.color).multiplyScalar(this.light.intensity);const e=this.material.color,t=Math.max(e.r,e.g,e.b);t>1&&e.multiplyScalar(1/t),this.children[0].material.color.copy(this.material.color)}this.matrixWorld.extractRotation(this.light.matrixWorld).scale(this.scale).copyPosition(this.light.matrixWorld),this.children[0].matrixWorld.copy(this.matrixWorld)}dispose(){this.geometry.dispose(),this.material.dispose(),this.children[0].geometry.dispose(),this.children[0].material.dispose()}}const Oy={type:"change"},Dm={type:"start"},zS={type:"end"},ac=new _.Ray,Ly=new _.Plane,eI=Math.cos(70*_.MathUtils.DEG2RAD),xt=new _.Vector3,Qt=2*Math.PI,$e={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},Pd=1e-6;class tI extends _.Controls{constructor(e,t=null){super(e,t),this.state=$e.NONE,this.target=new _.Vector3,this.cursor=new _.Vector3,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:_.MOUSE.ROTATE,MIDDLE:_.MOUSE.DOLLY,RIGHT:_.MOUSE.PAN},this.touches={ONE:_.TOUCH.ROTATE,TWO:_.TOUCH.DOLLY_PAN},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 _.Vector3,this._lastQuaternion=new _.Quaternion,this._lastTargetPosition=new _.Vector3,this._quat=new _.Quaternion().setFromUnitVectors(e.up,new _.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new _.Spherical,this._sphericalDelta=new _.Spherical,this._scale=1,this._panOffset=new _.Vector3,this._rotateStart=new _.Vector2,this._rotateEnd=new _.Vector2,this._rotateDelta=new _.Vector2,this._panStart=new _.Vector2,this._panEnd=new _.Vector2,this._panDelta=new _.Vector2,this._dollyStart=new _.Vector2,this._dollyEnd=new _.Vector2,this._dollyDelta=new _.Vector2,this._dollyDirection=new _.Vector3,this._mouse=new _.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=iI.bind(this),this._onPointerDown=sI.bind(this),this._onPointerUp=nI.bind(this),this._onContextMenu=hI.bind(this),this._onMouseWheel=oI.bind(this),this._onKeyDown=lI.bind(this),this._onTouchStart=cI.bind(this),this._onTouchMove=uI.bind(this),this._onMouseDown=rI.bind(this),this._onMouseMove=aI.bind(this),this._interceptControlDown=dI.bind(this),this._interceptControlUp=pI.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}set cursorStyle(e){this._cursorStyle=e,e==="grab"?this.domElement.style.cursor="grab":this.domElement.style.cursor="auto"}get cursorStyle(){return this._cursorStyle}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents(),this.domElement.getRootNode().removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction="auto"}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){this._domElementKeyEvents!==null&&(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(Oy),this.update(),this.state=$e.NONE}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;xt.copy(t).sub(this.target),xt.applyQuaternion(this._quat),this._spherical.setFromVector3(xt),this.autoRotate&&this.state===$e.NONE&&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 s=this.minAzimuthAngle,i=this.maxAzimuthAngle;isFinite(s)&&isFinite(i)&&(s<-Math.PI?s+=Qt:s>Math.PI&&(s-=Qt),i<-Math.PI?i+=Qt:i>Math.PI&&(i-=Qt),s<=i?this._spherical.theta=Math.max(s,Math.min(i,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(s+i)/2?Math.max(s,this._spherical.theta):Math.min(i,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let n=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const a=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),n=a!=this._spherical.radius}if(xt.setFromSpherical(this._spherical),xt.applyQuaternion(this._quatInverse),t.copy(this.target).add(xt),this.object.lookAt(this.target),this.enableDamping===!0?(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 a=null;if(this.object.isPerspectiveCamera){const o=xt.length();a=this._clampDistance(o*this._scale);const l=o-a;this.object.position.addScaledVector(this._dollyDirection,l),this.object.updateMatrixWorld(),n=!!l}else if(this.object.isOrthographicCamera){const o=new _.Vector3(this._mouse.x,this._mouse.y,0);o.unproject(this.object);const l=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),n=l!==this.object.zoom;const c=new _.Vector3(this._mouse.x,this._mouse.y,0);c.unproject(this.object),this.object.position.sub(c).add(o),this.object.updateMatrixWorld(),a=xt.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;a!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(a).add(this.object.position):(ac.origin.copy(this.object.position),ac.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(ac.direction))<eI?this.object.lookAt(this.target):(Ly.setFromNormalAndCoplanarPoint(this.object.up,this.target),ac.intersectPlane(Ly,this.target))))}else if(this.object.isOrthographicCamera){const a=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),a!==this.object.zoom&&(this.object.updateProjectionMatrix(),n=!0)}return this._scale=1,this._performCursorZoom=!1,n||this._lastPosition.distanceToSquared(this.object.position)>Pd||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Pd||this._lastTargetPosition.distanceToSquared(this.target)>Pd?(this.dispatchEvent(Oy),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?Qt/60*this.autoRotateSpeed*e:Qt/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){xt.setFromMatrixColumn(t,0),xt.multiplyScalar(-e),this._panOffset.add(xt)}_panUp(e,t){this.screenSpacePanning===!0?xt.setFromMatrixColumn(t,1):(xt.setFromMatrixColumn(t,0),xt.crossVectors(this.object.up,xt)),xt.multiplyScalar(e),this._panOffset.add(xt)}_pan(e,t){const s=this.domElement;if(this.object.isPerspectiveCamera){const i=this.object.position;xt.copy(i).sub(this.target);let n=xt.length();n*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*n/s.clientHeight,this.object.matrix),this._panUp(2*t*n/s.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/s.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/s.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 s=this.domElement.getBoundingClientRect(),i=e-s.left,n=t-s.top,a=s.width,o=s.height;this._mouse.x=i/a*2-1,this._mouse.y=-(n/o)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Qt*this._rotateDelta.x/t.clientHeight),this._rotateUp(Qt*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(Qt*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(-Qt*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(Qt*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(-Qt*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),s=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._rotateStart.set(s,i)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),s=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panStart.set(s,i)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),s=e.pageX-t.x,i=e.pageY-t.y,n=Math.sqrt(s*s+i*i);this._dollyStart.set(0,n)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const s=this._getSecondPointerPosition(e),i=.5*(e.pageX+s.x),n=.5*(e.pageY+s.y);this._rotateEnd.set(i,n)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Qt*this._rotateDelta.x/t.clientHeight),this._rotateUp(Qt*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),s=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panEnd.set(s,i)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),s=e.pageX-t.x,i=e.pageY-t.y,n=Math.sqrt(s*s+i*i);this._dollyEnd.set(0,n),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const a=(e.pageX+t.x)*.5,o=(e.pageY+t.y)*.5;this._updateZoomParameters(a,o)}_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){this._pointers.splice(t,1);return}}_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];t===void 0&&(t=new _.Vector2,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,s={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:s.deltaY*=16;break;case 2:s.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(s.deltaY*=10),s}}function sI(r){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(r.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(r)&&(this._addPointer(r),r.pointerType==="touch"?this._onTouchStart(r):this._onMouseDown(r),this._cursorStyle==="grab"&&(this.domElement.style.cursor="grabbing")))}function iI(r){this.enabled!==!1&&(r.pointerType==="touch"?this._onTouchMove(r):this._onMouseMove(r))}function nI(r){switch(this._removePointer(r),this._pointers.length){case 0:this.domElement.releasePointerCapture(r.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(zS),this.state=$e.NONE,this._cursorStyle==="grab"&&(this.domElement.style.cursor="grab");break;case 1:const e=this._pointers[0],t=this._pointerPositions[e];this._onTouchStart({pointerId:e,pageX:t.x,pageY:t.y});break}}function rI(r){let e;switch(r.button){case 0:e=this.mouseButtons.LEFT;break;case 1:e=this.mouseButtons.MIDDLE;break;case 2:e=this.mouseButtons.RIGHT;break;default:e=-1}switch(e){case _.MOUSE.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(r),this.state=$e.DOLLY;break;case _.MOUSE.ROTATE:if(r.ctrlKey||r.metaKey||r.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(r),this.state=$e.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(r),this.state=$e.ROTATE}break;case _.MOUSE.PAN:if(r.ctrlKey||r.metaKey||r.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(r),this.state=$e.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(r),this.state=$e.PAN}break;default:this.state=$e.NONE}this.state!==$e.NONE&&this.dispatchEvent(Dm)}function aI(r){switch(this.state){case $e.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(r);break;case $e.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(r);break;case $e.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(r);break}}function oI(r){this.enabled===!1||this.enableZoom===!1||this.state!==$e.NONE||(r.preventDefault(),this.dispatchEvent(Dm),this._handleMouseWheel(this._customWheelEvent(r)),this.dispatchEvent(zS))}function lI(r){this.enabled!==!1&&this._handleKeyDown(r)}function cI(r){switch(this._trackPointer(r),this._pointers.length){case 1:switch(this.touches.ONE){case _.TOUCH.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(r),this.state=$e.TOUCH_ROTATE;break;case _.TOUCH.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(r),this.state=$e.TOUCH_PAN;break;default:this.state=$e.NONE}break;case 2:switch(this.touches.TWO){case _.TOUCH.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(r),this.state=$e.TOUCH_DOLLY_PAN;break;case _.TOUCH.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(r),this.state=$e.TOUCH_DOLLY_ROTATE;break;default:this.state=$e.NONE}break;default:this.state=$e.NONE}this.state!==$e.NONE&&this.dispatchEvent(Dm)}function uI(r){switch(this._trackPointer(r),this.state){case $e.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(r),this.update();break;case $e.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(r),this.update();break;case $e.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(r),this.update();break;case $e.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(r),this.update();break;default:this.state=$e.NONE}}function hI(r){this.enabled!==!1&&r.preventDefault()}function dI(r){r.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function pI(r){r.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}/*!
20
+ C11,8.22,10.74,8,10.43,8z`})});function ri(i){return u.jsx("li",{className:`reorder-item ${i.draggingIndex===i.index?"dragging":""}`,draggable:!0,onDragStart:()=>i.onDragStart(i.index),onDragOver:e=>{e.preventDefault(),i.onDragOver(i.index)},onDragEnd:i.onDragEnd,children:u.jsxs("div",{children:[Ws,u.jsx("span",{children:i.title}),u.jsx("button",{className:"closeIcon",onClick:()=>i.onDelete(i.index),children:Gs})]})})}function ai(i){const[e,t]=b.useState(!1),[s,n]=b.useState(i.options),[a,r]=b.useState(null),o=g=>{i.onDragComplete(g),n(g)},c=g=>{const y=[...s];y.splice(g,1),o(y)},l=g=>{r(g)},h=g=>{if(a===g||a===null)return;const y=[...s],_=y.splice(a,1)[0];y.splice(g,0,_),r(g),n(y)},p=()=>{i.onDragComplete(s),r(null)};let m="dropdown draggable";return i.subdropdown&&(m+=" subdropdown"),u.jsxs("div",{className:m,onMouseEnter:()=>t(!0),onMouseLeave:()=>t(!1),children:[u.jsx(St,{title:i.title}),u.jsx("ul",{className:"reorder-list",style:{display:e?"block":"none"},children:s.map((g,y)=>u.jsx(ri,{title:g,index:y,draggingIndex:a,onDelete:c,onDragStart:l,onDragOver:h,onDragEnd:p},g))})]})}function oi(i){const[e,t]=b.useState(!1),s=[];i.options.map((a,r)=>{i.onSelect!==void 0&&(a.onSelect=i.onSelect),s.push(u.jsx(li,{option:a},r))});let n="dropdown";return i.subdropdown&&(n+=" subdropdown"),u.jsxs("div",{className:n,onMouseEnter:()=>t(!0),onMouseLeave:()=>t(!1),children:[u.jsx(St,{title:i.title}),u.jsx("ul",{style:{visibility:e?"visible":"hidden"},children:s})]})}function li(i){const{option:e}=i,[t,s]=b.useState("");let n;switch(e.type){case"draggable":n=u.jsx(ai,{title:e.title,options:e.value,onDragComplete:a=>{e.onDragComplete!==void 0&&e.onDragComplete(a)},subdropdown:!0});break;case"dropdown":n=u.jsx(oi,{title:e.title,options:e.value,onSelect:e.onSelect,subdropdown:!0});break;case"option":n=u.jsx("button",{onClick:()=>{e.onSelect!==void 0&&e.onSelect(e.value),e.selectable&&(t!==e.title?s(e.title):s(""))},children:e.title});break}return u.jsx("li",{className:t===e.title?"selected":"",children:n},W())}function Te(i){const[e,t]=b.useState(i.open!==void 0?i.open:!1),[s,n]=b.useState(i.visible!==void 0?i.visible:!1),a=!e||i.children===void 0,r=()=>{i.three.dispatchEvent({type:I.REMOVE_SCENE,value:i.scene})};return u.jsxs("div",{className:`accordion ${a?"hide":""}`,children:[u.jsxs("button",{className:"toggle",onClick:()=>{const o=!e;i.onToggle!==void 0&&i.onToggle(o),t(o)},children:[u.jsx("p",{className:`status ${e?"open":""}`,children:"Toggle"}),u.jsx("p",{className:"label",children:ze(i.label)})]}),i.onRefresh?u.jsxs(u.Fragment,{children:[u.jsx("button",{className:"visibility",style:{opacity:s?1:.25},onClick:()=>{const c=i.three.getScene(i.scene.uuid);if(c){const l=!c.visible;c.visible=l,n(l)}}}),u.jsx("button",{className:"refresh",onClick:i.onRefresh}),u.jsx("button",{className:"remove",onClick:r})]}):null,i.button,u.jsx("div",{className:e?"open":"",children:u.jsx("div",{children:i.children})},Math.random())]})}function xt(i){if(i.child===void 0)return console.log("Hermes - No child attached"),null;const e=b.useRef(null),[t,s]=b.useState(!1),n=i.child.children.length>0,a=[];return i.child.children.length>0&&i.child.children.map((r,o)=>{a.push(u.jsx(xt,{child:r,three:i.three},o))}),b.useEffect(()=>{if(i.child){const r=i.child.uuid.split(".")[0],o=i.three.getScene(r);if(o!==null)try{const c=o.getObjectByProperty("uuid",i.child.uuid);c!==void 0?e.current.style.opacity=c.visible?"1":"0.25":console.log(`Hermes - Can't find child: ${i.child.uuid}`)}catch(c){console.log("Error looking for child:",c),console.log(i.child),console.log(i.three.scenes),console.log(o)}else console.log(`Hermes (ChildObject) - Can't find Scene: ${r} with child UUID: ${i.child.uuid}`,i.three.scenes,i.three.scene,o)}},[t]),u.jsxs("div",{className:"childObject",children:[u.jsxs("div",{className:"child",children:[n?u.jsx("button",{className:"status",style:{backgroundPositionX:t?"-14px":"2px"},onClick:()=>{s(!t)}}):null,u.jsx("button",{className:"name",style:{left:n?"20px":"5px"},onClick:()=>{i.child!==void 0?(i.three.getObject(i.child.uuid),!t&&n&&s(!0)):console.log("Hermes - No child attached...")},children:i.child.name.length>0?`${i.child.name} (${i.child.type})`:`${i.child.type}::${i.child.uuid}`}),u.jsx("button",{className:"visibility",ref:e,onClick:()=>{if(i.child){const r=i.three.getScene(i.child.uuid);if(r!==null){const o=r.getObjectByProperty("uuid",i.child.uuid);if(o!==void 0){const c="visible",l=!o.visible;e.current.style.opacity=l?"1":"0.25",i.three.updateObject(i.child.uuid,c,l),B(o,c,l)}else console.log(`Hermes - Couldn't find object: ${i.child.uuid}`,r)}else console.log(`Hermes - Couldn't find object in scene: ${i.child.uuid}, ${i.child.name}`)}}}),u.jsx("div",{className:`icon ${Fs(i.child)}`})]}),u.jsx("div",{className:t?"open":"",children:u.jsx("div",{className:"container",children:a})})]},Math.random())}function Ye(i){const e=[];return i.child?.children.map((t,s)=>{e.push(u.jsx(xt,{child:t,scene:i.scene,three:i.three},s))}),u.jsx("div",{className:`scene ${i.class!==void 0?i.class:""}`,children:e})}function Ne(i){const[e,t]=b.useState(i.defaultValue);return b.useEffect(()=>{let s=!1,n=-1,a=0,r=i.defaultValue,o=!1;const c=g=>{o=g.ctrlKey},l=g=>{s=!0,a=Number(i.input.current?.value),n=g.clientX,document.addEventListener("mouseup",p,!1),document.addEventListener("mousemove",h,!1),document.addEventListener("contextmenu",p,!1)},h=g=>{if(!s)return;const y=i.step!==void 0?i.step:1,_=(g.clientX-n)*y*(o?10:1);r=Number((a+_).toFixed(4)),i.min!==void 0&&(r=Math.max(r,i.min)),i.max!==void 0&&(r=Math.min(r,i.max)),i.onChange!==void 0&&i.onChange(r),t(r)},p=()=>{s=!1,document.removeEventListener("mouseup",p),document.removeEventListener("mousemove",h),document.removeEventListener("contextmenu",p)},m=g=>{const y=Number(g.target.value);i.onChange!==void 0&&i.onChange(y),t(y)};return i.label.current?.addEventListener("mousedown",l,!1),i.sliderRef!==void 0&&i.sliderRef.current?.addEventListener("input",m),document.addEventListener("keydown",c,!1),document.addEventListener("keyup",c,!1),()=>{i.label.current?.removeEventListener("mousedown",l),i.sliderRef!==void 0&&i.sliderRef.current?.removeEventListener("input",m),document.removeEventListener("mouseup",p),document.removeEventListener("mousemove",h),document.removeEventListener("contextmenu",p),document.removeEventListener("keydown",c),document.addEventListener("keyup",c,!1)}},[]),e}function ge(i){const e=b.useRef(null),t=b.useRef(null),[s,n]=b.useState(i.value);return Ne({label:i.labelRef,input:e,sliderRef:t,defaultValue:s,min:i.min,max:i.max,step:i.step,onChange:a=>{n(a),i.onChange!==void 0&&i.onChange(i.prop,a)}}),u.jsxs(u.Fragment,{children:[i.type==="number"&&u.jsx("input",{alt:i.alt,className:i.className,ref:e,type:"number",value:s,min:i.min,max:i.max,step:i.step,disabled:i.disabled,name:W(),onChange:a=>{if(n(a.target.value),a.target.value.length===0)return;const r=Number(a.target.value);isNaN(r)||i.onChange!==void 0&&i.onChange(i.prop,r)}}),i.type==="range"&&u.jsxs(u.Fragment,{children:[u.jsx("input",{type:"text",value:s.toString(),disabled:i.disabled,ref:e,className:"min",name:W(),onChange:a=>{if(a.target.value.length===0)return;const r=Number(a.target.value);isNaN(r)||(n(r),i.onChange!==void 0&&i.onChange(i.prop,r))}}),u.jsx("input",{disabled:i.disabled,type:"range",value:s,min:i.min,max:i.max,step:i.step,ref:t,name:W(),onChange:Fe})]})]})}function Ys(i){const e=b.useRef(null),t=b.useRef(null),s=b.useRef(null),n=b.useRef(null),a=b.useRef(null),r=b.useRef(null),o=b.useRef(null),c=b.useRef(null),l=b.useRef(null),h=b.useRef(null),[p,m]=b.useState(i.value.x),[g,y]=b.useState(i.value.y),[_,E]=b.useState({min:Math.min(i.min,Math.min(i.value.x,i.value.y)),max:Math.max(i.max,Math.max(i.value.x,i.value.y))}),[v,C]=b.useState(!1);Ne({label:o,input:e,defaultValue:p,min:_.min,max:_.max,step:.01,onChange:A=>{m(A),i.onChange({target:{value:{x:A,y:g}}})}}),Ne({label:c,input:t,defaultValue:g,min:_.min,max:_.max,step:.01,onChange:A=>{y(A),i.onChange({target:{value:{x:p,y:A}}})}}),Ne({label:l,input:s,defaultValue:_.min,min:_.min-1,max:_.max+1,step:.01,onChange:A=>{E({min:A,max:_.max})}}),Ne({label:h,input:n,defaultValue:_.max,min:_.min-1,max:_.max+1,step:.01,onChange:A=>{E({min:_.min,max:A})}});function x(){v||(window.addEventListener("mousemove",S),window.addEventListener("mouseup",O),C(!0))}function O(){window.removeEventListener("mousemove",S),window.removeEventListener("mouseup",O),C(!1)}function S(A){const F=a.current.getBoundingClientRect(),Q=he(0,99,A.clientX-F.left)/99,re=1-he(0,99,A.clientY-F.top)/99,de=K(Me(_.min,_.max,Q),3),ve=K(Me(_.min,_.max,re),3);i.onChange({target:{value:{x:de,y:ve}}}),m(de),y(ve)}function w(){const A=Number(s.current.value);E({min:A,max:_.max}),p<A&&m(he(A,_.max,p)),g<A&&y(he(A,_.max,g))}function M(){const A=Number(n.current.value);E({min:_.min,max:A}),p>A&&m(he(_.min,A,p)),g>A&&y(he(_.min,A,g))}b.useEffect(()=>{r.current.style.left=`${$e(_.min,_.max,p)*100}%`,r.current.style.top=`${(1-$e(_.min,_.max,g))*100}%`},[_,p,g]);const L=i.step!==void 0?i.step:.01;return u.jsxs("div",{className:"vector2",children:[u.jsxs("div",{className:"fields",children:[u.jsxs("div",{children:[u.jsx("span",{ref:o,children:"X"}),u.jsx("input",{ref:e,type:"number",value:p,min:_.min,max:_.max,step:L,name:W(),onChange:A=>{if(m(A.target.value),A.target.value.length===0)return;const F=Number(A.target.value);isNaN(F)||(i.onChange({target:{value:{x:F,y:g}}}),F<_.min&&E({min:F,max:_.max}))}})]}),u.jsxs("div",{children:[u.jsx("span",{ref:c,children:"Y"}),u.jsx("input",{ref:t,type:"number",value:g,min:_.min,max:_.max,step:L,name:W(),onChange:A=>{if(y(A.target.value),A.target.value.length===0)return;const F=Number(A.target.value);isNaN(F)||(i.onChange({target:{value:{x:p,y:F}}}),F>_.max&&E({min:_.min,max:F}))}})]}),u.jsxs("div",{children:[u.jsx("span",{ref:l,children:"Min"}),u.jsx("input",{ref:s,type:"number",value:_.min,step:L,name:W(),onChange:w})]}),u.jsxs("div",{children:[u.jsx("span",{ref:h,children:"Max"}),u.jsx("input",{ref:n,type:"number",value:_.max,step:L,name:W(),onChange:M})]})]}),u.jsxs("div",{className:"input",ref:a,onMouseDown:x,onMouseUp:O,children:[u.jsx("div",{className:"x"}),u.jsx("div",{className:"y"}),u.jsx("div",{className:"pt",ref:r})]})]})}function Pt(i){const e=i.value.x!==void 0&&i.value.y!==void 0&&i.value.z!==void 0,t=i.value.isEuler!==void 0,s=i.value.elements!==void 0,n=i.step!==void 0?i.step:.01,a=[];if(t){const r=b.useMemo(()=>i.value,[]);["_x","_y","_z"].forEach(c=>{const l=b.useRef(null);a.push(u.jsxs("div",{children:[u.jsx("span",{ref:l,children:c.substring(1).toUpperCase()}),u.jsx(ge,{value:Z.radToDeg(r[c]),type:"number",prop:c,step:.1,labelRef:l,onChange:(h,p)=>{r[h]=Z.degToRad(p),i.onChange({target:{value:r}})}})]},c))})}else if(e){const r=b.useMemo(()=>i.value,[]),o=(l,h)=>{r[l]=h,i.onChange({target:{value:r}})};["x","y","z"].forEach(l=>{const h=b.useRef(null);a.push(u.jsxs("div",{children:[u.jsx("label",{ref:h,children:l.toUpperCase()}),u.jsx(ge,{value:r[l],type:"number",prop:l,step:n,labelRef:h,onChange:o})]},l))})}else if(s){const r=b.useMemo(()=>i.value,[]),o=(c,l)=>{const h=Number(c);r.elements[h]=l,i.onChange({target:{value:r}})};for(let c=0;c<9;c++){const l=b.useRef(null);a.push(u.jsxs("div",{children:[u.jsx("label",{ref:l,children:c+1}),u.jsx(ge,{value:r.elements[c],type:"number",prop:c.toString(),step:n,labelRef:l,onChange:o})]},c.toString()))}}return u.jsx("div",{className:"grid3",children:a},Math.random().toString())}function Zs(i){const e=i.value.x!==void 0,t=i.step!==void 0?i.step:.01,s=[];if(e){const n=b.useMemo(()=>i.value,[]),a=(o,c)=>{n[o]=c,i.onChange({target:{value:n}})};["x","y","z","w"].forEach(o=>{const c=b.useRef(null);s.push(u.jsxs("div",{children:[u.jsx("label",{ref:c,children:o.toUpperCase()}),u.jsx(ge,{value:n[o],type:"number",prop:o,step:t,labelRef:c,onChange:a})]},o))})}else{const n=b.useMemo(()=>i.value,[]),a=(r,o)=>{const c=Number(r);n.elements[c]=o,i.onChange({target:{value:n}})};for(let r=0;r<16;r++){const o=b.useRef(null);s.push(u.jsxs("div",{children:[u.jsx("span",{ref:o,children:r+1}),u.jsx(ge,{value:n.elements[r],type:"number",prop:r.toString(),step:t,labelRef:o,onChange:a})]},r.toString()))}}return u.jsx("div",{className:"grid4",children:s})}function qs(i){return!(i==="defaultAttributeValues"||i==="forceSinglePass"||i==="linecap"||i==="linejoin"||i==="linewidth"||i==="normalMapType"||i==="precision"||i==="shadowSide"||i==="uniformsGroups"||i==="uniformsNeedUpdate"||i==="userData"||i==="version"||i==="wireframeLinecap"||i==="wireframeLinejoin"||i==="wireframeLinewidth"||i.slice(0,4)==="clip"||i.slice(0,7)==="polygon"||i.slice(0,7)==="stencil"||i.slice(0,2)==="is")}function $s(i){switch(i){case"Alpha Map":return"alphaMap";case"Anisotropy Map":return"anisotropyMap";case"AO Map":return"aoMap";case"Bump Map":return"bumpMap";case"Clearcoat Map":return"clearcoatMap";case"Clearcoat Normal Map":return"clearcoatNormalMap";case"Clearcoat Roughness Map":return"clearcoatRoughnessMap";case"Displacement Map":return"displacementMap";case"Emissive Map":return"emissiveMap";case"Gradient Map":return"gradientMap";case"Iridescence Map":return"iridescenceMap";case"Iridescence Thickness Map":return"iridescenceThicknessMap";case"Map":return"map";case"Matcap":return"matcap";case"Normal Map":return"normalMap";case"Roughness Map":return"roughnessMap";case"Sheen Color Map":return"sheenColorMap";case"Sheen Roughness Map":return"sheenRoughnessMap";case"Specular Color Map":return"specularColorMap";case"Specular Map Intensity":return"specularIntensityMap";case"Thickness Map":return"thicknessMap";case"Transmission Map":return"transmissionMap"}return i}function Qe(i){switch(i){case"alphaHash":return"Alpha Hash";case"alphaMap":return"Alpha Map";case"alphaToCoverage":return"Alpha To Coverage";case"anisotropy":return"Anisotropy";case"anisotropyMap":return"Anisotropy Map";case"anisotropyRotation":return"Anisotropy Rotation";case"aoMap":return"AO Map";case"aoMapIntensity":return"AO Map Intensity";case"attenuationColor":return"Attenuation Color";case"attenuationDistance":return"Attenuation Distance";case"blendAlpha":return"Blend Alpha";case"blendColor":return"Blend Color";case"blendDst":return"Blend Dst";case"blendDstAlpha":return"Blend Dst Alha";case"blendEquation":return"Blend Equation";case"blendEquationAlpha":return"Blend Equation Alpha";case"blending":return"Blending";case"blendSrc":return"Blend Src";case"blendSrcAlpha":return"Blend Src Alpha";case"bumpMap":return"Bump Map";case"bumpScale":return"Bump Scale";case"clearcoat":return"Clearcoat";case"clearcoatMap":return"Clearcoat Map";case"clearcoatNormalMap":return"Clearcoat Normal Map";case"clearcoatNormalScale":return"Clearcoat Normal Scale";case"clearcoatRoughness":return"Clearcoat Roughness";case"clearcoatRoughnessMap":return"Clearcoat Roughness Map";case"color":return"Color";case"colorWrite":return"Color Write";case"defines":return"Defines";case"depthFunc":return"Depth Func";case"depthTest":return"Depth Test";case"depthWrite":return"Depth Write";case"dispersion":return"Dispersion";case"displacementBias":return"Displacement Bias";case"displacementMap":return"Displacement Map";case"displacementScale":return"Displacement Scale";case"dithering":return"Dithering";case"emissive":return"Emissive";case"emissiveMap":return"Emissive Map";case"emissiveIntensity":return"Emissive Intensity";case"envMap":return"Environment Map";case"envMapIntensity":return"Environment Map Intensity";case"envMapRotation":return"Environment Map Rotation";case"extensions":return"Extensions";case"flatShading":return"Flat Shading";case"fragmentShader":return"Fragment Shader";case"fog":return"Fog";case"glslVersion":return"GLSL Version";case"gradientMap":return"Gradient Map";case"ior":return"IOR";case"iridescence":return"Iridescence";case"iridescenceIOR":return"Iridescence IOR";case"iridescenceMap":return"Iridescence Map";case"iridescenceThicknessMap":return"Iridescence Thickness Map";case"iridescenceThicknessRange":return"Iridescence Thickness Range";case"lights":return"Lights";case"lightMap":return"Light Map";case"lightMapIntensity":return"Light Map Intensity";case"map":return"Map";case"matcap":return"Matcap";case"metalness":return"Metalness";case"metalnessMap":return"Metalness Map";case"name":return"Name";case"normalMap":return"Normal Map";case"normalScale":return"Normal Scale";case"premultipliedAlpha":return"Premultiplied Alpha";case"opacity":return"Opacity";case"reflectivity":return"Reflectivity";case"refractionRatio":return"Refraction Ratio";case"roughness":return"Roughness";case"roughnessMap":return"Roughness Map";case"sheen":return"Sheen";case"sheenColor":return"Sheen Color";case"sheenColorMap":return"Sheen Color Map";case"sheenRoughness":return"Sheen Roughness";case"sheenRoughnessMap":return"Sheen Roughness Map";case"shininess":return"Shininess";case"side":return"Side";case"size":return"Size";case"sizeAttenuation":return"Size Attenuation";case"specular":return"Specular";case"specularColor":return"Specular Color";case"specularColorMap":return"Specular Color Map";case"specularIntensity":return"Specular Intensity";case"specularIntensityMap":return"Specular Map Intensity";case"thickness":return"Thickness";case"thicknessMap":return"Thickness Map";case"toneMapped":return"Tone Mapped";case"transmission":return"Transmission";case"transmissionMap":return"Transmission Map";case"transparent":return"Transparent";case"type":return"Type";case"uuid":return"UUID";case"uniforms":return"Uniforms";case"vertexColors":return"Vertex Colors";case"vertexShader":return"Vertex Shader";case"visible":return"Visible";case"wireframe":return"Wireframe"}return i}function ci(i){const e=i.toLowerCase();return e.search("intensity")>-1||e==="anisotropyrotation"||e==="blendalpha"||e==="bumpscale"||e==="clearcoatroughness"||e==="displacementbias"||e==="displacementscale"||e==="metalness"||e==="opacity"||e==="reflectivity"||e==="refractionratio"||e==="roughness"||e==="sheenroughness"}function Ks(){const i=document.createElement("input");return i.type="file",new Promise((e,t)=>{i.addEventListener("change",function(){if(i.files===null)t();else{const s=i.files[0],n=new FileReader;n.onload=function(a){e(a.target.result)},n.readAsDataURL(s)}}),i.click()})}const Xs=[{title:"Front",value:d.FrontSide},{title:"Back",value:d.BackSide},{title:"Double",value:d.DoubleSide}],Qs=[{title:"No Blending",value:d.NoBlending},{title:"Normal",value:d.NormalBlending},{title:"Additive",value:d.AdditiveBlending},{title:"Subtractive",value:d.SubtractiveBlending},{title:"Multiply",value:d.MultiplyBlending},{title:"Custom",value:d.CustomBlending}],Js=[{title:"Add",value:d.AddEquation},{title:"Subtract",value:d.SubtractEquation},{title:"Reverse Subtract",value:d.ReverseSubtractEquation},{title:"Min",value:d.MinEquation},{title:"Max",value:d.MaxEquation}],en=[{title:"Zero",value:d.ZeroFactor},{title:"One",value:d.OneFactor},{title:"Src Color",value:d.SrcColorFactor},{title:"One Minus Src Color",value:d.OneMinusSrcColorFactor},{title:"Src Alpha",value:d.SrcAlphaFactor},{title:"One Minus Src Alpha",value:d.OneMinusSrcAlphaFactor},{title:"Dst Alpha",value:d.DstAlphaFactor},{title:"One Minus Dst Alpha",value:d.OneMinusDstAlphaFactor},{title:"Dst Color",value:d.DstColorFactor},{title:"One Minus Dst Color",value:d.OneMinusDstColorFactor},{title:"Src Alpha Saturate",value:d.SrcAlphaSaturateFactor},{title:"Constant Color",value:d.ConstantColorFactor},{title:"One Minus Constant Color",value:d.OneMinusConstantColorFactor},{title:"Constant Alpha",value:d.ConstantAlphaFactor},{title:"One Minus Constant Alpha",value:d.OneMinusConstantAlphaFactor}],tn=[{title:"Zero",value:d.ZeroFactor},{title:"One",value:d.OneFactor},{title:"Src Color",value:d.SrcColorFactor},{title:"One Minus Src Color",value:d.OneMinusSrcColorFactor},{title:"Src Alpha",value:d.SrcAlphaFactor},{title:"One Minus Src Alpha",value:d.OneMinusSrcAlphaFactor},{title:"Dst Alpha",value:d.DstAlphaFactor},{title:"One Minus Dst Alpha",value:d.OneMinusDstAlphaFactor},{title:"Dst Color",value:d.DstColorFactor},{title:"One Minus Dst Color",value:d.OneMinusDstColorFactor},{title:"Constant Color",value:d.ConstantColorFactor},{title:"One Minus Constant Color",value:d.OneMinusConstantColorFactor},{title:"Constant Alpha",value:d.ConstantAlphaFactor},{title:"One Minus Constant Alpha",value:d.OneMinusConstantAlphaFactor}];function Ae(i,e){i.needsUpdate=!0,i.type="option",i.options=e}function sn(i,e,t,s){return{type:"boolean",title:Qe(i),prop:i,value:e,needsUpdate:!0,onChange:(n,a)=>{s.updateObject(t.uuid,`material.${i}`,a),s.updateObject(t.uuid,"material.needsUpdate",!0);const r=s.getScene(t.uuid);if(r!==null){const o=r.getObjectByProperty("uuid",t.uuid);B(o,`material.${i}`,a)}}}}function nn(i,e,t,s){const n={type:"number",title:Qe(i),prop:i,value:e,min:void 0,max:void 0,step:.01,needsUpdate:!0,onChange:(a,r)=>{s.updateObject(t.uuid,`material.${i}`,r),s.updateObject(t.uuid,"material.needsUpdate",!0);const o=s.getScene(t.uuid);if(o!==null){const c=o.getObjectByProperty("uuid",t.uuid);B(c,`material.${i}`,r)}}};switch(i){case"blending":Ae(n,Qs);break;case"blendDst":Ae(n,tn);break;case"blendEquation":Ae(n,Js);break;case"blendSrc":Ae(n,en);break;case"side":Ae(n,Xs);break}return ci(i)&&(n.value=Number(e),n.type="range",n.min=Math.min(0,n.value),n.max=Math.max(1,n.value),n.step=.01),n}function rn(i,e,t,s){const n={type:"string",title:Qe(i),prop:i,value:e,needsUpdate:!0,onChange:(r,o)=>{s.updateObject(t.uuid,`material.${i}`,o),s.updateObject(t.uuid,"material.needsUpdate",!0);const c=s.getScene(t.uuid);if(c!==null){const l=c.getObjectByProperty("uuid",t.uuid);B(l,`material.${i}`,o)}},onKeyDown:r=>{}};return(i==="vertexShader"||i==="fragmentShader")&&(n.type="field",n.disabled=!1,n.latest=n.value,n.onChange=(r,o)=>{n.latest=o,s.updateObject(t.uuid,`material.${i}`,o);const c=s.getScene(t.uuid);if(c!==null){const l=c.getObjectByProperty("uuid",t.uuid);B(l,`material.${i}`,o)}},n.onKeyDown=r=>{if(r.key==="Enter"&&(r.altKey||r.metaKey)){s.updateObject(t.uuid,"material.needsUpdate",!0);const o=s.getScene(t.uuid);if(o!==null){const c=o.getObjectByProperty("uuid",t.uuid);B(c,"material.needsUpdate",!0)}}}),n}function an(i){return i.x!==void 0&&i.y!==void 0&&i.z===void 0}function on(i){return i.x!==void 0&&i.y!==void 0&&i.z!==void 0&&i.w===void 0}function ln(i){return i.x!==void 0&&i.y!==void 0&&i.z!==void 0&&i.w!==void 0}function Ct(i){i.sort((e,t)=>e.title<t.title?-1:e.title>t.title?1:0)}function ke(i,e,t,s,n="",a=!1){const r=Qe(i).split(".")[0].replaceAll("[","").replaceAll("]",""),o=n.length>0?`${n}.${i}`:i,c=typeof e;if(c==="boolean"||c==="string")return{title:r,prop:o,type:c,value:e,disabled:a,onChange:(l,h)=>{s.updateObject(t.uuid,`material.${o}`,h);const p=s.getScene(t.uuid);if(p!==null){const m=p.getObjectByProperty("uuid",t.uuid);B(m,`material.${o}`,h)}}};if(c==="number"){const l={title:r,prop:o,type:"number",value:e,step:.01,disabled:a,onChange:(h,p)=>{s.updateObject(t.uuid,`material.${o}`,p);const m=s.getScene(t.uuid);if(m!==null){const g=m.getObjectByProperty("uuid",t.uuid);B(g,`material.${o}`,p)}}};return ci(r)&&(l.type="range",l.min=0,l.max=1),l}else{if(e.isColor)return{title:r,prop:o,type:"color",value:e,disabled:a,onChange:(l,h)=>{const p=new d.Color(h);s.updateObject(t.uuid,`material.${o}`,p);const m=s.getScene(t.uuid);if(m!==null){const g=m.getObjectByProperty("uuid",t.uuid);B(g,`material.${o}`,p)}}};if(Array.isArray(e)){const l=[];for(const h in e){const p=e[h],m=`[${h.toString()}]`;if(p.value!==void 0){const g=ke(`${m}.value`,p.value,t,s,o,a);g!==void 0&&l.push(g)}else{const g=ke(m,p,t,s,o,a);g!==void 0&&l.push(g)}}if(l.length>0)return Ct(l),{title:r,items:l}}else{if(an(e))return{title:r,prop:o,type:"vector2",value:e,disabled:a,onChange:(l,h)=>{s.updateObject(t.uuid,`material.${o}`,h);const p=s.getScene(t.uuid);if(p!==null){const m=p.getObjectByProperty("uuid",t.uuid);B(m,`material.${o}`,h)}}};if(on(e))return{title:r,prop:o,type:"grid3",value:e,disabled:a,onChange:(l,h)=>{s.updateObject(t.uuid,`material.${o}`,h);const p=s.getScene(t.uuid);if(p!==null){const m=p.getObjectByProperty("uuid",t.uuid);B(m,`material.${o}`,h)}}};if(ln(e))return{title:r,prop:o,type:"grid4",value:e,disabled:a,onChange:(l,h)=>{s.updateObject(t.uuid,`material.${o}`,h);const p=s.getScene(t.uuid);if(p!==null){const m=p.getObjectByProperty("uuid",t.uuid);B(m,`material.${o}`,h)}}};if(e.isEuler)return{title:r,prop:o,type:"euler",value:e,disabled:a,onChange:(l,h)=>{s.updateObject(t.uuid,`material.${o}`,h);const p=s.getScene(t.uuid);if(p!==null){const m=p.getObjectByProperty("uuid",t.uuid);B(m,`material.${o}`,h)}}};if(e.src!==void 0)return{title:r,type:"image",value:e,disabled:a,onChange:(l,h)=>{const p=$s(i),m=n.length>0?`${n}.${p}`:p;s.createTexture(t.uuid,`material.${m}`,h);const g=s.getScene(t.uuid);if(g!==null){const y=g.getObjectByProperty("uuid",t.uuid);if(y!==void 0){const _=E=>{const v=y.material,C=m.split(".");switch(C.length){case 1:v[C[0]]=E;break;case 2:v[C[0]][C[1]]=E;break;case 3:v[C[0]][C[1]][C[2]]=E;break;case 4:v[C[0]][C[1]][C[2]][C[3]]=E;break;case 5:v[C[0]][C[1]][C[2]][C[3]][C[4]]=E;break}v.needsUpdate=!0};h.src.length>0?ni(h.src).then(E=>{E.offset.set(h.offset[0],h.offset[1]),E.repeat.set(h.repeat[0],h.repeat[1]),_(E)}):_(null)}}}};if(e.elements!==void 0)return{title:r,prop:o,type:e.elements.length>9?"grid4":"grid3",value:e,disabled:a,onChange:(l,h)=>{s.updateObject(t.uuid,`material.${o}`,h);const p=s.getScene(t.uuid);if(p!==null){const m=p.getObjectByProperty("uuid",t.uuid);B(m,`material.${o}`,h)}}};{const l=[],h=i==="defines"||i==="extensions";try{for(const p in e){const m=e[p];if(m!==void 0)if(m.value!==void 0){const g=ke(`${p}.value`,m.value,t,s,o,h);g!==void 0&&l.push(g)}else{const g=ke(p,m,t,s,o,h);g!==void 0&&l.push(g)}}}catch{console.log("Hermes - Issue cycling through material object:",i,e)}if(l.length>0)return Ct(l),{title:r,items:l}}}}}function It(i,e,t){const s=[];for(const n in i){if(!qs(n)||n.search("Node")>-1)continue;const a=typeof i[n],r=i[n];if(a==="boolean")s.push(sn(n,r,e,t));else if(a==="number")s.push(nn(n,r,e,t));else if(a==="string")s.push(rn(n,r,e,t));else if(a==="object"){const o=ke(n,r,e,t);o!==void 0&&s.push(o)}else r!==void 0&&console.log("Hermes - Other Material Prop Type:",n,a,r)}return Ct(s),s.push({title:"Update Material",type:"button",onChange:()=>{t.updateObject(e.uuid,"material.needsUpdate",!0);const n=t.getScene(e.uuid);if(n!==null){const a=n.getObjectByProperty("uuid",e.uuid);B(a,"material.needsUpdate",!0)}}}),s}function cn(i,e){function t(){return`${e.name}_material`}const s=localStorage.getItem(t()),n=s!==null?s==="open":!1;function a(o){localStorage.setItem(t(),o?"open":"closed")}const r=i.material;if(Array.isArray(r)){const o=[],c=r.length;for(let l=0;l<c;l++)o.push(u.jsx(X,{three:e,title:`Material ${l}`,items:It(r[l],i,e)},`Material ${l}`));return u.jsx(u.Fragment,{children:o})}else return u.jsx(X,{three:e,title:"Material",items:It(r,i,e),expanded:n,onToggle:o=>{a(o)}})}const Lt="data:image/gif;base64,R0lGODlhDgFkAIAAAP///wAAACH/C1hNUCBEYXRhWE1QPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgOS4xLWMwMDIgNzkuZGJhM2RhM2I1LCAyMDIzLzEyLzE1LTEwOjQyOjM3ICAgICAgICAiPiA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPiA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtbG5zOnhtcE1NPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvbW0vIiB4bWxuczpzdFJlZj0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL3NUeXBlL1Jlc291cmNlUmVmIyIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgMjUuNiAoTWFjaW50b3NoKSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDoyMDk3M0NEODAxQjQxMUVGODVGNENDMkUyMUExNDk1NSIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDoyMDk3M0NEOTAxQjQxMUVGODVGNENDMkUyMUExNDk1NSI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOkE4ODc3Qzg5MDFCMzExRUY4NUY0Q0MyRTIxQTE0OTU1IiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOkE4ODc3QzhBMDFCMzExRUY4NUY0Q0MyRTIxQTE0OTU1Ii8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+Af/+/fz7+vn49/b19PPy8fDv7u3s6+rp6Ofm5eTj4uHg397d3Nva2djX1tXU09LR0M/OzczLysnIx8bFxMPCwcC/vr28u7q5uLe2tbSzsrGwr66trKuqqainpqWko6KhoJ+enZybmpmYl5aVlJOSkZCPjo2Mi4qJiIeGhYSDgoGAf359fHt6eXh3dnV0c3JxcG9ubWxramloZ2ZlZGNiYWBfXl1cW1pZWFdWVVRTUlFQT05NTEtKSUhHRkVEQ0JBQD8+PTw7Ojk4NzY1NDMyMTAvLi0sKyopKCcmJSQjIiEgHx4dHBsaGRgXFhUUExIREA8ODQwLCgkIBwYFBAMCAQAAIfkEAAAAAAAsAAAAAA4BZAAAAv+Mj6nL7Q+jnLTai7PevPsPhuJIluaJpurKtu4Lx/JM1/aN5/rO9/4PDAqHxKLxiEwql8ym8wmNSqfUqvWKzWq33K73Cw6Lx+Sy+YxOq9fstvsNj8vn9Lr9js/r9/y+/w8YKDhIWGh4iJiouMjY6PgIGSk5SVlpeYmZqTkJAGDQ+dnpuekmGgAKejpKuiZqmprKqoZKGyrbOlqrejub6xvLGyw8TFzcprurGuvqybxq7ETbrItsCz0l7Zpc+6p9/cS967w9/S2FTF0u/mzehK4Oqz3eTl9vf4+fr7/P3+//DzCgwIEECxo8iDChwoUMGzp8CDGixIkUK1q8iDGjxo0XHDt6/AgypMiRJEuaPIkypcqVLFt+KwAAOw==";function hn(i){const e=i.step!==void 0?i.step:.01,t=b.useRef(null),s=b.useRef(null),n=b.useRef(null),a=b.useRef(null),r=b.useRef(null),[o]=b.useState(i.value),[c,l]=b.useState(i.value.offset[0]),[h,p]=b.useState(i.value.offset[1]),[m,g]=b.useState(i.value.repeat[0]),[y,_]=b.useState(i.value.repeat[1]);function E(C,x,O,S,w){if(i.onChange!==void 0){const M=i.prop!==void 0?i.prop:i.title;i.onChange(M,{src:C,offset:[x,O],repeat:[S,w]})}}function v(C){const x=t.current.src,O=C.target.value;switch(C.target){case s.current:l(O),E(x,O,h,m,y);break;case n.current:p(O),E(x,c,O,m,y);break;case a.current:g(O),E(x,c,h,O,y);break;case r.current:_(O),E(x,c,h,m,O);break}}return u.jsxs("div",{className:"imageField",children:[u.jsx("img",{alt:i.title,ref:t,onClick:()=>{Ks().then(C=>{t.current.src=C,E(C,c,h,m,y)})},src:o.src.length>0?o.src:Lt}),u.jsxs("div",{className:"fields",children:[u.jsxs("div",{children:[u.jsx("span",{children:"Offset:"}),u.jsx("input",{ref:s,type:"number",value:c,step:e,name:W(),onChange:v}),u.jsx("input",{ref:n,type:"number",value:h,step:e,name:W(),onChange:v})]}),u.jsxs("div",{children:[u.jsx("span",{children:"Repeat:"}),u.jsx("input",{ref:a,type:"number",value:m,step:e,name:W(),onChange:v}),u.jsx("input",{ref:r,type:"number",value:y,step:e,name:W(),onChange:v})]}),u.jsx("button",{onClick:()=>{E("",c,h,m,y),t.current.src=Lt},children:"Clear"})]})]})}function Ze(i){let e=i.value;e!==void 0&&(e.isColor!==void 0?e=gt(i.value):i.type==="color"&&(e=gt(new d.Color().setStyle(i.value,d.LinearSRGBColorSpace))));const[t,s]=b.useState(e),n=b.useRef(null),a=l=>{let h=l.target.value;if(i.type==="boolean")h=l.target.checked;else if(i.type==="option"&&(typeof i.value=="number"?h=Number(h):typeof i.value=="boolean"?h=!!h:typeof i.value=="object"&&(h=JSON.parse(h)),i.options!==void 0)){const p=i.options.length;for(let m=0;m<p&&i.options[m].value!==h;m++);}s(h),i.onChange!==void 0&&i.onChange(i.prop!==void 0?i.prop:i.title,h)},r={};i.disabled&&(r.opacity=.8);const o=i.type==="field"||i.type==="string"&&(t.length>100||t.search(`
21
+ `)>-1),c=o||i.type==="image"||i.type==="vector2";return u.jsxs("div",{className:`field ${c?"block":""}`,style:r,children:[i.type!=="button"&&u.jsx("span",{ref:n,children:ze(i.title)},"fieldLabel"),i.type==="string"&&!o&&u.jsx("input",{type:"text",disabled:i.disabled,onChange:a,value:t,name:W()}),(i.type==="field"||i.type==="string"&&o)&&u.jsx("textarea",{cols:50,rows:10,disabled:i.disabled!==void 0?i.disabled:!0,onChange:a,onKeyDown:l=>{i.onKeyDown!==void 0&&i.onKeyDown(l)},value:t,name:W()}),i.type==="boolean"&&u.jsx("input",{type:"checkbox",disabled:i.disabled,onChange:a,checked:t,name:W()}),i.type==="number"&&u.jsx(ge,{value:t,type:i.type,prop:i.prop!==void 0?i.prop:i.title,min:i.min,max:i.max,step:i.step,disabled:i.disabled,labelRef:n,onChange:i.onChange}),i.type==="range"&&u.jsx(ge,{value:t,type:i.type,prop:i.prop!==void 0?i.prop:i.title,min:i.min,max:i.max,step:i.step,disabled:i.disabled,labelRef:n,onChange:i.onChange}),i.type==="color"&&u.jsxs(u.Fragment,{children:[u.jsx("input",{type:"text",value:t.toString(),onChange:a,disabled:i.disabled,className:"color",name:W()}),u.jsx("input",{type:"color",value:t,onChange:a,disabled:i.disabled,name:W()})]}),i.type==="button"&&u.jsx("button",{disabled:i.disabled,onClick:()=>{i.onChange!==void 0&&i.onChange(i.prop!==void 0?i.prop:i.title,!0)},children:i.title}),i.type==="image"&&u.jsx(hn,{title:i.title,prop:i.prop,value:i.value,onChange:i.onChange}),i.type==="option"&&u.jsx(u.Fragment,{children:u.jsx("select",{onChange:a,disabled:i.disabled,defaultValue:i.value,name:W(),children:i.options?.map((l,h)=>u.jsx("option",{value:l.value,children:ze(l.title)},h))})}),i.type==="vector2"&&u.jsx(Ys,{step:i.step,value:t,min:0,max:1,onChange:a}),i.type==="grid3"&&u.jsx(Pt,{step:i.step,value:t,onChange:a}),i.type==="grid4"&&u.jsx(Zs,{step:i.step,value:t,onChange:a}),i.type==="euler"&&u.jsx(Pt,{step:i.step,value:t,onChange:a})]})}function dn(i){return"items"in i}class X extends b.Component{subgroupNames=[];subgroupElements=[];valueOverrides=new Map;three;constructor(e){super(e),this.three=e.three,this.state={lastUpdated:Date.now()}}addGroup(e){const t=[];e.items.forEach(a=>{t.push({type:a.type,prop:a.prop,title:a.title!==void 0?a.title:a.prop,value:a.value,min:a.min,max:a.max,step:a.step,options:a.options,disabled:a.disabled,onChange:(r,o)=>{e.onUpdate(r,o)}})});const s=b.createRef(),n=u.jsx(X,{three:this.props.three,ref:s,title:e.title,expanded:e.expanded,items:t},Math.random());return this.subgroupNames.push(e.title),this.subgroupElements.push(n),this.setState({lastUpdated:Date.now()}),s}removeGroup(e){const t=this.subgroupNames.length;for(let s=0;s<t;s++){const n=this.subgroupNames[s];if(e===n){this.subgroupNames.splice(s,1),this.subgroupElements.splice(s,1),this.setState({lastUpdated:Date.now()});return}}}setField(e,t){this.valueOverrides.set(e,t),this.setState({lastUpdated:Date.now()})}render(){const e=[];return this.props.items.forEach(t=>{if(dn(t))e.push(u.jsx(X,{three:this.props.three,title:ze(t.title),items:t.items},Math.random()));else{const s=this.valueOverrides.get(t.title),n=s!==void 0?s:t.value;e.push(u.jsx(Ze,{title:t.title,prop:t.prop,value:n,type:t.type,min:t.min,max:t.max,step:t.step,disabled:t.disabled,options:t.options,onChange:(a,r)=>{t.onChange!==void 0&&(this.valueOverrides.delete(t.title),t.onChange(a,r))},onKeyDown:a=>{t.onKeyDown!==void 0&&t.onKeyDown(a)}},Math.random()))}}),this.subgroupElements.forEach(t=>e.push(t)),u.jsx(Te,{three:this.props.three,label:this.props.title,open:this.props.expanded===!0,onToggle:t=>{this.props.onToggle&&this.props?.onToggle(t)},children:e})}}class U extends b.Component{static instance;static groups=[];static groupsRefs=[];static groupTitles=[];static three;constructor(e){super(e),this.state={lastUpdate:Date.now()},U.instance=this,U.three=e.three,e.three.addEventListener(I.ADD_GROUP,this.addGroup),e.three.addEventListener(I.REMOVE_GROUP,this.removeGroup)}componentWillUnmount(){this.props.three.removeEventListener(I.ADD_GROUP,this.addGroup),this.props.three.removeEventListener(I.REMOVE_GROUP,this.removeGroup)}render(){return u.jsx("div",{className:"customGroups",children:U.groups},this.state.lastUpdate)}addGroup=e=>{const t=JSON.parse(e.value),s=[];t.items.forEach(n=>{s.push({type:n.type,prop:n.prop,title:n.title!==void 0?n.title:n.prop,value:n.value,min:n.min,max:n.max,step:n.step,options:n.options,disabled:n.disabled,onChange:(a,r)=>{this.props.three.updateGroup(t.title,a,r)}})}),U.groups.push(u.jsx(X,{three:this.props.three,title:t.title,items:s},Math.random())),U.groupTitles.push(t.title),this.setState({lastUpdate:Date.now()})};removeGroup=e=>{const t=e.value,s=U.groupTitles.length;for(let n=0;n<s;n++)if(t===U.groupTitles[n]){U.groups.splice(n,1),U.groupTitles.splice(n,1),this.setState({lastUpdate:Date.now()});return}};static addEditorGroup(e){const t=U.groupTitles.length;for(let r=0;r<t;r++)if(U.groupTitles[r]===e.title)return U.groupsRefs[r];const s=[];e.items.forEach(r=>{s.push({type:r.type,prop:r.prop,title:r.title!==void 0?r.title:r.prop,value:r.value,min:r.min,max:r.max,step:r.step,options:r.options,disabled:r.disabled,onChange:(o,c)=>{e.onUpdate(o,c)}})}),e.subgroups&&e.subgroups.length>0&&e.subgroups.forEach(r=>{const o=[];r.items.forEach(c=>{o.push({type:c.type,prop:c.prop,title:c.title!==void 0?c.title:c.prop,value:c.value,min:c.min,max:c.max,step:c.step,options:c.options,disabled:c.disabled,onChange:(l,h)=>{r.onUpdate(l,h)}})}),s.push({three:U.three,title:r.title,expanded:r.expanded,items:o})});const n=b.createRef(),a=u.jsx(X,{three:U.three,ref:n,title:e.title,expanded:e.expanded,items:s},Math.random());return U.groups.push(a),U.groupsRefs.push(n),U.groupTitles.push(e.title),setTimeout(()=>{U.instance.setState({lastUpdate:Date.now()})},0),n}static removeEditorGroup(e){const t=U.groupTitles.length;for(let s=0;s<t;s++)if(e===U.groupTitles[s]){U.groups.splice(s,1),U.groupTitles.splice(s,1),U.instance.setState({lastUpdate:Date.now()});return}}static removeAllGroups(){for(let e=U.groupTitles.length;e>0;e--)U.groups.splice(e,1),U.groupTitles.splice(e,1);U.instance.setState({lastUpdate:Date.now()})}}function Ut(i){switch(i){case"fov":return"FOV";case"zoom":return"Zoom";case"near":return"Near";case"far":return"Far";case"focus":return"Focus";case"aspect":return"Aspect";case"filmGauge":return"Film Gauge";case"filmOffset":return"Film Offset";case"left":return"Left";case"right":return"Right";case"top":return"Top";case"bottom":return"Bottom"}return i}function un(i,e){function t(){return`${e.name}_camera`}const s=localStorage.getItem(t()),n=s!==null?s==="open":!1;function a(o){localStorage.setItem(t(),o?"open":"closed")}const r=[];if(i.perspectiveCameraInfo!==void 0)for(const o in i.perspectiveCameraInfo)r.push({title:Ut(o),prop:o,type:"number",step:.01,value:i.perspectiveCameraInfo[o],onChange:(c,l)=>{e.updateObject(i.uuid,c,l),e.requestMethod(i.uuid,"updateProjectionMatrix");const h=e.getScene(i.uuid);if(h!==null){const p=h.getObjectByProperty("uuid",i.uuid);p!==void 0&&(B(p,c,l),p.updateProjectionMatrix())}}});else if(i.orthographicCameraInfo!==void 0)for(const o in i.orthographicCameraInfo)r.push({title:Ut(o),prop:o,type:"number",step:.01,value:i.orthographicCameraInfo[o],onChange:(c,l)=>{e.updateObject(i.uuid,c,l),e.requestMethod(i.uuid,"updateProjectionMatrix");const h=e.getScene(i.uuid);if(h!==null){const p=h.getObjectByProperty("uuid",i.uuid);p!==void 0&&(B(p,c,l),p.updateProjectionMatrix())}}});return u.jsx(X,{three:e,title:"Camera",items:r,expanded:n,onToggle:o=>{a(o)}})}/*!
459
22
  * camera-controls
460
23
  * https://github.com/yomotsu/camera-controls
461
24
  * (c) 2017 @yomotsu
462
25
  * Released under the MIT License.
463
- */const it={LEFT:1,RIGHT:2,MIDDLE:4},L=Object.freeze({NONE:0,ROTATE:1,TRUCK:2,SCREEN_PAN:4,OFFSET:8,DOLLY:16,ZOOM:32,TOUCH_ROTATE:64,TOUCH_TRUCK:128,TOUCH_SCREEN_PAN:256,TOUCH_OFFSET:512,TOUCH_DOLLY:1024,TOUCH_ZOOM:2048,TOUCH_DOLLY_TRUCK:4096,TOUCH_DOLLY_SCREEN_PAN:8192,TOUCH_DOLLY_OFFSET:16384,TOUCH_DOLLY_ROTATE:32768,TOUCH_ZOOM_TRUCK:65536,TOUCH_ZOOM_OFFSET:131072,TOUCH_ZOOM_SCREEN_PAN:262144,TOUCH_ZOOM_ROTATE:524288}),sa={NONE:0,IN:1,OUT:-1};function nr(r){return r.isPerspectiveCamera}function xn(r){return r.isOrthographicCamera}const ia=Math.PI*2,Iy=Math.PI/2,GS=1e-5,oo=Math.PI/180;function qs(r,e,t){return Math.max(e,Math.min(t,r))}function Xe(r,e=GS){return Math.abs(r)<e}function Ve(r,e,t=GS){return Xe(r-e,t)}function Uy(r,e){return Math.round(r/e)*e}function lo(r){return isFinite(r)?r:r<0?-Number.MAX_VALUE:Number.MAX_VALUE}function co(r){return Math.abs(r)<Number.MAX_VALUE?r:r*(1/0)}function oc(r,e,t,s,i=1/0,n){s=Math.max(1e-4,s);const a=2/s,o=a*n,l=1/(1+o+.48*o*o+.235*o*o*o);let c=r-e;const u=e,h=i*s;c=qs(c,-h,h),e=r-c;const d=(t.value+a*c)*n;t.value=(t.value-a*d)*l;let p=e+(c+d)*l;return u-r>0==p>u&&(p=u,t.value=(p-u)/n),p}function Vy(r,e,t,s,i=1/0,n,a){s=Math.max(1e-4,s);const o=2/s,l=o*n,c=1/(1+l+.48*l*l+.235*l*l*l);let u=e.x,h=e.y,d=e.z,p=r.x-u,f=r.y-h,m=r.z-d;const x=u,y=h,b=d,v=i*s,S=v*v,M=p*p+f*f+m*m;if(M>S){const q=Math.sqrt(M);p=p/q*v,f=f/q*v,m=m/q*v}u=r.x-p,h=r.y-f,d=r.z-m;const A=(t.x+o*p)*n,C=(t.y+o*f)*n,P=(t.z+o*m)*n;t.x=(t.x-o*A)*c,t.y=(t.y-o*C)*c,t.z=(t.z-o*P)*c,a.x=u+(p+A)*c,a.y=h+(f+C)*c,a.z=d+(m+P)*c;const B=x-r.x,V=y-r.y,Y=b-r.z,J=a.x-x,K=a.y-y,te=a.z-b;return B*J+V*K+Y*te>0&&(a.x=x,a.y=y,a.z=b,t.x=(a.x-x)/n,t.y=(a.y-y)/n,t.z=(a.z-b)/n),a}function Fd(r,e){e.set(0,0),r.forEach(t=>{e.x+=t.clientX,e.y+=t.clientY}),e.x/=r.length,e.y/=r.length}function Bd(r,e){return xn(r)?(console.warn(`${e} is not supported in OrthographicCamera`),!0):!1}class fI{constructor(){this._listeners={}}addEventListener(e,t){const s=this._listeners;s[e]===void 0&&(s[e]=[]),s[e].indexOf(t)===-1&&s[e].push(t)}hasEventListener(e,t){const s=this._listeners;return s[e]!==void 0&&s[e].indexOf(t)!==-1}removeEventListener(e,t){const i=this._listeners[e];if(i!==void 0){const n=i.indexOf(t);n!==-1&&i.splice(n,1)}}removeAllEventListeners(e){if(!e){this._listeners={};return}Array.isArray(this._listeners[e])&&(this._listeners[e].length=0)}dispatchEvent(e){const s=this._listeners[e.type];if(s!==void 0){e.target=this;const i=s.slice(0);for(let n=0,a=i.length;n<a;n++)i[n].call(this,e)}}}var Dd;const mI="2.10.1",lc=1/8,gI=/Mac/.test((Dd=globalThis?.navigator)===null||Dd===void 0?void 0:Dd.platform);let he,ky,cc,Od,Kt,pe,Be,na,uo,hi,di,rr,zy,Gy,Ms,ho,ra,$y,Ld,Wy,Id,Ud,uc;class gi extends fI{static install(e){he=e.THREE,ky=Object.freeze(new he.Vector3(0,0,0)),cc=Object.freeze(new he.Vector3(0,1,0)),Od=Object.freeze(new he.Vector3(0,0,1)),Kt=new he.Vector2,pe=new he.Vector3,Be=new he.Vector3,na=new he.Vector3,uo=new he.Vector3,hi=new he.Vector3,di=new he.Vector3,rr=new he.Vector3,zy=new he.Vector3,Gy=new he.Vector3,Ms=new he.Spherical,ho=new he.Spherical,ra=new he.Box3,$y=new he.Box3,Ld=new he.Sphere,Wy=new he.Quaternion,Id=new he.Quaternion,Ud=new he.Matrix4,uc=new he.Raycaster}static get ACTION(){return L}set verticalDragToForward(e){console.warn("camera-controls: `verticalDragToForward` was removed. Use `mouseButtons.left = CameraControls.ACTION.SCREEN_PAN` instead.")}constructor(e,t){super(),this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.minDistance=Number.EPSILON,this.maxDistance=1/0,this.infinityDolly=!1,this.minZoom=.01,this.maxZoom=1/0,this.smoothTime=.25,this.draggingSmoothTime=.125,this.maxSpeed=1/0,this.azimuthRotateSpeed=1,this.polarRotateSpeed=1,this.dollySpeed=1,this.dollyDragInverted=!1,this.truckSpeed=2,this.dollyToCursor=!1,this.dragToOffset=!1,this.boundaryFriction=0,this.restThreshold=.01,this.colliderMeshes=[],this.cancel=()=>{},this._enabled=!0,this._state=L.NONE,this._viewport=null,this._changedDolly=0,this._changedZoom=0,this._hasRested=!0,this._boundaryEnclosesCamera=!1,this._needsUpdate=!0,this._updatedLastTime=!1,this._elementRect=new DOMRect,this._isDragging=!1,this._dragNeedsUpdate=!0,this._activePointers=[],this._lockedPointer=null,this._interactiveArea=new DOMRect(0,0,1,1),this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._isUserControllingOffset=!1,this._isUserControllingZoom=!1,this._lastDollyDirection=sa.NONE,this._thetaVelocity={value:0},this._phiVelocity={value:0},this._radiusVelocity={value:0},this._targetVelocity=new he.Vector3,this._focalOffsetVelocity=new he.Vector3,this._zoomVelocity={value:0},this._truckInternal=(y,b,v,S)=>{let M,A;if(nr(this._camera)){const C=pe.copy(this._camera.position).sub(this._target),P=this._camera.getEffectiveFOV()*oo,B=C.length()*Math.tan(P*.5);M=this.truckSpeed*y*B/this._elementRect.height,A=this.truckSpeed*b*B/this._elementRect.height}else if(xn(this._camera)){const C=this._camera;M=this.truckSpeed*y*(C.right-C.left)/C.zoom/this._elementRect.width,A=this.truckSpeed*b*(C.top-C.bottom)/C.zoom/this._elementRect.height}else return;S?(v?this.setFocalOffset(this._focalOffsetEnd.x+M,this._focalOffsetEnd.y,this._focalOffsetEnd.z,!0):this.truck(M,0,!0),this.forward(-A,!0)):v?this.setFocalOffset(this._focalOffsetEnd.x+M,this._focalOffsetEnd.y+A,this._focalOffsetEnd.z,!0):this.truck(M,A,!0)},this._rotateInternal=(y,b)=>{const v=ia*this.azimuthRotateSpeed*y/this._elementRect.height,S=ia*this.polarRotateSpeed*b/this._elementRect.height;this.rotate(v,S,!0)},this._dollyInternal=(y,b,v)=>{const S=Math.pow(.95,-y*this.dollySpeed),M=this._sphericalEnd.radius,A=this._sphericalEnd.radius*S,C=qs(A,this.minDistance,this.maxDistance),P=C-A;this.infinityDolly&&this.dollyToCursor?this._dollyToNoClamp(A,!0):this.infinityDolly&&!this.dollyToCursor?(this.dollyInFixed(P,!0),this._dollyToNoClamp(C,!0)):this._dollyToNoClamp(C,!0),this.dollyToCursor&&(this._changedDolly+=(this.infinityDolly?A:C)-M,this._dollyControlCoord.set(b,v)),this._lastDollyDirection=Math.sign(-y)},this._zoomInternal=(y,b,v)=>{const S=Math.pow(.95,y*this.dollySpeed),M=this._zoom,A=this._zoom*S;this.zoomTo(A,!0),this.dollyToCursor&&(this._changedZoom+=A-M,this._dollyControlCoord.set(b,v))},typeof he>"u"&&console.error("camera-controls: `THREE` is undefined. You must first run `CameraControls.install( { THREE: THREE } )`. Check the docs for further information."),this._camera=e,this._yAxisUpSpace=new he.Quaternion().setFromUnitVectors(this._camera.up,cc),this._yAxisUpSpaceInverse=this._yAxisUpSpace.clone().invert(),this._state=L.NONE,this._target=new he.Vector3,this._targetEnd=this._target.clone(),this._focalOffset=new he.Vector3,this._focalOffsetEnd=this._focalOffset.clone(),this._spherical=new he.Spherical().setFromVector3(pe.copy(this._camera.position).applyQuaternion(this._yAxisUpSpace)),this._sphericalEnd=this._spherical.clone(),this._lastDistance=this._spherical.radius,this._zoom=this._camera.zoom,this._zoomEnd=this._zoom,this._lastZoom=this._zoom,this._nearPlaneCorners=[new he.Vector3,new he.Vector3,new he.Vector3,new he.Vector3],this._updateNearPlaneCorners(),this._boundary=new he.Box3(new he.Vector3(-1/0,-1/0,-1/0),new he.Vector3(1/0,1/0,1/0)),this._cameraUp0=this._camera.up.clone(),this._target0=this._target.clone(),this._position0=this._camera.position.clone(),this._zoom0=this._zoom,this._focalOffset0=this._focalOffset.clone(),this._dollyControlCoord=new he.Vector2,this.mouseButtons={left:L.ROTATE,middle:L.DOLLY,right:L.TRUCK,wheel:nr(this._camera)?L.DOLLY:xn(this._camera)?L.ZOOM:L.NONE},this.touches={one:L.TOUCH_ROTATE,two:nr(this._camera)?L.TOUCH_DOLLY_TRUCK:xn(this._camera)?L.TOUCH_ZOOM_TRUCK:L.NONE,three:L.TOUCH_TRUCK};const s=new he.Vector2,i=new he.Vector2,n=new he.Vector2,a=y=>{if(!this._enabled||!this._domElement)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){const S=this._domElement.getBoundingClientRect(),M=y.clientX/S.width,A=y.clientY/S.height;if(M<this._interactiveArea.left||M>this._interactiveArea.right||A<this._interactiveArea.top||A>this._interactiveArea.bottom)return}const b=y.pointerType!=="mouse"?null:(y.buttons&it.LEFT)===it.LEFT?it.LEFT:(y.buttons&it.MIDDLE)===it.MIDDLE?it.MIDDLE:(y.buttons&it.RIGHT)===it.RIGHT?it.RIGHT:null;if(b!==null){const S=this._findPointerByMouseButton(b);S&&this._disposePointer(S)}if((y.buttons&it.LEFT)===it.LEFT&&this._lockedPointer)return;const v={pointerId:y.pointerId,clientX:y.clientX,clientY:y.clientY,deltaX:0,deltaY:0,mouseButton:b};this._activePointers.push(v),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.ownerDocument.addEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",l),this._isDragging=!0,d(y)},o=y=>{y.cancelable&&y.preventDefault();const b=y.pointerId,v=this._lockedPointer||this._findPointerById(b);if(v){if(v.clientX=y.clientX,v.clientY=y.clientY,v.deltaX=y.movementX,v.deltaY=y.movementY,this._state=0,y.pointerType==="touch")switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else(!this._isDragging&&this._lockedPointer||this._isDragging&&(y.buttons&it.LEFT)===it.LEFT)&&(this._state=this._state|this.mouseButtons.left),this._isDragging&&(y.buttons&it.MIDDLE)===it.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),this._isDragging&&(y.buttons&it.RIGHT)===it.RIGHT&&(this._state=this._state|this.mouseButtons.right);p()}},l=y=>{const b=this._findPointerById(y.pointerId);if(!(b&&b===this._lockedPointer)){if(b&&this._disposePointer(b),y.pointerType==="touch")switch(this._activePointers.length){case 0:this._state=L.NONE;break;case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else this._state=L.NONE;f()}};let c=-1;const u=y=>{if(!this._domElement||!this._enabled||this.mouseButtons.wheel===L.NONE)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){const A=this._domElement.getBoundingClientRect(),C=y.clientX/A.width,P=y.clientY/A.height;if(C<this._interactiveArea.left||C>this._interactiveArea.right||P<this._interactiveArea.top||P>this._interactiveArea.bottom)return}if(y.preventDefault(),this.dollyToCursor||this.mouseButtons.wheel===L.ROTATE||this.mouseButtons.wheel===L.TRUCK){const A=performance.now();c-A<1e3&&this._getClientRect(this._elementRect),c=A}const b=gI?-1:-3,v=y.deltaMode===1||y.ctrlKey?y.deltaY/b:y.deltaY/(b*10),S=this.dollyToCursor?(y.clientX-this._elementRect.x)/this._elementRect.width*2-1:0,M=this.dollyToCursor?(y.clientY-this._elementRect.y)/this._elementRect.height*-2+1:0;switch(this.mouseButtons.wheel){case L.ROTATE:{this._rotateInternal(y.deltaX,y.deltaY),this._isUserControllingRotate=!0;break}case L.TRUCK:{this._truckInternal(y.deltaX,y.deltaY,!1,!1),this._isUserControllingTruck=!0;break}case L.SCREEN_PAN:{this._truckInternal(y.deltaX,y.deltaY,!1,!0),this._isUserControllingTruck=!0;break}case L.OFFSET:{this._truckInternal(y.deltaX,y.deltaY,!0,!1),this._isUserControllingOffset=!0;break}case L.DOLLY:{this._dollyInternal(-v,S,M),this._isUserControllingDolly=!0;break}case L.ZOOM:{this._zoomInternal(-v,S,M),this._isUserControllingZoom=!0;break}}this.dispatchEvent({type:"control"})},h=y=>{if(!(!this._domElement||!this._enabled)){if(this.mouseButtons.right===gi.ACTION.NONE){const b=y instanceof PointerEvent?y.pointerId:0,v=this._findPointerById(b);v&&this._disposePointer(v),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l);return}y.preventDefault()}},d=y=>{if(!this._enabled)return;if(Fd(this._activePointers,Kt),this._getClientRect(this._elementRect),s.copy(Kt),i.copy(Kt),this._activePointers.length>=2){const v=Kt.x-this._activePointers[1].clientX,S=Kt.y-this._activePointers[1].clientY,M=Math.sqrt(v*v+S*S);n.set(0,M);const A=(this._activePointers[0].clientX+this._activePointers[1].clientX)*.5,C=(this._activePointers[0].clientY+this._activePointers[1].clientY)*.5;i.set(A,C)}if(this._state=0,!y)this._lockedPointer&&(this._state=this._state|this.mouseButtons.left);else if("pointerType"in y&&y.pointerType==="touch")switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else!this._lockedPointer&&(y.buttons&it.LEFT)===it.LEFT&&(this._state=this._state|this.mouseButtons.left),(y.buttons&it.MIDDLE)===it.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),(y.buttons&it.RIGHT)===it.RIGHT&&(this._state=this._state|this.mouseButtons.right);((this._state&L.ROTATE)===L.ROTATE||(this._state&L.TOUCH_ROTATE)===L.TOUCH_ROTATE||(this._state&L.TOUCH_DOLLY_ROTATE)===L.TOUCH_DOLLY_ROTATE||(this._state&L.TOUCH_ZOOM_ROTATE)===L.TOUCH_ZOOM_ROTATE)&&(this._sphericalEnd.theta=this._spherical.theta,this._sphericalEnd.phi=this._spherical.phi,this._thetaVelocity.value=0,this._phiVelocity.value=0),((this._state&L.TRUCK)===L.TRUCK||(this._state&L.SCREEN_PAN)===L.SCREEN_PAN||(this._state&L.TOUCH_TRUCK)===L.TOUCH_TRUCK||(this._state&L.TOUCH_SCREEN_PAN)===L.TOUCH_SCREEN_PAN||(this._state&L.TOUCH_DOLLY_TRUCK)===L.TOUCH_DOLLY_TRUCK||(this._state&L.TOUCH_DOLLY_SCREEN_PAN)===L.TOUCH_DOLLY_SCREEN_PAN||(this._state&L.TOUCH_ZOOM_TRUCK)===L.TOUCH_ZOOM_TRUCK||(this._state&L.TOUCH_ZOOM_SCREEN_PAN)===L.TOUCH_DOLLY_SCREEN_PAN)&&(this._targetEnd.copy(this._target),this._targetVelocity.set(0,0,0)),((this._state&L.DOLLY)===L.DOLLY||(this._state&L.TOUCH_DOLLY)===L.TOUCH_DOLLY||(this._state&L.TOUCH_DOLLY_TRUCK)===L.TOUCH_DOLLY_TRUCK||(this._state&L.TOUCH_DOLLY_SCREEN_PAN)===L.TOUCH_DOLLY_SCREEN_PAN||(this._state&L.TOUCH_DOLLY_OFFSET)===L.TOUCH_DOLLY_OFFSET||(this._state&L.TOUCH_DOLLY_ROTATE)===L.TOUCH_DOLLY_ROTATE)&&(this._sphericalEnd.radius=this._spherical.radius,this._radiusVelocity.value=0),((this._state&L.ZOOM)===L.ZOOM||(this._state&L.TOUCH_ZOOM)===L.TOUCH_ZOOM||(this._state&L.TOUCH_ZOOM_TRUCK)===L.TOUCH_ZOOM_TRUCK||(this._state&L.TOUCH_ZOOM_SCREEN_PAN)===L.TOUCH_ZOOM_SCREEN_PAN||(this._state&L.TOUCH_ZOOM_OFFSET)===L.TOUCH_ZOOM_OFFSET||(this._state&L.TOUCH_ZOOM_ROTATE)===L.TOUCH_ZOOM_ROTATE)&&(this._zoomEnd=this._zoom,this._zoomVelocity.value=0),((this._state&L.OFFSET)===L.OFFSET||(this._state&L.TOUCH_OFFSET)===L.TOUCH_OFFSET||(this._state&L.TOUCH_DOLLY_OFFSET)===L.TOUCH_DOLLY_OFFSET||(this._state&L.TOUCH_ZOOM_OFFSET)===L.TOUCH_ZOOM_OFFSET)&&(this._focalOffsetEnd.copy(this._focalOffset),this._focalOffsetVelocity.set(0,0,0)),this.dispatchEvent({type:"controlstart"})},p=()=>{if(!this._enabled||!this._dragNeedsUpdate)return;this._dragNeedsUpdate=!1,Fd(this._activePointers,Kt);const b=this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement?this._lockedPointer||this._activePointers[0]:null,v=b?-b.deltaX:i.x-Kt.x,S=b?-b.deltaY:i.y-Kt.y;if(i.copy(Kt),((this._state&L.ROTATE)===L.ROTATE||(this._state&L.TOUCH_ROTATE)===L.TOUCH_ROTATE||(this._state&L.TOUCH_DOLLY_ROTATE)===L.TOUCH_DOLLY_ROTATE||(this._state&L.TOUCH_ZOOM_ROTATE)===L.TOUCH_ZOOM_ROTATE)&&(this._rotateInternal(v,S),this._isUserControllingRotate=!0),(this._state&L.DOLLY)===L.DOLLY||(this._state&L.ZOOM)===L.ZOOM){const M=this.dollyToCursor?(s.x-this._elementRect.x)/this._elementRect.width*2-1:0,A=this.dollyToCursor?(s.y-this._elementRect.y)/this._elementRect.height*-2+1:0,C=this.dollyDragInverted?-1:1;(this._state&L.DOLLY)===L.DOLLY?(this._dollyInternal(C*S*lc,M,A),this._isUserControllingDolly=!0):(this._zoomInternal(C*S*lc,M,A),this._isUserControllingZoom=!0)}if((this._state&L.TOUCH_DOLLY)===L.TOUCH_DOLLY||(this._state&L.TOUCH_ZOOM)===L.TOUCH_ZOOM||(this._state&L.TOUCH_DOLLY_TRUCK)===L.TOUCH_DOLLY_TRUCK||(this._state&L.TOUCH_ZOOM_TRUCK)===L.TOUCH_ZOOM_TRUCK||(this._state&L.TOUCH_DOLLY_SCREEN_PAN)===L.TOUCH_DOLLY_SCREEN_PAN||(this._state&L.TOUCH_ZOOM_SCREEN_PAN)===L.TOUCH_ZOOM_SCREEN_PAN||(this._state&L.TOUCH_DOLLY_OFFSET)===L.TOUCH_DOLLY_OFFSET||(this._state&L.TOUCH_ZOOM_OFFSET)===L.TOUCH_ZOOM_OFFSET||(this._state&L.TOUCH_DOLLY_ROTATE)===L.TOUCH_DOLLY_ROTATE||(this._state&L.TOUCH_ZOOM_ROTATE)===L.TOUCH_ZOOM_ROTATE){const M=Kt.x-this._activePointers[1].clientX,A=Kt.y-this._activePointers[1].clientY,C=Math.sqrt(M*M+A*A),P=n.y-C;n.set(0,C);const B=this.dollyToCursor?(i.x-this._elementRect.x)/this._elementRect.width*2-1:0,V=this.dollyToCursor?(i.y-this._elementRect.y)/this._elementRect.height*-2+1:0;(this._state&L.TOUCH_DOLLY)===L.TOUCH_DOLLY||(this._state&L.TOUCH_DOLLY_ROTATE)===L.TOUCH_DOLLY_ROTATE||(this._state&L.TOUCH_DOLLY_TRUCK)===L.TOUCH_DOLLY_TRUCK||(this._state&L.TOUCH_DOLLY_SCREEN_PAN)===L.TOUCH_DOLLY_SCREEN_PAN||(this._state&L.TOUCH_DOLLY_OFFSET)===L.TOUCH_DOLLY_OFFSET?(this._dollyInternal(P*lc,B,V),this._isUserControllingDolly=!0):(this._zoomInternal(P*lc,B,V),this._isUserControllingZoom=!0)}((this._state&L.TRUCK)===L.TRUCK||(this._state&L.TOUCH_TRUCK)===L.TOUCH_TRUCK||(this._state&L.TOUCH_DOLLY_TRUCK)===L.TOUCH_DOLLY_TRUCK||(this._state&L.TOUCH_ZOOM_TRUCK)===L.TOUCH_ZOOM_TRUCK)&&(this._truckInternal(v,S,!1,!1),this._isUserControllingTruck=!0),((this._state&L.SCREEN_PAN)===L.SCREEN_PAN||(this._state&L.TOUCH_SCREEN_PAN)===L.TOUCH_SCREEN_PAN||(this._state&L.TOUCH_DOLLY_SCREEN_PAN)===L.TOUCH_DOLLY_SCREEN_PAN||(this._state&L.TOUCH_ZOOM_SCREEN_PAN)===L.TOUCH_ZOOM_SCREEN_PAN)&&(this._truckInternal(v,S,!1,!0),this._isUserControllingTruck=!0),((this._state&L.OFFSET)===L.OFFSET||(this._state&L.TOUCH_OFFSET)===L.TOUCH_OFFSET||(this._state&L.TOUCH_DOLLY_OFFSET)===L.TOUCH_DOLLY_OFFSET||(this._state&L.TOUCH_ZOOM_OFFSET)===L.TOUCH_ZOOM_OFFSET)&&(this._truckInternal(v,S,!0,!1),this._isUserControllingOffset=!0),this.dispatchEvent({type:"control"})},f=()=>{Fd(this._activePointers,Kt),i.copy(Kt),this._dragNeedsUpdate=!1,(this._activePointers.length===0||this._activePointers.length===1&&this._activePointers[0]===this._lockedPointer)&&(this._isDragging=!1),this._activePointers.length===0&&this._domElement&&(this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this.dispatchEvent({type:"controlend"}))};this.lockPointer=()=>{!this._enabled||!this._domElement||(this.cancel(),this._lockedPointer={pointerId:-1,clientX:0,clientY:0,deltaX:0,deltaY:0,mouseButton:null},this._activePointers.push(this._lockedPointer),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.requestPointerLock(),this._domElement.ownerDocument.addEventListener("pointerlockchange",m),this._domElement.ownerDocument.addEventListener("pointerlockerror",x),this._domElement.ownerDocument.addEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",l),d())},this.unlockPointer=()=>{var y,b,v;this._lockedPointer!==null&&(this._disposePointer(this._lockedPointer),this._lockedPointer=null),(y=this._domElement)===null||y===void 0||y.ownerDocument.exitPointerLock(),(b=this._domElement)===null||b===void 0||b.ownerDocument.removeEventListener("pointerlockchange",m),(v=this._domElement)===null||v===void 0||v.ownerDocument.removeEventListener("pointerlockerror",x),this.cancel()};const m=()=>{this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement||this.unlockPointer()},x=()=>{this.unlockPointer()};this._addAllEventListeners=y=>{this._domElement=y,this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none",this._domElement.addEventListener("pointerdown",a),this._domElement.addEventListener("pointercancel",l),this._domElement.addEventListener("wheel",u,{passive:!1}),this._domElement.addEventListener("contextmenu",h)},this._removeAllEventListeners=()=>{this._domElement&&(this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect="",this._domElement.removeEventListener("pointerdown",a),this._domElement.removeEventListener("pointercancel",l),this._domElement.removeEventListener("wheel",u,{passive:!1}),this._domElement.removeEventListener("contextmenu",h),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.ownerDocument.removeEventListener("pointerlockchange",m),this._domElement.ownerDocument.removeEventListener("pointerlockerror",x))},this.cancel=()=>{this._state!==L.NONE&&(this._state=L.NONE,this._activePointers.length=0,f())},t&&this.connect(t),this.update(0)}get camera(){return this._camera}set camera(e){this._camera=e,this.updateCameraUp(),this._camera.updateProjectionMatrix(),this._updateNearPlaneCorners(),this._needsUpdate=!0}get enabled(){return this._enabled}set enabled(e){this._enabled=e,this._domElement&&(e?(this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none"):(this.cancel(),this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect=""))}get active(){return!this._hasRested}get currentAction(){return this._state}get distance(){return this._spherical.radius}set distance(e){this._spherical.radius===e&&this._sphericalEnd.radius===e||(this._spherical.radius=e,this._sphericalEnd.radius=e,this._needsUpdate=!0)}get azimuthAngle(){return this._spherical.theta}set azimuthAngle(e){this._spherical.theta===e&&this._sphericalEnd.theta===e||(this._spherical.theta=e,this._sphericalEnd.theta=e,this._needsUpdate=!0)}get polarAngle(){return this._spherical.phi}set polarAngle(e){this._spherical.phi===e&&this._sphericalEnd.phi===e||(this._spherical.phi=e,this._sphericalEnd.phi=e,this._needsUpdate=!0)}get boundaryEnclosesCamera(){return this._boundaryEnclosesCamera}set boundaryEnclosesCamera(e){this._boundaryEnclosesCamera=e,this._needsUpdate=!0}set interactiveArea(e){this._interactiveArea.width=qs(e.width,0,1),this._interactiveArea.height=qs(e.height,0,1),this._interactiveArea.x=qs(e.x,0,1-this._interactiveArea.width),this._interactiveArea.y=qs(e.y,0,1-this._interactiveArea.height)}addEventListener(e,t){super.addEventListener(e,t)}removeEventListener(e,t){super.removeEventListener(e,t)}rotate(e,t,s=!1){return this.rotateTo(this._sphericalEnd.theta+e,this._sphericalEnd.phi+t,s)}rotateAzimuthTo(e,t=!1){return this.rotateTo(e,this._sphericalEnd.phi,t)}rotatePolarTo(e,t=!1){return this.rotateTo(this._sphericalEnd.theta,e,t)}rotateTo(e,t,s=!1){this._isUserControllingRotate=!1;const i=qs(e,this.minAzimuthAngle,this.maxAzimuthAngle),n=qs(t,this.minPolarAngle,this.maxPolarAngle);this._sphericalEnd.theta=i,this._sphericalEnd.phi=n,this._sphericalEnd.makeSafe(),this._needsUpdate=!0,s||(this._spherical.theta=this._sphericalEnd.theta,this._spherical.phi=this._sphericalEnd.phi);const a=!s||Ve(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Ve(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold);return this._createOnRestPromise(a)}dolly(e,t=!1){return this.dollyTo(this._sphericalEnd.radius-e,t)}dollyTo(e,t=!1){return this._isUserControllingDolly=!1,this._lastDollyDirection=sa.NONE,this._changedDolly=0,this._dollyToNoClamp(qs(e,this.minDistance,this.maxDistance),t)}_dollyToNoClamp(e,t=!1){const s=this._sphericalEnd.radius;if(this.colliderMeshes.length>=1){const a=this._collisionTest(),o=Ve(a,this._spherical.radius);if(!(s>e)&&o)return Promise.resolve();this._sphericalEnd.radius=Math.min(e,a)}else this._sphericalEnd.radius=e;this._needsUpdate=!0,t||(this._spherical.radius=this._sphericalEnd.radius);const n=!t||Ve(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(n)}dollyInFixed(e,t=!1){this._targetEnd.add(this._getCameraDirection(uo).multiplyScalar(e)),t||this._target.copy(this._targetEnd);const s=!t||Ve(this._target.x,this._targetEnd.x,this.restThreshold)&&Ve(this._target.y,this._targetEnd.y,this.restThreshold)&&Ve(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(s)}zoom(e,t=!1){return this.zoomTo(this._zoomEnd+e,t)}zoomTo(e,t=!1){this._isUserControllingZoom=!1,this._zoomEnd=qs(e,this.minZoom,this.maxZoom),this._needsUpdate=!0,t||(this._zoom=this._zoomEnd);const s=!t||Ve(this._zoom,this._zoomEnd,this.restThreshold);return this._changedZoom=0,this._createOnRestPromise(s)}pan(e,t,s=!1){return console.warn("`pan` has been renamed to `truck`"),this.truck(e,t,s)}truck(e,t,s=!1){this._camera.updateMatrix(),hi.setFromMatrixColumn(this._camera.matrix,0),di.setFromMatrixColumn(this._camera.matrix,1),hi.multiplyScalar(e),di.multiplyScalar(-t);const i=pe.copy(hi).add(di),n=Be.copy(this._targetEnd).add(i);return this.moveTo(n.x,n.y,n.z,s)}forward(e,t=!1){pe.setFromMatrixColumn(this._camera.matrix,0),pe.crossVectors(this._camera.up,pe),pe.multiplyScalar(e);const s=Be.copy(this._targetEnd).add(pe);return this.moveTo(s.x,s.y,s.z,t)}elevate(e,t=!1){return pe.copy(this._camera.up).multiplyScalar(e),this.moveTo(this._targetEnd.x+pe.x,this._targetEnd.y+pe.y,this._targetEnd.z+pe.z,t)}moveTo(e,t,s,i=!1){this._isUserControllingTruck=!1;const n=pe.set(e,t,s).sub(this._targetEnd);this._encloseToBoundary(this._targetEnd,n,this.boundaryFriction),this._needsUpdate=!0,i||this._target.copy(this._targetEnd);const a=!i||Ve(this._target.x,this._targetEnd.x,this.restThreshold)&&Ve(this._target.y,this._targetEnd.y,this.restThreshold)&&Ve(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(a)}lookInDirectionOf(e,t,s,i=!1){const o=pe.set(e,t,s).sub(this._targetEnd).normalize().multiplyScalar(-this._sphericalEnd.radius).add(this._targetEnd);return this.setPosition(o.x,o.y,o.z,i)}fitToBox(e,t,{cover:s=!1,paddingLeft:i=0,paddingRight:n=0,paddingBottom:a=0,paddingTop:o=0}={}){const l=[],c=e.isBox3?ra.copy(e):ra.setFromObject(e);c.isEmpty()&&(console.warn("camera-controls: fitTo() cannot be used with an empty box. Aborting"),Promise.resolve());const u=Uy(this._sphericalEnd.theta,Iy),h=Uy(this._sphericalEnd.phi,Iy);l.push(this.rotateTo(u,h,t));const d=pe.setFromSpherical(this._sphericalEnd).normalize(),p=Wy.setFromUnitVectors(d,Od),f=Ve(Math.abs(d.y),1);f&&p.multiply(Id.setFromAxisAngle(cc,u)),p.multiply(this._yAxisUpSpaceInverse);const m=$y.makeEmpty();Be.copy(c.min).applyQuaternion(p),m.expandByPoint(Be),Be.copy(c.min).setX(c.max.x).applyQuaternion(p),m.expandByPoint(Be),Be.copy(c.min).setY(c.max.y).applyQuaternion(p),m.expandByPoint(Be),Be.copy(c.max).setZ(c.min.z).applyQuaternion(p),m.expandByPoint(Be),Be.copy(c.min).setZ(c.max.z).applyQuaternion(p),m.expandByPoint(Be),Be.copy(c.max).setY(c.min.y).applyQuaternion(p),m.expandByPoint(Be),Be.copy(c.max).setX(c.min.x).applyQuaternion(p),m.expandByPoint(Be),Be.copy(c.max).applyQuaternion(p),m.expandByPoint(Be),m.min.x-=i,m.min.y-=a,m.max.x+=n,m.max.y+=o,p.setFromUnitVectors(Od,d),f&&p.premultiply(Id.invert()),p.premultiply(this._yAxisUpSpace);const x=m.getSize(pe),y=m.getCenter(Be).applyQuaternion(p);if(nr(this._camera)){const b=this.getDistanceToFitBox(x.x,x.y,x.z,s);l.push(this.moveTo(y.x,y.y,y.z,t)),l.push(this.dollyTo(b,t)),l.push(this.setFocalOffset(0,0,0,t))}else if(xn(this._camera)){const b=this._camera,v=b.right-b.left,S=b.top-b.bottom,M=s?Math.max(v/x.x,S/x.y):Math.min(v/x.x,S/x.y);l.push(this.moveTo(y.x,y.y,y.z,t)),l.push(this.zoomTo(M,t)),l.push(this.setFocalOffset(0,0,0,t))}return Promise.all(l)}fitToSphere(e,t){const s=[],n="isObject3D"in e?gi.createBoundingSphere(e,Ld):Ld.copy(e);if(s.push(this.moveTo(n.center.x,n.center.y,n.center.z,t)),nr(this._camera)){const a=this.getDistanceToFitSphere(n.radius);s.push(this.dollyTo(a,t))}else if(xn(this._camera)){const a=this._camera.right-this._camera.left,o=this._camera.top-this._camera.bottom,l=2*n.radius,c=Math.min(a/l,o/l);s.push(this.zoomTo(c,t))}return s.push(this.setFocalOffset(0,0,0,t)),Promise.all(s)}setLookAt(e,t,s,i,n,a,o=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=sa.NONE,this._changedDolly=0;const l=Be.set(i,n,a),c=pe.set(e,t,s);this._targetEnd.copy(l),this._sphericalEnd.setFromVector3(c.sub(l).applyQuaternion(this._yAxisUpSpace)),this.normalizeRotations(),this._needsUpdate=!0,o||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const u=!o||Ve(this._target.x,this._targetEnd.x,this.restThreshold)&&Ve(this._target.y,this._targetEnd.y,this.restThreshold)&&Ve(this._target.z,this._targetEnd.z,this.restThreshold)&&Ve(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Ve(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&Ve(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(u)}lerpLookAt(e,t,s,i,n,a,o,l,c,u,h,d,p,f=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=sa.NONE,this._changedDolly=0;const m=pe.set(i,n,a),x=Be.set(e,t,s);Ms.setFromVector3(x.sub(m).applyQuaternion(this._yAxisUpSpace));const y=na.set(u,h,d),b=Be.set(o,l,c);ho.setFromVector3(b.sub(y).applyQuaternion(this._yAxisUpSpace)),this._targetEnd.copy(m.lerp(y,p));const v=ho.theta-Ms.theta,S=ho.phi-Ms.phi,M=ho.radius-Ms.radius;this._sphericalEnd.set(Ms.radius+M*p,Ms.phi+S*p,Ms.theta+v*p),this.normalizeRotations(),this._needsUpdate=!0,f||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const A=!f||Ve(this._target.x,this._targetEnd.x,this.restThreshold)&&Ve(this._target.y,this._targetEnd.y,this.restThreshold)&&Ve(this._target.z,this._targetEnd.z,this.restThreshold)&&Ve(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Ve(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&Ve(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(A)}setPosition(e,t,s,i=!1){return this.setLookAt(e,t,s,this._targetEnd.x,this._targetEnd.y,this._targetEnd.z,i)}setTarget(e,t,s,i=!1){const n=this.getPosition(pe),a=this.setLookAt(n.x,n.y,n.z,e,t,s,i);return this._sphericalEnd.phi=qs(this._sphericalEnd.phi,this.minPolarAngle,this.maxPolarAngle),a}setFocalOffset(e,t,s,i=!1){this._isUserControllingOffset=!1,this._focalOffsetEnd.set(e,t,s),this._needsUpdate=!0,i||this._focalOffset.copy(this._focalOffsetEnd);const n=!i||Ve(this._focalOffset.x,this._focalOffsetEnd.x,this.restThreshold)&&Ve(this._focalOffset.y,this._focalOffsetEnd.y,this.restThreshold)&&Ve(this._focalOffset.z,this._focalOffsetEnd.z,this.restThreshold);return this._createOnRestPromise(n)}setOrbitPoint(e,t,s){this._camera.updateMatrixWorld(),hi.setFromMatrixColumn(this._camera.matrixWorldInverse,0),di.setFromMatrixColumn(this._camera.matrixWorldInverse,1),rr.setFromMatrixColumn(this._camera.matrixWorldInverse,2);const i=pe.set(e,t,s),n=i.distanceTo(this._camera.position),a=i.sub(this._camera.position);hi.multiplyScalar(a.x),di.multiplyScalar(a.y),rr.multiplyScalar(a.z),pe.copy(hi).add(di).add(rr),pe.z=pe.z+n,this.dollyTo(n,!1),this.setFocalOffset(-pe.x,pe.y,-pe.z,!1),this.moveTo(e,t,s,!1)}setBoundary(e){if(!e){this._boundary.min.set(-1/0,-1/0,-1/0),this._boundary.max.set(1/0,1/0,1/0),this._needsUpdate=!0;return}this._boundary.copy(e),this._boundary.clampPoint(this._targetEnd,this._targetEnd),this._needsUpdate=!0}setViewport(e,t,s,i){if(e===null){this._viewport=null;return}this._viewport=this._viewport||new he.Vector4,typeof e=="number"?this._viewport.set(e,t,s,i):this._viewport.copy(e)}getDistanceToFitBox(e,t,s,i=!1){if(Bd(this._camera,"getDistanceToFitBox"))return this._spherical.radius;const n=e/t,a=this._camera.getEffectiveFOV()*oo,o=this._camera.aspect;return((i?n>o:n<o)?t:e/o)*.5/Math.tan(a*.5)+s*.5}getDistanceToFitSphere(e){if(Bd(this._camera,"getDistanceToFitSphere"))return this._spherical.radius;const t=this._camera.getEffectiveFOV()*oo,s=Math.atan(Math.tan(t*.5)*this._camera.aspect)*2,i=1<this._camera.aspect?t:s;return e/Math.sin(i*.5)}getTarget(e,t=!0){return(e&&e.isVector3?e:new he.Vector3).copy(t?this._targetEnd:this._target)}getPosition(e,t=!0){return(e&&e.isVector3?e:new he.Vector3).setFromSpherical(t?this._sphericalEnd:this._spherical).applyQuaternion(this._yAxisUpSpaceInverse).add(t?this._targetEnd:this._target)}getSpherical(e,t=!0){return(e||new he.Spherical).copy(t?this._sphericalEnd:this._spherical)}getFocalOffset(e,t=!0){return(e&&e.isVector3?e:new he.Vector3).copy(t?this._focalOffsetEnd:this._focalOffset)}normalizeRotations(){this._sphericalEnd.theta=this._sphericalEnd.theta%ia,this._sphericalEnd.theta<0&&(this._sphericalEnd.theta+=ia),this._spherical.theta+=ia*Math.round((this._sphericalEnd.theta-this._spherical.theta)/ia)}stop(){this._focalOffset.copy(this._focalOffsetEnd),this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd),this._zoom=this._zoomEnd}reset(e=!1){if(!Ve(this._camera.up.x,this._cameraUp0.x)||!Ve(this._camera.up.y,this._cameraUp0.y)||!Ve(this._camera.up.z,this._cameraUp0.z)){this._camera.up.copy(this._cameraUp0);const s=this.getPosition(pe);this.updateCameraUp(),this.setPosition(s.x,s.y,s.z)}const t=[this.setLookAt(this._position0.x,this._position0.y,this._position0.z,this._target0.x,this._target0.y,this._target0.z,e),this.setFocalOffset(this._focalOffset0.x,this._focalOffset0.y,this._focalOffset0.z,e),this.zoomTo(this._zoom0,e)];return Promise.all(t)}saveState(){this._cameraUp0.copy(this._camera.up),this.getTarget(this._target0),this.getPosition(this._position0),this._zoom0=this._zoom,this._focalOffset0.copy(this._focalOffset)}updateCameraUp(){this._yAxisUpSpace.setFromUnitVectors(this._camera.up,cc),this._yAxisUpSpaceInverse.copy(this._yAxisUpSpace).invert()}applyCameraUp(){const e=pe.subVectors(this._target,this._camera.position).normalize(),t=Be.crossVectors(e,this._camera.up);this._camera.up.crossVectors(t,e).normalize(),this._camera.updateMatrixWorld();const s=this.getPosition(pe);this.updateCameraUp(),this.setPosition(s.x,s.y,s.z)}update(e){const t=this._sphericalEnd.theta-this._spherical.theta,s=this._sphericalEnd.phi-this._spherical.phi,i=this._sphericalEnd.radius-this._spherical.radius,n=zy.subVectors(this._targetEnd,this._target),a=Gy.subVectors(this._focalOffsetEnd,this._focalOffset),o=this._zoomEnd-this._zoom;if(Xe(t))this._thetaVelocity.value=0,this._spherical.theta=this._sphericalEnd.theta;else{const h=this._isUserControllingRotate?this.draggingSmoothTime:this.smoothTime;this._spherical.theta=oc(this._spherical.theta,this._sphericalEnd.theta,this._thetaVelocity,h,1/0,e),this._needsUpdate=!0}if(Xe(s))this._phiVelocity.value=0,this._spherical.phi=this._sphericalEnd.phi;else{const h=this._isUserControllingRotate?this.draggingSmoothTime:this.smoothTime;this._spherical.phi=oc(this._spherical.phi,this._sphericalEnd.phi,this._phiVelocity,h,1/0,e),this._needsUpdate=!0}if(Xe(i))this._radiusVelocity.value=0,this._spherical.radius=this._sphericalEnd.radius;else{const h=this._isUserControllingDolly?this.draggingSmoothTime:this.smoothTime;this._spherical.radius=oc(this._spherical.radius,this._sphericalEnd.radius,this._radiusVelocity,h,this.maxSpeed,e),this._needsUpdate=!0}if(Xe(n.x)&&Xe(n.y)&&Xe(n.z))this._targetVelocity.set(0,0,0),this._target.copy(this._targetEnd);else{const h=this._isUserControllingTruck?this.draggingSmoothTime:this.smoothTime;Vy(this._target,this._targetEnd,this._targetVelocity,h,this.maxSpeed,e,this._target),this._needsUpdate=!0}if(Xe(a.x)&&Xe(a.y)&&Xe(a.z))this._focalOffsetVelocity.set(0,0,0),this._focalOffset.copy(this._focalOffsetEnd);else{const h=this._isUserControllingOffset?this.draggingSmoothTime:this.smoothTime;Vy(this._focalOffset,this._focalOffsetEnd,this._focalOffsetVelocity,h,this.maxSpeed,e,this._focalOffset),this._needsUpdate=!0}if(Xe(o))this._zoomVelocity.value=0,this._zoom=this._zoomEnd;else{const h=this._isUserControllingZoom?this.draggingSmoothTime:this.smoothTime;this._zoom=oc(this._zoom,this._zoomEnd,this._zoomVelocity,h,1/0,e)}if(this.dollyToCursor){if(nr(this._camera)&&this._changedDolly!==0){const h=this._spherical.radius-this._lastDistance,d=this._camera,p=this._getCameraDirection(uo),f=pe.copy(p).cross(d.up).normalize();f.lengthSq()===0&&(f.x=1);const m=Be.crossVectors(f,p),x=this._sphericalEnd.radius*Math.tan(d.getEffectiveFOV()*oo*.5),b=(this._sphericalEnd.radius-h-this._sphericalEnd.radius)/this._sphericalEnd.radius,v=na.copy(this._targetEnd).add(f.multiplyScalar(this._dollyControlCoord.x*x*d.aspect)).add(m.multiplyScalar(this._dollyControlCoord.y*x)),S=pe.copy(this._targetEnd).lerp(v,b),M=this._lastDollyDirection===sa.IN&&this._spherical.radius<=this.minDistance,A=this._lastDollyDirection===sa.OUT&&this.maxDistance<=this._spherical.radius;if(this.infinityDolly&&(M||A)){this._sphericalEnd.radius-=h,this._spherical.radius-=h;const P=Be.copy(p).multiplyScalar(-h);S.add(P)}this._boundary.clampPoint(S,S);const C=Be.subVectors(S,this._targetEnd);this._targetEnd.copy(S),this._target.add(C),this._changedDolly-=h,Xe(this._changedDolly)&&(this._changedDolly=0)}else if(xn(this._camera)&&this._changedZoom!==0){const h=this._zoom-this._lastZoom,d=this._camera,p=pe.set(this._dollyControlCoord.x,this._dollyControlCoord.y,(d.near+d.far)/(d.near-d.far)).unproject(d),f=Be.set(0,0,-1).applyQuaternion(d.quaternion),m=na.copy(p).add(f.multiplyScalar(-p.dot(d.up))),y=-(this._zoom-h-this._zoom)/this._zoom,b=this._getCameraDirection(uo),v=this._targetEnd.dot(b),S=pe.copy(this._targetEnd).lerp(m,y),M=S.dot(b),A=b.multiplyScalar(M-v);S.sub(A),this._boundary.clampPoint(S,S);const C=Be.subVectors(S,this._targetEnd);this._targetEnd.copy(S),this._target.add(C),this._changedZoom-=h,Xe(this._changedZoom)&&(this._changedZoom=0)}}this._camera.zoom!==this._zoom&&(this._camera.zoom=this._zoom,this._camera.updateProjectionMatrix(),this._updateNearPlaneCorners(),this._needsUpdate=!0),this._dragNeedsUpdate=!0;const l=this._collisionTest();this._spherical.radius=Math.min(this._spherical.radius,l),this._spherical.makeSafe(),this._camera.position.setFromSpherical(this._spherical).applyQuaternion(this._yAxisUpSpaceInverse).add(this._target),this._camera.lookAt(this._target),(!Xe(this._focalOffset.x)||!Xe(this._focalOffset.y)||!Xe(this._focalOffset.z))&&(hi.setFromMatrixColumn(this._camera.matrix,0),di.setFromMatrixColumn(this._camera.matrix,1),rr.setFromMatrixColumn(this._camera.matrix,2),hi.multiplyScalar(this._focalOffset.x),di.multiplyScalar(-this._focalOffset.y),rr.multiplyScalar(this._focalOffset.z),pe.copy(hi).add(di).add(rr),this._camera.position.add(pe),this._camera.updateMatrixWorld()),this._boundaryEnclosesCamera&&this._encloseToBoundary(this._camera.position.copy(this._target),pe.setFromSpherical(this._spherical).applyQuaternion(this._yAxisUpSpaceInverse),1);const u=this._needsUpdate;return u&&!this._updatedLastTime?(this._hasRested=!1,this.dispatchEvent({type:"wake"}),this.dispatchEvent({type:"update"})):u?(this.dispatchEvent({type:"update"}),Xe(t,this.restThreshold)&&Xe(s,this.restThreshold)&&Xe(i,this.restThreshold)&&Xe(n.x,this.restThreshold)&&Xe(n.y,this.restThreshold)&&Xe(n.z,this.restThreshold)&&Xe(a.x,this.restThreshold)&&Xe(a.y,this.restThreshold)&&Xe(a.z,this.restThreshold)&&Xe(o,this.restThreshold)&&!this._hasRested&&(this._hasRested=!0,this.dispatchEvent({type:"rest"}))):!u&&this._updatedLastTime&&this.dispatchEvent({type:"sleep"}),this._lastDistance=this._spherical.radius,this._lastZoom=this._zoom,this._updatedLastTime=u,this._needsUpdate=!1,u}toJSON(){return JSON.stringify({enabled:this._enabled,minDistance:this.minDistance,maxDistance:lo(this.maxDistance),minZoom:this.minZoom,maxZoom:lo(this.maxZoom),minPolarAngle:this.minPolarAngle,maxPolarAngle:lo(this.maxPolarAngle),minAzimuthAngle:lo(this.minAzimuthAngle),maxAzimuthAngle:lo(this.maxAzimuthAngle),smoothTime:this.smoothTime,draggingSmoothTime:this.draggingSmoothTime,dollySpeed:this.dollySpeed,truckSpeed:this.truckSpeed,dollyToCursor:this.dollyToCursor,target:this._targetEnd.toArray(),position:pe.setFromSpherical(this._sphericalEnd).add(this._targetEnd).toArray(),zoom:this._zoomEnd,focalOffset:this._focalOffsetEnd.toArray(),target0:this._target0.toArray(),position0:this._position0.toArray(),zoom0:this._zoom0,focalOffset0:this._focalOffset0.toArray()})}fromJSON(e,t=!1){const s=JSON.parse(e);this.enabled=s.enabled,this.minDistance=s.minDistance,this.maxDistance=co(s.maxDistance),this.minZoom=s.minZoom,this.maxZoom=co(s.maxZoom),this.minPolarAngle=s.minPolarAngle,this.maxPolarAngle=co(s.maxPolarAngle),this.minAzimuthAngle=co(s.minAzimuthAngle),this.maxAzimuthAngle=co(s.maxAzimuthAngle),this.smoothTime=s.smoothTime,this.draggingSmoothTime=s.draggingSmoothTime,this.dollySpeed=s.dollySpeed,this.truckSpeed=s.truckSpeed,this.dollyToCursor=s.dollyToCursor,this._target0.fromArray(s.target0),this._position0.fromArray(s.position0),this._zoom0=s.zoom0,this._focalOffset0.fromArray(s.focalOffset0),this.moveTo(s.target[0],s.target[1],s.target[2],t),Ms.setFromVector3(pe.fromArray(s.position).sub(this._targetEnd).applyQuaternion(this._yAxisUpSpace)),this.rotateTo(Ms.theta,Ms.phi,t),this.dollyTo(Ms.radius,t),this.zoomTo(s.zoom,t),this.setFocalOffset(s.focalOffset[0],s.focalOffset[1],s.focalOffset[2],t),this._needsUpdate=!0}connect(e){if(this._domElement){console.warn("camera-controls is already connected.");return}e.setAttribute("data-camera-controls-version",mI),this._addAllEventListeners(e),this._getClientRect(this._elementRect)}disconnect(){this.cancel(),this._removeAllEventListeners(),this._domElement&&(this._domElement.removeAttribute("data-camera-controls-version"),this._domElement=void 0)}dispose(){this.removeAllEventListeners(),this.disconnect()}_getTargetDirection(e){return e.setFromSpherical(this._spherical).divideScalar(this._spherical.radius).applyQuaternion(this._yAxisUpSpaceInverse)}_getCameraDirection(e){return this._getTargetDirection(e).negate()}_findPointerById(e){return this._activePointers.find(t=>t.pointerId===e)}_findPointerByMouseButton(e){return this._activePointers.find(t=>t.mouseButton===e)}_disposePointer(e){this._activePointers.splice(this._activePointers.indexOf(e),1)}_encloseToBoundary(e,t,s){const i=t.lengthSq();if(i===0)return e;const n=Be.copy(t).add(e),o=this._boundary.clampPoint(n,na).sub(n),l=o.lengthSq();if(l===0)return e.add(t);if(l===i)return e;if(s===0)return e.add(t).add(o);{const c=1+s*l/t.dot(o);return e.add(Be.copy(t).multiplyScalar(c)).add(o.multiplyScalar(1-s))}}_updateNearPlaneCorners(){if(nr(this._camera)){const e=this._camera,t=e.near,s=e.getEffectiveFOV()*oo,i=Math.tan(s*.5)*t,n=i*e.aspect;this._nearPlaneCorners[0].set(-n,-i,0),this._nearPlaneCorners[1].set(n,-i,0),this._nearPlaneCorners[2].set(n,i,0),this._nearPlaneCorners[3].set(-n,i,0)}else if(xn(this._camera)){const e=this._camera,t=1/e.zoom,s=e.left*t,i=e.right*t,n=e.top*t,a=e.bottom*t;this._nearPlaneCorners[0].set(s,n,0),this._nearPlaneCorners[1].set(i,n,0),this._nearPlaneCorners[2].set(i,a,0),this._nearPlaneCorners[3].set(s,a,0)}}_collisionTest(){let e=1/0;if(!(this.colliderMeshes.length>=1)||Bd(this._camera,"_collisionTest"))return e;const s=this._getTargetDirection(uo);Ud.lookAt(ky,s,this._camera.up);for(let i=0;i<4;i++){const n=Be.copy(this._nearPlaneCorners[i]);n.applyMatrix4(Ud);const a=na.addVectors(this._target,n);uc.set(a,s),uc.far=this._spherical.radius+1;const o=uc.intersectObjects(this.colliderMeshes);o.length!==0&&o[0].distance<e&&(e=o[0].distance)}return e}_getClientRect(e){if(!this._domElement)return;const t=this._domElement.getBoundingClientRect();return e.x=t.left,e.y=t.top,this._viewport?(e.x+=this._viewport.x,e.y+=t.height-this._viewport.w-this._viewport.y,e.width=this._viewport.z,e.height=this._viewport.w):(e.width=t.width,e.height=t.height),e}_createOnRestPromise(e){return e?Promise.resolve():(this._hasRested=!1,this.dispatchEvent({type:"transitionstart"}),new Promise(t=>{const s=()=>{this.removeEventListener("rest",s),t()};this.addEventListener("rest",s)}))}_addAllEventListeners(e){}_removeAllEventListeners(){}get dampingFactor(){return console.warn(".dampingFactor has been deprecated. use smoothTime (in seconds) instead."),0}set dampingFactor(e){console.warn(".dampingFactor has been deprecated. use smoothTime (in seconds) instead.")}get draggingDampingFactor(){return console.warn(".draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead."),0}set draggingDampingFactor(e){console.warn(".draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead.")}static createBoundingSphere(e,t=new he.Sphere){const s=t,i=s.center;ra.makeEmpty(),e.traverseVisible(a=>{a.isMesh&&ra.expandByObject(a)}),ra.getCenter(i);let n=0;return e.traverseVisible(a=>{if(!a.isMesh)return;const o=a;if(!o.geometry)return;const l=o.geometry.clone();l.applyMatrix4(o.matrixWorld);const u=l.attributes.position;for(let h=0,d=u.count;h<d;h++)pe.fromBufferAttribute(u,h),n=Math.max(n,i.distanceToSquared(pe))}),s.radius=Math.sqrt(n),s}}const wu=r=>{const[e,t]=X.useState(r.options[r.index]),s=()=>{r.onToggle(!r.open)},i=a=>{a!==e&&(r.onSelect(a),t(a)),r.onToggle(!1)},n=r.open?`${r.options.length*31-1}px`:"0px";return F.jsxs("div",{className:`dropdown ${r.up===!0?"up":""}`,children:[F.jsx("div",{className:"dropdown-toggle",onClick:s,children:`${r.title}: ${e}`}),F.jsx("ul",{className:"dropdown-menu",style:{height:n},children:r.options.map(a=>F.jsx("li",{onClick:()=>i(a),children:a},a))})]})},ar=X.forwardRef(function(e,t){const s=["Renderer","Depth","Normals","UVs","Wireframe"],[i,n]=X.useState("Renderer"),[a,o]=X.useState(!1),[l,c]=X.useState(!1),[u,h]=X.useState(!1);return F.jsxs("div",{className:`CameraWindow ${e.name}`,children:[F.jsx("div",{ref:t,className:"clickable",onClick:()=>{u&&h(!1)}}),F.jsxs("div",{className:"options",children:[e.camera!==null&&F.jsx(wu,{title:"Camera",index:e.options.indexOf(e.camera.name),open:u,options:e.options,onSelect:e.onSelectCamera,onToggle:d=>{d&&l&&c(!1),h(d)},up:!0}),F.jsx(wu,{title:"Mode",index:s.indexOf(i),open:l,options:s,onSelect:d=>{if(d===i)return;const p=d;e.onSelectRenderMode(p),n(p)},onToggle:d=>{d&&u&&h(!1),a&&o(!1),c(d)},up:!0})]})]})}),yI=`out vec3 worldPosition;
26
+ */const H={LEFT:1,RIGHT:2,MIDDLE:4},f=Object.freeze({NONE:0,ROTATE:1,TRUCK:2,SCREEN_PAN:4,OFFSET:8,DOLLY:16,ZOOM:32,TOUCH_ROTATE:64,TOUCH_TRUCK:128,TOUCH_SCREEN_PAN:256,TOUCH_OFFSET:512,TOUCH_DOLLY:1024,TOUCH_ZOOM:2048,TOUCH_DOLLY_TRUCK:4096,TOUCH_DOLLY_SCREEN_PAN:8192,TOUCH_DOLLY_OFFSET:16384,TOUCH_DOLLY_ROTATE:32768,TOUCH_ZOOM_TRUCK:65536,TOUCH_ZOOM_OFFSET:131072,TOUCH_ZOOM_SCREEN_PAN:262144,TOUCH_ZOOM_ROTATE:524288}),Ee={NONE:0,IN:1,OUT:-1};function pe(i){return i.isPerspectiveCamera}function ce(i){return i.isOrthographicCamera}const Se=Math.PI*2,Nt=Math.PI/2,hi=1e-5,Re=Math.PI/180;function J(i,e,t){return Math.max(e,Math.min(t,i))}function z(i,e=hi){return Math.abs(i)<e}function k(i,e,t=hi){return z(i-e,t)}function kt(i,e){return Math.round(i/e)*e}function De(i){return isFinite(i)?i:i<0?-Number.MAX_VALUE:Number.MAX_VALUE}function Pe(i){return Math.abs(i)<Number.MAX_VALUE?i:i*(1/0)}function je(i,e,t,s,n=1/0,a){s=Math.max(1e-4,s);const r=2/s,o=r*a,c=1/(1+o+.48*o*o+.235*o*o*o);let l=i-e;const h=e,p=n*s;l=J(l,-p,p),e=i-l;const m=(t.value+r*l)*a;t.value=(t.value-r*m)*c;let g=e+(l+m)*c;return h-i>0==g>h&&(g=h,t.value=(g-h)/a),g}function Ft(i,e,t,s,n=1/0,a,r){s=Math.max(1e-4,s);const o=2/s,c=o*a,l=1/(1+c+.48*c*c+.235*c*c*c);let h=e.x,p=e.y,m=e.z,g=i.x-h,y=i.y-p,_=i.z-m;const E=h,v=p,C=m,x=n*s,O=x*x,S=g*g+y*y+_*_;if(S>O){const ue=Math.sqrt(S);g=g/ue*x,y=y/ue*x,_=_/ue*x}h=i.x-g,p=i.y-y,m=i.z-_;const w=(t.x+o*g)*a,M=(t.y+o*y)*a,L=(t.z+o*_)*a;t.x=(t.x-o*w)*l,t.y=(t.y-o*M)*l,t.z=(t.z-o*L)*l,r.x=h+(g+w)*l,r.y=p+(y+M)*l,r.z=m+(_+L)*l;const A=E-i.x,F=v-i.y,Q=C-i.z,re=r.x-E,de=r.y-v,ve=r.z-C;return A*re+F*de+Q*ve>0&&(r.x=E,r.y=v,r.z=C,t.x=(r.x-E)/a,t.y=(r.y-v)/a,t.z=(r.z-C)/a),r}function at(i,e){e.set(0,0),i.forEach(t=>{e.x+=t.clientX,e.y+=t.clientY}),e.x/=i.length,e.y/=i.length}function ot(i,e){return ce(i)?(console.warn(`${e} is not supported in OrthographicCamera`),!0):!1}class pn{constructor(){this._listeners={}}addEventListener(e,t){const s=this._listeners;s[e]===void 0&&(s[e]=[]),s[e].indexOf(t)===-1&&s[e].push(t)}hasEventListener(e,t){const s=this._listeners;return s[e]!==void 0&&s[e].indexOf(t)!==-1}removeEventListener(e,t){const n=this._listeners[e];if(n!==void 0){const a=n.indexOf(t);a!==-1&&n.splice(a,1)}}removeAllEventListeners(e){if(!e){this._listeners={};return}Array.isArray(this._listeners[e])&&(this._listeners[e].length=0)}dispatchEvent(e){const s=this._listeners[e.type];if(s!==void 0){e.target=this;const n=s.slice(0);for(let a=0,r=n.length;a<r;a++)n[a].call(this,e)}}}var lt;const mn="2.10.1",Be=1/8,fn=/Mac/.test((lt=globalThis?.navigator)===null||lt===void 0?void 0:lt.platform);let R,zt,Ve,ct,Y,D,N,xe,Ie,ee,te,me,Ht,jt,$,Le,Oe,Bt,ht,Vt,dt,ut,Ge;class se extends pn{static install(e){R=e.THREE,zt=Object.freeze(new R.Vector3(0,0,0)),Ve=Object.freeze(new R.Vector3(0,1,0)),ct=Object.freeze(new R.Vector3(0,0,1)),Y=new R.Vector2,D=new R.Vector3,N=new R.Vector3,xe=new R.Vector3,Ie=new R.Vector3,ee=new R.Vector3,te=new R.Vector3,me=new R.Vector3,Ht=new R.Vector3,jt=new R.Vector3,$=new R.Spherical,Le=new R.Spherical,Oe=new R.Box3,Bt=new R.Box3,ht=new R.Sphere,Vt=new R.Quaternion,dt=new R.Quaternion,ut=new R.Matrix4,Ge=new R.Raycaster}static get ACTION(){return f}set verticalDragToForward(e){console.warn("camera-controls: `verticalDragToForward` was removed. Use `mouseButtons.left = CameraControls.ACTION.SCREEN_PAN` instead.")}constructor(e,t){super(),this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.minDistance=Number.EPSILON,this.maxDistance=1/0,this.infinityDolly=!1,this.minZoom=.01,this.maxZoom=1/0,this.smoothTime=.25,this.draggingSmoothTime=.125,this.maxSpeed=1/0,this.azimuthRotateSpeed=1,this.polarRotateSpeed=1,this.dollySpeed=1,this.dollyDragInverted=!1,this.truckSpeed=2,this.dollyToCursor=!1,this.dragToOffset=!1,this.boundaryFriction=0,this.restThreshold=.01,this.colliderMeshes=[],this.cancel=()=>{},this._enabled=!0,this._state=f.NONE,this._viewport=null,this._changedDolly=0,this._changedZoom=0,this._hasRested=!0,this._boundaryEnclosesCamera=!1,this._needsUpdate=!0,this._updatedLastTime=!1,this._elementRect=new DOMRect,this._isDragging=!1,this._dragNeedsUpdate=!0,this._activePointers=[],this._lockedPointer=null,this._interactiveArea=new DOMRect(0,0,1,1),this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._isUserControllingOffset=!1,this._isUserControllingZoom=!1,this._lastDollyDirection=Ee.NONE,this._thetaVelocity={value:0},this._phiVelocity={value:0},this._radiusVelocity={value:0},this._targetVelocity=new R.Vector3,this._focalOffsetVelocity=new R.Vector3,this._zoomVelocity={value:0},this._truckInternal=(v,C,x,O)=>{let S,w;if(pe(this._camera)){const M=D.copy(this._camera.position).sub(this._target),L=this._camera.getEffectiveFOV()*Re,A=M.length()*Math.tan(L*.5);S=this.truckSpeed*v*A/this._elementRect.height,w=this.truckSpeed*C*A/this._elementRect.height}else if(ce(this._camera)){const M=this._camera;S=this.truckSpeed*v*(M.right-M.left)/M.zoom/this._elementRect.width,w=this.truckSpeed*C*(M.top-M.bottom)/M.zoom/this._elementRect.height}else return;O?(x?this.setFocalOffset(this._focalOffsetEnd.x+S,this._focalOffsetEnd.y,this._focalOffsetEnd.z,!0):this.truck(S,0,!0),this.forward(-w,!0)):x?this.setFocalOffset(this._focalOffsetEnd.x+S,this._focalOffsetEnd.y+w,this._focalOffsetEnd.z,!0):this.truck(S,w,!0)},this._rotateInternal=(v,C)=>{const x=Se*this.azimuthRotateSpeed*v/this._elementRect.height,O=Se*this.polarRotateSpeed*C/this._elementRect.height;this.rotate(x,O,!0)},this._dollyInternal=(v,C,x)=>{const O=Math.pow(.95,-v*this.dollySpeed),S=this._sphericalEnd.radius,w=this._sphericalEnd.radius*O,M=J(w,this.minDistance,this.maxDistance),L=M-w;this.infinityDolly&&this.dollyToCursor?this._dollyToNoClamp(w,!0):this.infinityDolly&&!this.dollyToCursor?(this.dollyInFixed(L,!0),this._dollyToNoClamp(M,!0)):this._dollyToNoClamp(M,!0),this.dollyToCursor&&(this._changedDolly+=(this.infinityDolly?w:M)-S,this._dollyControlCoord.set(C,x)),this._lastDollyDirection=Math.sign(-v)},this._zoomInternal=(v,C,x)=>{const O=Math.pow(.95,v*this.dollySpeed),S=this._zoom,w=this._zoom*O;this.zoomTo(w,!0),this.dollyToCursor&&(this._changedZoom+=w-S,this._dollyControlCoord.set(C,x))},typeof R>"u"&&console.error("camera-controls: `THREE` is undefined. You must first run `CameraControls.install( { THREE: THREE } )`. Check the docs for further information."),this._camera=e,this._yAxisUpSpace=new R.Quaternion().setFromUnitVectors(this._camera.up,Ve),this._yAxisUpSpaceInverse=this._yAxisUpSpace.clone().invert(),this._state=f.NONE,this._target=new R.Vector3,this._targetEnd=this._target.clone(),this._focalOffset=new R.Vector3,this._focalOffsetEnd=this._focalOffset.clone(),this._spherical=new R.Spherical().setFromVector3(D.copy(this._camera.position).applyQuaternion(this._yAxisUpSpace)),this._sphericalEnd=this._spherical.clone(),this._lastDistance=this._spherical.radius,this._zoom=this._camera.zoom,this._zoomEnd=this._zoom,this._lastZoom=this._zoom,this._nearPlaneCorners=[new R.Vector3,new R.Vector3,new R.Vector3,new R.Vector3],this._updateNearPlaneCorners(),this._boundary=new R.Box3(new R.Vector3(-1/0,-1/0,-1/0),new R.Vector3(1/0,1/0,1/0)),this._cameraUp0=this._camera.up.clone(),this._target0=this._target.clone(),this._position0=this._camera.position.clone(),this._zoom0=this._zoom,this._focalOffset0=this._focalOffset.clone(),this._dollyControlCoord=new R.Vector2,this.mouseButtons={left:f.ROTATE,middle:f.DOLLY,right:f.TRUCK,wheel:pe(this._camera)?f.DOLLY:ce(this._camera)?f.ZOOM:f.NONE},this.touches={one:f.TOUCH_ROTATE,two:pe(this._camera)?f.TOUCH_DOLLY_TRUCK:ce(this._camera)?f.TOUCH_ZOOM_TRUCK:f.NONE,three:f.TOUCH_TRUCK};const s=new R.Vector2,n=new R.Vector2,a=new R.Vector2,r=v=>{if(!this._enabled||!this._domElement)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){const O=this._domElement.getBoundingClientRect(),S=v.clientX/O.width,w=v.clientY/O.height;if(S<this._interactiveArea.left||S>this._interactiveArea.right||w<this._interactiveArea.top||w>this._interactiveArea.bottom)return}const C=v.pointerType!=="mouse"?null:(v.buttons&H.LEFT)===H.LEFT?H.LEFT:(v.buttons&H.MIDDLE)===H.MIDDLE?H.MIDDLE:(v.buttons&H.RIGHT)===H.RIGHT?H.RIGHT:null;if(C!==null){const O=this._findPointerByMouseButton(C);O&&this._disposePointer(O)}if((v.buttons&H.LEFT)===H.LEFT&&this._lockedPointer)return;const x={pointerId:v.pointerId,clientX:v.clientX,clientY:v.clientY,deltaX:0,deltaY:0,mouseButton:C};this._activePointers.push(x),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",c),this._domElement.ownerDocument.addEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",c),this._isDragging=!0,m(v)},o=v=>{v.cancelable&&v.preventDefault();const C=v.pointerId,x=this._lockedPointer||this._findPointerById(C);if(x){if(x.clientX=v.clientX,x.clientY=v.clientY,x.deltaX=v.movementX,x.deltaY=v.movementY,this._state=0,v.pointerType==="touch")switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else(!this._isDragging&&this._lockedPointer||this._isDragging&&(v.buttons&H.LEFT)===H.LEFT)&&(this._state=this._state|this.mouseButtons.left),this._isDragging&&(v.buttons&H.MIDDLE)===H.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),this._isDragging&&(v.buttons&H.RIGHT)===H.RIGHT&&(this._state=this._state|this.mouseButtons.right);g()}},c=v=>{const C=this._findPointerById(v.pointerId);if(!(C&&C===this._lockedPointer)){if(C&&this._disposePointer(C),v.pointerType==="touch")switch(this._activePointers.length){case 0:this._state=f.NONE;break;case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else this._state=f.NONE;y()}};let l=-1;const h=v=>{if(!this._domElement||!this._enabled||this.mouseButtons.wheel===f.NONE)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){const w=this._domElement.getBoundingClientRect(),M=v.clientX/w.width,L=v.clientY/w.height;if(M<this._interactiveArea.left||M>this._interactiveArea.right||L<this._interactiveArea.top||L>this._interactiveArea.bottom)return}if(v.preventDefault(),this.dollyToCursor||this.mouseButtons.wheel===f.ROTATE||this.mouseButtons.wheel===f.TRUCK){const w=performance.now();l-w<1e3&&this._getClientRect(this._elementRect),l=w}const C=fn?-1:-3,x=v.deltaMode===1||v.ctrlKey?v.deltaY/C:v.deltaY/(C*10),O=this.dollyToCursor?(v.clientX-this._elementRect.x)/this._elementRect.width*2-1:0,S=this.dollyToCursor?(v.clientY-this._elementRect.y)/this._elementRect.height*-2+1:0;switch(this.mouseButtons.wheel){case f.ROTATE:{this._rotateInternal(v.deltaX,v.deltaY),this._isUserControllingRotate=!0;break}case f.TRUCK:{this._truckInternal(v.deltaX,v.deltaY,!1,!1),this._isUserControllingTruck=!0;break}case f.SCREEN_PAN:{this._truckInternal(v.deltaX,v.deltaY,!1,!0),this._isUserControllingTruck=!0;break}case f.OFFSET:{this._truckInternal(v.deltaX,v.deltaY,!0,!1),this._isUserControllingOffset=!0;break}case f.DOLLY:{this._dollyInternal(-x,O,S),this._isUserControllingDolly=!0;break}case f.ZOOM:{this._zoomInternal(-x,O,S),this._isUserControllingZoom=!0;break}}this.dispatchEvent({type:"control"})},p=v=>{if(!(!this._domElement||!this._enabled)){if(this.mouseButtons.right===se.ACTION.NONE){const C=v instanceof PointerEvent?v.pointerId:0,x=this._findPointerById(C);x&&this._disposePointer(x),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",c);return}v.preventDefault()}},m=v=>{if(!this._enabled)return;if(at(this._activePointers,Y),this._getClientRect(this._elementRect),s.copy(Y),n.copy(Y),this._activePointers.length>=2){const x=Y.x-this._activePointers[1].clientX,O=Y.y-this._activePointers[1].clientY,S=Math.sqrt(x*x+O*O);a.set(0,S);const w=(this._activePointers[0].clientX+this._activePointers[1].clientX)*.5,M=(this._activePointers[0].clientY+this._activePointers[1].clientY)*.5;n.set(w,M)}if(this._state=0,!v)this._lockedPointer&&(this._state=this._state|this.mouseButtons.left);else if("pointerType"in v&&v.pointerType==="touch")switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else!this._lockedPointer&&(v.buttons&H.LEFT)===H.LEFT&&(this._state=this._state|this.mouseButtons.left),(v.buttons&H.MIDDLE)===H.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),(v.buttons&H.RIGHT)===H.RIGHT&&(this._state=this._state|this.mouseButtons.right);((this._state&f.ROTATE)===f.ROTATE||(this._state&f.TOUCH_ROTATE)===f.TOUCH_ROTATE||(this._state&f.TOUCH_DOLLY_ROTATE)===f.TOUCH_DOLLY_ROTATE||(this._state&f.TOUCH_ZOOM_ROTATE)===f.TOUCH_ZOOM_ROTATE)&&(this._sphericalEnd.theta=this._spherical.theta,this._sphericalEnd.phi=this._spherical.phi,this._thetaVelocity.value=0,this._phiVelocity.value=0),((this._state&f.TRUCK)===f.TRUCK||(this._state&f.SCREEN_PAN)===f.SCREEN_PAN||(this._state&f.TOUCH_TRUCK)===f.TOUCH_TRUCK||(this._state&f.TOUCH_SCREEN_PAN)===f.TOUCH_SCREEN_PAN||(this._state&f.TOUCH_DOLLY_TRUCK)===f.TOUCH_DOLLY_TRUCK||(this._state&f.TOUCH_DOLLY_SCREEN_PAN)===f.TOUCH_DOLLY_SCREEN_PAN||(this._state&f.TOUCH_ZOOM_TRUCK)===f.TOUCH_ZOOM_TRUCK||(this._state&f.TOUCH_ZOOM_SCREEN_PAN)===f.TOUCH_DOLLY_SCREEN_PAN)&&(this._targetEnd.copy(this._target),this._targetVelocity.set(0,0,0)),((this._state&f.DOLLY)===f.DOLLY||(this._state&f.TOUCH_DOLLY)===f.TOUCH_DOLLY||(this._state&f.TOUCH_DOLLY_TRUCK)===f.TOUCH_DOLLY_TRUCK||(this._state&f.TOUCH_DOLLY_SCREEN_PAN)===f.TOUCH_DOLLY_SCREEN_PAN||(this._state&f.TOUCH_DOLLY_OFFSET)===f.TOUCH_DOLLY_OFFSET||(this._state&f.TOUCH_DOLLY_ROTATE)===f.TOUCH_DOLLY_ROTATE)&&(this._sphericalEnd.radius=this._spherical.radius,this._radiusVelocity.value=0),((this._state&f.ZOOM)===f.ZOOM||(this._state&f.TOUCH_ZOOM)===f.TOUCH_ZOOM||(this._state&f.TOUCH_ZOOM_TRUCK)===f.TOUCH_ZOOM_TRUCK||(this._state&f.TOUCH_ZOOM_SCREEN_PAN)===f.TOUCH_ZOOM_SCREEN_PAN||(this._state&f.TOUCH_ZOOM_OFFSET)===f.TOUCH_ZOOM_OFFSET||(this._state&f.TOUCH_ZOOM_ROTATE)===f.TOUCH_ZOOM_ROTATE)&&(this._zoomEnd=this._zoom,this._zoomVelocity.value=0),((this._state&f.OFFSET)===f.OFFSET||(this._state&f.TOUCH_OFFSET)===f.TOUCH_OFFSET||(this._state&f.TOUCH_DOLLY_OFFSET)===f.TOUCH_DOLLY_OFFSET||(this._state&f.TOUCH_ZOOM_OFFSET)===f.TOUCH_ZOOM_OFFSET)&&(this._focalOffsetEnd.copy(this._focalOffset),this._focalOffsetVelocity.set(0,0,0)),this.dispatchEvent({type:"controlstart"})},g=()=>{if(!this._enabled||!this._dragNeedsUpdate)return;this._dragNeedsUpdate=!1,at(this._activePointers,Y);const C=this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement?this._lockedPointer||this._activePointers[0]:null,x=C?-C.deltaX:n.x-Y.x,O=C?-C.deltaY:n.y-Y.y;if(n.copy(Y),((this._state&f.ROTATE)===f.ROTATE||(this._state&f.TOUCH_ROTATE)===f.TOUCH_ROTATE||(this._state&f.TOUCH_DOLLY_ROTATE)===f.TOUCH_DOLLY_ROTATE||(this._state&f.TOUCH_ZOOM_ROTATE)===f.TOUCH_ZOOM_ROTATE)&&(this._rotateInternal(x,O),this._isUserControllingRotate=!0),(this._state&f.DOLLY)===f.DOLLY||(this._state&f.ZOOM)===f.ZOOM){const S=this.dollyToCursor?(s.x-this._elementRect.x)/this._elementRect.width*2-1:0,w=this.dollyToCursor?(s.y-this._elementRect.y)/this._elementRect.height*-2+1:0,M=this.dollyDragInverted?-1:1;(this._state&f.DOLLY)===f.DOLLY?(this._dollyInternal(M*O*Be,S,w),this._isUserControllingDolly=!0):(this._zoomInternal(M*O*Be,S,w),this._isUserControllingZoom=!0)}if((this._state&f.TOUCH_DOLLY)===f.TOUCH_DOLLY||(this._state&f.TOUCH_ZOOM)===f.TOUCH_ZOOM||(this._state&f.TOUCH_DOLLY_TRUCK)===f.TOUCH_DOLLY_TRUCK||(this._state&f.TOUCH_ZOOM_TRUCK)===f.TOUCH_ZOOM_TRUCK||(this._state&f.TOUCH_DOLLY_SCREEN_PAN)===f.TOUCH_DOLLY_SCREEN_PAN||(this._state&f.TOUCH_ZOOM_SCREEN_PAN)===f.TOUCH_ZOOM_SCREEN_PAN||(this._state&f.TOUCH_DOLLY_OFFSET)===f.TOUCH_DOLLY_OFFSET||(this._state&f.TOUCH_ZOOM_OFFSET)===f.TOUCH_ZOOM_OFFSET||(this._state&f.TOUCH_DOLLY_ROTATE)===f.TOUCH_DOLLY_ROTATE||(this._state&f.TOUCH_ZOOM_ROTATE)===f.TOUCH_ZOOM_ROTATE){const S=Y.x-this._activePointers[1].clientX,w=Y.y-this._activePointers[1].clientY,M=Math.sqrt(S*S+w*w),L=a.y-M;a.set(0,M);const A=this.dollyToCursor?(n.x-this._elementRect.x)/this._elementRect.width*2-1:0,F=this.dollyToCursor?(n.y-this._elementRect.y)/this._elementRect.height*-2+1:0;(this._state&f.TOUCH_DOLLY)===f.TOUCH_DOLLY||(this._state&f.TOUCH_DOLLY_ROTATE)===f.TOUCH_DOLLY_ROTATE||(this._state&f.TOUCH_DOLLY_TRUCK)===f.TOUCH_DOLLY_TRUCK||(this._state&f.TOUCH_DOLLY_SCREEN_PAN)===f.TOUCH_DOLLY_SCREEN_PAN||(this._state&f.TOUCH_DOLLY_OFFSET)===f.TOUCH_DOLLY_OFFSET?(this._dollyInternal(L*Be,A,F),this._isUserControllingDolly=!0):(this._zoomInternal(L*Be,A,F),this._isUserControllingZoom=!0)}((this._state&f.TRUCK)===f.TRUCK||(this._state&f.TOUCH_TRUCK)===f.TOUCH_TRUCK||(this._state&f.TOUCH_DOLLY_TRUCK)===f.TOUCH_DOLLY_TRUCK||(this._state&f.TOUCH_ZOOM_TRUCK)===f.TOUCH_ZOOM_TRUCK)&&(this._truckInternal(x,O,!1,!1),this._isUserControllingTruck=!0),((this._state&f.SCREEN_PAN)===f.SCREEN_PAN||(this._state&f.TOUCH_SCREEN_PAN)===f.TOUCH_SCREEN_PAN||(this._state&f.TOUCH_DOLLY_SCREEN_PAN)===f.TOUCH_DOLLY_SCREEN_PAN||(this._state&f.TOUCH_ZOOM_SCREEN_PAN)===f.TOUCH_ZOOM_SCREEN_PAN)&&(this._truckInternal(x,O,!1,!0),this._isUserControllingTruck=!0),((this._state&f.OFFSET)===f.OFFSET||(this._state&f.TOUCH_OFFSET)===f.TOUCH_OFFSET||(this._state&f.TOUCH_DOLLY_OFFSET)===f.TOUCH_DOLLY_OFFSET||(this._state&f.TOUCH_ZOOM_OFFSET)===f.TOUCH_ZOOM_OFFSET)&&(this._truckInternal(x,O,!0,!1),this._isUserControllingOffset=!0),this.dispatchEvent({type:"control"})},y=()=>{at(this._activePointers,Y),n.copy(Y),this._dragNeedsUpdate=!1,(this._activePointers.length===0||this._activePointers.length===1&&this._activePointers[0]===this._lockedPointer)&&(this._isDragging=!1),this._activePointers.length===0&&this._domElement&&(this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",c),this.dispatchEvent({type:"controlend"}))};this.lockPointer=()=>{!this._enabled||!this._domElement||(this.cancel(),this._lockedPointer={pointerId:-1,clientX:0,clientY:0,deltaX:0,deltaY:0,mouseButton:null},this._activePointers.push(this._lockedPointer),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",c),this._domElement.requestPointerLock(),this._domElement.ownerDocument.addEventListener("pointerlockchange",_),this._domElement.ownerDocument.addEventListener("pointerlockerror",E),this._domElement.ownerDocument.addEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",c),m())},this.unlockPointer=()=>{var v,C,x;this._lockedPointer!==null&&(this._disposePointer(this._lockedPointer),this._lockedPointer=null),(v=this._domElement)===null||v===void 0||v.ownerDocument.exitPointerLock(),(C=this._domElement)===null||C===void 0||C.ownerDocument.removeEventListener("pointerlockchange",_),(x=this._domElement)===null||x===void 0||x.ownerDocument.removeEventListener("pointerlockerror",E),this.cancel()};const _=()=>{this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement||this.unlockPointer()},E=()=>{this.unlockPointer()};this._addAllEventListeners=v=>{this._domElement=v,this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none",this._domElement.addEventListener("pointerdown",r),this._domElement.addEventListener("pointercancel",c),this._domElement.addEventListener("wheel",h,{passive:!1}),this._domElement.addEventListener("contextmenu",p)},this._removeAllEventListeners=()=>{this._domElement&&(this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect="",this._domElement.removeEventListener("pointerdown",r),this._domElement.removeEventListener("pointercancel",c),this._domElement.removeEventListener("wheel",h,{passive:!1}),this._domElement.removeEventListener("contextmenu",p),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",c),this._domElement.ownerDocument.removeEventListener("pointerlockchange",_),this._domElement.ownerDocument.removeEventListener("pointerlockerror",E))},this.cancel=()=>{this._state!==f.NONE&&(this._state=f.NONE,this._activePointers.length=0,y())},t&&this.connect(t),this.update(0)}get camera(){return this._camera}set camera(e){this._camera=e,this.updateCameraUp(),this._camera.updateProjectionMatrix(),this._updateNearPlaneCorners(),this._needsUpdate=!0}get enabled(){return this._enabled}set enabled(e){this._enabled=e,this._domElement&&(e?(this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none"):(this.cancel(),this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect=""))}get active(){return!this._hasRested}get currentAction(){return this._state}get distance(){return this._spherical.radius}set distance(e){this._spherical.radius===e&&this._sphericalEnd.radius===e||(this._spherical.radius=e,this._sphericalEnd.radius=e,this._needsUpdate=!0)}get azimuthAngle(){return this._spherical.theta}set azimuthAngle(e){this._spherical.theta===e&&this._sphericalEnd.theta===e||(this._spherical.theta=e,this._sphericalEnd.theta=e,this._needsUpdate=!0)}get polarAngle(){return this._spherical.phi}set polarAngle(e){this._spherical.phi===e&&this._sphericalEnd.phi===e||(this._spherical.phi=e,this._sphericalEnd.phi=e,this._needsUpdate=!0)}get boundaryEnclosesCamera(){return this._boundaryEnclosesCamera}set boundaryEnclosesCamera(e){this._boundaryEnclosesCamera=e,this._needsUpdate=!0}set interactiveArea(e){this._interactiveArea.width=J(e.width,0,1),this._interactiveArea.height=J(e.height,0,1),this._interactiveArea.x=J(e.x,0,1-this._interactiveArea.width),this._interactiveArea.y=J(e.y,0,1-this._interactiveArea.height)}addEventListener(e,t){super.addEventListener(e,t)}removeEventListener(e,t){super.removeEventListener(e,t)}rotate(e,t,s=!1){return this.rotateTo(this._sphericalEnd.theta+e,this._sphericalEnd.phi+t,s)}rotateAzimuthTo(e,t=!1){return this.rotateTo(e,this._sphericalEnd.phi,t)}rotatePolarTo(e,t=!1){return this.rotateTo(this._sphericalEnd.theta,e,t)}rotateTo(e,t,s=!1){this._isUserControllingRotate=!1;const n=J(e,this.minAzimuthAngle,this.maxAzimuthAngle),a=J(t,this.minPolarAngle,this.maxPolarAngle);this._sphericalEnd.theta=n,this._sphericalEnd.phi=a,this._sphericalEnd.makeSafe(),this._needsUpdate=!0,s||(this._spherical.theta=this._sphericalEnd.theta,this._spherical.phi=this._sphericalEnd.phi);const r=!s||k(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&k(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold);return this._createOnRestPromise(r)}dolly(e,t=!1){return this.dollyTo(this._sphericalEnd.radius-e,t)}dollyTo(e,t=!1){return this._isUserControllingDolly=!1,this._lastDollyDirection=Ee.NONE,this._changedDolly=0,this._dollyToNoClamp(J(e,this.minDistance,this.maxDistance),t)}_dollyToNoClamp(e,t=!1){const s=this._sphericalEnd.radius;if(this.colliderMeshes.length>=1){const r=this._collisionTest(),o=k(r,this._spherical.radius);if(!(s>e)&&o)return Promise.resolve();this._sphericalEnd.radius=Math.min(e,r)}else this._sphericalEnd.radius=e;this._needsUpdate=!0,t||(this._spherical.radius=this._sphericalEnd.radius);const a=!t||k(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(a)}dollyInFixed(e,t=!1){this._targetEnd.add(this._getCameraDirection(Ie).multiplyScalar(e)),t||this._target.copy(this._targetEnd);const s=!t||k(this._target.x,this._targetEnd.x,this.restThreshold)&&k(this._target.y,this._targetEnd.y,this.restThreshold)&&k(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(s)}zoom(e,t=!1){return this.zoomTo(this._zoomEnd+e,t)}zoomTo(e,t=!1){this._isUserControllingZoom=!1,this._zoomEnd=J(e,this.minZoom,this.maxZoom),this._needsUpdate=!0,t||(this._zoom=this._zoomEnd);const s=!t||k(this._zoom,this._zoomEnd,this.restThreshold);return this._changedZoom=0,this._createOnRestPromise(s)}pan(e,t,s=!1){return console.warn("`pan` has been renamed to `truck`"),this.truck(e,t,s)}truck(e,t,s=!1){this._camera.updateMatrix(),ee.setFromMatrixColumn(this._camera.matrix,0),te.setFromMatrixColumn(this._camera.matrix,1),ee.multiplyScalar(e),te.multiplyScalar(-t);const n=D.copy(ee).add(te),a=N.copy(this._targetEnd).add(n);return this.moveTo(a.x,a.y,a.z,s)}forward(e,t=!1){D.setFromMatrixColumn(this._camera.matrix,0),D.crossVectors(this._camera.up,D),D.multiplyScalar(e);const s=N.copy(this._targetEnd).add(D);return this.moveTo(s.x,s.y,s.z,t)}elevate(e,t=!1){return D.copy(this._camera.up).multiplyScalar(e),this.moveTo(this._targetEnd.x+D.x,this._targetEnd.y+D.y,this._targetEnd.z+D.z,t)}moveTo(e,t,s,n=!1){this._isUserControllingTruck=!1;const a=D.set(e,t,s).sub(this._targetEnd);this._encloseToBoundary(this._targetEnd,a,this.boundaryFriction),this._needsUpdate=!0,n||this._target.copy(this._targetEnd);const r=!n||k(this._target.x,this._targetEnd.x,this.restThreshold)&&k(this._target.y,this._targetEnd.y,this.restThreshold)&&k(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(r)}lookInDirectionOf(e,t,s,n=!1){const o=D.set(e,t,s).sub(this._targetEnd).normalize().multiplyScalar(-this._sphericalEnd.radius).add(this._targetEnd);return this.setPosition(o.x,o.y,o.z,n)}fitToBox(e,t,{cover:s=!1,paddingLeft:n=0,paddingRight:a=0,paddingBottom:r=0,paddingTop:o=0}={}){const c=[],l=e.isBox3?Oe.copy(e):Oe.setFromObject(e);l.isEmpty()&&(console.warn("camera-controls: fitTo() cannot be used with an empty box. Aborting"),Promise.resolve());const h=kt(this._sphericalEnd.theta,Nt),p=kt(this._sphericalEnd.phi,Nt);c.push(this.rotateTo(h,p,t));const m=D.setFromSpherical(this._sphericalEnd).normalize(),g=Vt.setFromUnitVectors(m,ct),y=k(Math.abs(m.y),1);y&&g.multiply(dt.setFromAxisAngle(Ve,h)),g.multiply(this._yAxisUpSpaceInverse);const _=Bt.makeEmpty();N.copy(l.min).applyQuaternion(g),_.expandByPoint(N),N.copy(l.min).setX(l.max.x).applyQuaternion(g),_.expandByPoint(N),N.copy(l.min).setY(l.max.y).applyQuaternion(g),_.expandByPoint(N),N.copy(l.max).setZ(l.min.z).applyQuaternion(g),_.expandByPoint(N),N.copy(l.min).setZ(l.max.z).applyQuaternion(g),_.expandByPoint(N),N.copy(l.max).setY(l.min.y).applyQuaternion(g),_.expandByPoint(N),N.copy(l.max).setX(l.min.x).applyQuaternion(g),_.expandByPoint(N),N.copy(l.max).applyQuaternion(g),_.expandByPoint(N),_.min.x-=n,_.min.y-=r,_.max.x+=a,_.max.y+=o,g.setFromUnitVectors(ct,m),y&&g.premultiply(dt.invert()),g.premultiply(this._yAxisUpSpace);const E=_.getSize(D),v=_.getCenter(N).applyQuaternion(g);if(pe(this._camera)){const C=this.getDistanceToFitBox(E.x,E.y,E.z,s);c.push(this.moveTo(v.x,v.y,v.z,t)),c.push(this.dollyTo(C,t)),c.push(this.setFocalOffset(0,0,0,t))}else if(ce(this._camera)){const C=this._camera,x=C.right-C.left,O=C.top-C.bottom,S=s?Math.max(x/E.x,O/E.y):Math.min(x/E.x,O/E.y);c.push(this.moveTo(v.x,v.y,v.z,t)),c.push(this.zoomTo(S,t)),c.push(this.setFocalOffset(0,0,0,t))}return Promise.all(c)}fitToSphere(e,t){const s=[],a="isObject3D"in e?se.createBoundingSphere(e,ht):ht.copy(e);if(s.push(this.moveTo(a.center.x,a.center.y,a.center.z,t)),pe(this._camera)){const r=this.getDistanceToFitSphere(a.radius);s.push(this.dollyTo(r,t))}else if(ce(this._camera)){const r=this._camera.right-this._camera.left,o=this._camera.top-this._camera.bottom,c=2*a.radius,l=Math.min(r/c,o/c);s.push(this.zoomTo(l,t))}return s.push(this.setFocalOffset(0,0,0,t)),Promise.all(s)}setLookAt(e,t,s,n,a,r,o=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=Ee.NONE,this._changedDolly=0;const c=N.set(n,a,r),l=D.set(e,t,s);this._targetEnd.copy(c),this._sphericalEnd.setFromVector3(l.sub(c).applyQuaternion(this._yAxisUpSpace)),this.normalizeRotations(),this._needsUpdate=!0,o||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const h=!o||k(this._target.x,this._targetEnd.x,this.restThreshold)&&k(this._target.y,this._targetEnd.y,this.restThreshold)&&k(this._target.z,this._targetEnd.z,this.restThreshold)&&k(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&k(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&k(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(h)}lerpLookAt(e,t,s,n,a,r,o,c,l,h,p,m,g,y=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=Ee.NONE,this._changedDolly=0;const _=D.set(n,a,r),E=N.set(e,t,s);$.setFromVector3(E.sub(_).applyQuaternion(this._yAxisUpSpace));const v=xe.set(h,p,m),C=N.set(o,c,l);Le.setFromVector3(C.sub(v).applyQuaternion(this._yAxisUpSpace)),this._targetEnd.copy(_.lerp(v,g));const x=Le.theta-$.theta,O=Le.phi-$.phi,S=Le.radius-$.radius;this._sphericalEnd.set($.radius+S*g,$.phi+O*g,$.theta+x*g),this.normalizeRotations(),this._needsUpdate=!0,y||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const w=!y||k(this._target.x,this._targetEnd.x,this.restThreshold)&&k(this._target.y,this._targetEnd.y,this.restThreshold)&&k(this._target.z,this._targetEnd.z,this.restThreshold)&&k(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&k(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&k(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(w)}setPosition(e,t,s,n=!1){return this.setLookAt(e,t,s,this._targetEnd.x,this._targetEnd.y,this._targetEnd.z,n)}setTarget(e,t,s,n=!1){const a=this.getPosition(D),r=this.setLookAt(a.x,a.y,a.z,e,t,s,n);return this._sphericalEnd.phi=J(this._sphericalEnd.phi,this.minPolarAngle,this.maxPolarAngle),r}setFocalOffset(e,t,s,n=!1){this._isUserControllingOffset=!1,this._focalOffsetEnd.set(e,t,s),this._needsUpdate=!0,n||this._focalOffset.copy(this._focalOffsetEnd);const a=!n||k(this._focalOffset.x,this._focalOffsetEnd.x,this.restThreshold)&&k(this._focalOffset.y,this._focalOffsetEnd.y,this.restThreshold)&&k(this._focalOffset.z,this._focalOffsetEnd.z,this.restThreshold);return this._createOnRestPromise(a)}setOrbitPoint(e,t,s){this._camera.updateMatrixWorld(),ee.setFromMatrixColumn(this._camera.matrixWorldInverse,0),te.setFromMatrixColumn(this._camera.matrixWorldInverse,1),me.setFromMatrixColumn(this._camera.matrixWorldInverse,2);const n=D.set(e,t,s),a=n.distanceTo(this._camera.position),r=n.sub(this._camera.position);ee.multiplyScalar(r.x),te.multiplyScalar(r.y),me.multiplyScalar(r.z),D.copy(ee).add(te).add(me),D.z=D.z+a,this.dollyTo(a,!1),this.setFocalOffset(-D.x,D.y,-D.z,!1),this.moveTo(e,t,s,!1)}setBoundary(e){if(!e){this._boundary.min.set(-1/0,-1/0,-1/0),this._boundary.max.set(1/0,1/0,1/0),this._needsUpdate=!0;return}this._boundary.copy(e),this._boundary.clampPoint(this._targetEnd,this._targetEnd),this._needsUpdate=!0}setViewport(e,t,s,n){if(e===null){this._viewport=null;return}this._viewport=this._viewport||new R.Vector4,typeof e=="number"?this._viewport.set(e,t,s,n):this._viewport.copy(e)}getDistanceToFitBox(e,t,s,n=!1){if(ot(this._camera,"getDistanceToFitBox"))return this._spherical.radius;const a=e/t,r=this._camera.getEffectiveFOV()*Re,o=this._camera.aspect;return((n?a>o:a<o)?t:e/o)*.5/Math.tan(r*.5)+s*.5}getDistanceToFitSphere(e){if(ot(this._camera,"getDistanceToFitSphere"))return this._spherical.radius;const t=this._camera.getEffectiveFOV()*Re,s=Math.atan(Math.tan(t*.5)*this._camera.aspect)*2,n=1<this._camera.aspect?t:s;return e/Math.sin(n*.5)}getTarget(e,t=!0){return(e&&e.isVector3?e:new R.Vector3).copy(t?this._targetEnd:this._target)}getPosition(e,t=!0){return(e&&e.isVector3?e:new R.Vector3).setFromSpherical(t?this._sphericalEnd:this._spherical).applyQuaternion(this._yAxisUpSpaceInverse).add(t?this._targetEnd:this._target)}getSpherical(e,t=!0){return(e||new R.Spherical).copy(t?this._sphericalEnd:this._spherical)}getFocalOffset(e,t=!0){return(e&&e.isVector3?e:new R.Vector3).copy(t?this._focalOffsetEnd:this._focalOffset)}normalizeRotations(){this._sphericalEnd.theta=this._sphericalEnd.theta%Se,this._sphericalEnd.theta<0&&(this._sphericalEnd.theta+=Se),this._spherical.theta+=Se*Math.round((this._sphericalEnd.theta-this._spherical.theta)/Se)}stop(){this._focalOffset.copy(this._focalOffsetEnd),this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd),this._zoom=this._zoomEnd}reset(e=!1){if(!k(this._camera.up.x,this._cameraUp0.x)||!k(this._camera.up.y,this._cameraUp0.y)||!k(this._camera.up.z,this._cameraUp0.z)){this._camera.up.copy(this._cameraUp0);const s=this.getPosition(D);this.updateCameraUp(),this.setPosition(s.x,s.y,s.z)}const t=[this.setLookAt(this._position0.x,this._position0.y,this._position0.z,this._target0.x,this._target0.y,this._target0.z,e),this.setFocalOffset(this._focalOffset0.x,this._focalOffset0.y,this._focalOffset0.z,e),this.zoomTo(this._zoom0,e)];return Promise.all(t)}saveState(){this._cameraUp0.copy(this._camera.up),this.getTarget(this._target0),this.getPosition(this._position0),this._zoom0=this._zoom,this._focalOffset0.copy(this._focalOffset)}updateCameraUp(){this._yAxisUpSpace.setFromUnitVectors(this._camera.up,Ve),this._yAxisUpSpaceInverse.copy(this._yAxisUpSpace).invert()}applyCameraUp(){const e=D.subVectors(this._target,this._camera.position).normalize(),t=N.crossVectors(e,this._camera.up);this._camera.up.crossVectors(t,e).normalize(),this._camera.updateMatrixWorld();const s=this.getPosition(D);this.updateCameraUp(),this.setPosition(s.x,s.y,s.z)}update(e){const t=this._sphericalEnd.theta-this._spherical.theta,s=this._sphericalEnd.phi-this._spherical.phi,n=this._sphericalEnd.radius-this._spherical.radius,a=Ht.subVectors(this._targetEnd,this._target),r=jt.subVectors(this._focalOffsetEnd,this._focalOffset),o=this._zoomEnd-this._zoom;if(z(t))this._thetaVelocity.value=0,this._spherical.theta=this._sphericalEnd.theta;else{const p=this._isUserControllingRotate?this.draggingSmoothTime:this.smoothTime;this._spherical.theta=je(this._spherical.theta,this._sphericalEnd.theta,this._thetaVelocity,p,1/0,e),this._needsUpdate=!0}if(z(s))this._phiVelocity.value=0,this._spherical.phi=this._sphericalEnd.phi;else{const p=this._isUserControllingRotate?this.draggingSmoothTime:this.smoothTime;this._spherical.phi=je(this._spherical.phi,this._sphericalEnd.phi,this._phiVelocity,p,1/0,e),this._needsUpdate=!0}if(z(n))this._radiusVelocity.value=0,this._spherical.radius=this._sphericalEnd.radius;else{const p=this._isUserControllingDolly?this.draggingSmoothTime:this.smoothTime;this._spherical.radius=je(this._spherical.radius,this._sphericalEnd.radius,this._radiusVelocity,p,this.maxSpeed,e),this._needsUpdate=!0}if(z(a.x)&&z(a.y)&&z(a.z))this._targetVelocity.set(0,0,0),this._target.copy(this._targetEnd);else{const p=this._isUserControllingTruck?this.draggingSmoothTime:this.smoothTime;Ft(this._target,this._targetEnd,this._targetVelocity,p,this.maxSpeed,e,this._target),this._needsUpdate=!0}if(z(r.x)&&z(r.y)&&z(r.z))this._focalOffsetVelocity.set(0,0,0),this._focalOffset.copy(this._focalOffsetEnd);else{const p=this._isUserControllingOffset?this.draggingSmoothTime:this.smoothTime;Ft(this._focalOffset,this._focalOffsetEnd,this._focalOffsetVelocity,p,this.maxSpeed,e,this._focalOffset),this._needsUpdate=!0}if(z(o))this._zoomVelocity.value=0,this._zoom=this._zoomEnd;else{const p=this._isUserControllingZoom?this.draggingSmoothTime:this.smoothTime;this._zoom=je(this._zoom,this._zoomEnd,this._zoomVelocity,p,1/0,e)}if(this.dollyToCursor){if(pe(this._camera)&&this._changedDolly!==0){const p=this._spherical.radius-this._lastDistance,m=this._camera,g=this._getCameraDirection(Ie),y=D.copy(g).cross(m.up).normalize();y.lengthSq()===0&&(y.x=1);const _=N.crossVectors(y,g),E=this._sphericalEnd.radius*Math.tan(m.getEffectiveFOV()*Re*.5),C=(this._sphericalEnd.radius-p-this._sphericalEnd.radius)/this._sphericalEnd.radius,x=xe.copy(this._targetEnd).add(y.multiplyScalar(this._dollyControlCoord.x*E*m.aspect)).add(_.multiplyScalar(this._dollyControlCoord.y*E)),O=D.copy(this._targetEnd).lerp(x,C),S=this._lastDollyDirection===Ee.IN&&this._spherical.radius<=this.minDistance,w=this._lastDollyDirection===Ee.OUT&&this.maxDistance<=this._spherical.radius;if(this.infinityDolly&&(S||w)){this._sphericalEnd.radius-=p,this._spherical.radius-=p;const L=N.copy(g).multiplyScalar(-p);O.add(L)}this._boundary.clampPoint(O,O);const M=N.subVectors(O,this._targetEnd);this._targetEnd.copy(O),this._target.add(M),this._changedDolly-=p,z(this._changedDolly)&&(this._changedDolly=0)}else if(ce(this._camera)&&this._changedZoom!==0){const p=this._zoom-this._lastZoom,m=this._camera,g=D.set(this._dollyControlCoord.x,this._dollyControlCoord.y,(m.near+m.far)/(m.near-m.far)).unproject(m),y=N.set(0,0,-1).applyQuaternion(m.quaternion),_=xe.copy(g).add(y.multiplyScalar(-g.dot(m.up))),v=-(this._zoom-p-this._zoom)/this._zoom,C=this._getCameraDirection(Ie),x=this._targetEnd.dot(C),O=D.copy(this._targetEnd).lerp(_,v),S=O.dot(C),w=C.multiplyScalar(S-x);O.sub(w),this._boundary.clampPoint(O,O);const M=N.subVectors(O,this._targetEnd);this._targetEnd.copy(O),this._target.add(M),this._changedZoom-=p,z(this._changedZoom)&&(this._changedZoom=0)}}this._camera.zoom!==this._zoom&&(this._camera.zoom=this._zoom,this._camera.updateProjectionMatrix(),this._updateNearPlaneCorners(),this._needsUpdate=!0),this._dragNeedsUpdate=!0;const c=this._collisionTest();this._spherical.radius=Math.min(this._spherical.radius,c),this._spherical.makeSafe(),this._camera.position.setFromSpherical(this._spherical).applyQuaternion(this._yAxisUpSpaceInverse).add(this._target),this._camera.lookAt(this._target),(!z(this._focalOffset.x)||!z(this._focalOffset.y)||!z(this._focalOffset.z))&&(ee.setFromMatrixColumn(this._camera.matrix,0),te.setFromMatrixColumn(this._camera.matrix,1),me.setFromMatrixColumn(this._camera.matrix,2),ee.multiplyScalar(this._focalOffset.x),te.multiplyScalar(-this._focalOffset.y),me.multiplyScalar(this._focalOffset.z),D.copy(ee).add(te).add(me),this._camera.position.add(D),this._camera.updateMatrixWorld()),this._boundaryEnclosesCamera&&this._encloseToBoundary(this._camera.position.copy(this._target),D.setFromSpherical(this._spherical).applyQuaternion(this._yAxisUpSpaceInverse),1);const h=this._needsUpdate;return h&&!this._updatedLastTime?(this._hasRested=!1,this.dispatchEvent({type:"wake"}),this.dispatchEvent({type:"update"})):h?(this.dispatchEvent({type:"update"}),z(t,this.restThreshold)&&z(s,this.restThreshold)&&z(n,this.restThreshold)&&z(a.x,this.restThreshold)&&z(a.y,this.restThreshold)&&z(a.z,this.restThreshold)&&z(r.x,this.restThreshold)&&z(r.y,this.restThreshold)&&z(r.z,this.restThreshold)&&z(o,this.restThreshold)&&!this._hasRested&&(this._hasRested=!0,this.dispatchEvent({type:"rest"}))):!h&&this._updatedLastTime&&this.dispatchEvent({type:"sleep"}),this._lastDistance=this._spherical.radius,this._lastZoom=this._zoom,this._updatedLastTime=h,this._needsUpdate=!1,h}toJSON(){return JSON.stringify({enabled:this._enabled,minDistance:this.minDistance,maxDistance:De(this.maxDistance),minZoom:this.minZoom,maxZoom:De(this.maxZoom),minPolarAngle:this.minPolarAngle,maxPolarAngle:De(this.maxPolarAngle),minAzimuthAngle:De(this.minAzimuthAngle),maxAzimuthAngle:De(this.maxAzimuthAngle),smoothTime:this.smoothTime,draggingSmoothTime:this.draggingSmoothTime,dollySpeed:this.dollySpeed,truckSpeed:this.truckSpeed,dollyToCursor:this.dollyToCursor,target:this._targetEnd.toArray(),position:D.setFromSpherical(this._sphericalEnd).add(this._targetEnd).toArray(),zoom:this._zoomEnd,focalOffset:this._focalOffsetEnd.toArray(),target0:this._target0.toArray(),position0:this._position0.toArray(),zoom0:this._zoom0,focalOffset0:this._focalOffset0.toArray()})}fromJSON(e,t=!1){const s=JSON.parse(e);this.enabled=s.enabled,this.minDistance=s.minDistance,this.maxDistance=Pe(s.maxDistance),this.minZoom=s.minZoom,this.maxZoom=Pe(s.maxZoom),this.minPolarAngle=s.minPolarAngle,this.maxPolarAngle=Pe(s.maxPolarAngle),this.minAzimuthAngle=Pe(s.minAzimuthAngle),this.maxAzimuthAngle=Pe(s.maxAzimuthAngle),this.smoothTime=s.smoothTime,this.draggingSmoothTime=s.draggingSmoothTime,this.dollySpeed=s.dollySpeed,this.truckSpeed=s.truckSpeed,this.dollyToCursor=s.dollyToCursor,this._target0.fromArray(s.target0),this._position0.fromArray(s.position0),this._zoom0=s.zoom0,this._focalOffset0.fromArray(s.focalOffset0),this.moveTo(s.target[0],s.target[1],s.target[2],t),$.setFromVector3(D.fromArray(s.position).sub(this._targetEnd).applyQuaternion(this._yAxisUpSpace)),this.rotateTo($.theta,$.phi,t),this.dollyTo($.radius,t),this.zoomTo(s.zoom,t),this.setFocalOffset(s.focalOffset[0],s.focalOffset[1],s.focalOffset[2],t),this._needsUpdate=!0}connect(e){if(this._domElement){console.warn("camera-controls is already connected.");return}e.setAttribute("data-camera-controls-version",mn),this._addAllEventListeners(e),this._getClientRect(this._elementRect)}disconnect(){this.cancel(),this._removeAllEventListeners(),this._domElement&&(this._domElement.removeAttribute("data-camera-controls-version"),this._domElement=void 0)}dispose(){this.removeAllEventListeners(),this.disconnect()}_getTargetDirection(e){return e.setFromSpherical(this._spherical).divideScalar(this._spherical.radius).applyQuaternion(this._yAxisUpSpaceInverse)}_getCameraDirection(e){return this._getTargetDirection(e).negate()}_findPointerById(e){return this._activePointers.find(t=>t.pointerId===e)}_findPointerByMouseButton(e){return this._activePointers.find(t=>t.mouseButton===e)}_disposePointer(e){this._activePointers.splice(this._activePointers.indexOf(e),1)}_encloseToBoundary(e,t,s){const n=t.lengthSq();if(n===0)return e;const a=N.copy(t).add(e),o=this._boundary.clampPoint(a,xe).sub(a),c=o.lengthSq();if(c===0)return e.add(t);if(c===n)return e;if(s===0)return e.add(t).add(o);{const l=1+s*c/t.dot(o);return e.add(N.copy(t).multiplyScalar(l)).add(o.multiplyScalar(1-s))}}_updateNearPlaneCorners(){if(pe(this._camera)){const e=this._camera,t=e.near,s=e.getEffectiveFOV()*Re,n=Math.tan(s*.5)*t,a=n*e.aspect;this._nearPlaneCorners[0].set(-a,-n,0),this._nearPlaneCorners[1].set(a,-n,0),this._nearPlaneCorners[2].set(a,n,0),this._nearPlaneCorners[3].set(-a,n,0)}else if(ce(this._camera)){const e=this._camera,t=1/e.zoom,s=e.left*t,n=e.right*t,a=e.top*t,r=e.bottom*t;this._nearPlaneCorners[0].set(s,a,0),this._nearPlaneCorners[1].set(n,a,0),this._nearPlaneCorners[2].set(n,r,0),this._nearPlaneCorners[3].set(s,r,0)}}_collisionTest(){let e=1/0;if(!(this.colliderMeshes.length>=1)||ot(this._camera,"_collisionTest"))return e;const s=this._getTargetDirection(Ie);ut.lookAt(zt,s,this._camera.up);for(let n=0;n<4;n++){const a=N.copy(this._nearPlaneCorners[n]);a.applyMatrix4(ut);const r=xe.addVectors(this._target,a);Ge.set(r,s),Ge.far=this._spherical.radius+1;const o=Ge.intersectObjects(this.colliderMeshes);o.length!==0&&o[0].distance<e&&(e=o[0].distance)}return e}_getClientRect(e){if(!this._domElement)return;const t=this._domElement.getBoundingClientRect();return e.x=t.left,e.y=t.top,this._viewport?(e.x+=this._viewport.x,e.y+=t.height-this._viewport.w-this._viewport.y,e.width=this._viewport.z,e.height=this._viewport.w):(e.width=t.width,e.height=t.height),e}_createOnRestPromise(e){return e?Promise.resolve():(this._hasRested=!1,this.dispatchEvent({type:"transitionstart"}),new Promise(t=>{const s=()=>{this.removeEventListener("rest",s),t()};this.addEventListener("rest",s)}))}_addAllEventListeners(e){}_removeAllEventListeners(){}get dampingFactor(){return console.warn(".dampingFactor has been deprecated. use smoothTime (in seconds) instead."),0}set dampingFactor(e){console.warn(".dampingFactor has been deprecated. use smoothTime (in seconds) instead.")}get draggingDampingFactor(){return console.warn(".draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead."),0}set draggingDampingFactor(e){console.warn(".draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead.")}static createBoundingSphere(e,t=new R.Sphere){const s=t,n=s.center;Oe.makeEmpty(),e.traverseVisible(r=>{r.isMesh&&Oe.expandByObject(r)}),Oe.getCenter(n);let a=0;return e.traverseVisible(r=>{if(!r.isMesh)return;const o=r;if(!o.geometry)return;const c=o.geometry.clone();c.applyMatrix4(o.matrixWorld);const h=c.attributes.position;for(let p=0,m=h.count;p<m;p++)D.fromBufferAttribute(h,p),a=Math.max(a,n.distanceToSquared(D))}),s.radius=Math.sqrt(a),s}}const Ke=i=>{const[e,t]=b.useState(i.options[i.index]),s=()=>{i.onToggle(!i.open)},n=r=>{r!==e&&(i.onSelect(r),t(r)),i.onToggle(!1)},a=i.open?`${i.options.length*31-1}px`:"0px";return u.jsxs("div",{className:`dropdown ${i.up===!0?"up":""}`,children:[u.jsx("div",{className:"dropdown-toggle",onClick:s,children:`${i.title}: ${e}`}),u.jsx("ul",{className:"dropdown-menu",style:{height:a},children:i.options.map(r=>u.jsx("li",{onClick:()=>n(r),children:r},r))})]})},fe=b.forwardRef(function(e,t){const s=["Renderer","Depth","Normals","UVs","Wireframe"],[n,a]=b.useState("Renderer"),[r,o]=b.useState(!1),[c,l]=b.useState(!1),[h,p]=b.useState(!1);return u.jsxs("div",{className:`CameraWindow ${e.name}`,children:[u.jsx("div",{ref:t,className:"clickable",onClick:()=>{h&&p(!1)}}),u.jsxs("div",{className:"options",children:[e.camera!==null&&u.jsx(Ke,{title:"Camera",index:e.options.indexOf(e.camera.name),open:h,options:e.options,onSelect:e.onSelectCamera,onToggle:m=>{m&&c&&l(!1),p(m)},up:!0}),u.jsx(Ke,{title:"Mode",index:s.indexOf(n),open:c,options:s,onSelect:m=>{if(m===n)return;const g=m;e.onSelectRenderMode(g),a(g)},onToggle:m=>{m&&h&&p(!1),r&&o(!1),l(m)},up:!0})]})]})}),gn=`out vec3 worldPosition;
464
27
  uniform float uDistance;
465
28
 
466
29
  void main() {
@@ -469,7 +32,7 @@ void main() {
469
32
  worldPosition.xz += cameraPosition.xz;
470
33
 
471
34
  gl_Position = projectionMatrix * modelViewMatrix * vec4(worldPosition, 1.0);
472
- }`,xI=`out vec4 fragColor;
35
+ }`,vn=`out vec4 fragColor;
473
36
  in vec3 worldPosition;
474
37
  uniform float uDivisions;
475
38
  uniform float uScale;
@@ -537,11 +100,7 @@ void main() {
537
100
  fragColor.a = mix(fragColor.a, baseOpacity * uGridOpacity, nextGrid);
538
101
 
539
102
  if (fragColor.a <= minAlpha) discard;
540
- }`;class $S extends _.ShaderMaterial{constructor(e){super({extensions:{derivatives:!0},uniforms:{uScale:{value:e?.scale!==void 0?e?.scale:.1},uDivisions:{value:e?.divisions!==void 0?e?.divisions:10},uColor:{value:e?.color!==void 0?e?.color:new _.Color(16777215)},uDistance:{value:e?.distance!==void 0?e?.distance:1e4},uSubgridOpacity:{value:e?.subgridOpacity!==void 0?e?.subgridOpacity:.15},uGridOpacity:{value:e?.gridOpacity!==void 0?e?.gridOpacity:.25}},glslVersion:_.GLSL3,side:_.DoubleSide,transparent:!0,name:"InfiniteGrid",vertexShader:yI,fragmentShader:xI})}get color(){return this.uniforms.uColor.value}set color(e){this.uniforms.uColor.value=e}get gridOpacity(){return this.uniforms.uGridOpacity.value}set gridOpacity(e){this.uniforms.uGridOpacity.value=e}get subgridOpacity(){return this.uniforms.uSubgridOpacity.value}set subgridOpacity(e){this.uniforms.uSubgridOpacity.value=e}}class WS extends _.Mesh{gridMaterial;constructor(e){const t=new $S(e);super(new _.PlaneGeometry,t),this.gridMaterial=t,this.frustumCulled=!1,this.name="InfiniteGridHelper"}get color(){return this.gridMaterial.color}set color(e){this.gridMaterial.color=e}get gridOpacity(){return this.gridMaterial.gridOpacity}set gridOpacity(e){this.gridMaterial.gridOpacity=e}get subgridOpacity(){return this.gridMaterial.subgridOpacity}set subgridOpacity(e){this.gridMaterial.subgridOpacity=e}}/**
541
- * @license
542
- * Copyright 2010-2026 Three.js Authors
543
- * SPDX-License-Identifier: MIT
544
- */g.BRDF_GGX;g.BRDF_Lambert;g.BasicPointShadowFilter;g.BasicShadowFilter;g.Break;g.Const;g.Continue;g.DFGLUT;g.D_GGX;const _I=g.Discard;g.EPSILON;g.F_Schlick;const Vd=g.Fn;g.INFINITY;const bI=g.If;g.Loop;g.NodeAccess;g.NodeShaderStage;g.NodeType;g.NodeUpdateType;g.PCFShadowFilter;g.PCFSoftShadowFilter;g.PI;g.PI2;g.TWO_PI;g.HALF_PI;g.PointShadowFilter;g.Return;g.Schlick_to_F0;g.ShaderNode;g.Stack;g.Switch;g.TBNViewMatrix;g.VSMShadowFilter;g.V_GGX_SmithCorrelated;g.Var;g.VarIntent;const Hy=g.abs;g.acesFilmicToneMapping;g.acos;g.add;g.addMethodChaining;g.addNodeElement;g.agxToneMapping;g.all;g.alphaT;g.and;g.anisotropy;g.anisotropyB;g.anisotropyT;g.any;g.append;g.array;g.arrayBuffer;g.asin;g.assign;g.atan;g.atomicAdd;g.atomicAnd;g.atomicFunc;g.atomicLoad;g.atomicMax;g.atomicMin;g.atomicOr;g.atomicStore;g.atomicSub;g.atomicXor;g.attenuationColor;g.attenuationDistance;g.attribute;g.attributeArray;g.backgroundBlurriness;g.backgroundIntensity;g.backgroundRotation;g.batch;g.bentNormalView;g.billboarding;g.bitAnd;g.bitNot;g.bitOr;g.bitXor;g.bitangentGeometry;g.bitangentLocal;g.bitangentView;g.bitangentWorld;g.bitcast;g.blendBurn;g.blendColor;g.blendDodge;g.blendOverlay;g.blendScreen;g.blur;g.bool;g.buffer;g.bufferAttribute;g.bumpMap;g.builtin;g.builtinAOContext;g.builtinShadowContext;g.bvec2;g.bvec3;g.bvec4;g.bypass;g.cache;g.call;g.cameraFar;g.cameraIndex;g.cameraNear;g.cameraNormalMatrix;const hc=g.cameraPosition;g.cameraProjectionMatrix;g.cameraProjectionMatrixInverse;g.cameraViewMatrix;g.cameraViewport;g.cameraWorldMatrix;g.cbrt;g.cdl;g.ceil;g.checker;g.cineonToneMapping;g.clamp;g.clearcoat;g.clearcoatNormalView;g.clearcoatRoughness;g.clipSpace;g.code;g.color;g.colorSpaceToWorking;g.colorToDirection;g.compute;g.computeKernel;g.computeSkinning;g.context;g.convert;g.convertColorSpace;g.convertToTexture;g.countLeadingZeros;g.countOneBits;g.countTrailingZeros;g.cos;g.cross;g.cubeTexture;g.cubeTextureBase;g.dFdx;g.dFdy;g.dashSize;g.debug;g.decrement;g.decrementBefore;g.defaultBuildStages;g.defaultShaderStages;g.defined;g.degrees;g.deltaTime;g.densityFog;g.densityFogFactor;g.depth;g.depthPass;g.determinant;g.difference;g.diffuseColor;g.directPointLight;g.directionToColor;g.directionToFaceDirection;g.dispersion;const TI=g.distance;g.div;g.dot;g.drawIndex;g.dynamicBufferAttribute;g.element;g.emissive;g.equal;g.equirectUV;g.exp;g.exp2;g.exponentialHeightFogFactor;g.expression;g.faceDirection;g.faceForward;g.faceforward;const Jt=g.float;g.floatBitsToInt;g.floatBitsToUint;const SI=g.floor;g.fog;const vI=g.fract;g.frameGroup;g.frameId;g.frontFacing;const MI=g.fwidth;g.gain;g.gapSize;g.getConstNodeType;g.getCurrentStack;g.getDirection;g.getDistanceAttenuation;g.getGeometryRoughness;g.getNormalFromDepth;g.interleavedGradientNoise;g.vogelDiskSample;g.getParallaxCorrectNormal;g.getRoughness;g.getScreenPosition;g.getShIrradianceAt;g.getShadowMaterial;g.getShadowRenderObjectFunction;g.getTextureIndex;g.getViewPosition;g.globalId;g.glsl;g.glslFn;g.grayscale;g.greaterThan;g.greaterThanEqual;g.hash;g.highpModelNormalViewMatrix;g.highpModelViewMatrix;g.hue;g.increment;g.incrementBefore;g.instance;g.instanceIndex;g.instancedArray;g.instancedBufferAttribute;g.instancedDynamicBufferAttribute;g.instancedMesh;g.int;g.intBitsToFloat;g.inverse;g.inverseSqrt;g.inversesqrt;g.invocationLocalIndex;g.invocationSubgroupIndex;g.ior;g.iridescence;g.iridescenceIOR;g.iridescenceThickness;g.ivec2;g.ivec3;g.ivec4;g.js;g.label;g.length;g.lengthSq;g.lessThan;const wI=g.lessThanEqual;g.lightPosition;g.lightProjectionUV;g.lightShadowMatrix;g.lightTargetDirection;g.lightTargetPosition;g.lightViewPosition;g.lightingContext;g.lights;const CI=g.linearDepth;g.linearToneMapping;g.localId;const jy=g.log;g.log2;g.logarithmicDepthToViewZ;g.luminance;g.mat2;g.mat3;g.mat4;g.matcapUV;g.materialAO;g.materialAlphaTest;g.materialAnisotropy;g.materialAnisotropyVector;g.materialAttenuationColor;g.materialAttenuationDistance;g.materialClearcoat;g.materialClearcoatNormal;g.materialClearcoatRoughness;g.materialColor;g.materialDispersion;g.materialEmissive;g.materialEnvIntensity;g.materialEnvRotation;g.materialIOR;g.materialIridescence;g.materialIridescenceIOR;g.materialIridescenceThickness;g.materialLightMap;g.materialLineDashOffset;g.materialLineDashSize;g.materialLineGapSize;g.materialLineScale;g.materialLineWidth;g.materialMetalness;g.materialNormal;g.materialOpacity;g.materialPointSize;g.materialReference;g.materialReflectivity;g.materialRefractionRatio;g.materialRotation;g.materialRoughness;g.materialSheen;g.materialSheenRoughness;g.materialShininess;g.materialSpecular;g.materialSpecularColor;g.materialSpecularIntensity;g.materialSpecularStrength;g.materialThickness;g.materialTransmission;const qy=g.max;g.maxMipLevel;g.mediumpModelViewMatrix;g.metalness;const kd=g.min,Xy=g.mix;g.mixElement;g.mod;g.modInt;g.modelDirection;g.modelNormalMatrix;g.modelPosition;g.modelRadius;g.modelScale;g.modelViewMatrix;g.modelViewPosition;g.modelViewProjection;g.modelWorldMatrix;g.modelWorldMatrixInverse;g.morphReference;g.mrt;g.mul;g.mx_aastep;g.mx_add;g.mx_atan2;g.mx_cell_noise_float;g.mx_contrast;g.mx_divide;g.mx_fractal_noise_float;g.mx_fractal_noise_vec2;g.mx_fractal_noise_vec3;g.mx_fractal_noise_vec4;g.mx_frame;g.mx_heighttonormal;g.mx_hsvtorgb;g.mx_ifequal;g.mx_ifgreater;g.mx_ifgreatereq;g.mx_invert;g.mx_modulo;g.mx_multiply;g.mx_noise_float;g.mx_noise_vec3;g.mx_noise_vec4;g.mx_place2d;g.mx_power;g.mx_ramp4;g.mx_ramplr;g.mx_ramptb;g.mx_rgbtohsv;g.mx_rotate2d;g.mx_rotate3d;g.mx_safepower;g.mx_separate;g.mx_splitlr;g.mx_splittb;g.mx_srgb_texture_to_lin_rec709;g.mx_subtract;g.mx_timer;g.mx_transform_uv;g.mx_unifiednoise2d;g.mx_unifiednoise3d;g.mx_worley_noise_float;g.mx_worley_noise_vec2;g.mx_worley_noise_vec3;g.negate;g.neutralToneMapping;g.nodeArray;g.nodeImmutable;g.nodeObject;g.nodeObjectIntent;g.nodeObjects;g.nodeProxy;g.nodeProxyIntent;g.normalFlat;g.normalGeometry;g.normalLocal;g.normalMap;g.normalView;g.normalViewGeometry;g.normalWorld;g.normalWorldGeometry;g.normalize;g.not;g.notEqual;g.numWorkgroups;g.objectDirection;g.objectGroup;g.objectPosition;g.objectRadius;g.objectScale;g.objectViewPosition;g.objectWorldMatrix;g.OnBeforeObjectUpdate;g.OnBeforeMaterialUpdate;g.OnObjectUpdate;g.OnMaterialUpdate;g.oneMinus;g.or;g.orthographicDepthToViewZ;g.oscSawtooth;g.oscSine;g.oscSquare;g.oscTriangle;g.output;g.outputStruct;g.overloadingFn;g.packHalf2x16;g.packSnorm2x16;g.packUnorm2x16;g.parabola;g.parallaxDirection;g.parallaxUV;g.parameter;g.pass;g.passTexture;g.pcurve;g.perspectiveDepthToViewZ;g.pmremTexture;g.pointShadow;g.pointUV;g.pointWidth;g.positionGeometry;const AI=g.positionLocal;g.positionPrevious;g.positionView;g.positionViewDirection;g.positionWorld;g.positionWorldDirection;g.posterize;const Yy=g.pow;g.pow2;g.pow3;g.pow4;g.premultiplyAlpha;g.property;g.radians;g.rand;g.range;g.rangeFog;g.rangeFogFactor;g.reciprocal;g.reference;g.referenceBuffer;g.reflect;g.reflectVector;g.reflectView;g.reflector;g.refract;g.refractVector;g.refractView;g.reinhardToneMapping;g.remap;const EI=g.remapClamp;g.renderGroup;g.renderOutput;g.rendererReference;g.replaceDefaultUV;g.rotate;g.rotateUV;g.roughness;g.round;g.rtt;g.sRGBTransferEOTF;g.sRGBTransferOETF;g.sample;g.sampler;g.samplerComparison;g.saturate;g.saturation;g.screen;g.screenCoordinate;g.screenDPR;g.screenSize;g.screenUV;g.select;g.setCurrentStack;g.setName;g.shaderStages;g.shadow;g.shadowPositionWorld;g.shapeCircle;g.sharedUniformGroup;g.sheen;g.sheenRoughness;g.shiftLeft;g.shiftRight;g.shininess;g.sign;g.sin;g.sinc;g.skinning;g.smoothstep;g.smoothstepElement;g.specularColor;g.specularF90;g.spherizeUV;g.split;g.spritesheetUV;g.sqrt;g.stack;g.step;g.stepElement;g.storage;g.storageBarrier;g.storageTexture;g.string;g.struct;g.sub;g.subgroupAdd;g.subgroupAll;g.subgroupAnd;g.subgroupAny;g.subgroupBallot;g.subgroupBroadcast;g.subgroupBroadcastFirst;g.subBuild;g.subgroupElect;g.subgroupExclusiveAdd;g.subgroupExclusiveMul;g.subgroupInclusiveAdd;g.subgroupInclusiveMul;g.subgroupIndex;g.subgroupMax;g.subgroupMin;g.subgroupMul;g.subgroupOr;g.subgroupShuffle;g.subgroupShuffleDown;g.subgroupShuffleUp;g.subgroupShuffleXor;g.subgroupSize;g.subgroupXor;g.tan;g.tangentGeometry;g.tangentLocal;g.tangentView;g.tangentWorld;g.texture;g.texture3D;g.textureBarrier;g.textureBicubic;g.textureBicubicLevel;g.textureCubeUV;g.textureLoad;g.textureSize;g.textureLevel;g.textureStore;g.thickness;g.time;g.toneMapping;g.toneMappingExposure;g.toonOutlinePass;g.transformDirection;g.transformNormal;g.transformNormalToView;g.transformedClearcoatNormalView;g.transformedNormalView;g.transformedNormalWorld;g.transmission;g.transpose;g.triNoise3D;g.triplanarTexture;g.triplanarTextures;g.trunc;g.uint;g.uintBitsToFloat;const aa=g.uniform;g.uniformArray;g.uniformCubeTexture;g.uniformGroup;g.uniformFlow;g.uniformTexture;g.unpackHalf2x16;g.unpackSnorm2x16;g.unpackUnorm2x16;g.unpremultiplyAlpha;g.userData;const NI=g.uv;g.uvec2;g.uvec3;g.uvec4;g.varying;const RI=g.varyingProperty;g.vec2;const PI=g.vec3,Om=g.vec4;g.vectorComponents;g.velocity;g.vertexColor;g.vertexIndex;g.vertexStage;g.vibrance;g.viewZToLogarithmicDepth;g.viewZToOrthographicDepth;g.viewZToPerspectiveDepth;g.viewZToReversedOrthographicDepth;g.viewZToReversedPerspectiveDepth;g.viewport;g.viewportCoordinate;g.viewportDepthTexture;g.viewportLinearDepth;g.viewportMipTexture;g.viewportOpaqueMipTexture;g.viewportResolution;g.viewportSafeUV;g.viewportSharedTexture;g.viewportSize;g.viewportTexture;g.viewportUV;g.wgsl;g.wgslFn;g.workgroupArray;g.workgroupBarrier;g.workgroupId;g.workingToColorSpace;g.xor;class HS extends st{uScale;uDivisions;uColor;uDistance;uSubgridOpacity;uGridOpacity;constructor(e){super(),this.name="InfiniteGrid",this.side=_.DoubleSide,this.transparent=!0,this.uScale=aa(e?.scale??.1),this.uDivisions=aa(e?.divisions??10),this.uColor=aa(e?.color??new _.Color(16777215)),this.uDistance=aa(e?.distance??1e4),this.uSubgridOpacity=aa(e?.subgridOpacity??.15),this.uGridOpacity=aa(e?.gridOpacity??.25);const{uScale:t,uDivisions:s,uColor:i,uDistance:n,uSubgridOpacity:a,uGridOpacity:o}=this,l=RI("vec3","vWorldPosition");this.positionNode=Vd(()=>{const u=AI.xzy.mul(n).add(PI(hc.x,Jt(0),hc.z));return l.assign(u),u})();const c=Vd(([u])=>{const h=l.xz.div(u),d=MI(h),p=Hy(vI(h.sub(.5)).sub(.5)).div(d).div(2),f=kd(p.x,p.y);return Jt(1).sub(kd(f,Jt(1)))});this.outputNode=Vd(()=>{const u=l,h=qy(Jt(200),Hy(hc.y.sub(u.y))),d=Jt(TI(hc,u)),p=jy(h).div(jy(s)),f=Yy(s,SI(p)),m=f.mul(s),x=m.mul(s),y=c(f.mul(t)),b=c(m.mul(t)),v=c(x.mul(t)),S=h.sub(f).div(m.sub(f)),M=Jt(.3),A=qy(S.sub(Jt(1)).add(M),Jt(0)).div(M),C=y.mul(Yy(Jt(1).sub(kd(d.div(n),Jt(1))),Jt(3))),P=Jt(.5),B=C.sub(A).mul(a),V=Xy(B,C.mul(o).sub(A.mul(o.sub(a)).mul(P)),b),Y=Jt(Xy(V,C.mul(o),v));return bI(wI(Y,Jt(1/127)),()=>{_I()}),Om(i,Y)})()}get color(){return this.uColor.value}set color(e){this.uColor.value=e}get gridOpacity(){return this.uGridOpacity.value}set gridOpacity(e){this.uGridOpacity.value=e}get subgridOpacity(){return this.uSubgridOpacity.value}set subgridOpacity(e){this.uSubgridOpacity.value=e}}class jS extends _.Mesh{gridMaterial;constructor(e){const t=new HS(e);super(new _.PlaneGeometry,t),this.gridMaterial=t,this.frustumCulled=!1,this.name="InfiniteGridHelper"}get color(){return this.gridMaterial.color}set color(e){this.gridMaterial.color=e}get gridOpacity(){return this.gridMaterial.gridOpacity}set gridOpacity(e){this.gridMaterial.gridOpacity=e}get subgridOpacity(){return this.gridMaterial.subgridOpacity}set subgridOpacity(e){this.gridMaterial.subgridOpacity=e}}function zd(r){const[e,t]=X.useState(r.selected),s="toggle"+(e?" selected":"");return F.jsx("button",{className:s,onClick:()=>{const i=!e;t(i),r.onClick(i)},style:{backgroundImage:`url(${r.icon})`,backgroundPositionX:"center",backgroundPositionY:r.top!==void 0?`${r.top}px`:"center",backgroundSize:`${r.width!==void 0?`${r.width}px`:"26px"} ${r.height}px`}},r.name)}class qS extends um{constructor(){super();const e=EI(CI(),.1,.5,0,1).oneMinus();this.colorNode=Om(e,e,e,1)}}const FI=`#include <common>
103
+ }`;class di extends d.ShaderMaterial{constructor(e){super({extensions:{derivatives:!0},uniforms:{uScale:{value:e?.scale!==void 0?e?.scale:.1},uDivisions:{value:e?.divisions!==void 0?e?.divisions:10},uColor:{value:e?.color!==void 0?e?.color:new d.Color(16777215)},uDistance:{value:e?.distance!==void 0?e?.distance:1e4},uSubgridOpacity:{value:e?.subgridOpacity!==void 0?e?.subgridOpacity:.15},uGridOpacity:{value:e?.gridOpacity!==void 0?e?.gridOpacity:.25}},glslVersion:d.GLSL3,side:d.DoubleSide,transparent:!0,name:"InfiniteGrid",vertexShader:gn,fragmentShader:vn})}get color(){return this.uniforms.uColor.value}set color(e){this.uniforms.uColor.value=e}get gridOpacity(){return this.uniforms.uGridOpacity.value}set gridOpacity(e){this.uniforms.uGridOpacity.value=e}get subgridOpacity(){return this.uniforms.uSubgridOpacity.value}set subgridOpacity(e){this.uniforms.uSubgridOpacity.value=e}}class ui extends d.Mesh{gridMaterial;constructor(e){const t=new di(e);super(new d.PlaneGeometry,t),this.gridMaterial=t,this.frustumCulled=!1,this.name="InfiniteGridHelper"}get color(){return this.gridMaterial.color}set color(e){this.gridMaterial.color=e}get gridOpacity(){return this.gridMaterial.gridOpacity}set gridOpacity(e){this.gridMaterial.gridOpacity=e}get subgridOpacity(){return this.gridMaterial.subgridOpacity}set subgridOpacity(e){this.gridMaterial.subgridOpacity=e}}class pi extends Fi{uScale;uDivisions;uColor;uDistance;uSubgridOpacity;uGridOpacity;constructor(e){super(),this.name="InfiniteGrid",this.side=d.DoubleSide,this.transparent=!0,this.uScale=T.uniform(e?.scale??.1),this.uDivisions=T.uniform(e?.divisions??10),this.uColor=T.uniform(e?.color??new d.Color(16777215)),this.uDistance=T.uniform(e?.distance??1e4),this.uSubgridOpacity=T.uniform(e?.subgridOpacity??.15),this.uGridOpacity=T.uniform(e?.gridOpacity??.25);const{uScale:t,uDivisions:s,uColor:n,uDistance:a,uSubgridOpacity:r,uGridOpacity:o}=this,c=T.varyingProperty("vec3","vWorldPosition");this.positionNode=T.Fn(()=>{const h=T.positionLocal.xzy.mul(a).add(T.vec3(T.cameraPosition.x,T.float(0),T.cameraPosition.z));return c.assign(h),h})();const l=T.Fn(([h])=>{const p=c.xz.div(h),m=T.fwidth(p),g=T.abs(T.fract(p.sub(.5)).sub(.5)).div(m).div(2),y=T.min(g.x,g.y);return T.float(1).sub(T.min(y,T.float(1)))});this.outputNode=T.Fn(()=>{const h=c,p=T.max(T.float(200),T.abs(T.cameraPosition.y.sub(h.y))),m=T.float(T.distance(T.cameraPosition,h)),g=T.log(p).div(T.log(s)),y=T.pow(s,T.floor(g)),_=y.mul(s),E=_.mul(s),v=l(y.mul(t)),C=l(_.mul(t)),x=l(E.mul(t)),O=p.sub(y).div(_.sub(y)),S=T.float(.3),w=T.max(O.sub(T.float(1)).add(S),T.float(0)).div(S),M=v.mul(T.pow(T.float(1).sub(T.min(m.div(a),T.float(1))),T.float(3))),L=T.float(.5),A=M.sub(w).mul(r),F=T.mix(A,M.mul(o).sub(w.mul(o.sub(r)).mul(L)),C),Q=T.float(T.mix(F,M.mul(o),x));return T.If(T.lessThanEqual(Q,T.float(1/127)),()=>{T.Discard()}),T.vec4(n,Q)})()}get color(){return this.uColor.value}set color(e){this.uColor.value=e}get gridOpacity(){return this.uGridOpacity.value}set gridOpacity(e){this.uGridOpacity.value=e}get subgridOpacity(){return this.uSubgridOpacity.value}set subgridOpacity(e){this.uSubgridOpacity.value=e}}class mi extends d.Mesh{gridMaterial;constructor(e){const t=new pi(e);super(new d.PlaneGeometry,t),this.gridMaterial=t,this.frustumCulled=!1,this.name="InfiniteGridHelper"}get color(){return this.gridMaterial.color}set color(e){this.gridMaterial.color=e}get gridOpacity(){return this.gridMaterial.gridOpacity}set gridOpacity(e){this.gridMaterial.gridOpacity=e}get subgridOpacity(){return this.gridMaterial.subgridOpacity}set subgridOpacity(e){this.gridMaterial.subgridOpacity=e}}function pt(i){const[e,t]=b.useState(i.selected),s="toggle"+(e?" selected":"");return u.jsx("button",{className:s,onClick:()=>{const n=!e;t(n),i.onClick(n)},style:{backgroundImage:`url(${i.icon})`,backgroundPositionX:"center",backgroundPositionY:i.top!==void 0?`${i.top}px`:"center",backgroundSize:`${i.width!==void 0?`${i.width}px`:"26px"} ${i.height}px`}},i.name)}class fi extends Yt{constructor(){super();const e=T.remapClamp(T.linearDepth(),.1,.5,0,1).oneMinus();this.colorNode=T.vec4(e,e,e,1)}}const _n=`#include <common>
545
104
  #include <batching_pars_vertex>
546
105
  #include <uv_pars_vertex>
547
106
  #include <color_pars_vertex>
@@ -571,7 +130,7 @@ void main() {
571
130
  #include <logdepthbuf_vertex>
572
131
  #include <clipping_planes_vertex>
573
132
  #include <worldpos_vertex>
574
- }`,BI=`
133
+ }`,Cn=`
575
134
  uniform float opacity;
576
135
  #include <common>
577
136
  #include <uv_pars_fragment>
@@ -581,4 +140,4 @@ void main() {
581
140
  #include <clipping_planes_fragment>
582
141
  if (opacity < 0.015) discard;
583
142
  gl_FragColor = vec4(vec3(vUv, 0.0), opacity);
584
- }`;class XS extends _.ShaderMaterial{constructor(){super({defines:{USE_UV:""},uniforms:{opacity:{value:1}},vertexShader:FI,fragmentShader:BI,transparent:!0})}}class YS extends um{constructor(){super(),this.colorNode=Om(NI(),0,1)}}const or=new _.Raycaster,Dt=new _.Vector3,gn=new _.Vector3,Ke=new _.Quaternion,Zy={X:new _.Vector3(1,0,0),Y:new _.Vector3(0,1,0),Z:new _.Vector3(0,0,1)},Gd={type:"change"},Qy={type:"mouseDown",mode:null},Ky={type:"mouseUp",mode:null},Jy={type:"objectChange"};class DI extends _.Controls{constructor(e,t=null){super(void 0,t);const s=new kI(this);this._root=s;const i=new zI;this._gizmo=i,s.add(i);const n=new GI;this._plane=n,s.add(n);const a=this;function o(v,S){let M=S;Object.defineProperty(a,v,{get:function(){return M!==void 0?M:S},set:function(A){M!==A&&(M=A,n[v]=A,i[v]=A,a.dispatchEvent({type:v+"-changed",value:A}),a.dispatchEvent(Gd))}}),a[v]=S,n[v]=S,i[v]=S}o("camera",e),o("object",void 0),o("enabled",!0),o("axis",null),o("mode","translate"),o("translationSnap",null),o("rotationSnap",null),o("scaleSnap",null),o("space","world"),o("size",1),o("dragging",!1),o("showX",!0),o("showY",!0),o("showZ",!0),o("minX",-1/0),o("maxX",1/0),o("minY",-1/0),o("maxY",1/0),o("minZ",-1/0),o("maxZ",1/0);const l=new _.Vector3,c=new _.Vector3,u=new _.Quaternion,h=new _.Quaternion,d=new _.Vector3,p=new _.Quaternion,f=new _.Vector3,m=new _.Vector3,x=new _.Vector3,y=0,b=new _.Vector3;o("worldPosition",l),o("worldPositionStart",c),o("worldQuaternion",u),o("worldQuaternionStart",h),o("cameraPosition",d),o("cameraQuaternion",p),o("pointStart",f),o("pointEnd",m),o("rotationAxis",x),o("rotationAngle",y),o("eye",b),this._offset=new _.Vector3,this._startNorm=new _.Vector3,this._endNorm=new _.Vector3,this._cameraScale=new _.Vector3,this._parentPosition=new _.Vector3,this._parentQuaternion=new _.Quaternion,this._parentQuaternionInv=new _.Quaternion,this._parentScale=new _.Vector3,this._worldScaleStart=new _.Vector3,this._worldQuaternionInv=new _.Quaternion,this._worldScale=new _.Vector3,this._positionStart=new _.Vector3,this._quaternionStart=new _.Quaternion,this._scaleStart=new _.Vector3,this._getPointer=OI.bind(this),this._onPointerDown=II.bind(this),this._onPointerHover=LI.bind(this),this._onPointerMove=UI.bind(this),this._onPointerUp=VI.bind(this),t!==null&&this.connect(t)}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointermove",this._onPointerHover),this.domElement.addEventListener("pointerup",this._onPointerUp),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerHover),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.style.touchAction="auto"}getHelper(){return this._root}pointerHover(e){if(this.object===void 0||this.dragging===!0)return;e!==null&&or.setFromCamera(e,this.camera);const t=$d(this._gizmo.picker[this.mode],or);t?this.axis=t.object.name:this.axis=null}pointerDown(e){if(!(this.object===void 0||this.dragging===!0||e!=null&&e.button!==0)&&this.axis!==null){e!==null&&or.setFromCamera(e,this.camera);const t=$d(this._plane,or,!0);t&&(this.object.updateMatrixWorld(),this.object.parent.updateMatrixWorld(),this._positionStart.copy(this.object.position),this._quaternionStart.copy(this.object.quaternion),this._scaleStart.copy(this.object.scale),this.object.matrixWorld.decompose(this.worldPositionStart,this.worldQuaternionStart,this._worldScaleStart),this.pointStart.copy(t.point).sub(this.worldPositionStart)),this.dragging=!0,Qy.mode=this.mode,this.dispatchEvent(Qy)}}pointerMove(e){const t=this.axis,s=this.mode,i=this.object;let n=this.space;if(s==="scale"?n="local":(t==="E"||t==="XYZE"||t==="XYZ")&&(n="world"),i===void 0||t===null||this.dragging===!1||e!==null&&e.button!==-1)return;e!==null&&or.setFromCamera(e,this.camera);const a=$d(this._plane,or,!0);if(a){if(this.pointEnd.copy(a.point).sub(this.worldPositionStart),s==="translate")this._offset.copy(this.pointEnd).sub(this.pointStart),n==="local"&&t!=="XYZ"&&this._offset.applyQuaternion(this._worldQuaternionInv),t.indexOf("X")===-1&&(this._offset.x=0),t.indexOf("Y")===-1&&(this._offset.y=0),t.indexOf("Z")===-1&&(this._offset.z=0),n==="local"&&t!=="XYZ"?this._offset.applyQuaternion(this._quaternionStart).divide(this._parentScale):this._offset.applyQuaternion(this._parentQuaternionInv).divide(this._parentScale),i.position.copy(this._offset).add(this._positionStart),this.translationSnap&&(n==="local"&&(i.position.applyQuaternion(Ke.copy(this._quaternionStart).invert()),t.search("X")!==-1&&(i.position.x=Math.round(i.position.x/this.translationSnap)*this.translationSnap),t.search("Y")!==-1&&(i.position.y=Math.round(i.position.y/this.translationSnap)*this.translationSnap),t.search("Z")!==-1&&(i.position.z=Math.round(i.position.z/this.translationSnap)*this.translationSnap),i.position.applyQuaternion(this._quaternionStart)),n==="world"&&(i.parent&&i.position.add(Dt.setFromMatrixPosition(i.parent.matrixWorld)),t.search("X")!==-1&&(i.position.x=Math.round(i.position.x/this.translationSnap)*this.translationSnap),t.search("Y")!==-1&&(i.position.y=Math.round(i.position.y/this.translationSnap)*this.translationSnap),t.search("Z")!==-1&&(i.position.z=Math.round(i.position.z/this.translationSnap)*this.translationSnap),i.parent&&i.position.sub(Dt.setFromMatrixPosition(i.parent.matrixWorld)))),i.position.x=Math.max(this.minX,Math.min(this.maxX,i.position.x)),i.position.y=Math.max(this.minY,Math.min(this.maxY,i.position.y)),i.position.z=Math.max(this.minZ,Math.min(this.maxZ,i.position.z));else if(s==="scale"){if(t.search("XYZ")!==-1){let o=this.pointEnd.length()/this.pointStart.length();this.pointEnd.dot(this.pointStart)<0&&(o*=-1),gn.set(o,o,o)}else Dt.copy(this.pointStart),gn.copy(this.pointEnd),Dt.applyQuaternion(this._worldQuaternionInv),gn.applyQuaternion(this._worldQuaternionInv),gn.divide(Dt),t.search("X")===-1&&(gn.x=1),t.search("Y")===-1&&(gn.y=1),t.search("Z")===-1&&(gn.z=1);i.scale.copy(this._scaleStart).multiply(gn),this.scaleSnap&&(t.search("X")!==-1&&(i.scale.x=Math.round(i.scale.x/this.scaleSnap)*this.scaleSnap||this.scaleSnap),t.search("Y")!==-1&&(i.scale.y=Math.round(i.scale.y/this.scaleSnap)*this.scaleSnap||this.scaleSnap),t.search("Z")!==-1&&(i.scale.z=Math.round(i.scale.z/this.scaleSnap)*this.scaleSnap||this.scaleSnap))}else if(s==="rotate"){this._offset.copy(this.pointEnd).sub(this.pointStart);const o=20/this.worldPosition.distanceTo(Dt.setFromMatrixPosition(this.camera.matrixWorld));let l=!1;t==="XYZE"?(this.rotationAxis.copy(this._offset).cross(this.eye).normalize(),this.rotationAngle=this._offset.dot(Dt.copy(this.rotationAxis).cross(this.eye))*o):(t==="X"||t==="Y"||t==="Z")&&(this.rotationAxis.copy(Zy[t]),Dt.copy(Zy[t]),n==="local"&&Dt.applyQuaternion(this.worldQuaternion),Dt.cross(this.eye),Dt.length()===0?l=!0:this.rotationAngle=this._offset.dot(Dt.normalize())*o),(t==="E"||l)&&(this.rotationAxis.copy(this.eye),this.rotationAngle=this.pointEnd.angleTo(this.pointStart),this._startNorm.copy(this.pointStart).normalize(),this._endNorm.copy(this.pointEnd).normalize(),this.rotationAngle*=this._endNorm.cross(this._startNorm).dot(this.eye)<0?1:-1),this.rotationSnap&&(this.rotationAngle=Math.round(this.rotationAngle/this.rotationSnap)*this.rotationSnap),n==="local"&&t!=="E"&&t!=="XYZE"?(i.quaternion.copy(this._quaternionStart),i.quaternion.multiply(Ke.setFromAxisAngle(this.rotationAxis,this.rotationAngle)).normalize()):(this.rotationAxis.applyQuaternion(this._parentQuaternionInv),i.quaternion.copy(Ke.setFromAxisAngle(this.rotationAxis,this.rotationAngle)),i.quaternion.multiply(this._quaternionStart).normalize())}this.dispatchEvent(Gd),this.dispatchEvent(Jy)}}pointerUp(e){e!==null&&e.button!==0||(this.dragging&&this.axis!==null&&(Ky.mode=this.mode,this.dispatchEvent(Ky)),this.dragging=!1,this.axis=null)}dispose(){this.disconnect(),this._root.dispose()}attach(e){return this.object=e,this._root.visible=!0,this}detach(){return this.object=void 0,this.axis=null,this._root.visible=!1,this}reset(){this.enabled&&this.dragging&&(this.object.position.copy(this._positionStart),this.object.quaternion.copy(this._quaternionStart),this.object.scale.copy(this._scaleStart),this.dispatchEvent(Gd),this.dispatchEvent(Jy),this.pointStart.copy(this.pointEnd))}getRaycaster(){return or}getMode(){return this.mode}setMode(e){this.mode=e}setTranslationSnap(e){this.translationSnap=e}setRotationSnap(e){this.rotationSnap=e}setScaleSnap(e){this.scaleSnap=e}setSize(e){this.size=e}setSpace(e){this.space=e}setColors(e,t,s,i){const n=this._gizmo.materialLib;n.xAxis.color.set(e),n.yAxis.color.set(t),n.zAxis.color.set(s),n.active.color.set(i),n.xAxisTransparent.color.set(e),n.yAxisTransparent.color.set(t),n.zAxisTransparent.color.set(s),n.activeTransparent.color.set(i),n.xAxis._color&&n.xAxis._color.set(e),n.yAxis._color&&n.yAxis._color.set(t),n.zAxis._color&&n.zAxis._color.set(s),n.active._color&&n.active._color.set(i),n.xAxisTransparent._color&&n.xAxisTransparent._color.set(e),n.yAxisTransparent._color&&n.yAxisTransparent._color.set(t),n.zAxisTransparent._color&&n.zAxisTransparent._color.set(s),n.activeTransparent._color&&n.activeTransparent._color.set(i)}}function OI(r){if(this.domElement.ownerDocument.pointerLockElement)return{x:0,y:0,button:r.button};{const e=this.domElement.getBoundingClientRect();return{x:(r.clientX-e.left)/e.width*2-1,y:-(r.clientY-e.top)/e.height*2+1,button:r.button}}}function LI(r){if(this.enabled)switch(r.pointerType){case"mouse":case"pen":this.pointerHover(this._getPointer(r));break}}function II(r){this.enabled&&(document.pointerLockElement||this.domElement.setPointerCapture(r.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.pointerHover(this._getPointer(r)),this.pointerDown(this._getPointer(r)))}function UI(r){this.enabled&&this.pointerMove(this._getPointer(r))}function VI(r){this.enabled&&(this.domElement.releasePointerCapture(r.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.pointerUp(this._getPointer(r)))}function $d(r,e,t){const s=e.intersectObject(r,!0);for(let i=0;i<s.length;i++)if(s[i].object.visible||t)return s[i];return!1}const dc=new _.Euler,je=new _.Vector3(0,1,0),ex=new _.Vector3(0,0,0),tx=new _.Matrix4,pc=new _.Quaternion,Mc=new _.Quaternion,pi=new _.Vector3,sx=new _.Matrix4,To=new _.Vector3(1,0,0),cr=new _.Vector3(0,1,0),So=new _.Vector3(0,0,1),fc=new _.Vector3,po=new _.Vector3,fo=new _.Vector3;class kI extends _.Object3D{constructor(e){super(),this.isTransformControlsRoot=!0,this.controls=e,this.visible=!1}updateMatrixWorld(e){const t=this.controls;t.object!==void 0&&(t.object.updateMatrixWorld(),t.object.parent===null?console.error("TransformControls: The attached 3D object must be a part of the scene graph."):t.object.parent.matrixWorld.decompose(t._parentPosition,t._parentQuaternion,t._parentScale),t.object.matrixWorld.decompose(t.worldPosition,t.worldQuaternion,t._worldScale),t._parentQuaternionInv.copy(t._parentQuaternion).invert(),t._worldQuaternionInv.copy(t.worldQuaternion).invert()),t.camera.updateMatrixWorld(),t.camera.matrixWorld.decompose(t.cameraPosition,t.cameraQuaternion,t._cameraScale),t.camera.isOrthographicCamera?t.camera.getWorldDirection(t.eye).negate():t.eye.copy(t.cameraPosition).sub(t.worldPosition).normalize(),super.updateMatrixWorld(e)}dispose(){this.traverse(function(e){e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose()})}}class zI extends _.Object3D{constructor(){super(),this.isTransformControlsGizmo=!0,this.type="TransformControlsGizmo";const e=new _.MeshBasicMaterial({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),t=new _.LineBasicMaterial({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),s=e.clone();s.opacity=.15;const i=t.clone();i.opacity=.5;const n=e.clone();n.color.setHex(16711680);const a=e.clone();a.color.setHex(65280);const o=e.clone();o.color.setHex(255);const l=e.clone();l.color.setHex(16711680),l.opacity=.5;const c=e.clone();c.color.setHex(65280),c.opacity=.5;const u=e.clone();u.color.setHex(255),u.opacity=.5;const h=e.clone();h.opacity=.25;const d=e.clone();d.color.setHex(16776960),d.opacity=.25;const p=e.clone();p.color.setHex(16776960);const f=e.clone();f.color.setHex(7895160),this.materialLib={xAxis:n,yAxis:a,zAxis:o,active:p,xAxisTransparent:l,yAxisTransparent:c,zAxisTransparent:u,activeTransparent:d};const m=new _.CylinderGeometry(0,.04,.1,12);m.translate(0,.05,0);const x=new _.BoxGeometry(.08,.08,.08);x.translate(0,.04,0);const y=new _.BufferGeometry;y.setAttribute("position",new _.Float32BufferAttribute([0,0,0,1,0,0],3));const b=new _.CylinderGeometry(.0075,.0075,.5,3);b.translate(0,.25,0);function v(q,oe){const Pe=new _.TorusGeometry(q,.0075,3,64,oe*Math.PI*2);return Pe.rotateY(Math.PI/2),Pe.rotateX(Math.PI/2),Pe}function S(){const q=new _.BufferGeometry;return q.setAttribute("position",new _.Float32BufferAttribute([0,0,0,1,1,1],3)),q}const M={X:[[new _.Mesh(m,n),[.5,0,0],[0,0,-Math.PI/2]],[new _.Mesh(m,n),[-.5,0,0],[0,0,Math.PI/2]],[new _.Mesh(b,n),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new _.Mesh(m,a),[0,.5,0]],[new _.Mesh(m,a),[0,-.5,0],[Math.PI,0,0]],[new _.Mesh(b,a)]],Z:[[new _.Mesh(m,o),[0,0,.5],[Math.PI/2,0,0]],[new _.Mesh(m,o),[0,0,-.5],[-Math.PI/2,0,0]],[new _.Mesh(b,o),null,[Math.PI/2,0,0]]],XYZ:[[new _.Mesh(new _.OctahedronGeometry(.1,0),h),[0,0,0]]],XY:[[new _.Mesh(new _.BoxGeometry(.15,.15,.01),u),[.15,.15,0]]],YZ:[[new _.Mesh(new _.BoxGeometry(.15,.15,.01),l),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new _.Mesh(new _.BoxGeometry(.15,.15,.01),c),[.15,0,.15],[-Math.PI/2,0,0]]]},A={X:[[new _.Mesh(new _.CylinderGeometry(.2,0,.6,4),s),[.3,0,0],[0,0,-Math.PI/2]],[new _.Mesh(new _.CylinderGeometry(.2,0,.6,4),s),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new _.Mesh(new _.CylinderGeometry(.2,0,.6,4),s),[0,.3,0]],[new _.Mesh(new _.CylinderGeometry(.2,0,.6,4),s),[0,-.3,0],[0,0,Math.PI]]],Z:[[new _.Mesh(new _.CylinderGeometry(.2,0,.6,4),s),[0,0,.3],[Math.PI/2,0,0]],[new _.Mesh(new _.CylinderGeometry(.2,0,.6,4),s),[0,0,-.3],[-Math.PI/2,0,0]]],XYZ:[[new _.Mesh(new _.OctahedronGeometry(.2,0),s)]],XY:[[new _.Mesh(new _.BoxGeometry(.2,.2,.01),s),[.15,.15,0]]],YZ:[[new _.Mesh(new _.BoxGeometry(.2,.2,.01),s),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new _.Mesh(new _.BoxGeometry(.2,.2,.01),s),[.15,0,.15],[-Math.PI/2,0,0]]]},C={START:[[new _.Mesh(new _.OctahedronGeometry(.01,2),i),null,null,null,"helper"]],END:[[new _.Mesh(new _.OctahedronGeometry(.01,2),i),null,null,null,"helper"]],DELTA:[[new _.Line(S(),i),null,null,null,"helper"]],X:[[new _.Line(y,i),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new _.Line(y,i),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new _.Line(y,i),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},P={XYZE:[[new _.Mesh(v(.5,1),f),null,[0,Math.PI/2,0]]],X:[[new _.Mesh(v(.5,.5),n)]],Y:[[new _.Mesh(v(.5,.5),a),null,[0,0,-Math.PI/2]]],Z:[[new _.Mesh(v(.5,.5),o),null,[0,Math.PI/2,0]]],E:[[new _.Mesh(v(.75,1),d),null,[0,Math.PI/2,0]]]},B={AXIS:[[new _.Line(y,i),[-1e3,0,0],null,[1e6,1,1],"helper"]]},V={XYZE:[[new _.Mesh(new _.SphereGeometry(.25,10,8),s)]],X:[[new _.Mesh(new _.TorusGeometry(.5,.1,4,24),s),[0,0,0],[0,-Math.PI/2,-Math.PI/2]]],Y:[[new _.Mesh(new _.TorusGeometry(.5,.1,4,24),s),[0,0,0],[Math.PI/2,0,0]]],Z:[[new _.Mesh(new _.TorusGeometry(.5,.1,4,24),s),[0,0,0],[0,0,-Math.PI/2]]],E:[[new _.Mesh(new _.TorusGeometry(.75,.1,2,24),s)]]},Y={X:[[new _.Mesh(x,n),[.5,0,0],[0,0,-Math.PI/2]],[new _.Mesh(b,n),[0,0,0],[0,0,-Math.PI/2]],[new _.Mesh(x,n),[-.5,0,0],[0,0,Math.PI/2]]],Y:[[new _.Mesh(x,a),[0,.5,0]],[new _.Mesh(b,a)],[new _.Mesh(x,a),[0,-.5,0],[0,0,Math.PI]]],Z:[[new _.Mesh(x,o),[0,0,.5],[Math.PI/2,0,0]],[new _.Mesh(b,o),[0,0,0],[Math.PI/2,0,0]],[new _.Mesh(x,o),[0,0,-.5],[-Math.PI/2,0,0]]],XY:[[new _.Mesh(new _.BoxGeometry(.15,.15,.01),u),[.15,.15,0]]],YZ:[[new _.Mesh(new _.BoxGeometry(.15,.15,.01),l),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new _.Mesh(new _.BoxGeometry(.15,.15,.01),c),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new _.Mesh(new _.BoxGeometry(.1,.1,.1),h)]]},J={X:[[new _.Mesh(new _.CylinderGeometry(.2,0,.6,4),s),[.3,0,0],[0,0,-Math.PI/2]],[new _.Mesh(new _.CylinderGeometry(.2,0,.6,4),s),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new _.Mesh(new _.CylinderGeometry(.2,0,.6,4),s),[0,.3,0]],[new _.Mesh(new _.CylinderGeometry(.2,0,.6,4),s),[0,-.3,0],[0,0,Math.PI]]],Z:[[new _.Mesh(new _.CylinderGeometry(.2,0,.6,4),s),[0,0,.3],[Math.PI/2,0,0]],[new _.Mesh(new _.CylinderGeometry(.2,0,.6,4),s),[0,0,-.3],[-Math.PI/2,0,0]]],XY:[[new _.Mesh(new _.BoxGeometry(.2,.2,.01),s),[.15,.15,0]]],YZ:[[new _.Mesh(new _.BoxGeometry(.2,.2,.01),s),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new _.Mesh(new _.BoxGeometry(.2,.2,.01),s),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new _.Mesh(new _.BoxGeometry(.2,.2,.2),s),[0,0,0]]]},K={X:[[new _.Line(y,i),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new _.Line(y,i),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new _.Line(y,i),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]};function te(q){const oe=new _.Object3D;for(const Pe in q)for(let ge=q[Pe].length;ge--;){const le=q[Pe][ge][0].clone(),Ue=q[Pe][ge][1],He=q[Pe][ge][2],$t=q[Pe][ge][3],Fe=q[Pe][ge][4];le.name=Pe,le.tag=Fe,Ue&&le.position.set(Ue[0],Ue[1],Ue[2]),He&&le.rotation.set(He[0],He[1],He[2]),$t&&le.scale.set($t[0],$t[1],$t[2]),le.updateMatrix();const Ct=le.geometry.clone();Ct.applyMatrix4(le.matrix),le.geometry=Ct,le.renderOrder=1/0,le.position.set(0,0,0),le.rotation.set(0,0,0),le.scale.set(1,1,1),oe.add(le)}return oe}this.gizmo={},this.picker={},this.helper={},this.add(this.gizmo.translate=te(M)),this.add(this.gizmo.rotate=te(P)),this.add(this.gizmo.scale=te(Y)),this.add(this.picker.translate=te(A)),this.add(this.picker.rotate=te(V)),this.add(this.picker.scale=te(J)),this.add(this.helper.translate=te(C)),this.add(this.helper.rotate=te(B)),this.add(this.helper.scale=te(K)),this.picker.translate.visible=!1,this.picker.rotate.visible=!1,this.picker.scale.visible=!1}updateMatrixWorld(e){const s=(this.mode==="scale"?"local":this.space)==="local"?this.worldQuaternion:Mc;this.gizmo.translate.visible=this.mode==="translate",this.gizmo.rotate.visible=this.mode==="rotate",this.gizmo.scale.visible=this.mode==="scale",this.helper.translate.visible=this.mode==="translate",this.helper.rotate.visible=this.mode==="rotate",this.helper.scale.visible=this.mode==="scale";let i=[];i=i.concat(this.picker[this.mode].children),i=i.concat(this.gizmo[this.mode].children),i=i.concat(this.helper[this.mode].children);for(let n=0;n<i.length;n++){const a=i[n];a.visible=!0,a.rotation.set(0,0,0),a.position.copy(this.worldPosition);let o;if(this.camera.isOrthographicCamera?o=(this.camera.top-this.camera.bottom)/this.camera.zoom:o=this.worldPosition.distanceTo(this.cameraPosition)*Math.min(1.9*Math.tan(Math.PI*this.camera.fov/360)/this.camera.zoom,7),a.scale.set(1,1,1).multiplyScalar(o*this.size/4),a.tag==="helper"){a.visible=!1,a.name==="AXIS"?(a.visible=!!this.axis,this.axis==="X"&&(Ke.setFromEuler(dc.set(0,0,0)),a.quaternion.copy(s).multiply(Ke),Math.abs(je.copy(To).applyQuaternion(s).dot(this.eye))>.9&&(a.visible=!1)),this.axis==="Y"&&(Ke.setFromEuler(dc.set(0,0,Math.PI/2)),a.quaternion.copy(s).multiply(Ke),Math.abs(je.copy(cr).applyQuaternion(s).dot(this.eye))>.9&&(a.visible=!1)),this.axis==="Z"&&(Ke.setFromEuler(dc.set(0,Math.PI/2,0)),a.quaternion.copy(s).multiply(Ke),Math.abs(je.copy(So).applyQuaternion(s).dot(this.eye))>.9&&(a.visible=!1)),this.axis==="XYZE"&&(Ke.setFromEuler(dc.set(0,Math.PI/2,0)),je.copy(this.rotationAxis),a.quaternion.setFromRotationMatrix(tx.lookAt(ex,je,cr)),a.quaternion.multiply(Ke),a.visible=this.dragging),this.axis==="E"&&(a.visible=!1)):a.name==="START"?(a.position.copy(this.worldPositionStart),a.visible=this.dragging):a.name==="END"?(a.position.copy(this.worldPosition),a.visible=this.dragging):a.name==="DELTA"?(a.position.copy(this.worldPositionStart),a.quaternion.copy(this.worldQuaternionStart),Dt.set(1e-10,1e-10,1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1),Dt.applyQuaternion(this.worldQuaternionStart.clone().invert()),a.scale.copy(Dt),a.visible=this.dragging):(a.quaternion.copy(s),this.dragging?a.position.copy(this.worldPositionStart):a.position.copy(this.worldPosition),this.axis&&(a.visible=this.axis.search(a.name)!==-1));continue}a.quaternion.copy(s),this.mode==="translate"||this.mode==="scale"?(a.name==="X"&&Math.abs(je.copy(To).applyQuaternion(s).dot(this.eye))>.99&&(a.scale.set(1e-10,1e-10,1e-10),a.visible=!1),a.name==="Y"&&Math.abs(je.copy(cr).applyQuaternion(s).dot(this.eye))>.99&&(a.scale.set(1e-10,1e-10,1e-10),a.visible=!1),a.name==="Z"&&Math.abs(je.copy(So).applyQuaternion(s).dot(this.eye))>.99&&(a.scale.set(1e-10,1e-10,1e-10),a.visible=!1),a.name==="XY"&&Math.abs(je.copy(So).applyQuaternion(s).dot(this.eye))<.2&&(a.scale.set(1e-10,1e-10,1e-10),a.visible=!1),a.name==="YZ"&&Math.abs(je.copy(To).applyQuaternion(s).dot(this.eye))<.2&&(a.scale.set(1e-10,1e-10,1e-10),a.visible=!1),a.name==="XZ"&&Math.abs(je.copy(cr).applyQuaternion(s).dot(this.eye))<.2&&(a.scale.set(1e-10,1e-10,1e-10),a.visible=!1)):this.mode==="rotate"&&(pc.copy(s),je.copy(this.eye).applyQuaternion(Ke.copy(s).invert()),a.name.search("E")!==-1&&a.quaternion.setFromRotationMatrix(tx.lookAt(this.eye,ex,cr)),a.name==="X"&&(Ke.setFromAxisAngle(To,Math.atan2(-je.y,je.z)),Ke.multiplyQuaternions(pc,Ke),a.quaternion.copy(Ke)),a.name==="Y"&&(Ke.setFromAxisAngle(cr,Math.atan2(je.x,je.z)),Ke.multiplyQuaternions(pc,Ke),a.quaternion.copy(Ke)),a.name==="Z"&&(Ke.setFromAxisAngle(So,Math.atan2(je.y,je.x)),Ke.multiplyQuaternions(pc,Ke),a.quaternion.copy(Ke))),a.visible=a.visible&&(a.name.indexOf("X")===-1||this.showX),a.visible=a.visible&&(a.name.indexOf("Y")===-1||this.showY),a.visible=a.visible&&(a.name.indexOf("Z")===-1||this.showZ),a.visible=a.visible&&(a.name.indexOf("E")===-1||this.showX&&this.showY&&this.showZ),a.material._color=a.material._color||a.material.color.clone(),a.material._opacity=a.material._opacity||a.material.opacity,a.material.color.copy(a.material._color),a.material.opacity=a.material._opacity,this.enabled&&this.axis&&(a.name===this.axis?(a.material.color.copy(this.materialLib.active.color),a.material.opacity=1):this.axis.split("").some(function(l){return a.name===l})&&(a.material.color.copy(this.materialLib.active.color),a.material.opacity=1))}super.updateMatrixWorld(e)}}class GI extends _.Mesh{constructor(){super(new _.PlaneGeometry(1e5,1e5,2,2),new _.MeshBasicMaterial({visible:!1,wireframe:!0,side:_.DoubleSide,transparent:!0,opacity:.1,toneMapped:!1})),this.isTransformControlsPlane=!0,this.type="TransformControlsPlane"}updateMatrixWorld(e){let t=this.space;switch(this.position.copy(this.worldPosition),this.mode==="scale"&&(t="local"),fc.copy(To).applyQuaternion(t==="local"?this.worldQuaternion:Mc),po.copy(cr).applyQuaternion(t==="local"?this.worldQuaternion:Mc),fo.copy(So).applyQuaternion(t==="local"?this.worldQuaternion:Mc),je.copy(po),this.mode){case"translate":case"scale":switch(this.axis){case"X":je.copy(this.eye).cross(fc),pi.copy(fc).cross(je);break;case"Y":je.copy(this.eye).cross(po),pi.copy(po).cross(je);break;case"Z":je.copy(this.eye).cross(fo),pi.copy(fo).cross(je);break;case"XY":pi.copy(fo);break;case"YZ":pi.copy(fc);break;case"XZ":je.copy(fo),pi.copy(po);break;case"XYZ":case"E":pi.set(0,0,0);break}break;case"rotate":default:pi.set(0,0,0)}pi.length()===0?this.quaternion.copy(this.cameraQuaternion):(sx.lookAt(Dt.set(0,0,0),pi,je),this.quaternion.setFromRotationMatrix(sx)),super.updateMatrixWorld(e)}}class bt extends _.EventDispatcher{static DRAG_START="Transform::dragStart";static DRAG_END="Transform::dragEnd";static _instance;three;activeCamera;controls=new Map;visibility=new Map;setApp(e){this.three=e,this.three.addEventListener(me.SET_SCENE,this.setScene)}clear(){for(const e of this.controls.values()){e.detach(),e.disconnect();const t=e.getHelper();Ri(t)}this.controls=new Map,this.visibility=new Map}add(e){let t=this.controls.get(e);if(t===void 0){const s=document.querySelector(".clickable");t=new DI(this.activeCamera,s),t.getHelper().name=e,t.setSize(.5),t.setSpace("local"),this.controls.set(e,t),this.visibility.set(e,!0),t.addEventListener("mouseDown",()=>{this.dispatchEvent({type:bt.DRAG_START})}),t.addEventListener("mouseUp",()=>{this.dispatchEvent({type:bt.DRAG_END})}),t.addEventListener("dragging-changed",i=>{mt.instance?.toggleOrbitControls(i.value)})}return t}get(e){return this.controls.get(e)}remove(e){const t=this.get(e);return t===void 0?!1:(t.detach(),t.disconnect(),Ri(t.getHelper()),this.controls.delete(e),!0)}enabled(e){this.controls.forEach(t=>{t.enabled=e})}updateCamera(e,t){this.activeCamera=e,this.controls.forEach(s=>{s.camera!==e&&(s.camera=e,e.getWorldPosition(s.cameraPosition),e.getWorldQuaternion(s.cameraQuaternion)),s.domElement!==t&&(s.disconnect(),s.domElement=t,s.connect(t))})}show(){this.controls.forEach(e=>{const t=e.getHelper(),s=this.visibility.get(t.name);s!==void 0&&(t.visible=s)})}hide(){this.controls.forEach(e=>{const t=e.getHelper();this.visibility.set(t.name,t.visible),t.visible=!1})}setScene=()=>{this.clear()};static get instance(){return bt._instance||(bt._instance=new bt),bt._instance}}const $I=new _.BoxGeometry,Wd=new _.Vector2;class wc extends _.Object3D{curve=new _.CatmullRomCurve3;line;draggable;curvePos;tension=.5;closed=!1;subdivide=50;curveType;offset=1;lineMaterial;_camera;_curvePercentage=0;_draggableScale=10;_transform;raycaster;draggedMat=new _.MeshBasicMaterial;parentGroup;group;constructor(e,t){const s=new _.Color(Sh(.5,1,Math.random()),Sh(.5,1,Math.random()),Sh(.5,1,Math.random()));super(),this.name=e,this.lineMaterial=new _.LineBasicMaterial({color:s}),this.line=new _.Line(new _.BufferGeometry,this.lineMaterial),this.line.name="line",this.line.visible=!1,this.add(this.line),this._camera=t,this.curveType="catmullrom",this.draggedMat.color=s,this.draggable=new _.Object3D,this.draggable.name="draggablePoints",this.add(this.draggable),this.curvePos=new _.Mesh(new _.SphereGeometry(1.5),new _.MeshBasicMaterial({color:s})),this.curvePos.name="curvePos",this.curvePos.scale.setScalar(this._draggableScale),this.curvePos.visible=!1,this.add(this.curvePos),this.raycaster=new _.Raycaster,this.raycaster.params.Line.threshold=3,this.enable()}enable(){document.addEventListener("pointerdown",this.onMouseClick)}disable(){document.removeEventListener("pointerdown",this.onMouseClick)}dispose=()=>{this._transform&&(this._transform.removeEventListener("objectChange",this.updateSpline),bt.instance.remove(this.name)),this.disable(),this.parentGroup.removeGroup(this.name)};hideTransform=()=>{this._transform?.detach()};exportSpline=()=>{const e=[];this.draggable.children.forEach(t=>{e.push([As(t.position.x,3),As(t.position.y,3),As(t.position.z,3)])}),rx({name:this.name,points:e,tension:this.tension,closed:this.closed,subdivide:this.subdivide,type:this.curveType}),console.log("Spline copied!")};showPoints=(e=!0)=>{this.draggable.visible=e};addPoints=(e=[])=>{if(e.length>0){const t=e.length-1;for(let s=0;s<t;s++)this.addPoint(e[s],!1);this.addPoint(e[t])}};addPoint=(e,t=!0)=>{const s=this.draggable.children.length,i=new _.Mesh($I,this.draggedMat);i.name=`point_${s}`,i.position.copy(e),i.scale.setScalar(this._draggableScale),this.draggable.add(i),this._transform?.attach(i);const n=this.points.length>1;return n&&t&&this.updateSpline(),this.line.visible=n,this.updateCurrentPoint(),i};addNextPt=()=>{const e=this.draggable.children.length,t=e>1?this.draggable.children[e-1].position.clone():new _.Vector3,s=this.addPoint(t);this.updateField(s.position)};removePoint=e=>{if(this._transform?.object===e){this._transform?.detach();const t=this.draggable.children[this.draggable.children.length-1];this._transform?.attach(t),this.updateField(t.position)}Ri(e),this.updateSpline()};removePointAt=e=>{const t=this.draggable.children[e];this.removePoint(t)};removeSelectedPt=()=>{this._transform?.object!==void 0&&this.removePoint(this._transform?.object)};updateLastPoint(e){const t=this.draggable.children.length;t>0&&(this.draggable.children[t-1].position.copy(e),this.updateSpline())}updateSpline=()=>{this.points.length<2||(this.curve=new _.CatmullRomCurve3(this.points,this.closed,this.curveType,this.tension),this.line.geometry.dispose(),this.line.geometry=new _.BufferGeometry().setFromPoints(this.curve.getPoints(this.subdivide)),this.curvePos.position.copy(this.getPointAt(this._curvePercentage)))};updateField(e){this.group.current?.setField("Current Point",e)}onMouseClick=e=>{if(!mt.instance||!mt.instance.currentWindow||this._transform&&!this._transform.getHelper().visible)return;const s=mt.instance.currentWindow.current.getBoundingClientRect();Wd.x=(e.clientX-s.x)/s.width*2-1,Wd.y=-((e.clientY-s.y)/s.height)*2+1,this.raycaster.setFromCamera(Wd,this.camera);const i=this.raycaster.intersectObjects(this.draggable.children,!1);if(i.length>0){const n=i[0].object;n!==this._transform?.object&&(this._transform?.attach(n),this.updateField(n.position))}};getPointAt(e){return this.curve.points.length>1?this.curve.getPointAt(e):this.curve.points.length===1?this.curve.points[0]:new _.Vector3}getTangentAt(e){return this.curve.getTangentAt(e)}get points(){const e=[];return this.draggable.children.forEach(t=>{e.push(t.position)}),e}get total(){return this.draggable.children.length}get draggableScale(){return this._draggableScale}set draggableScale(e){this._draggableScale=e,this.draggable.children.forEach(t=>t.scale.setScalar(e)),this.curvePos.scale.setScalar(e)}get camera(){return this._camera}set camera(e){this._camera=e,this._transform!==void 0&&(this._transform.camera=e)}get curvePercentage(){return this._curvePercentage}set curvePercentage(e){this._curvePercentage=e,this.curvePos.position.copy(this.getPointAt(e))}updateCurrentPoint(){if(this._transform?.object&&this.group){const e=this._transform?.object;e.name.search("point")>-1&&this.updateField(e.position)}}onUpdateTransform=()=>{this.updateCurrentPoint(),this.updateSpline()};initDebug(e,t){const s=this.draggable.children;this.visible=t,this.parentGroup=e,this._transform=bt.instance.add(this.name),this._transform.camera=this._camera,this._transform.addEventListener("objectChange",this.onUpdateTransform),s.length>0&&this._transform.attach(s[s.length-1]),mt.instance?.helpersContainer.add(this._transform.getHelper());const i=s.length>0?s[s.length-1].position:{x:0,y:0,z:0};this.group=e.addGroup({title:this.name,expanded:t,items:[{prop:"Closed",type:"boolean",value:this.closed},{prop:"Visible",type:"boolean",value:this.visible},{prop:"Show Position",type:"boolean",value:this.curvePos.visible},{prop:"Show Points",type:"boolean",value:this.draggable.visible},{prop:"Color",type:"color",value:`#${this.draggedMat.color.getHexString()}`},{prop:"Curve",type:"option",options:[{title:"Catmullrom",value:"catmullrom"},{title:"Centripetal",value:"centripetal"},{title:"Chordal",value:"chordal"}]},{prop:"Draggable Scale",type:"range",min:.01,max:100,step:.01,value:this._draggableScale},{prop:"Subdivide",type:"range",min:1,max:1e3,step:1,value:this.subdivide},{prop:"Tension",type:"range",min:0,max:1,step:.01,value:this.tension},{prop:"New Pt Offset",type:"range",min:0,max:10,value:this.offset},{prop:"Curve At",type:"range",min:0,max:1,step:.01,value:0},{prop:"Toggle Transform",type:"button"},{prop:"Add Point",type:"button"},{prop:"Remove Point",type:"button"},{prop:"Export",type:"button"},{prop:"Delete",type:"button"},{prop:"Current Point",type:"grid3",value:i}],onUpdate:(n,a)=>{switch(n){case"Closed":this.closed=a,this.updateSpline();break;case"Visible":this.visible=a;break;case"Color":this.lineMaterial.color.setStyle(a),this.draggedMat.color.setStyle(a);break;case"Curve":this.curveType=a,this.updateSpline();break;case"Draggable Scale":this.draggableScale=a;break;case"Subdivide":this.subdivide=a,this.updateSpline();break;case"Tension":this.tension=a,this.updateSpline();break;case"New Pt Offset":this.offset=a;break;case"Curve At":this.curvePos.position.copy(this.getPointAt(a));break;case"Show Position":this.curvePos.visible=a;break;case"Show Points":this.draggable.visible=a;break;case"Toggle Transform":this._transform&&(this._transform.getHelper().visible=!this._transform.getHelper().visible);break;case"Add Point":this.addNextPt();break;case"Remove Point":this.removeSelectedPt();break;case"Export":this.exportSpline();break;case"Delete":this.parent.currentSpline=null,Ri(this);break;case"Current Point":if(this.group.current&&this._transform?.object){const o=this._transform?.object;o.name.search("point")>-1&&(o.position.copy(a),this.updateSpline())}break}}}),this.draggable.children.forEach(n=>{this.debugPoint(n)})}debugPoint=e=>{e.name,e.visible=this.draggable.visible}}let mc=0;class ZS extends _.Object3D{defaultScale=10;currentSpline=null;_camera;group=null;three;splineDataText="";constructor(e,t){super(),this.name="Spline Editor",this._camera=e,this.three=t,this.three.addEventListener(me.ADD_SPLINE,this.onAddSpline)}initDebug(){this.group=Ce.addEditorGroup({title:this.name,items:[{type:"field",prop:"Spline Data",value:"",disabled:!1},{type:"button",prop:"Import Spline"},{type:"button",prop:"New Spline"},{type:"boolean",prop:"Show Points",value:!0},{type:"boolean",prop:"Draw Mode",value:!1},{type:"boolean",prop:"Visible",value:this.visible},{type:"range",prop:"Default Scale",min:0,max:50,step:.01,value:this.defaultScale}],onUpdate:(e,t)=>{switch(e){case"New Spline":this.createSpline();break;case"Spline Data":this.splineDataText=t;break;case"Import Spline":this.createSplineFromJSON(JSON.parse(this.splineDataText));break;case"Show Points":this.showPoints(t);break;case"Visible":this.visible=t;break;case"Default Scale":this.defaultScale=t;break;case"Draw Mode":t?this.enableClickToDraw():this.disableClickToDraw();break}}})}dispose(){this.three.removeEventListener(me.ADD_SPLINE,this.onAddSpline),Ce.removeEditorGroup(this.name)}addSpline(e,t){e.draggableScale=this.defaultScale,e.hideTransform(),this.group?.current!==null&&e.initDebug(this.group.current,t),this.add(e),this.currentSpline=e}createSpline=(e=[])=>{const t=`Spline ${mc+1}`,s=new wc(t,this._camera);return s.addPoints(e),this.addSpline(s,!0),mc++,s};createSplineFromArray=e=>{const t=[];return e.forEach(s=>{t.push(new _.Vector3(s[0],s[1],s[2]))}),this.createSpline(t)};createSplineFromCatmullRom=e=>this.createSpline(e.points);createSplineFromJSON=e=>{const t=[];e.points.forEach(i=>{t.push(new _.Vector3(i[0],i[1],i[2]))});const s=new wc(e.name,this._camera);return s.closed=e.closed,s.subdivide=e.subdivide,s.tension=e.tension,s.type=e.type,s.addPoints(t),s.updateSpline(),this.addSpline(s,!1),s};showPoints=(e=!0)=>{this.children.forEach(t=>{t.showPoints(e)})};onAddSpline=e=>{const t=JSON.parse(e.value),s=t.name!==void 0?t.name:`Spline ${mc+1}`,i=new wc(s,this.camera);t.tension!==void 0&&(i.tension=t.tension),t.closed!==void 0&&(i.closed=t.closed),t.subdivide!==void 0&&(i.subdivide=t.subdivide),t.type!==void 0&&(i.curveType=t.type);const n=[];t.points.forEach(a=>{n.push(new _.Vector3(a[0],a[1],a[2]))}),i.addPoints(n),this.addSpline(i,!1),mc++};isMouseDown=!1;enableClickToDraw(){document.querySelectorAll(".clickable").forEach(e=>{e.addEventListener("mousedown",this.onClickCanvas),e.addEventListener("mousemove",this.onMouseMove),e.addEventListener("mouseup",this.onMouseUp)})}disableClickToDraw(){document.querySelectorAll(".clickable").forEach(e=>{e.removeEventListener("mousedown",this.onClickCanvas),e.removeEventListener("mousemove",this.onMouseMove),e.removeEventListener("mouseup",this.onMouseUp)})}onClickCanvas=e=>{if(e.button!==0)return;if(this._camera.type!=="OrthographicCamera"){console.warn("Spline Editor - 3D Camera not supported in Draw Mode");return}const s=e.target.getBoundingClientRect(),i=(e.clientX-s.left)/s.width*2-1,n=-((e.clientY-s.top)/s.height)*2+1;if(mt.instance){const o=new _.Raycaster;o.setFromCamera(new _.Vector2(i,n),this._camera);const l=o.intersectObjects(mt.instance.helpersContainer.children,!0);for(let c=0;c<l.length;c++){const u=l[c];if(!(u.object.isLine||u.object.isTransformControlsPlane)&&u.object.isObject3D)return}}this.currentSpline===null&&(this.currentSpline=this.createSpline());const a=this.mouseToSplinePos(i,n,s.width,s.height);this.currentSpline?.addPoint(a),this.isMouseDown=!0};onMouseMove=e=>{if(!this.isMouseDown)return;const s=e.target.getBoundingClientRect(),i=(e.clientX-s.left)/s.width*2-1,n=-((e.clientY-s.top)/s.height)*2+1,a=this.mouseToSplinePos(i,n,s.width,s.height);this.currentSpline?.updateLastPoint(a),this.currentSpline?.updateField(a)};onMouseUp=()=>{this.isMouseDown=!1};mouseToSplinePos(e,t,s,i){const n=new _.Vector3,a=Math.PI/2,o=this._camera,l=o.zoom,c=o.rotation.x===-6123233995736766e-32&&o.rotation.y===0&&o.rotation.z===0,u=o.rotation.x===-Math.PI&&o.rotation.y===12246467991473532e-32&&o.rotation.z===Math.PI,h=o.rotation.x===-6162975822039155e-48&&o.rotation.y===-a&&o.rotation.z===0,d=o.rotation.x===-6162975822039155e-48&&o.rotation.y===a&&o.rotation.z===0,p=o.rotation.x===-1.5707953264174506&&o.rotation.y===0&&o.rotation.z===0,f=o.rotation.x===1.5707953264174506&&o.rotation.y===0&&o.rotation.z===0;let m=e,x=t;u||d?m*=-1:p&&(x*=-1);const y=s/2/l,b=i/2/l;if(this.currentSpline===null&&(this.currentSpline=this.createSpline()),c||u){const v=m*y+o.position.x,S=x*b+o.position.y;n.set(v,S,0)}else if(h||d){const v=m*y+o.position.z,S=x*b+o.position.y;n.set(0,S,v)}else if(p||f){const v=m*y+o.position.x,S=x*b+o.position.z;n.set(v,0,S)}return n}get camera(){return this._camera}set camera(e){this._camera=e,this.children.forEach(t=>{const s=t;s.camera=e})}}const ix=["Single","Side by Side","Stacked","Quad"],WI="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAACXBIWXMAAAsTAAALEwEAmpwYAAAC60lEQVRYhe2YT4hNcRTHP48xpmYaNAvRyEQxEhnKQljYsRm9/EmSyJiMFAsMZWNhJYoNIUVJ2VGiyb9ZzIpMpkQSahbGv9GMYWrM+1rc2zjvzvvdd+99rzdvMd+6de75nd+5387vnN/v/G5KEuWMKRNNIB8mCRaKiiL5qQb2ApuBuUAV0Ad0AJeB3sSeJRX6LJbULTf6JTUn9Z+KWMUpPyp/Avoa4CNQZ3Sj/lNpdL/xottR7AjOkHRUUpekN5I6JbVLavDH75lIfZN0UFKTpCWS0pJem/HeJBEMG6yV1ONYtgFJbZJ+GF1jDh+zJb03NuliEuwMkMo4yErS2RA/LcbuYVyCrm1mA7Dal/8Cu4FG4JD/HsTTkCy6a+SVMTPQuc1sBKb78nHghi+/A+YBxwL2lbhRY+ThuARdEVxu5JdGFvACr0otdoZ8Y4+Rn0Sn5sFFsMvI6YB9MzA1YJ8mN8k1wAHzfj4uQVdyrpI0aJL7oqTtkq4FiqPLyCOSbktqlbRL0jlJQ2b8QdwCUZ4qvhRStZL0XFK1pMd57CRvq5mfhKBriRfiFUMY6oD7eOdwPlQAN4G10dfWg+uouwXsiOssAj4AC+JMcEWwvnAuOTEr7gTXPmg34zagOwkbIIOXAo9CbDYBrcBXYN+4UUdy2sRflyS5zVNlfPX7ugpJW5V9nI7mmh+lYU0lCZ2B3TOnAVuAk0BTwC5nuhWro46KauBOQJch5OpRaoIW34GreGf+YZdRqS9NAj4Bp4ClQDvwOWxCqSM4ADQEdKE5XvbXzlITrAVe4TW+M6NMKDXBFLAMuAD0ACfIc7pMZBXXA2cY3/xmodQRHAL2A2+NLtj8ZiEKwUL/z2WMPAJcAVYALWSf8dZuDFGWeBHwKxm3sWYhiGG8Tfo6sA2vSfiSy4GrH3wGrDcfKSSKKf6v1E9yF0XK9Q1XBPuMXMw8HXTonQFwETwNzMFr64v1jzgFHIk9ybHEZYPJo65QlD3Bf2/Q/eaHPiSWAAAAAElFTkSuQmCC",HI="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAACXBIWXMAAAsTAAALEwEAmpwYAAAETklEQVRYhe2YXYhVVRTHf3d0/JhyUrMpFbImM+whSa3Mynww+4AeIgiKoozooQ+KyMyXIAujF6OXqHyI6iEKKYgIP/owsjSFqCkprdDUTEcjbWZ0HHV+Pex1ucfb9Z57Z9REXHA4Z++99l7/s/ZZ/7X2KaiczNLwfwPIk9MA+yunNMAG4DHgV+BvoB3YFff2TPstYEyfrajVroI6Sr1GvahsbJC63HzZq04pmztSvU5tVRuqYRiYg78JeBR4HPg5ntdmxovz9wJfA3uAxuibDLQCA+IqynnAQuBuYCnwMLC1rx48U12U8cZqdWqMDcx4cI16qTpYbVKHqa+ovWUeHKsujn7VL9ULq2HI+wY7gVeBJdGeFu3J4ZUiy/cAXeHRRuAQsC/GC0B3eG4BcH/0tUV7czUAeVsMsBF4Kha9HZgCvAncAuwPnXHA0wFuGLANuDrGuoGDwFxgTqzzQ7RX5FrP2eLsdb76vnogtme6+nE8H1YPlQXHwbi3q9eqn0e7Tb25VrsF68vFY0lb1AGcDTwItGQ8tQM4AIwGmqP/EPAu8A0wElgJfFGzxTo8mKWXu9Rd4ZF96jvqjSbauEC9Sn1O3R463epLaku99voCsFXdkAH3kNpcQW+IiT/bQne3eufxBtioPqP2mKhioXpWzpxb1T8C5Ifh4ZptVoriRmAIKdrI3Lujf3bobAPeJpF0NVkKrAFuI9HTOBIxnxFrF4OgQKKr/dnJlQA+AcwABgOHA4zAamA5cE7orQL+zAEHiWI+A2bFC7aSguheYCgpqAphZz3wSB7AecCICv2TgH8oFRib4gVqka0k0h8CXAxMBW6ooDejFoCvA9OBQUAvKWM0kDz4XUZvNKXtyZMWUl7vBbaQXq457PeEziDgx/KJlQAuIPFdMcEXv5OdYWBP9M8k8VpnDQCvB4aTSrCNJB5cSdrW3tBpIJVnR0qdUTxAfdGUOVTnmwqEanNmqltC/9OgqePKg5eom8PgdvW+oJ9Kupera0O3U50TL3lcAaI+oHaF4R3qa6Z822wq0Saq89T1lmSxOrxeW/Xm4uGkiqQDmECKuKHxHW0HdpMiewSpvGqKeR8Ay0iBsYIjg6261PE2o9Q3Yqv+MqWxO9R1Hl12qs+q49Vlppy82pSr+5xJKsko4AXgHlJ0t5NIeg3wLXAlqZhtIUV8J6nmWwX8QiLjdhL5TwMWkY4R6/rrwYKlMr1Y321QZ/vfwBijPqm+rF4Wc7PjE9QllurGVeoV5gRNHsAm9fnMom3qrKPoTjKdMXaYyrFygEWQ72XWW24qhPu8xcUc2UU6O8wFPjmK7jhgPHAuMJGUGQ6U6WwE5sfzTXGvei7KA9hFOiR9D/wOfFVFt4dS2tpfRe83Ur7/CPiJakfOGgBCypubatArl2r8VfOax/LfzABKtePAzHO/5FgC7KBEzB2kOrDfUm8mOeFySv9+OyFyGmB/5aQH+C9BVKmVCNuMZgAAAABJRU5ErkJggg==",jI="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAYAAACpF6WWAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAQ0lEQVQ4jWP8////fwYqAxYozUhFM/8zkaKYWIWkGEq0b0ZdSjQY5i79TyWagRGaTUdzFEEw6lLqGzqwLoVVJ1StpwA9sBwbUqAh5gAAAABJRU5ErkJggg==";class mt extends X.Component{static instance=null;scene;renderer;currentScene;scenes=new Map;cameras=new Map;controls=new Map;currentCamera;currentWindow;helpersContainer=new _.Group;grid;cameraHelpers=new Map;lightHelpers=new Map;interactionHelper=new _.AxesHelper(25);currentTransform;splineEditor;depthMaterial;normalsMaterial;uvMaterial;wireframeMaterial=new _.MeshBasicMaterial({opacity:.33,transparent:!0,wireframe:!0});playing=!1;rafID=-1;cameraControlsRafID=-1;width=0;height=0;tlCam=null;trCam=null;blCam=null;brCam=null;tlRender="Renderer";trRender="Renderer";blRender="Renderer";brRender="Renderer";cameraVisibility=!0;lightVisibility=!0;gridVisibility=!0;rendererReady=!1;selectedItem=void 0;debugCamera;raycaster=new _.Raycaster;pointer=new _.Vector2;cameraControls=void 0;canvasRef;containerRef;tlWindow;trWindow;blWindow;brWindow;editorCameras=["Top","Bottom","Left","Right","Front","Back","Orthographic","UI","Debug"];constructor(e){super(e),this.props.three.addEventListener(me.ADD_RENDERER,this.setupRenderer),this.scene=new _.Scene,this.scene.name=this.scene.uuid="",this.canvasRef=X.createRef(),this.containerRef=X.createRef(),this.tlWindow=X.createRef(),this.trWindow=X.createRef(),this.blWindow=X.createRef(),this.brWindow=X.createRef();const t=e.three.name,s=localStorage,i=s.getItem(`${t}_mode`);this.state={mode:i!==null?i:"Single",modeOpen:!1,renderModeOpen:!1,interactionMode:"Orbit",interactionModeOpen:!1,lastUpdate:Date.now()},s.setItem(`${t}_mode`,this.state.mode),s.setItem(`${t}_tlCam`,s.getItem(`${t}_tlCam`)!==null?s.getItem(`${t}_tlCam`):"Debug"),s.setItem(`${t}_trCam`,s.getItem(`${t}_trCam`)!==null?s.getItem(`${t}_trCam`):"Orthographic"),s.setItem(`${t}_blCam`,s.getItem(`${t}_blCam`)!==null?s.getItem(`${t}_blCam`):"Front"),s.setItem(`${t}_brCam`,s.getItem(`${t}_brCam`)!==null?s.getItem(`${t}_brCam`):"Top"),s.setItem(`${t}_tlRender`,s.getItem(`${t}_tlRender`)!==null?s.getItem(`${t}_tlRender`):"Renderer"),s.setItem(`${t}_trRender`,s.getItem(`${t}_trRender`)!==null?s.getItem(`${t}_trRender`):"Renderer"),s.setItem(`${t}_blRender`,s.getItem(`${t}_blRender`)!==null?s.getItem(`${t}_blRender`):"Renderer"),s.setItem(`${t}_brRender`,s.getItem(`${t}_brRender`)!==null?s.getItem(`${t}_brRender`):"Renderer");const n={Vector2:_.Vector2,Vector3:_.Vector3,Vector4:_.Vector4,Quaternion:_.Quaternion,Matrix4:_.Matrix4,Spherical:_.Spherical,Box3:_.Box3,Sphere:_.Sphere,Raycaster:_.Raycaster};gi.install({THREE:n}),this.setupScene(),this.setupTools();const a=localStorage.getItem(this.expandedCameraVisibility);a!==null&&(this.cameraVisibility=a==="open"),this.saveExpandedCameraVisibility();const o=localStorage.getItem(this.expandedLightVisibility);o!==null&&(this.lightVisibility=o==="open"),this.saveExpandedLightVisibility();const l=localStorage.getItem(this.expandedGridVisibility);l!==null&&(this.gridVisibility=l==="open"),this.grid&&(this.grid.visible=this.gridVisibility),this.saveExpandedGridVisibility(),mt.instance=this}componentDidMount(){this.enable(),this.assignControls(),this.resize(),this.play(),bt.instance.setApp(this.props.three),bt.instance.activeCamera=this.debugCamera,this.props.three.requestRenderer()}componentDidUpdate(e,t,s){t.mode!==this.state.mode&&(this.assignControls(),this.resize())}componentWillUnmount(){this.disable(),this.clear(),Ce.removeEditorGroup("View Settings")}render(){const e=[];return this.cameras.forEach((t,s)=>{e.push(s)}),F.jsxs("div",{className:"multiview",children:[F.jsx("canvas",{ref:this.canvasRef}),F.jsxs("div",{className:`cameras ${this.state.mode==="Single"||this.state.mode==="Stacked"?"single":""}`,ref:this.containerRef,children:[this.state.mode==="Single"&&F.jsx(F.Fragment,{children:F.jsx(ar,{name:"tl",camera:this.tlCam,options:e,ref:this.tlWindow,onSelectCamera:t=>{this.controls.get(this.tlCam.name)?.dispose();const s=this.cameras.get(t);s!==void 0&&(this.clearCamera(this.tlCam),this.tlCam=s,localStorage.setItem(`${this.appID}_tlCam`,s.name),this.createControls(s,this.tlWindow.current))},onSelectRenderMode:t=>{this.tlRender=t,localStorage.setItem(`${this.appID}_tlRender`,t)}})}),(this.state.mode==="Side by Side"||this.state.mode==="Stacked")&&F.jsxs(F.Fragment,{children:[F.jsx(ar,{name:"tl",camera:this.tlCam,options:e,ref:this.tlWindow,onSelectCamera:t=>{this.controls.get(this.tlCam.name)?.dispose();const s=this.cameras.get(t);s!==void 0&&(this.clearCamera(this.tlCam),this.tlCam=s,localStorage.setItem(`${this.appID}_tlCam`,s.name),this.createControls(s,this.tlWindow.current))},onSelectRenderMode:t=>{this.tlRender=t,localStorage.setItem(`${this.appID}_tlRender`,t)}}),F.jsx(ar,{name:"tr",camera:this.trCam,options:e,ref:this.trWindow,onSelectCamera:t=>{this.controls.get(this.trCam.name)?.dispose();const s=this.cameras.get(t);s!==void 0&&(this.clearCamera(this.trCam),this.trCam=s,localStorage.setItem(`${this.appID}_trCam`,s.name),this.createControls(s,this.trWindow.current))},onSelectRenderMode:t=>{this.trRender=t,localStorage.setItem(`${this.appID}_trRender`,t)}})]}),this.state.mode==="Quad"&&F.jsxs(F.Fragment,{children:[F.jsx(ar,{name:"tl",camera:this.tlCam,options:e,ref:this.tlWindow,onSelectCamera:t=>{this.controls.get(this.tlCam.name)?.dispose();const s=this.cameras.get(t);s!==void 0&&(this.clearCamera(this.tlCam),this.tlCam=s,localStorage.setItem(`${this.appID}_tlCam`,s.name),this.createControls(s,this.tlWindow.current))},onSelectRenderMode:t=>{this.tlRender=t,localStorage.setItem(`${this.appID}_tlRender`,t)}}),F.jsx(ar,{name:"tr",camera:this.trCam,options:e,ref:this.trWindow,onSelectCamera:t=>{this.controls.get(this.trCam.name)?.dispose();const s=this.cameras.get(t);s!==void 0&&(this.clearCamera(this.trCam),this.trCam=s,localStorage.setItem(`${this.appID}_trCam`,s.name),this.createControls(s,this.trWindow.current))},onSelectRenderMode:t=>{this.trRender=t,localStorage.setItem(`${this.appID}_trRender`,t)}}),F.jsx(ar,{name:"bl",camera:this.blCam,options:e,ref:this.blWindow,onSelectCamera:t=>{this.controls.get(this.blCam.name)?.dispose();const s=this.cameras.get(t);s!==void 0&&(this.clearCamera(this.blCam),this.blCam=s,localStorage.setItem(`${this.appID}_blCam`,s.name),this.createControls(s,this.blWindow.current))},onSelectRenderMode:t=>{this.blRender=t,localStorage.setItem(`${this.appID}_blRender`,t)}}),F.jsx(ar,{name:"br",camera:this.brCam,options:e,ref:this.brWindow,onSelectCamera:t=>{this.controls.get(this.brCam.name)?.dispose();const s=this.cameras.get(t);s!==void 0&&(this.clearCamera(this.brCam),this.brCam=s,localStorage.setItem(`${this.appID}_brCam`,s.name),this.createControls(s,this.brWindow.current))},onSelectRenderMode:t=>{this.brRender=t,localStorage.setItem(`${this.appID}_brRender`,t)}})]})]}),F.jsxs("div",{className:"settings",children:[F.jsx(wu,{title:"View",index:ix.indexOf(this.state.mode),options:ix,onSelect:t=>{t!==this.state.mode&&(this.killControls(),this.setState({mode:t}),localStorage.setItem(`${this.appID}_mode`,t))},open:this.state.modeOpen,onToggle:t=>{this.setState({modeOpen:t,renderModeOpen:!1,interactionModeOpen:!1})}}),F.jsx(wu,{title:"Interact",index:this.state.interactionMode==="Orbit"?0:1,options:["Orbit Mode","Selection Mode"],onSelect:t=>{this.interactionHelper.visible=t==="Selection Mode",this.setState({interactionMode:this.interactionHelper.visible?"Selection":"Orbit"})},open:this.state.interactionModeOpen,onToggle:t=>{this.setState({modeOpen:!1,renderModeOpen:!1,interactionModeOpen:t})}}),F.jsx(zd,{name:"cameraHelper",icon:WI,selected:this.cameraVisibility,height:24,top:2,onClick:t=>{if(this.cameraVisibility=t,this.saveExpandedCameraVisibility(),this.cameraHelpers.forEach(s=>{s.visible=t}),this.selectedItem!==void 0&&!t){const s=this.cameraHelpers.get(this.selectedItem.name);s!==void 0&&(s.visible=!0)}}}),F.jsx(zd,{name:"lightHelper",icon:HI,selected:this.lightVisibility,height:24,top:4,onClick:t=>{if(this.lightVisibility=t,this.saveExpandedLightVisibility(),this.lightHelpers.forEach(s=>{s.visible=t}),this.selectedItem!==void 0&&!t&&this.selectedItem.isLight===!0){const s=this.lightHelpers.get(this.selectedItem.name);s!==void 0&&(s.visible=!0)}}}),F.jsx(zd,{name:"gridHelper",icon:jI,selected:this.gridVisibility,height:21,width:21,onClick:t=>{this.setGridVisibility(t)}})]},this.state.lastUpdate)]})}setupRenderer=e=>{this.renderer&&this.renderer.dispose(),this.rendererReady=!1;const t=this.canvasRef.current;this.props.three.canvas=t;const s=e.value;s.type==="WebGLRenderer"?(this.renderer=new _.WebGLRenderer({canvas:t,stencil:!1}),this.depthMaterial=new _.MeshDepthMaterial,this.normalsMaterial=new _.MeshNormalMaterial,this.uvMaterial=new XS,this.grid=new WS,this.scene.add(this.grid),this.rendererReady=!0):s.type==="WebGPURenderer"&&(this.renderer=new Rd({canvas:t,stencil:!1}),this.grid=new jS,this.scene.add(this.grid)),this.renderer&&(this.renderer.autoClear=!1,this.renderer.shadowMap.enabled=!0,this.renderer.setClearColor(0),this.renderer.setPixelRatio(devicePixelRatio),this.renderer.setScissorTest(!0),this.resize(),this.props.three.renderer=this.renderer,this.depthMaterial=new qS,this.normalsMaterial=new oT,this.uvMaterial=new YS,s.type==="WebGPURenderer"&&this.renderer.init().then(()=>{this.rendererReady=!0})),this.props.three.requestScene()};setupScene(){this.helpersContainer.name="helpers",this.scene.add(this.helpersContainer),this.interactionHelper.name="interactionHelper",this.interactionHelper.visible=!1,this.helpersContainer.add(this.interactionHelper);const e=(n,a)=>{const o=new _.OrthographicCamera(-100,100,100,-100,0,3e3);return o.name=n,o.position.copy(a),o.lookAt(0,0,0),this.cameras.set(n,o),o},t=1e3;e("Top",new _.Vector3(0,t,0)),e("Bottom",new _.Vector3(0,-t,0)),e("Left",new _.Vector3(-t,0,0)),e("Right",new _.Vector3(t,0,0)),e("Front",new _.Vector3(0,0,t)),e("Back",new _.Vector3(0,0,-t)),e("Orthographic",new _.Vector3(t,t,t)),e("UI",new _.Vector3),this.debugCamera=new _.PerspectiveCamera(60,1,.01,3e3),this.debugCamera.name="Debug",this.debugCamera.position.set(300,300,300),this.debugCamera.lookAt(0,0,0),this.cameras.set("Debug",this.debugCamera),this.currentCamera=this.debugCamera;const s=localStorage,i=this.props.three.name;this.tlCam=this.cameras.get(s.getItem(`${i}_tlCam`)),this.trCam=this.cameras.get(s.getItem(`${i}_trCam`)),this.blCam=this.cameras.get(s.getItem(`${i}_blCam`)),this.brCam=this.cameras.get(s.getItem(`${i}_brCam`)),this.tlCam===void 0&&(this.tlCam=this.cameras.get("Debug")),this.trCam===void 0&&(this.trCam=this.cameras.get("Orthographic")),this.blCam===void 0&&(this.blCam=this.cameras.get("Front")),this.brCam===void 0&&(this.brCam=this.cameras.get("Top")),Ce.addEditorGroup({title:"Editor",items:[{type:"button",prop:"Hide All Transforms"},{type:"button",prop:"Resize"}],onUpdate:(n,a)=>{switch(n){case"Hide All Transforms":bt.instance.hide();break;case"Resize":this.resize();break}},subgroups:[{title:"Debug Camera",items:[{type:"range",prop:"Near",step:1e-4,min:.001,max:1e3,value:this.debugCamera.near},{type:"range",prop:"Far",step:.001,min:.001,max:1e4,value:this.debugCamera.far}],onUpdate:(n,a)=>{switch(n){case"Near":this.debugCamera.near=a,this.debugCamera.updateProjectionMatrix();break;case"Far":this.debugCamera.far=a,this.debugCamera.updateProjectionMatrix();break}}},{title:"Grid",items:[{type:"number",prop:"Position",value:0},{type:"color",prop:"Color",value:"#FFFFFF"},{type:"range",prop:"Grid Opacity",value:.25,min:0,max:1,step:.01},{type:"range",prop:"Subgrid Opacity",value:.15,min:0,max:1,step:.01}],onUpdate:(n,a)=>{switch(n){case"Position":this.grid&&(this.grid.position.y=a);break;case"Color":this.grid&&this.grid.color.setStyle(a);break;case"Grid Opacity":this.grid&&(this.grid.gridOpacity=a);break;case"Subgrid Opacity":this.grid&&(this.grid.subgridOpacity=a);break}}}]})}setupTools(){this.splineEditor=new ZS(this.currentCamera,this.three),this.splineEditor.initDebug(),this.helpersContainer.add(this.splineEditor)}play(){this.playing=!0,this.onUpdate()}pause(){this.playing=!1,cancelAnimationFrame(this.rafID),this.rafID=-1}toggleOrbitControls(e){this.controls.forEach(t=>{t.enabled=!e})}clear(){this.three.dispatchEvent({type:me.CLEAR_OBJECT}),Ce.removeAllGroups(),this.clearLightHelpers(),this.clearControls(),this.currentTransform!==void 0&&(this.currentTransform.removeEventListener("objectChange",this.onUpdateTransform),bt.instance.remove(this.currentTransform.getHelper().name)),this.currentTransform=void 0,bt.instance.clear(),this.cameras.forEach(e=>{this.editorCameras.indexOf(e.name)<0&&this.three.dispatchEvent({type:me.REMOVE_CAMERA,value:e})}),this.currentCamera=this.debugCamera,this.currentScene=void 0,this.scenes.forEach(e=>{this.three.dispatchEvent({type:me.REMOVE_SCENE,value:e})}),this.scenes.clear()}setGridVisibility(e){this.gridVisibility=e,this.saveExpandedGridVisibility(),this.grid&&(this.grid.visible=e)}update(){this.renderer&&this.rendererReady&&this.renderer?.clear(),this.controls.forEach(e=>e.update()),this.cameraHelpers.forEach(e=>e.update()),this.lightHelpers.forEach(e=>{e.update!==void 0&&e.update()}),this.props.onSceneUpdate!==void 0&&this.currentScene!==void 0&&this.props.onSceneUpdate(this.currentScene)}draw(){if(this.rendererReady)switch(this.renderer&&this.renderer?.clear(),this.state.mode){case"Single":this.drawSingle();break;case"Side by Side":case"Stacked":this.drawDouble();break;case"Quad":this.drawQuad();break}}onUpdate=()=>{this.playing&&(this.update(),this.draw(),this.rafID=requestAnimationFrame(this.onUpdate))};enable(){const e=this.containerRef.current;e.addEventListener("mousemove",this.onMouseMove),e.addEventListener("click",this.onClick),window.addEventListener("keydown",this.onKey),window.addEventListener("resize",this.resize),this.three.addEventListener(me.ADD_SCENE,this.addScene),this.three.addEventListener(me.SET_SCENE,this.sceneUpdate),this.three.addEventListener(me.REMOVE_SCENE,this.removeScene),this.three.addEventListener(me.ADD_CAMERA,this.addCamera),this.three.addEventListener(me.REMOVE_CAMERA,this.removeCamera),this.three.addEventListener(me.SET_OBJECT,this.onSetSelectedItem)}disable(){const e=this.containerRef.current;e.removeEventListener("mousemove",this.onMouseMove),e.removeEventListener("click",this.onClick),window.removeEventListener("keydown",this.onKey),window.removeEventListener("resize",this.resize),this.three.removeEventListener(me.ADD_SCENE,this.addScene),this.three.removeEventListener(me.SET_SCENE,this.sceneUpdate),this.three.removeEventListener(me.ADD_CAMERA,this.addCamera),this.three.removeEventListener(me.REMOVE_CAMERA,this.removeCamera),this.three.removeEventListener(me.SET_OBJECT,this.onSetSelectedItem)}resize=()=>{this.width=window.innerWidth-300,this.height=window.innerHeight,this.renderer?.setSize(this.width,this.height);const e=Math.floor(this.width/2),t=Math.floor(this.height/2);this.props.three.resize(this.width,this.height),this.props.onSceneResize!==void 0&&this.currentScene!==void 0&&this.props.onSceneResize(this.currentScene,this.width,this.height);let s=this.width,i=this.height;switch(this.state.mode){case"Side by Side":s=e,i=this.height;break;case"Stacked":s=this.width,i=t;break;case"Quad":s=e,i=t;break}const n=s/i;this.cameras.forEach(a=>{a instanceof _.OrthographicCamera?(a.left=s/-2,a.right=s/2,a.top=i/2,a.bottom=i/-2,a.name==="UI"&&(a.position.x=this.width/2,a.position.y=this.height/-2,a.position.z=100),a.updateProjectionMatrix()):a instanceof _.PerspectiveCamera&&(a.aspect=n,a.updateProjectionMatrix()),this.cameraHelpers.get(a.name)?.update()})};addScene=e=>{const t=this.props.scenes.get(e.value.name);if(t!==void 0){const s=new t;s.visible=!1,this.props.onSceneAdd!==void 0&&this.props.onSceneAdd(s),this.props.three.scene=s,this.scenes.set(e.value.name,s),this.scene.add(s)}else console.log("Hermes - Scene not found:",e.value.name,this.props.scenes)};sceneUpdate=e=>{this.currentScene!==void 0&&(this.currentScene.visible=!1,this.clearLightHelpers());const t=this.scene.getObjectByName(e.value.name);t!==void 0&&(this.currentScene=t,this.currentScene.visible=!0,this.addLightHelpers(this.currentScene))};removeScene=e=>{const t=e.value.name;this.scenes.delete(t);const s=this.scene.getObjectByName(t);s&&setTimeout(()=>{Ri(s)},100),this.clearLightHelpers()};addCamera=e=>{const t=e.value,s=t.uuid,i=this.props.three.scene?.getObjectByProperty("uuid",t.uuid);if(i!==void 0){const n=i;this.cameras.set(s,n);const a=new _.CameraHelper(n);a.visible=this.cameraVisibility,this.cameraHelpers.set(s,a),this.helpersContainer.add(a),this.setState({lastUpdate:Date.now()})}};removeCamera=e=>{const s=e.value.uuid,i=this.cameraHelpers.get(s);i!==void 0&&(this.helpersContainer.remove(i),i.dispose()),this.cameras.delete(s),this.setState({lastUpdate:Date.now()})};onMouseMove=e=>{const t=new _.Vector2;this.renderer?.getSize(t);const s=Math.min(e.clientX,t.x),i=Math.min(e.clientY,t.y);this.pointer.x=Dr(s,0,t.x,-1,1),this.pointer.y=Dr(i,0,t.y,1,-1);const n=t.x/2,a=t.y/2,o=()=>{s<n?this.pointer.x=Dr(s,0,n,-1,1):this.pointer.x=Dr(s,n,t.x,-1,1)},l=()=>{i<a?this.pointer.y=Dr(i,0,a,1,-1):this.pointer.y=Dr(i,a,t.y,1,-1)};switch(this.state.mode){case"Quad":o(),l();break;case"Side by Side":o();break;case"Stacked":l(),l();break}if(this.updateCamera(s,i,n,a),this.state.interactionMode==="Orbit"||this.currentScene===void 0)return;const c=this.raycaster.intersectObjects(this.currentScene.children);c.length>0&&this.interactionHelper.position.copy(c[0].point)};onClick=e=>{if(this.state.interactionMode==="Orbit"||this.currentScene===void 0)return;const t=new _.Vector2;if(this.renderer.getSize(t),e.clientX>=t.x)return;this.onMouseMove(e);const s=this.raycaster.intersectObjects(this.currentScene.children);s.length>0&&(this.props.three.getObject(s[0].object.uuid),this.interactionHelper.visible=!1,this.setState({interactionMode:"Orbit",lastUpdate:Date.now()}))};onKey=e=>{if(this.selectedItem!==void 0){if(e.ctrlKey){if(this.currentCamera.name==="UI")return;const t=this.controls.get(this.currentCamera.name);e.key==="0"?(e.preventDefault(),this.clearControls(),this.cameraControls=new gi(this.currentCamera,this.currentWindow.current),this.selectedItem instanceof _.Mesh||this.selectedItem instanceof _.SkinnedMesh?(this.selectedItem.geometry.computeBoundingBox(),this.cameraControls.fitToBox(this.selectedItem.geometry.boundingBox,!0)):this.cameraControls.fitToSphere(this.selectedItem,!0),this.updateCameraControls(t,!0)):e.key==="1"?(e.preventDefault(),this.clearControls(),this.cameraControls=new gi(this.currentCamera,this.currentWindow.current),this.cameraControls.rotateTo(0,Math.PI*.5,!0),this.cameraControls.moveTo(this.selectedItem.position.x,this.selectedItem.position.y,0,!0),this.updateCameraControls(t)):e.key==="2"?(e.preventDefault(),this.clearControls(),this.cameraControls=new gi(this.currentCamera,this.currentWindow.current),this.cameraControls.rotateTo(0,0,!0),this.cameraControls.moveTo(this.selectedItem.position.x,0,this.selectedItem.position.z,!0),this.updateCameraControls(t)):e.key==="3"?(e.preventDefault(),this.clearControls(),this.cameraControls=new gi(this.currentCamera,this.currentWindow.current),this.cameraControls.rotateTo(Math.PI/2,Math.PI/2,!0),this.cameraControls.moveTo(0,this.selectedItem.position.y,this.selectedItem.position.z,!0),this.updateCameraControls(t)):e.key==="4"?(e.preventDefault(),this.clearControls(),this.cameraControls=new gi(this.currentCamera,this.currentWindow.current),this.cameraControls.rotateTo(Math.PI,Math.PI/2,!0),this.cameraControls.moveTo(this.selectedItem.position.x,this.selectedItem.position.y,0,!0),this.updateCameraControls(t)):e.key==="5"&&(e.preventDefault(),this.clearControls(),this.cameraControls=new gi(this.currentCamera,this.currentWindow.current),this.cameraControls.rotateTo(Yd(45),Yd(45),!0),this.updateCameraControls(t))}else if(this.currentTransform!==void 0)switch(e.key){case"r":this.currentTransform.setMode("rotate");break;case"s":this.currentTransform.setMode("scale");break;case"t":this.currentTransform.setMode("translate");break;case"q":this.currentTransform.setSpace(this.currentTransform.space==="local"?"world":"local");break}}};onSetSelectedItem=e=>{this.selectedItem!==void 0&&this.updateSelectedItemHelper(!1),this.selectedItem=void 0;const t=e.value.uuid;if(this.scenes.forEach(s=>{t.search(s.uuid)>-1&&(this.selectedItem=s.getObjectByProperty("uuid",t))}),this.selectedItem===void 0){console.log(`Hermes - Can't find selected item: ${e.value.uuid}, ${e.value.name}`);return}this.currentTransform!==void 0&&(this.currentTransform.removeEventListener("objectChange",this.onUpdateTransform),bt.instance.remove(this.currentTransform.getHelper().name)),this.currentTransform=bt.instance.add(e.value.name),this.currentTransform&&(this.currentTransform.attach(this.selectedItem),this.helpersContainer.add(this.currentTransform.getHelper()),this.currentTransform.addEventListener("objectChange",this.onUpdateTransform)),this.updateSelectedItemHelper(!0)};updateSelectedItemHelper(e){if(this.selectedItem!==void 0)if(this.cameraVisibility){if(this.selectedItem.isLight===!0&&!this.lightVisibility){const t=this.lightHelpers.get(this.selectedItem.name);t!==void 0&&(t.visible=e)}}else{const t=this.cameraHelpers.get(this.selectedItem.name);t!==void 0&&(t.visible=e)}}onUpdateTransform=()=>{this.selectedItem!==void 0&&(this.props.three.updateObject(this.selectedItem.uuid,"position",this.selectedItem.position),this.props.three.updateObject(this.selectedItem.uuid,"rotation",{x:this.selectedItem.rotation.x,y:this.selectedItem.rotation.y,z:this.selectedItem.rotation.z}),this.props.three.updateObject(this.selectedItem.uuid,"scale",this.selectedItem.scale),yh.instance.update())};clearLightHelpers=()=>{this.lightHelpers.forEach(e=>{this.helpersContainer.remove(e),e.dispose()}),this.lightHelpers.clear()};addLightHelpers=e=>{e.traverse(t=>{if(t.type.search("Light")>-1){let s;switch(t.type){case"DirectionalLight":s=new _.DirectionalLightHelper(t,100),s.name=`${t.name}Helper`,s.visible=this.lightVisibility,this.lightHelpers.set(t.name,s),this.helpersContainer.add(s);break;case"HemisphereLight":s=new _.HemisphereLightHelper(t,250),s.name=`${t.name}Helper`,s.visible=this.lightVisibility,this.lightHelpers.set(t.name,s),this.helpersContainer.add(s);break;case"RectAreaLight":s=new JL(t),s.name=`${t.name}Helper`,s.visible=this.lightVisibility,this.lightHelpers.set(t.name,s),this.helpersContainer.add(s);break;case"PointLight":s=new _.PointLightHelper(t,100),s.name=`${t.name}Helper`,s.visible=this.lightVisibility,this.lightHelpers.set(t.name,s),this.helpersContainer.add(s);break;case"SpotLight":s=new _.SpotLightHelper(t),s.name=`${t.name}Helper`,s.visible=this.lightVisibility,this.lightHelpers.set(t.name,s),this.helpersContainer.add(s);break}}})};createControls(e,t){const s=this.controls.get(e.name);if(s!==void 0&&s.dispose(),this.controls.delete(e.name),e.name==="UI")return;const i=new tI(e,t);switch(i.enableDamping=!0,i.dampingFactor=.1,e.name){case"Top":case"Bottom":case"Left":case"Right":case"Front":case"Back":i.enableRotate=!1;break}this.controls.set(e.name,i)}clearCamera(e){const t=this.cameraHelpers.get(e.name);t!==void 0&&(this.helpersContainer.remove(t),t.dispose(),this.cameraHelpers.delete(e.name));const s=this.controls.get(e.name);s!==void 0&&(s.dispose(),this.controls.delete(e.name))}killControls(){this.controls.forEach((e,t)=>{e.dispose();const s=this.cameraHelpers.get(t);s!==void 0&&(this.helpersContainer.remove(s),s.dispose()),this.cameraHelpers.delete(t),this.controls.delete(t)}),this.controls.clear(),this.cameraHelpers.clear()}assignControls(){switch(this.state.mode){case"Single":this.createControls(this.tlCam,this.tlWindow.current);break;case"Side by Side":case"Stacked":this.createControls(this.tlCam,this.tlWindow.current),this.createControls(this.trCam,this.trWindow.current);break;case"Quad":this.createControls(this.tlCam,this.tlWindow.current),this.createControls(this.trCam,this.trWindow.current),this.createControls(this.blCam,this.blWindow.current),this.createControls(this.brCam,this.brWindow.current);break}}updateCamera=(e,t,s,i)=>{switch(this.state.mode){case"Quad":t<i?e<s?this.currentCamera=this.tlCam:this.currentCamera=this.trCam:e<s?this.currentCamera=this.blCam:this.currentCamera=this.brCam;break;case"Side by Side":e<s?this.currentCamera=this.tlCam:this.currentCamera=this.trCam;break;case"Single":this.currentCamera=this.tlCam;break;case"Stacked":t<i?this.currentCamera=this.tlCam:this.currentCamera=this.trCam;break}this.splineEditor.camera=this.currentCamera,this.raycaster.setFromCamera(this.pointer,this.currentCamera),this.currentCamera===this.tlCam?this.currentWindow=this.tlWindow:this.currentCamera===this.trCam?this.currentWindow=this.trWindow:this.currentCamera===this.blCam?this.currentWindow=this.blWindow:this.currentCamera===this.brCam&&(this.currentWindow=this.brWindow),bt.instance.updateCamera(this.currentCamera,this.currentWindow.current)};updateCameraControls=(e,t=!1)=>{if(this.selectedItem===void 0)return;cancelAnimationFrame(this.cameraControlsRafID),this.cameraControlsRafID=-1,this.cameraControls&&(this.cameraControls.smoothTime=.1);const s=.15,i=new _.Clock;i.start(),this.selectedItem.getWorldPosition(e.target0);const n=()=>{const a=i.getDelta();this.cameraControls&&this.cameraControls.update(a),t&&(e.target.lerp(e.target0,s),e.object.position.lerp(e.position0,s),e.object.zoom=Ma(e.object.zoom,e.zoom0,s),e.object.updateProjectionMatrix(),e.dispatchEvent({type:"change"})),i.getElapsedTime()>=.5?(cancelAnimationFrame(this.cameraControlsRafID),this.cameraControlsRafID=-1,this.clearControls()):this.cameraControlsRafID=requestAnimationFrame(n)};n()};clearControls=()=>{this.cameraControls!==void 0&&(this.cameraControls.disconnect(),this.cameraControls.dispose(),this.cameraControls=void 0)};saveExpandedCameraVisibility(){localStorage.setItem(this.expandedCameraVisibility,this.cameraVisibility?"open":"closed")}saveExpandedLightVisibility(){localStorage.setItem(this.expandedLightVisibility,this.lightVisibility?"open":"closed")}saveExpandedGridVisibility(){localStorage.setItem(this.expandedGridVisibility,this.gridVisibility?"open":"closed")}getSceneOverride(e){switch(e){case"Depth":return this.depthMaterial;case"Normals":return this.normalsMaterial;case"Renderer":return null;case"UVs":return this.uvMaterial;case"Wireframe":return this.wireframeMaterial}return null}drawTo(e,t,s,i,n,a){switch(n.name){case"Left":case"Right":this.grid&&(this.grid.rotation.z=Math.PI/2);break;case"Front":case"Back":this.grid&&(this.grid.rotation.x=Math.PI/2);break}this.scene.overrideMaterial=a,this.renderer&&(this.renderer?.setScissor(e,t,s,i),this.renderer?.setViewport(e,t,s,i),this.renderer?.render(this.scene,n)),this.grid&&this.grid.rotation.set(0,0,0)}drawSingle(){const e=this.getSceneOverride(this.tlRender);this.drawTo(0,0,this.width,this.height,this.tlCam,e)}drawDouble=()=>{const e=this.getSceneOverride(this.tlRender),t=this.getSceneOverride(this.trRender),s=Math.floor(this.width/2),i=Math.floor(this.height/2),n=this.renderer instanceof Rd;if(this.state.mode==="Side by Side")this.drawTo(0,0,s,this.height,this.tlCam,e),this.drawTo(s,0,s,this.height,this.trCam,t);else{const a=this.height-i;n?(this.drawTo(0,0,this.width,i,this.tlCam,e),this.drawTo(0,a,this.width,i,this.trCam,t)):(this.drawTo(0,a,this.width,i,this.tlCam,e),this.drawTo(0,0,this.width,i,this.trCam,t))}};drawQuad=()=>{const e=this.renderer instanceof Rd,t=this.getSceneOverride(this.tlRender),s=this.getSceneOverride(this.trRender),i=this.getSceneOverride(this.blRender),n=this.getSceneOverride(this.brRender),a=Math.floor(this.width/2),o=Math.floor(this.height/2),l=this.height-o;let c=0,u=e?0:this.height-o;c=0,this.drawTo(c,u,a,o,this.tlCam,t),c=a,this.drawTo(c,u,a,o,this.trCam,s),u=e?l:0,c=0,this.scene.overrideMaterial=i,this.drawTo(c,u,a,o,this.blCam,i),c=a,this.drawTo(c,u,a,o,this.brCam,n)};get appID(){return this.props.three.name}get mode(){return this.state.mode}get three(){return this.props.three}get expandedCameraVisibility(){return`${this.appID}_multiviewCameraVisibility`}get expandedLightVisibility(){return`${this.appID}_multiviewLightVisibility`}get expandedGridVisibility(){return`${this.appID}_multiviewGridVisibility`}}class yh extends X.Component{static instance;matrix=new _.Matrix4;position=new _.Vector3;rotation=new _.Euler;scale=new _.Vector3;open=!1;constructor(e){super(e);const t=localStorage.getItem(this.expandedName),s=t!==null?t==="open":!1;this.open=s,this.saveExpanded(),this.state={lastUpdated:0,expanded:s},this.matrix.elements=e.object.matrix,e.object.uuid.length>0&&(this.position.setFromMatrixPosition(this.matrix),this.rotation.setFromRotationMatrix(this.matrix),this.scale.setFromMatrixScale(this.matrix)),yh.instance=this}update(){if(mt.instance){const e=mt.instance.selectedItem;if(e===void 0)return;this.position.x=As(e.position.x,3),this.position.y=As(e.position.y,3),this.position.z=As(e.position.z,3),this.rotation.copy(e.rotation),this.scale.x=As(e.scale.x,3),this.scale.y=As(e.scale.y,3),this.scale.z=As(e.scale.z,3),this.setState({lastUpdated:Date.now()})}}render(){return F.jsx(Os,{three:this.props.three,title:"Transform",expanded:this.open,items:[{title:"Position",prop:"position",type:"grid3",step:.1,value:this.position,onChange:this.updateTransform},{title:"Rotation",prop:"rotation",type:"euler",value:this.rotation,onChange:this.updateTransform},{title:"Scale",prop:"scale",type:"grid3",value:this.scale,onChange:this.updateTransform},{title:"Visible",prop:"visible",type:"boolean",value:this.props.object.visible,onChange:this.updateTransform}],onToggle:e=>{this.open=e,this.saveExpanded()}},this.state.lastUpdated)}updateTransform=(e,t)=>{const s=e==="rotation"?{x:t._x,y:t._y,z:t._z}:t;this.props.three.updateObject(this.props.object.uuid,e,s);const i=this.props.three.getScene(this.props.object.uuid);if(i){const n=i.getObjectByProperty("uuid",this.props.object.uuid);ut(n,e,s)}};saveExpanded(){localStorage.setItem(this.expandedName,this.open?"open":"closed")}get expandedName(){return`${this.props.three.name}_transform`}}function nx(r){switch(r){case"color":return"Color";case"intensity":return"Intensity";case"decay":return"Decay";case"distance":return"Distance";case"angle":return"Angle";case"penumbra":return"Penumbra";case"groundColor":return"Ground Color";case"width":return"Width";case"height":return"Height"}return r}function qI(r,e){function t(){return`${e.name}_light`}const s=localStorage.getItem(t()),i=s!==null?s==="open":!1;function n(o){localStorage.setItem(t(),o?"open":"closed")}const a=[];if(r.lightInfo!==void 0)for(const o in r.lightInfo){const l=r.lightInfo[o];l!==void 0&&(l.isColor!==void 0?a.push({title:nx(o),prop:o,type:"color",value:l,onChange:(c,u)=>{const h=new _.Color(u);e.updateObject(r.uuid,c,h);const d=e.getScene(r.uuid);if(d!==null){const p=d.getObjectByProperty("uuid",r.uuid);ut(p,c,h)}}}):a.push({title:nx(o),prop:o,type:typeof l,value:l,step:typeof l=="number"?.01:void 0,onChange:(c,u)=>{e.updateObject(r.uuid,c,u);const h=e.getScene(r.uuid);if(h!==null){const d=h.getObjectByProperty("uuid",r.uuid);ut(d,c,u)}}}))}return F.jsx(Os,{three:e,title:"Light",items:a,expanded:i,onToggle:o=>{n(o)}})}function XI(r){const e=r.object,t=r.three;function s(){return`${t.name}_animation`}const i=localStorage.getItem(s()),n=i!==null?i==="open":!1;function a(d){localStorage.setItem(s(),d?"open":"closed")}const o=[],l=[];let c=0;e.animations.forEach(d=>{c=Math.max(c,d.duration),d.duration>0&&l.push({title:d.name,items:[{title:"Duration",type:"number",value:d.duration,disabled:!0},{title:"Blend Mode",type:"option",disabled:!0,options:[{title:"Normal",value:2500},{title:"Additive",value:2501}]}]})}),o.push({title:"Animations",items:l});let u;const h=t.getScene(e.uuid);if(h!==null){const d=h.getObjectByProperty("uuid",e.uuid);if(d!==void 0){const p=d.mixer;if(p!==void 0){const m=[{title:"Time Scale",type:"range",value:p.timeScale,step:.01,min:-1,max:2,onChange:(x,y)=>{p.timeScale=y,t.updateObject(e.uuid,"mixer.timeScale",y)}}];m.push({title:"Stop All",type:"button",onChange:()=>{p.stopAllAction(),t.requestMethod(e.uuid,"stopAllAction",void 0,"mixer")}}),o.push({title:"Mixer",items:m}),u=new _.SkeletonHelper(d),mt.instance?.scene.add(u)}}}return X.useEffect(()=>()=>{u!==void 0&&Ri(u)},[]),F.jsx(Os,{three:r.three,title:"Animation",items:o,expanded:n,onToggle:d=>{a(d)}})}const Hd={name:"",uuid:"",type:"",visible:!1,matrix:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],animations:[],material:void 0,perspectiveCameraInfo:void 0,orthographicCameraInfo:void 0,lightInfo:void 0,children:[]};function QS(r){const[e,t]=X.useState(Hd);X.useEffect(()=>{function a(l){t(l.value)}function o(){t(Hd)}return r.three.addEventListener(me.CLEAR_OBJECT,o),r.three.addEventListener(me.SET_SCENE,o),r.three.addEventListener(me.SET_OBJECT,a),()=>{r.three.removeEventListener(me.CLEAR_OBJECT,o),r.three.removeEventListener(me.SET_SCENE,o),r.three.removeEventListener(me.SET_OBJECT,a)}},[]);const s=e.type.toLowerCase(),i=e.animations.length>0||e.mixer!==void 0,n=s.search("mesh")>-1||s.search("line")>-1||s.search("points")>-1;return n&&console.log(s,e),F.jsx(fa,{three:r.three,label:"Inspector",button:e.uuid.length>0?F.jsx("button",{className:"remove",onClick:()=>{bt.instance.remove(e.name),t(Hd)}}):void 0,children:F.jsx("div",{id:"Inspector",className:r.class,children:e.uuid.length>0&&F.jsxs(F.Fragment,{children:[F.jsxs(F.Fragment,{children:[F.jsx(yc,{type:"string",title:"Name",prop:"name",value:e.name,disabled:!0}),F.jsx(yc,{type:"string",title:"Type",prop:"type",value:e.type,disabled:!0}),F.jsx(yc,{type:"string",title:"UUID",prop:"uuid",value:e.uuid,disabled:!0})]}),F.jsxs(F.Fragment,{children:[F.jsx(yh,{object:e,three:r.three}),i?F.jsx(XI,{object:e,three:r.three}):null,s.search("camera")>-1?LM(e,r.three):null,s.search("light")>-1?qI(e,r.three):null,n?BM(e,r.three):null]})]})})},"Inspector")}class YI extends X.Component{autoClear=!0;autoClearColor=!0;autoClearDepth=!0;autoClearStencil=!0;outputColorSpace=_.SRGBColorSpace;localClippingEnabled=!1;clearColor=new _.Color(0);clearAlpha=1;toneMapping=_.NoToneMapping;toneMappingExposure=1;type="";constructor(e){super(e);const t=localStorage.getItem(this.expandedName),s=t!==null?t==="open":!1;if(this.state={expanded:s,lastUpdated:Date.now()},this.saveExpanded(s),mt.instance){const i=mt.instance.renderer;i&&(this.autoClear=i.autoClear,this.autoClearColor=i.autoClearColor,this.autoClearDepth=i.autoClearDepth,this.autoClearStencil=i.autoClearStencil,this.clearAlpha=i.getClearAlpha(),this.toneMapping=i.toneMapping,this.toneMappingExposure=i.toneMappingExposure,i instanceof _.WebGLRenderer&&(this.localClippingEnabled=i.localClippingEnabled,i.getClearColor(this.clearColor)))}this.props.three.addEventListener(me.ADD_RENDERER,this.onAddRenderer)}componentwillunmount(){this.props.three.removeEventListener(me.ADD_RENDERER,this.onAddRenderer)}onAddRenderer=e=>{const t=e.value;if(this.autoClear=t.autoClear,this.autoClearColor=t.autoClearColor,this.autoClearDepth=t.autoClearDepth,this.autoClearStencil=t.autoClearStencil,this.outputColorSpace=t.outputColorSpace,this.localClippingEnabled=t.localClippingEnabled,this.clearAlpha=t.clearAlpha,this.type=t.type,this.toneMapping=t.toneMapping,this.toneMappingExposure=t.toneMappingExposure,this.clearColor.setStyle(t.clearColor,_.LinearSRGBColorSpace),_.ColorManagement.enabled=t.colorManagement,mt.instance){const s=mt.instance.renderer;s&&(s.autoClearColor=this.autoClearColor,s.outputColorSpace=this.outputColorSpace,s instanceof _.WebGLRenderer&&(s.localClippingEnabled=this.localClippingEnabled),s.toneMapping=this.toneMapping,s.toneMappingExposure=this.toneMappingExposure,s.setClearColor(t.clearColor,this.clearAlpha))}this.setState({lastUpdated:Date.now()})};render(){const e=()=>{if(mt.instance){const t=mt.instance.renderer;t&&(t.autoClearColor=this.autoClearColor,t.outputColorSpace=this.outputColorSpace,t instanceof _.WebGLRenderer&&(t.localClippingEnabled=this.localClippingEnabled),t.toneMapping=this.toneMapping,t.toneMappingExposure=this.toneMappingExposure,t.setClearColor(this.clearColor.getStyle(),this.clearAlpha),this.props.three.updateRenderer({autoClear:this.autoClear,autoClearColor:this.autoClearColor,autoClearDepth:this.autoClearDepth,autoClearStencil:this.autoClearStencil,outputColorSpace:this.outputColorSpace,localClippingEnabled:this.localClippingEnabled,clearAlpha:this.clearAlpha,clearColor:this.clearColor.getStyle(),colorManagement:_.ColorManagement.enabled,toneMapping:this.toneMapping,toneMappingExposure:this.toneMappingExposure}))}};return F.jsx(Os,{three:this.props.three,title:"Renderer",expanded:this.state.expanded,items:[{type:"boolean",title:"Auto Clear",value:this.autoClear,onChange:(t,s)=>{this.autoClear=s}},{type:"boolean",title:"Auto Clear Color",value:this.autoClearColor,onChange:(t,s)=>{this.autoClearColor=s,e()}},{type:"boolean",title:"Auto Clear Depth",value:this.autoClearDepth,onChange:(t,s)=>{this.autoClearDepth=s,e()}},{type:"boolean",title:"Auto Clear Stencil",value:this.autoClearStencil,onChange:(t,s)=>{this.autoClearStencil=s,e()}},{type:"boolean",title:"Local Clipping",value:this.localClippingEnabled,onChange:(t,s)=>{this.localClippingEnabled=s,e()}},{type:"color",title:"Clear Color",value:`#${this.clearColor.getHexString()}`,onChange:(t,s)=>{this.clearColor.setStyle(s),e()}},{type:"range",title:"Clear Alpha",min:0,max:1,step:.01,value:this.clearAlpha,onChange:(t,s)=>{this.clearAlpha=s,e()}},{type:"boolean",title:"Color Management",value:_.ColorManagement.enabled,onChange:(t,s)=>{_.ColorManagement.enabled=s,e()}},{type:"option",title:"Color Space",value:this.outputColorSpace,options:[{title:"No Color Space",value:_.NoColorSpace},{title:"SRB Color Space",value:_.SRGBColorSpace},{title:"Linear SRB Color Space",value:_.LinearSRGBColorSpace}],onChange:(t,s)=>{this.outputColorSpace=s,e()}},{type:"option",title:"Tone Mapping",value:this.toneMapping,options:[{title:"None ",value:_.NoToneMapping},{title:"Linear ",value:_.LinearToneMapping},{title:"Reinhard",value:_.ReinhardToneMapping},{title:"Cineon ",value:_.CineonToneMapping},{title:"ACES Filmic",value:_.ACESFilmicToneMapping},{title:"AgX",value:_.AgXToneMapping},{title:"Neutral",value:_.NeutralToneMapping},{title:"Custom",value:_.CustomToneMapping}],onChange:(t,s)=>{this.toneMapping=s,e()}},{type:"range",title:"Tone Mapping Exposure",value:this.toneMappingExposure,min:0,max:2,step:.01,onChange:(t,s)=>{this.toneMappingExposure=s,e()}},{type:"string",title:"Type",value:this.type,disabled:!0},{type:"button",title:"Resize Scenes from Source",onChange:()=>{this.props.three.requestSize()}}],onToggle:t=>{this.setState({expanded:t}),this.saveExpanded(t)}},Math.random())}saveExpanded(e){localStorage.setItem(this.expandedName,e?"open":"closed")}get expandedName(){return`${this.props.three.name}_renderer`}}function KS(r){const[e]=X.useState([]),[t]=X.useState([]),[s,i]=X.useState(0),n=c=>{const u=c.value;e.push(u),t.push(F.jsx(fa,{three:r.three,label:`Scene: ${u.name}`,scene:u,open:!1,visible:!1,onRefresh:()=>{r.three.refreshScene(u.name)},children:F.jsx(gc,{child:u,scene:u,three:r.three})},u.name)),i(Date.now())},a=c=>{const u=c.value;for(let h=0;h<e.length;h++)if(u.uuid===e[h].uuid){e[h]=u,t[h]=F.jsx(fa,{three:r.three,label:`Scene: ${u.name}`,scene:u,open:t[h].props.open,visible:t[h].props.visible,onRefresh:()=>{r.three.refreshScene(u.name)},children:F.jsx(gc,{child:u,scene:u,three:r.three})},u.name),i(Date.now());return}},o=c=>{const u=c.value;for(let h=0;h<e.length;h++)if(u.uuid===e[h].uuid){e.splice(h,1),t.splice(h,1),i(Date.now());return}},l=c=>{const u=c.value.name;for(let h=0;h<e.length;h++){const d=e[h],p=d.name===u;t[h]=F.jsx(fa,{three:r.three,label:`Scene: ${d.name}`,scene:d,open:p,visible:p,onRefresh:()=>{r.three.refreshScene(d.name)},children:F.jsx(gc,{child:d,scene:d,three:r.three})},d.name)}i(Date.now())};return X.useEffect(()=>(r.three.addEventListener(me.ADD_SCENE,n),r.three.addEventListener(me.SET_SCENE,l),r.three.addEventListener(me.REFRESH_SCENE,a),r.three.addEventListener(me.REMOVE_SCENE,o),()=>{r.three.removeEventListener(me.ADD_SCENE,n),r.three.removeEventListener(me.SET_SCENE,l),r.three.removeEventListener(me.REFRESH_SCENE,a),r.three.removeEventListener(me.REMOVE_SCENE,o)}),[]),F.jsxs("div",{id:"SidePanel",children:[F.jsx("div",{className:"scenes",children:t},s),F.jsx(QS,{three:r.three}),F.jsx(YI,{three:r.three}),F.jsx(Ce,{three:r.three})]})}function JS(r){return F.jsxs("div",{className:"editor",ref:r.ref,style:r.style,children:[F.jsx("div",{className:"header",children:r.header}),r.children,F.jsx("div",{className:"footer",children:r.footer})]})}function ZI(r){return F.jsx(JS,{children:F.jsxs(F.Fragment,{children:[F.jsx(mt,{three:r.three,scenes:r.scenes,onSceneAdd:r.onSceneAdd,onSceneResize:r.onSceneResize,onSceneUpdate:r.onSceneUpdate}),F.jsx(KS,{three:r.three})]})})}exports.Accordion=fa;exports.Application=sM;exports.BaseRemote=Dp;exports.ChildObject=Lp;exports.ContainerObject=gc;exports.DepthNodeMaterial=qS;exports.Draggable=xx;exports.DraggableItem=yx;exports.Dropdown=_x;exports.DropdownItem=bx;exports.Editor=JS;exports.ElementProxy=eM;exports.ElementProxyReceiver=mx;exports.ExportTexture=Hi;exports.InfiniteGridHelper=WS;exports.InfiniteGridHelperGPU=jS;exports.InfiniteGridMaterial=$S;exports.InfiniteGridNodeMaterial=HS;exports.Inspector=QS;exports.MultiView=mt;exports.NavButton=Op;exports.ProxyManager=tM;exports.RemoteTheatre=rM;exports.RemoteThree=hM;exports.SidePanel=KS;exports.Spline=wc;exports.SplineEditor=ZS;exports.ThreeEditor=ZI;exports.Transform=bt;exports.UVMaterial=XS;exports.UVNodeMaterial=YS;exports.WebworkerEventHandlers=Kv;exports.anchorGeometry=px;exports.anchorGeometryTL=Fv;exports.animateObjectMaterial=Ev;exports.animateObjectTransform=Cv;exports.applyObjectMaterial=dx;exports.capitalize=Uo;exports.clamp=_n;exports.clearComposerGroups=$v;exports.colorToHex=jd;exports.copyToClipboard=rx;exports.createMask=Lv;exports.cubicBezier=Sv;exports.customizeTheatreElements=wv;exports.damp=gv;exports.defaultTheatreCallback=lv;exports.detectMaxFrameRate=lx;exports.detectSettings=cx;exports.dispose=Ri;exports.disposeMaterial=Fp;exports.disposeTexture=qd;exports.distance=mv;exports.generateCubemap=Wv;exports.getAngle=yv;exports.getObjectMaterialObject=hx;exports.getObjectMaterialProps=ux;exports.hierarchyUUID=ca;exports.inspectComposer=Gv;exports.inspectComposerPass=fx;exports.isColor=ax;exports.map=fv;exports.mix=Ma;exports.noop=Io;exports.normalize=Cc;exports.orthoCamera=Nv;exports.parseModelLite=Rv;exports.randomID=Tt;exports.renderToTexture=Pv;exports.resetThreeObjects=mo;exports.rgbaToHex=vv;exports.roundTo=As;exports.setMaterialBlendAdd=Vv;exports.setMaterialBlendMultiply=kv;exports.setMaterialBlendNormal=Uv;exports.setMaterialBlendScreen=zv;exports.supportsOffscreenCanvas=Ov;exports.triangle=Cu;exports.updateCameraOrtho=Bv;exports.updateCameraOrtho16x9=Dv;exports.useMask=Iv;exports.useStudio=Mv;
143
+ }`;class gi extends d.ShaderMaterial{constructor(){super({defines:{USE_UV:""},uniforms:{opacity:{value:1}},vertexShader:_n,fragmentShader:Cn,transparent:!0})}}class vi extends Yt{constructor(){super(),this.colorNode=T.vec4(T.uv(),0,1)}}class G extends d.EventDispatcher{static DRAG_START="Transform::dragStart";static DRAG_END="Transform::dragEnd";static _instance;three;activeCamera;controls=new Map;visibility=new Map;setApp(e){this.three=e,this.three.addEventListener(I.SET_SCENE,this.setScene)}clear(){for(const e of this.controls.values()){e.detach(),e.disconnect();const t=e.getHelper();ne(t)}this.controls=new Map,this.visibility=new Map}add(e){let t=this.controls.get(e);if(t===void 0){const s=document.querySelector(".clickable");t=new zi.TransformControls(this.activeCamera,s),t.getHelper().name=e,t.setSize(.5),t.setSpace("local"),this.controls.set(e,t),this.visibility.set(e,!0),t.addEventListener("mouseDown",()=>{this.dispatchEvent({type:G.DRAG_START})}),t.addEventListener("mouseUp",()=>{this.dispatchEvent({type:G.DRAG_END})}),t.addEventListener("dragging-changed",n=>{V.instance?.toggleOrbitControls(n.value)})}return t}get(e){return this.controls.get(e)}remove(e){const t=this.get(e);return t===void 0?!1:(t.detach(),t.disconnect(),ne(t.getHelper()),this.controls.delete(e),!0)}enabled(e){this.controls.forEach(t=>{t.enabled=e})}updateCamera(e,t){this.activeCamera=e,this.controls.forEach(s=>{s.camera!==e&&(s.camera=e,e.getWorldPosition(s.cameraPosition),e.getWorldQuaternion(s.cameraQuaternion)),s.domElement!==t&&(s.disconnect(),s.domElement=t,s.connect(t))})}show(){this.controls.forEach(e=>{const t=e.getHelper(),s=this.visibility.get(t.name);s!==void 0&&(t.visible=s)})}hide(){this.controls.forEach(e=>{const t=e.getHelper();this.visibility.set(t.name,t.visible),t.visible=!1})}setScene=()=>{this.clear()};static get instance(){return G._instance||(G._instance=new G),G._instance}}const yn=new d.BoxGeometry,mt=new d.Vector2;class qe extends d.Object3D{curve=new d.CatmullRomCurve3;line;draggable;curvePos;tension=.5;closed=!1;subdivide=50;curveType;offset=1;lineMaterial;_camera;_curvePercentage=0;_draggableScale=10;_transform;raycaster;draggedMat=new d.MeshBasicMaterial;parentGroup;group;constructor(e,t){const s=new d.Color(Z.lerp(.5,1,Math.random()),Z.lerp(.5,1,Math.random()),Z.lerp(.5,1,Math.random()));super(),this.name=e,this.lineMaterial=new d.LineBasicMaterial({color:s}),this.line=new d.Line(new d.BufferGeometry,this.lineMaterial),this.line.name="line",this.line.visible=!1,this.add(this.line),this._camera=t,this.curveType="catmullrom",this.draggedMat.color=s,this.draggable=new d.Object3D,this.draggable.name="draggablePoints",this.add(this.draggable),this.curvePos=new d.Mesh(new d.SphereGeometry(1.5),new d.MeshBasicMaterial({color:s})),this.curvePos.name="curvePos",this.curvePos.scale.setScalar(this._draggableScale),this.curvePos.visible=!1,this.add(this.curvePos),this.raycaster=new d.Raycaster,this.raycaster.params.Line.threshold=3,this.enable()}enable(){document.addEventListener("pointerdown",this.onMouseClick)}disable(){document.removeEventListener("pointerdown",this.onMouseClick)}dispose=()=>{this._transform&&(this._transform.removeEventListener("objectChange",this.updateSpline),G.instance.remove(this.name)),this.disable(),this.parentGroup.removeGroup(this.name)};hideTransform=()=>{this._transform?.detach()};exportSpline=()=>{const e=[];this.draggable.children.forEach(t=>{e.push([K(t.position.x,3),K(t.position.y,3),K(t.position.z,3)])}),Zt({name:this.name,points:e,tension:this.tension,closed:this.closed,subdivide:this.subdivide,type:this.curveType}),console.log("Spline copied!")};showPoints=(e=!0)=>{this.draggable.visible=e};addPoints=(e=[])=>{if(e.length>0){const t=e.length-1;for(let s=0;s<t;s++)this.addPoint(e[s],!1);this.addPoint(e[t])}};addPoint=(e,t=!0)=>{const s=this.draggable.children.length,n=new d.Mesh(yn,this.draggedMat);n.name=`point_${s}`,n.position.copy(e),n.scale.setScalar(this._draggableScale),this.draggable.add(n),this._transform?.attach(n);const a=this.points.length>1;return a&&t&&this.updateSpline(),this.line.visible=a,this.updateCurrentPoint(),n};addNextPt=()=>{const e=this.draggable.children.length,t=e>1?this.draggable.children[e-1].position.clone():new d.Vector3,s=this.addPoint(t);this.updateField(s.position)};removePoint=e=>{if(this._transform?.object===e){this._transform?.detach();const t=this.draggable.children[this.draggable.children.length-1];this._transform?.attach(t),this.updateField(t.position)}ne(e),this.updateSpline()};removePointAt=e=>{const t=this.draggable.children[e];this.removePoint(t)};removeSelectedPt=()=>{this._transform?.object!==void 0&&this.removePoint(this._transform?.object)};updateLastPoint(e){const t=this.draggable.children.length;t>0&&(this.draggable.children[t-1].position.copy(e),this.updateSpline())}updateSpline=()=>{this.points.length<2||(this.curve=new d.CatmullRomCurve3(this.points,this.closed,this.curveType,this.tension),this.line.geometry.dispose(),this.line.geometry=new d.BufferGeometry().setFromPoints(this.curve.getPoints(this.subdivide)),this.curvePos.position.copy(this.getPointAt(this._curvePercentage)))};updateField(e){this.group.current?.setField("Current Point",e)}onMouseClick=e=>{if(!V.instance||!V.instance.currentWindow||this._transform&&!this._transform.getHelper().visible)return;const s=V.instance.currentWindow.current.getBoundingClientRect();mt.x=(e.clientX-s.x)/s.width*2-1,mt.y=-((e.clientY-s.y)/s.height)*2+1,this.raycaster.setFromCamera(mt,this.camera);const n=this.raycaster.intersectObjects(this.draggable.children,!1);if(n.length>0){const a=n[0].object;a!==this._transform?.object&&(this._transform?.attach(a),this.updateField(a.position))}};getPointAt(e){return this.curve.points.length>1?this.curve.getPointAt(e):this.curve.points.length===1?this.curve.points[0]:new d.Vector3}getTangentAt(e){return this.curve.getTangentAt(e)}get points(){const e=[];return this.draggable.children.forEach(t=>{e.push(t.position)}),e}get total(){return this.draggable.children.length}get draggableScale(){return this._draggableScale}set draggableScale(e){this._draggableScale=e,this.draggable.children.forEach(t=>t.scale.setScalar(e)),this.curvePos.scale.setScalar(e)}get camera(){return this._camera}set camera(e){this._camera=e,this._transform!==void 0&&(this._transform.camera=e)}get curvePercentage(){return this._curvePercentage}set curvePercentage(e){this._curvePercentage=e,this.curvePos.position.copy(this.getPointAt(e))}updateCurrentPoint(){if(this._transform?.object&&this.group){const e=this._transform?.object;e.name.search("point")>-1&&this.updateField(e.position)}}onUpdateTransform=()=>{this.updateCurrentPoint(),this.updateSpline()};initDebug(e,t){const s=this.draggable.children;this.visible=t,this.parentGroup=e,this._transform=G.instance.add(this.name),this._transform.camera=this._camera,this._transform.addEventListener("objectChange",this.onUpdateTransform),s.length>0&&this._transform.attach(s[s.length-1]),V.instance?.helpersContainer.add(this._transform.getHelper());const n=s.length>0?s[s.length-1].position:{x:0,y:0,z:0};this.group=e.addGroup({title:this.name,expanded:t,items:[{prop:"Closed",type:"boolean",value:this.closed},{prop:"Visible",type:"boolean",value:this.visible},{prop:"Show Position",type:"boolean",value:this.curvePos.visible},{prop:"Show Points",type:"boolean",value:this.draggable.visible},{prop:"Color",type:"color",value:`#${this.draggedMat.color.getHexString()}`},{prop:"Curve",type:"option",options:[{title:"Catmullrom",value:"catmullrom"},{title:"Centripetal",value:"centripetal"},{title:"Chordal",value:"chordal"}]},{prop:"Draggable Scale",type:"range",min:.01,max:100,step:.01,value:this._draggableScale},{prop:"Subdivide",type:"range",min:1,max:1e3,step:1,value:this.subdivide},{prop:"Tension",type:"range",min:0,max:1,step:.01,value:this.tension},{prop:"New Pt Offset",type:"range",min:0,max:10,value:this.offset},{prop:"Curve At",type:"range",min:0,max:1,step:.01,value:0},{prop:"Toggle Transform",type:"button"},{prop:"Add Point",type:"button"},{prop:"Remove Point",type:"button"},{prop:"Export",type:"button"},{prop:"Delete",type:"button"},{prop:"Current Point",type:"grid3",value:n}],onUpdate:(a,r)=>{switch(a){case"Closed":this.closed=r,this.updateSpline();break;case"Visible":this.visible=r;break;case"Color":this.lineMaterial.color.setStyle(r),this.draggedMat.color.setStyle(r);break;case"Curve":this.curveType=r,this.updateSpline();break;case"Draggable Scale":this.draggableScale=r;break;case"Subdivide":this.subdivide=r,this.updateSpline();break;case"Tension":this.tension=r,this.updateSpline();break;case"New Pt Offset":this.offset=r;break;case"Curve At":this.curvePos.position.copy(this.getPointAt(r));break;case"Show Position":this.curvePos.visible=r;break;case"Show Points":this.draggable.visible=r;break;case"Toggle Transform":this._transform&&(this._transform.getHelper().visible=!this._transform.getHelper().visible);break;case"Add Point":this.addNextPt();break;case"Remove Point":this.removeSelectedPt();break;case"Export":this.exportSpline();break;case"Delete":this.parent.currentSpline=null,ne(this);break;case"Current Point":if(this.group.current&&this._transform?.object){const o=this._transform?.object;o.name.search("point")>-1&&(o.position.copy(r),this.updateSpline())}break}}}),this.draggable.children.forEach(a=>{this.debugPoint(a)})}debugPoint=e=>{e.name,e.visible=this.draggable.visible}}let We=0;class _i extends d.Object3D{defaultScale=10;currentSpline=null;_camera;group=null;three;splineDataText="";constructor(e,t){super(),this.name="Spline Editor",this._camera=e,this.three=t,this.three.addEventListener(I.ADD_SPLINE,this.onAddSpline)}initDebug(){this.group=U.addEditorGroup({title:this.name,items:[{type:"field",prop:"Spline Data",value:"",disabled:!1},{type:"button",prop:"Import Spline"},{type:"button",prop:"New Spline"},{type:"boolean",prop:"Show Points",value:!0},{type:"boolean",prop:"Draw Mode",value:!1},{type:"boolean",prop:"Visible",value:this.visible},{type:"range",prop:"Default Scale",min:0,max:50,step:.01,value:this.defaultScale}],onUpdate:(e,t)=>{switch(e){case"New Spline":this.createSpline();break;case"Spline Data":this.splineDataText=t;break;case"Import Spline":this.createSplineFromJSON(JSON.parse(this.splineDataText));break;case"Show Points":this.showPoints(t);break;case"Visible":this.visible=t;break;case"Default Scale":this.defaultScale=t;break;case"Draw Mode":t?this.enableClickToDraw():this.disableClickToDraw();break}}})}dispose(){this.three.removeEventListener(I.ADD_SPLINE,this.onAddSpline),U.removeEditorGroup(this.name)}addSpline(e,t){e.draggableScale=this.defaultScale,e.hideTransform(),this.group?.current!==null&&e.initDebug(this.group.current,t),this.add(e),this.currentSpline=e}createSpline=(e=[])=>{const t=`Spline ${We+1}`,s=new qe(t,this._camera);return s.addPoints(e),this.addSpline(s,!0),We++,s};createSplineFromArray=e=>{const t=[];return e.forEach(s=>{t.push(new d.Vector3(s[0],s[1],s[2]))}),this.createSpline(t)};createSplineFromCatmullRom=e=>this.createSpline(e.points);createSplineFromJSON=e=>{const t=[];e.points.forEach(n=>{t.push(new d.Vector3(n[0],n[1],n[2]))});const s=new qe(e.name,this._camera);return s.closed=e.closed,s.subdivide=e.subdivide,s.tension=e.tension,s.type=e.type,s.addPoints(t),s.updateSpline(),this.addSpline(s,!1),s};showPoints=(e=!0)=>{this.children.forEach(t=>{t.showPoints(e)})};onAddSpline=e=>{const t=JSON.parse(e.value),s=t.name!==void 0?t.name:`Spline ${We+1}`,n=new qe(s,this.camera);t.tension!==void 0&&(n.tension=t.tension),t.closed!==void 0&&(n.closed=t.closed),t.subdivide!==void 0&&(n.subdivide=t.subdivide),t.type!==void 0&&(n.curveType=t.type);const a=[];t.points.forEach(r=>{a.push(new d.Vector3(r[0],r[1],r[2]))}),n.addPoints(a),this.addSpline(n,!1),We++};isMouseDown=!1;enableClickToDraw(){document.querySelectorAll(".clickable").forEach(e=>{e.addEventListener("mousedown",this.onClickCanvas),e.addEventListener("mousemove",this.onMouseMove),e.addEventListener("mouseup",this.onMouseUp)})}disableClickToDraw(){document.querySelectorAll(".clickable").forEach(e=>{e.removeEventListener("mousedown",this.onClickCanvas),e.removeEventListener("mousemove",this.onMouseMove),e.removeEventListener("mouseup",this.onMouseUp)})}onClickCanvas=e=>{if(e.button!==0)return;if(this._camera.type!=="OrthographicCamera"){console.warn("Spline Editor - 3D Camera not supported in Draw Mode");return}const s=e.target.getBoundingClientRect(),n=(e.clientX-s.left)/s.width*2-1,a=-((e.clientY-s.top)/s.height)*2+1;if(V.instance){const o=new d.Raycaster;o.setFromCamera(new d.Vector2(n,a),this._camera);const c=o.intersectObjects(V.instance.helpersContainer.children,!0);for(let l=0;l<c.length;l++){const h=c[l];if(!(h.object.isLine||h.object.isTransformControlsPlane)&&h.object.isObject3D)return}}this.currentSpline===null&&(this.currentSpline=this.createSpline());const r=this.mouseToSplinePos(n,a,s.width,s.height);this.currentSpline?.addPoint(r),this.isMouseDown=!0};onMouseMove=e=>{if(!this.isMouseDown)return;const s=e.target.getBoundingClientRect(),n=(e.clientX-s.left)/s.width*2-1,a=-((e.clientY-s.top)/s.height)*2+1,r=this.mouseToSplinePos(n,a,s.width,s.height);this.currentSpline?.updateLastPoint(r),this.currentSpline?.updateField(r)};onMouseUp=()=>{this.isMouseDown=!1};mouseToSplinePos(e,t,s,n){const a=new d.Vector3,r=Math.PI/2,o=this._camera,c=o.zoom,l=o.rotation.x===-6123233995736766e-32&&o.rotation.y===0&&o.rotation.z===0,h=o.rotation.x===-Math.PI&&o.rotation.y===12246467991473532e-32&&o.rotation.z===Math.PI,p=o.rotation.x===-6162975822039155e-48&&o.rotation.y===-r&&o.rotation.z===0,m=o.rotation.x===-6162975822039155e-48&&o.rotation.y===r&&o.rotation.z===0,g=o.rotation.x===-1.5707953264174506&&o.rotation.y===0&&o.rotation.z===0,y=o.rotation.x===1.5707953264174506&&o.rotation.y===0&&o.rotation.z===0;let _=e,E=t;h||m?_*=-1:g&&(E*=-1);const v=s/2/c,C=n/2/c;if(this.currentSpline===null&&(this.currentSpline=this.createSpline()),l||h){const x=_*v+o.position.x,O=E*C+o.position.y;a.set(x,O,0)}else if(p||m){const x=_*v+o.position.z,O=E*C+o.position.y;a.set(0,O,x)}else if(g||y){const x=_*v+o.position.x,O=E*C+o.position.z;a.set(x,0,O)}return a}get camera(){return this._camera}set camera(e){this._camera=e,this.children.forEach(t=>{const s=t;s.camera=e})}}const Gt=["Single","Side by Side","Stacked","Quad"],bn="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAACXBIWXMAAAsTAAALEwEAmpwYAAAC60lEQVRYhe2YT4hNcRTHP48xpmYaNAvRyEQxEhnKQljYsRm9/EmSyJiMFAsMZWNhJYoNIUVJ2VGiyb9ZzIpMpkQSahbGv9GMYWrM+1rc2zjvzvvdd+99rzdvMd+6de75nd+5387vnN/v/G5KEuWMKRNNIB8mCRaKiiL5qQb2ApuBuUAV0Ad0AJeB3sSeJRX6LJbULTf6JTUn9Z+KWMUpPyp/Avoa4CNQZ3Sj/lNpdL/xottR7AjOkHRUUpekN5I6JbVLavDH75lIfZN0UFKTpCWS0pJem/HeJBEMG6yV1ONYtgFJbZJ+GF1jDh+zJb03NuliEuwMkMo4yErS2RA/LcbuYVyCrm1mA7Dal/8Cu4FG4JD/HsTTkCy6a+SVMTPQuc1sBKb78nHghi+/A+YBxwL2lbhRY+ThuARdEVxu5JdGFvACr0otdoZ8Y4+Rn0Sn5sFFsMvI6YB9MzA1YJ8mN8k1wAHzfj4uQVdyrpI0aJL7oqTtkq4FiqPLyCOSbktqlbRL0jlJQ2b8QdwCUZ4qvhRStZL0XFK1pMd57CRvq5mfhKBriRfiFUMY6oD7eOdwPlQAN4G10dfWg+uouwXsiOssAj4AC+JMcEWwvnAuOTEr7gTXPmg34zagOwkbIIOXAo9CbDYBrcBXYN+4UUdy2sRflyS5zVNlfPX7ugpJW5V9nI7mmh+lYU0lCZ2B3TOnAVuAk0BTwC5nuhWro46KauBOQJch5OpRaoIW34GreGf+YZdRqS9NAj4Bp4ClQDvwOWxCqSM4ADQEdKE5XvbXzlITrAVe4TW+M6NMKDXBFLAMuAD0ACfIc7pMZBXXA2cY3/xmodQRHAL2A2+NLtj8ZiEKwUL/z2WMPAJcAVYALWSf8dZuDFGWeBHwKxm3sWYhiGG8Tfo6sA2vSfiSy4GrH3wGrDcfKSSKKf6v1E9yF0XK9Q1XBPuMXMw8HXTonQFwETwNzMFr64v1jzgFHIk9ybHEZYPJo65QlD3Bf2/Q/eaHPiSWAAAAAElFTkSuQmCC",En="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAACXBIWXMAAAsTAAALEwEAmpwYAAAETklEQVRYhe2YXYhVVRTHf3d0/JhyUrMpFbImM+whSa3Mynww+4AeIgiKoozooQ+KyMyXIAujF6OXqHyI6iEKKYgIP/owsjSFqCkprdDUTEcjbWZ0HHV+Pex1ucfb9Z57Z9REXHA4Z++99l7/s/ZZ/7X2KaiczNLwfwPIk9MA+yunNMAG4DHgV+BvoB3YFff2TPstYEyfrajVroI6Sr1GvahsbJC63HzZq04pmztSvU5tVRuqYRiYg78JeBR4HPg5ntdmxovz9wJfA3uAxuibDLQCA+IqynnAQuBuYCnwMLC1rx48U12U8cZqdWqMDcx4cI16qTpYbVKHqa+ovWUeHKsujn7VL9ULq2HI+wY7gVeBJdGeFu3J4ZUiy/cAXeHRRuAQsC/GC0B3eG4BcH/0tUV7czUAeVsMsBF4Kha9HZgCvAncAuwPnXHA0wFuGLANuDrGuoGDwFxgTqzzQ7RX5FrP2eLsdb76vnogtme6+nE8H1YPlQXHwbi3q9eqn0e7Tb25VrsF68vFY0lb1AGcDTwItGQ8tQM4AIwGmqP/EPAu8A0wElgJfFGzxTo8mKWXu9Rd4ZF96jvqjSbauEC9Sn1O3R463epLaku99voCsFXdkAH3kNpcQW+IiT/bQne3eufxBtioPqP2mKhioXpWzpxb1T8C5Ifh4ZptVoriRmAIKdrI3Lujf3bobAPeJpF0NVkKrAFuI9HTOBIxnxFrF4OgQKKr/dnJlQA+AcwABgOHA4zAamA5cE7orQL+zAEHiWI+A2bFC7aSguheYCgpqAphZz3wSB7AecCICv2TgH8oFRib4gVqka0k0h8CXAxMBW6ooDejFoCvA9OBQUAvKWM0kDz4XUZvNKXtyZMWUl7vBbaQXq457PeEziDgx/KJlQAuIPFdMcEXv5OdYWBP9M8k8VpnDQCvB4aTSrCNJB5cSdrW3tBpIJVnR0qdUTxAfdGUOVTnmwqEanNmqltC/9OgqePKg5eom8PgdvW+oJ9Kupera0O3U50TL3lcAaI+oHaF4R3qa6Z822wq0Saq89T1lmSxOrxeW/Xm4uGkiqQDmECKuKHxHW0HdpMiewSpvGqKeR8Ay0iBsYIjg6261PE2o9Q3Yqv+MqWxO9R1Hl12qs+q49Vlppy82pSr+5xJKsko4AXgHlJ0t5NIeg3wLXAlqZhtIUV8J6nmWwX8QiLjdhL5TwMWkY4R6/rrwYKlMr1Y321QZ/vfwBijPqm+rF4Wc7PjE9QllurGVeoV5gRNHsAm9fnMom3qrKPoTjKdMXaYyrFygEWQ72XWW24qhPu8xcUc2UU6O8wFPjmK7jhgPHAuMJGUGQ6U6WwE5sfzTXGvei7KA9hFOiR9D/wOfFVFt4dS2tpfRe83Ur7/CPiJakfOGgBCypubatArl2r8VfOax/LfzABKtePAzHO/5FgC7KBEzB2kOrDfUm8mOeFySv9+OyFyGmB/5aQH+C9BVKmVCNuMZgAAAABJRU5ErkJggg==",Sn="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAYAAACpF6WWAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAQ0lEQVQ4jWP8////fwYqAxYozUhFM/8zkaKYWIWkGEq0b0ZdSjQY5i79TyWagRGaTUdzFEEw6lLqGzqwLoVVJ1StpwA9sBwbUqAh5gAAAABJRU5ErkJggg==";class V extends b.Component{static instance=null;scene;renderer;currentScene;scenes=new Map;cameras=new Map;controls=new Map;currentCamera;currentWindow;helpersContainer=new d.Group;grid;cameraHelpers=new Map;lightHelpers=new Map;interactionHelper=new d.AxesHelper(25);currentTransform;splineEditor;depthMaterial;normalsMaterial;uvMaterial;wireframeMaterial=new d.MeshBasicMaterial({opacity:.33,transparent:!0,wireframe:!0});playing=!1;rafID=-1;cameraControlsRafID=-1;width=0;height=0;tlCam=null;trCam=null;blCam=null;brCam=null;tlRender="Renderer";trRender="Renderer";blRender="Renderer";brRender="Renderer";cameraVisibility=!0;lightVisibility=!0;gridVisibility=!0;rendererReady=!1;selectedItem=void 0;debugCamera;raycaster=new d.Raycaster;pointer=new d.Vector2;cameraControls=void 0;canvasRef;containerRef;tlWindow;trWindow;blWindow;brWindow;editorCameras=["Top","Bottom","Left","Right","Front","Back","Orthographic","UI","Debug"];constructor(e){super(e),this.props.three.addEventListener(I.ADD_RENDERER,this.setupRenderer),this.scene=new d.Scene,this.scene.name=this.scene.uuid="",this.canvasRef=b.createRef(),this.containerRef=b.createRef(),this.tlWindow=b.createRef(),this.trWindow=b.createRef(),this.blWindow=b.createRef(),this.brWindow=b.createRef();const t=e.three.name,s=localStorage,n=s.getItem(`${t}_mode`);this.state={mode:n!==null?n:"Single",modeOpen:!1,renderModeOpen:!1,interactionMode:"Orbit",interactionModeOpen:!1,lastUpdate:Date.now()},s.setItem(`${t}_mode`,this.state.mode),s.setItem(`${t}_tlCam`,s.getItem(`${t}_tlCam`)!==null?s.getItem(`${t}_tlCam`):"Debug"),s.setItem(`${t}_trCam`,s.getItem(`${t}_trCam`)!==null?s.getItem(`${t}_trCam`):"Orthographic"),s.setItem(`${t}_blCam`,s.getItem(`${t}_blCam`)!==null?s.getItem(`${t}_blCam`):"Front"),s.setItem(`${t}_brCam`,s.getItem(`${t}_brCam`)!==null?s.getItem(`${t}_brCam`):"Top"),s.setItem(`${t}_tlRender`,s.getItem(`${t}_tlRender`)!==null?s.getItem(`${t}_tlRender`):"Renderer"),s.setItem(`${t}_trRender`,s.getItem(`${t}_trRender`)!==null?s.getItem(`${t}_trRender`):"Renderer"),s.setItem(`${t}_blRender`,s.getItem(`${t}_blRender`)!==null?s.getItem(`${t}_blRender`):"Renderer"),s.setItem(`${t}_brRender`,s.getItem(`${t}_brRender`)!==null?s.getItem(`${t}_brRender`):"Renderer");const a={Vector2:d.Vector2,Vector3:d.Vector3,Vector4:d.Vector4,Quaternion:d.Quaternion,Matrix4:d.Matrix4,Spherical:d.Spherical,Box3:d.Box3,Sphere:d.Sphere,Raycaster:d.Raycaster};se.install({THREE:a}),this.setupScene(),this.setupTools();const r=localStorage.getItem(this.expandedCameraVisibility);r!==null&&(this.cameraVisibility=r==="open"),this.saveExpandedCameraVisibility();const o=localStorage.getItem(this.expandedLightVisibility);o!==null&&(this.lightVisibility=o==="open"),this.saveExpandedLightVisibility();const c=localStorage.getItem(this.expandedGridVisibility);c!==null&&(this.gridVisibility=c==="open"),this.grid&&(this.grid.visible=this.gridVisibility),this.saveExpandedGridVisibility(),V.instance=this}componentDidMount(){this.enable(),this.assignControls(),this.resize(),this.play(),G.instance.setApp(this.props.three),G.instance.activeCamera=this.debugCamera,this.props.three.requestRenderer()}componentDidUpdate(e,t,s){t.mode!==this.state.mode&&(this.assignControls(),this.resize())}componentWillUnmount(){this.disable(),this.clear(),U.removeEditorGroup("View Settings")}render(){const e=[];return this.cameras.forEach((t,s)=>{e.push(s)}),u.jsxs("div",{className:"multiview",children:[u.jsx("canvas",{ref:this.canvasRef}),u.jsxs("div",{className:`cameras ${this.state.mode==="Single"||this.state.mode==="Stacked"?"single":""}`,ref:this.containerRef,children:[this.state.mode==="Single"&&u.jsx(u.Fragment,{children:u.jsx(fe,{name:"tl",camera:this.tlCam,options:e,ref:this.tlWindow,onSelectCamera:t=>{this.controls.get(this.tlCam.name)?.dispose();const s=this.cameras.get(t);s!==void 0&&(this.clearCamera(this.tlCam),this.tlCam=s,localStorage.setItem(`${this.appID}_tlCam`,s.name),this.createControls(s,this.tlWindow.current))},onSelectRenderMode:t=>{this.tlRender=t,localStorage.setItem(`${this.appID}_tlRender`,t)}})}),(this.state.mode==="Side by Side"||this.state.mode==="Stacked")&&u.jsxs(u.Fragment,{children:[u.jsx(fe,{name:"tl",camera:this.tlCam,options:e,ref:this.tlWindow,onSelectCamera:t=>{this.controls.get(this.tlCam.name)?.dispose();const s=this.cameras.get(t);s!==void 0&&(this.clearCamera(this.tlCam),this.tlCam=s,localStorage.setItem(`${this.appID}_tlCam`,s.name),this.createControls(s,this.tlWindow.current))},onSelectRenderMode:t=>{this.tlRender=t,localStorage.setItem(`${this.appID}_tlRender`,t)}}),u.jsx(fe,{name:"tr",camera:this.trCam,options:e,ref:this.trWindow,onSelectCamera:t=>{this.controls.get(this.trCam.name)?.dispose();const s=this.cameras.get(t);s!==void 0&&(this.clearCamera(this.trCam),this.trCam=s,localStorage.setItem(`${this.appID}_trCam`,s.name),this.createControls(s,this.trWindow.current))},onSelectRenderMode:t=>{this.trRender=t,localStorage.setItem(`${this.appID}_trRender`,t)}})]}),this.state.mode==="Quad"&&u.jsxs(u.Fragment,{children:[u.jsx(fe,{name:"tl",camera:this.tlCam,options:e,ref:this.tlWindow,onSelectCamera:t=>{this.controls.get(this.tlCam.name)?.dispose();const s=this.cameras.get(t);s!==void 0&&(this.clearCamera(this.tlCam),this.tlCam=s,localStorage.setItem(`${this.appID}_tlCam`,s.name),this.createControls(s,this.tlWindow.current))},onSelectRenderMode:t=>{this.tlRender=t,localStorage.setItem(`${this.appID}_tlRender`,t)}}),u.jsx(fe,{name:"tr",camera:this.trCam,options:e,ref:this.trWindow,onSelectCamera:t=>{this.controls.get(this.trCam.name)?.dispose();const s=this.cameras.get(t);s!==void 0&&(this.clearCamera(this.trCam),this.trCam=s,localStorage.setItem(`${this.appID}_trCam`,s.name),this.createControls(s,this.trWindow.current))},onSelectRenderMode:t=>{this.trRender=t,localStorage.setItem(`${this.appID}_trRender`,t)}}),u.jsx(fe,{name:"bl",camera:this.blCam,options:e,ref:this.blWindow,onSelectCamera:t=>{this.controls.get(this.blCam.name)?.dispose();const s=this.cameras.get(t);s!==void 0&&(this.clearCamera(this.blCam),this.blCam=s,localStorage.setItem(`${this.appID}_blCam`,s.name),this.createControls(s,this.blWindow.current))},onSelectRenderMode:t=>{this.blRender=t,localStorage.setItem(`${this.appID}_blRender`,t)}}),u.jsx(fe,{name:"br",camera:this.brCam,options:e,ref:this.brWindow,onSelectCamera:t=>{this.controls.get(this.brCam.name)?.dispose();const s=this.cameras.get(t);s!==void 0&&(this.clearCamera(this.brCam),this.brCam=s,localStorage.setItem(`${this.appID}_brCam`,s.name),this.createControls(s,this.brWindow.current))},onSelectRenderMode:t=>{this.brRender=t,localStorage.setItem(`${this.appID}_brRender`,t)}})]})]}),u.jsxs("div",{className:"settings",children:[u.jsx(Ke,{title:"View",index:Gt.indexOf(this.state.mode),options:Gt,onSelect:t=>{t!==this.state.mode&&(this.killControls(),this.setState({mode:t}),localStorage.setItem(`${this.appID}_mode`,t))},open:this.state.modeOpen,onToggle:t=>{this.setState({modeOpen:t,renderModeOpen:!1,interactionModeOpen:!1})}}),u.jsx(Ke,{title:"Interact",index:this.state.interactionMode==="Orbit"?0:1,options:["Orbit Mode","Selection Mode"],onSelect:t=>{this.interactionHelper.visible=t==="Selection Mode",this.setState({interactionMode:this.interactionHelper.visible?"Selection":"Orbit"})},open:this.state.interactionModeOpen,onToggle:t=>{this.setState({modeOpen:!1,renderModeOpen:!1,interactionModeOpen:t})}}),u.jsx(pt,{name:"cameraHelper",icon:bn,selected:this.cameraVisibility,height:24,top:2,onClick:t=>{if(this.cameraVisibility=t,this.saveExpandedCameraVisibility(),this.cameraHelpers.forEach(s=>{s.visible=t}),this.selectedItem!==void 0&&!t){const s=this.cameraHelpers.get(this.selectedItem.name);s!==void 0&&(s.visible=!0)}}}),u.jsx(pt,{name:"lightHelper",icon:En,selected:this.lightVisibility,height:24,top:4,onClick:t=>{if(this.lightVisibility=t,this.saveExpandedLightVisibility(),this.lightHelpers.forEach(s=>{s.visible=t}),this.selectedItem!==void 0&&!t&&this.selectedItem.isLight===!0){const s=this.lightHelpers.get(this.selectedItem.name);s!==void 0&&(s.visible=!0)}}}),u.jsx(pt,{name:"gridHelper",icon:Sn,selected:this.gridVisibility,height:21,width:21,onClick:t=>{this.setGridVisibility(t)}})]},this.state.lastUpdate)]})}setupRenderer=e=>{this.renderer&&this.renderer.dispose(),this.rendererReady=!1;const t=this.canvasRef.current;this.props.three.canvas=t;const s=e.value;s.type==="WebGLRenderer"?(this.renderer=new d.WebGLRenderer({canvas:t,stencil:!1}),this.depthMaterial=new d.MeshDepthMaterial,this.normalsMaterial=new d.MeshNormalMaterial,this.uvMaterial=new gi,this.grid=new ui,this.scene.add(this.grid),this.rendererReady=!0):s.type==="WebGPURenderer"&&(this.renderer=new tt({canvas:t,stencil:!1}),this.grid=new mi,this.scene.add(this.grid)),this.renderer&&(this.renderer.autoClear=!1,this.renderer.shadowMap.enabled=!0,this.renderer.setClearColor(0),this.renderer.setPixelRatio(devicePixelRatio),this.renderer.setScissorTest(!0),this.resize(),this.props.three.renderer=this.renderer,this.depthMaterial=new fi,this.normalsMaterial=new Ui,this.uvMaterial=new vi,s.type==="WebGPURenderer"?this.renderer.init().then(()=>{this.rendererReady=!0,this.props.three.requestScene()}):this.props.three.requestScene())};setupScene(){this.helpersContainer.name="helpers",this.scene.add(this.helpersContainer),this.interactionHelper.name="interactionHelper",this.interactionHelper.visible=!1,this.helpersContainer.add(this.interactionHelper);const e=(a,r)=>{const o=new d.OrthographicCamera(-100,100,100,-100,0,3e3);return o.name=a,o.position.copy(r),o.lookAt(0,0,0),this.cameras.set(a,o),o},t=1e3;e("Top",new d.Vector3(0,t,0)),e("Bottom",new d.Vector3(0,-t,0)),e("Left",new d.Vector3(-t,0,0)),e("Right",new d.Vector3(t,0,0)),e("Front",new d.Vector3(0,0,t)),e("Back",new d.Vector3(0,0,-t)),e("Orthographic",new d.Vector3(t,t,t)),e("UI",new d.Vector3),this.debugCamera=new d.PerspectiveCamera(60,1,.01,3e3),this.debugCamera.name="Debug",this.debugCamera.position.set(300,300,300),this.debugCamera.lookAt(0,0,0),this.cameras.set("Debug",this.debugCamera),this.currentCamera=this.debugCamera;const s=localStorage,n=this.props.three.name;this.tlCam=this.cameras.get(s.getItem(`${n}_tlCam`)),this.trCam=this.cameras.get(s.getItem(`${n}_trCam`)),this.blCam=this.cameras.get(s.getItem(`${n}_blCam`)),this.brCam=this.cameras.get(s.getItem(`${n}_brCam`)),this.tlCam===void 0&&(this.tlCam=this.cameras.get("Debug")),this.trCam===void 0&&(this.trCam=this.cameras.get("Orthographic")),this.blCam===void 0&&(this.blCam=this.cameras.get("Front")),this.brCam===void 0&&(this.brCam=this.cameras.get("Top")),U.addEditorGroup({title:"Editor",items:[{type:"button",prop:"Hide All Transforms"},{type:"button",prop:"Resize"}],onUpdate:(a,r)=>{switch(a){case"Hide All Transforms":G.instance.hide();break;case"Resize":this.resize();break}},subgroups:[{title:"Debug Camera",items:[{type:"range",prop:"Near",step:1e-4,min:.001,max:1e3,value:this.debugCamera.near},{type:"range",prop:"Far",step:.001,min:.001,max:1e4,value:this.debugCamera.far}],onUpdate:(a,r)=>{switch(a){case"Near":this.debugCamera.near=r,this.debugCamera.updateProjectionMatrix();break;case"Far":this.debugCamera.far=r,this.debugCamera.updateProjectionMatrix();break}}},{title:"Grid",items:[{type:"number",prop:"Position",value:0},{type:"color",prop:"Color",value:"#FFFFFF"},{type:"range",prop:"Grid Opacity",value:.25,min:0,max:1,step:.01},{type:"range",prop:"Subgrid Opacity",value:.15,min:0,max:1,step:.01}],onUpdate:(a,r)=>{switch(a){case"Position":this.grid&&(this.grid.position.y=r);break;case"Color":this.grid&&this.grid.color.setStyle(r);break;case"Grid Opacity":this.grid&&(this.grid.gridOpacity=r);break;case"Subgrid Opacity":this.grid&&(this.grid.subgridOpacity=r);break}}}]})}setupTools(){this.splineEditor=new _i(this.currentCamera,this.three),this.splineEditor.initDebug(),this.helpersContainer.add(this.splineEditor)}play(){this.playing=!0,this.onUpdate()}pause(){this.playing=!1,cancelAnimationFrame(this.rafID),this.rafID=-1}toggleOrbitControls(e){this.controls.forEach(t=>{t.enabled=!e})}clear(){this.three.dispatchEvent({type:I.CLEAR_OBJECT}),U.removeAllGroups(),this.clearLightHelpers(),this.clearControls(),this.currentTransform!==void 0&&(this.currentTransform.removeEventListener("objectChange",this.onUpdateTransform),G.instance.remove(this.currentTransform.getHelper().name)),this.currentTransform=void 0,G.instance.clear(),this.cameras.forEach(e=>{this.editorCameras.indexOf(e.name)<0&&this.three.dispatchEvent({type:I.REMOVE_CAMERA,value:e})}),this.currentCamera=this.debugCamera,this.currentScene=void 0,this.scenes.forEach(e=>{this.three.dispatchEvent({type:I.REMOVE_SCENE,value:e})}),this.scenes.clear()}setGridVisibility(e){this.gridVisibility=e,this.saveExpandedGridVisibility(),this.grid&&(this.grid.visible=e)}update(){this.renderer&&this.rendererReady&&this.renderer?.clear(),this.controls.forEach(e=>e.update()),this.cameraHelpers.forEach(e=>e.update()),this.lightHelpers.forEach(e=>{e.update!==void 0&&e.update()}),this.props.onSceneUpdate!==void 0&&this.currentScene!==void 0&&this.props.onSceneUpdate(this.currentScene)}draw(){if(this.rendererReady)switch(this.renderer&&this.renderer?.clear(),this.state.mode){case"Single":this.drawSingle();break;case"Side by Side":case"Stacked":this.drawDouble();break;case"Quad":this.drawQuad();break}}onUpdate=()=>{this.playing&&(this.update(),this.draw(),this.rafID=requestAnimationFrame(this.onUpdate))};enable(){const e=this.containerRef.current;e.addEventListener("mousemove",this.onMouseMove),e.addEventListener("click",this.onClick),window.addEventListener("keydown",this.onKey),window.addEventListener("resize",this.resize),this.three.addEventListener(I.ADD_SCENE,this.addScene),this.three.addEventListener(I.SET_SCENE,this.sceneUpdate),this.three.addEventListener(I.REMOVE_SCENE,this.removeScene),this.three.addEventListener(I.ADD_CAMERA,this.addCamera),this.three.addEventListener(I.REMOVE_CAMERA,this.removeCamera),this.three.addEventListener(I.SET_OBJECT,this.onSetSelectedItem)}disable(){const e=this.containerRef.current;e.removeEventListener("mousemove",this.onMouseMove),e.removeEventListener("click",this.onClick),window.removeEventListener("keydown",this.onKey),window.removeEventListener("resize",this.resize),this.three.removeEventListener(I.ADD_SCENE,this.addScene),this.three.removeEventListener(I.SET_SCENE,this.sceneUpdate),this.three.removeEventListener(I.ADD_CAMERA,this.addCamera),this.three.removeEventListener(I.REMOVE_CAMERA,this.removeCamera),this.three.removeEventListener(I.SET_OBJECT,this.onSetSelectedItem)}resize=()=>{this.width=window.innerWidth-300,this.height=window.innerHeight,this.renderer?.setSize(this.width,this.height);const e=Math.floor(this.width/2),t=Math.floor(this.height/2);this.props.three.resize(this.width,this.height),this.props.onSceneResize!==void 0&&this.currentScene!==void 0&&this.props.onSceneResize(this.currentScene,this.width,this.height);let s=this.width,n=this.height;switch(this.state.mode){case"Side by Side":s=e,n=this.height;break;case"Stacked":s=this.width,n=t;break;case"Quad":s=e,n=t;break}const a=s/n;this.cameras.forEach(r=>{r instanceof d.OrthographicCamera?(r.left=s/-2,r.right=s/2,r.top=n/2,r.bottom=n/-2,r.name==="UI"&&(r.position.x=this.width/2,r.position.y=this.height/-2,r.position.z=100),r.updateProjectionMatrix()):r instanceof d.PerspectiveCamera&&(r.aspect=a,r.updateProjectionMatrix()),this.cameraHelpers.get(r.name)?.update()})};addScene=e=>{const t=this.props.scenes.get(e.value.name);if(t!==void 0){const s=new t;s.visible=!1,this.props.onSceneAdd!==void 0&&this.props.onSceneAdd(s),this.props.three.scene=s,this.scenes.set(e.value.name,s),this.scene.add(s)}else console.log("Hermes - Scene not found:",e.value.name,this.props.scenes)};sceneUpdate=e=>{this.currentScene!==void 0&&(this.currentScene.visible=!1,this.clearLightHelpers());const t=this.scene.getObjectByName(e.value.name);t!==void 0&&(this.currentScene=t,this.currentScene.visible=!0,this.addLightHelpers(this.currentScene))};removeScene=e=>{const t=e.value.name;this.scenes.delete(t);const s=this.scene.getObjectByName(t);s&&setTimeout(()=>{ne(s)},100),this.clearLightHelpers()};addCamera=e=>{const t=e.value,s=t.uuid,n=this.props.three.scene?.getObjectByProperty("uuid",t.uuid);if(n!==void 0){const a=n;this.cameras.set(s,a);const r=new d.CameraHelper(a);r.visible=this.cameraVisibility,this.cameraHelpers.set(s,r),this.helpersContainer.add(r),this.setState({lastUpdate:Date.now()})}};removeCamera=e=>{const s=e.value.uuid,n=this.cameraHelpers.get(s);n!==void 0&&(this.helpersContainer.remove(n),n.dispose()),this.cameras.delete(s),this.setState({lastUpdate:Date.now()})};onMouseMove=e=>{const t=new d.Vector2;this.renderer?.getSize(t);const s=Math.min(e.clientX,t.x),n=Math.min(e.clientY,t.y);this.pointer.x=Z.mapLinear(s,0,t.x,-1,1),this.pointer.y=Z.mapLinear(n,0,t.y,1,-1);const a=t.x/2,r=t.y/2,o=()=>{s<a?this.pointer.x=Z.mapLinear(s,0,a,-1,1):this.pointer.x=Z.mapLinear(s,a,t.x,-1,1)},c=()=>{n<r?this.pointer.y=Z.mapLinear(n,0,r,1,-1):this.pointer.y=Z.mapLinear(n,r,t.y,1,-1)};switch(this.state.mode){case"Quad":o(),c();break;case"Side by Side":o();break;case"Stacked":c(),c();break}if(this.updateCamera(s,n,a,r),this.state.interactionMode==="Orbit"||this.currentScene===void 0)return;const l=this.raycaster.intersectObjects(this.currentScene.children);l.length>0&&this.interactionHelper.position.copy(l[0].point)};onClick=e=>{if(this.state.interactionMode==="Orbit"||this.currentScene===void 0)return;const t=new d.Vector2;if(this.renderer.getSize(t),e.clientX>=t.x)return;this.onMouseMove(e);const s=this.raycaster.intersectObjects(this.currentScene.children);s.length>0&&(this.props.three.getObject(s[0].object.uuid),this.interactionHelper.visible=!1,this.setState({interactionMode:"Orbit",lastUpdate:Date.now()}))};onKey=e=>{if(this.selectedItem!==void 0){if(e.ctrlKey){if(this.currentCamera.name==="UI")return;const t=this.controls.get(this.currentCamera.name);e.key==="0"?(e.preventDefault(),this.clearControls(),this.cameraControls=new se(this.currentCamera,this.currentWindow.current),this.selectedItem instanceof d.Mesh||this.selectedItem instanceof d.SkinnedMesh?(this.selectedItem.geometry.computeBoundingBox(),this.cameraControls.fitToBox(this.selectedItem.geometry.boundingBox,!0)):this.cameraControls.fitToSphere(this.selectedItem,!0),this.updateCameraControls(t,!0)):e.key==="1"?(e.preventDefault(),this.clearControls(),this.cameraControls=new se(this.currentCamera,this.currentWindow.current),this.cameraControls.rotateTo(0,Math.PI*.5,!0),this.cameraControls.moveTo(this.selectedItem.position.x,this.selectedItem.position.y,0,!0),this.updateCameraControls(t)):e.key==="2"?(e.preventDefault(),this.clearControls(),this.cameraControls=new se(this.currentCamera,this.currentWindow.current),this.cameraControls.rotateTo(0,0,!0),this.cameraControls.moveTo(this.selectedItem.position.x,0,this.selectedItem.position.z,!0),this.updateCameraControls(t)):e.key==="3"?(e.preventDefault(),this.clearControls(),this.cameraControls=new se(this.currentCamera,this.currentWindow.current),this.cameraControls.rotateTo(Math.PI/2,Math.PI/2,!0),this.cameraControls.moveTo(0,this.selectedItem.position.y,this.selectedItem.position.z,!0),this.updateCameraControls(t)):e.key==="4"?(e.preventDefault(),this.clearControls(),this.cameraControls=new se(this.currentCamera,this.currentWindow.current),this.cameraControls.rotateTo(Math.PI,Math.PI/2,!0),this.cameraControls.moveTo(this.selectedItem.position.x,this.selectedItem.position.y,0,!0),this.updateCameraControls(t)):e.key==="5"&&(e.preventDefault(),this.clearControls(),this.cameraControls=new se(this.currentCamera,this.currentWindow.current),this.cameraControls.rotateTo(Z.degToRad(45),Z.degToRad(45),!0),this.updateCameraControls(t))}else if(this.currentTransform!==void 0)switch(e.key){case"r":this.currentTransform.setMode("rotate");break;case"s":this.currentTransform.setMode("scale");break;case"t":this.currentTransform.setMode("translate");break;case"q":this.currentTransform.setSpace(this.currentTransform.space==="local"?"world":"local");break}}};onSetSelectedItem=e=>{this.selectedItem!==void 0&&this.updateSelectedItemHelper(!1),this.selectedItem=void 0;const t=e.value.uuid;if(this.scenes.forEach(s=>{t.search(s.uuid)>-1&&(this.selectedItem=s.getObjectByProperty("uuid",t))}),this.selectedItem===void 0){console.log(`Hermes - Can't find selected item: ${e.value.uuid}, ${e.value.name}`);return}this.currentTransform!==void 0&&(this.currentTransform.removeEventListener("objectChange",this.onUpdateTransform),G.instance.remove(this.currentTransform.getHelper().name)),this.currentTransform=G.instance.add(e.value.name),this.currentTransform&&(this.currentTransform.attach(this.selectedItem),this.helpersContainer.add(this.currentTransform.getHelper()),this.currentTransform.addEventListener("objectChange",this.onUpdateTransform)),this.updateSelectedItemHelper(!0)};updateSelectedItemHelper(e){if(this.selectedItem!==void 0)if(this.cameraVisibility){if(this.selectedItem.isLight===!0&&!this.lightVisibility){const t=this.lightHelpers.get(this.selectedItem.name);t!==void 0&&(t.visible=e)}}else{const t=this.cameraHelpers.get(this.selectedItem.name);t!==void 0&&(t.visible=e)}}onUpdateTransform=()=>{this.selectedItem!==void 0&&(this.props.three.updateObject(this.selectedItem.uuid,"position",this.selectedItem.position),this.props.three.updateObject(this.selectedItem.uuid,"rotation",{x:this.selectedItem.rotation.x,y:this.selectedItem.rotation.y,z:this.selectedItem.rotation.z}),this.props.three.updateObject(this.selectedItem.uuid,"scale",this.selectedItem.scale),Je.instance.update())};clearLightHelpers=()=>{this.lightHelpers.forEach(e=>{this.helpersContainer.remove(e),e.dispose()}),this.lightHelpers.clear()};addLightHelpers=e=>{e.traverse(t=>{if(t.type.search("Light")>-1){let s;switch(t.type){case"DirectionalLight":s=new d.DirectionalLightHelper(t,100),s.name=`${t.name}Helper`,s.visible=this.lightVisibility,this.lightHelpers.set(t.name,s),this.helpersContainer.add(s);break;case"HemisphereLight":s=new d.HemisphereLightHelper(t,250),s.name=`${t.name}Helper`,s.visible=this.lightVisibility,this.lightHelpers.set(t.name,s),this.helpersContainer.add(s);break;case"RectAreaLight":s=new Ni.RectAreaLightHelper(t),s.name=`${t.name}Helper`,s.visible=this.lightVisibility,this.lightHelpers.set(t.name,s),this.helpersContainer.add(s);break;case"PointLight":s=new d.PointLightHelper(t,100),s.name=`${t.name}Helper`,s.visible=this.lightVisibility,this.lightHelpers.set(t.name,s),this.helpersContainer.add(s);break;case"SpotLight":s=new d.SpotLightHelper(t),s.name=`${t.name}Helper`,s.visible=this.lightVisibility,this.lightHelpers.set(t.name,s),this.helpersContainer.add(s);break}}})};createControls(e,t){const s=this.controls.get(e.name);if(s!==void 0&&s.dispose(),this.controls.delete(e.name),e.name==="UI")return;const n=new ki.OrbitControls(e,t);switch(n.enableDamping=!0,n.dampingFactor=.1,e.name){case"Top":case"Bottom":case"Left":case"Right":case"Front":case"Back":n.enableRotate=!1;break}this.controls.set(e.name,n)}clearCamera(e){const t=this.cameraHelpers.get(e.name);t!==void 0&&(this.helpersContainer.remove(t),t.dispose(),this.cameraHelpers.delete(e.name));const s=this.controls.get(e.name);s!==void 0&&(s.dispose(),this.controls.delete(e.name))}killControls(){this.controls.forEach((e,t)=>{e.dispose();const s=this.cameraHelpers.get(t);s!==void 0&&(this.helpersContainer.remove(s),s.dispose()),this.cameraHelpers.delete(t),this.controls.delete(t)}),this.controls.clear(),this.cameraHelpers.clear()}assignControls(){switch(this.state.mode){case"Single":this.createControls(this.tlCam,this.tlWindow.current);break;case"Side by Side":case"Stacked":this.createControls(this.tlCam,this.tlWindow.current),this.createControls(this.trCam,this.trWindow.current);break;case"Quad":this.createControls(this.tlCam,this.tlWindow.current),this.createControls(this.trCam,this.trWindow.current),this.createControls(this.blCam,this.blWindow.current),this.createControls(this.brCam,this.brWindow.current);break}}updateCamera=(e,t,s,n)=>{switch(this.state.mode){case"Quad":t<n?e<s?this.currentCamera=this.tlCam:this.currentCamera=this.trCam:e<s?this.currentCamera=this.blCam:this.currentCamera=this.brCam;break;case"Side by Side":e<s?this.currentCamera=this.tlCam:this.currentCamera=this.trCam;break;case"Single":this.currentCamera=this.tlCam;break;case"Stacked":t<n?this.currentCamera=this.tlCam:this.currentCamera=this.trCam;break}this.splineEditor.camera=this.currentCamera,this.raycaster.setFromCamera(this.pointer,this.currentCamera),this.currentCamera===this.tlCam?this.currentWindow=this.tlWindow:this.currentCamera===this.trCam?this.currentWindow=this.trWindow:this.currentCamera===this.blCam?this.currentWindow=this.blWindow:this.currentCamera===this.brCam&&(this.currentWindow=this.brWindow),G.instance.updateCamera(this.currentCamera,this.currentWindow.current)};updateCameraControls=(e,t=!1)=>{if(this.selectedItem===void 0)return;cancelAnimationFrame(this.cameraControlsRafID),this.cameraControlsRafID=-1,this.cameraControls&&(this.cameraControls.smoothTime=.1);const s=.15,n=new d.Clock;n.start(),this.selectedItem.getWorldPosition(e.target0);const a=()=>{const r=n.getDelta();this.cameraControls&&this.cameraControls.update(r),t&&(e.target.lerp(e.target0,s),e.object.position.lerp(e.position0,s),e.object.zoom=Me(e.object.zoom,e.zoom0,s),e.object.updateProjectionMatrix(),e.dispatchEvent({type:"change"})),n.getElapsedTime()>=.5?(cancelAnimationFrame(this.cameraControlsRafID),this.cameraControlsRafID=-1,this.clearControls()):this.cameraControlsRafID=requestAnimationFrame(a)};a()};clearControls=()=>{this.cameraControls!==void 0&&(this.cameraControls.disconnect(),this.cameraControls.dispose(),this.cameraControls=void 0)};saveExpandedCameraVisibility(){localStorage.setItem(this.expandedCameraVisibility,this.cameraVisibility?"open":"closed")}saveExpandedLightVisibility(){localStorage.setItem(this.expandedLightVisibility,this.lightVisibility?"open":"closed")}saveExpandedGridVisibility(){localStorage.setItem(this.expandedGridVisibility,this.gridVisibility?"open":"closed")}getSceneOverride(e){switch(e){case"Depth":return this.depthMaterial;case"Normals":return this.normalsMaterial;case"Renderer":return null;case"UVs":return this.uvMaterial;case"Wireframe":return this.wireframeMaterial}return null}drawTo(e,t,s,n,a,r){switch(a.name){case"Left":case"Right":this.grid&&(this.grid.rotation.z=Math.PI/2);break;case"Front":case"Back":this.grid&&(this.grid.rotation.x=Math.PI/2);break}this.scene.overrideMaterial=r,this.renderer&&(this.renderer?.setScissor(e,t,s,n),this.renderer?.setViewport(e,t,s,n),this.renderer?.render(this.scene,a)),this.grid&&this.grid.rotation.set(0,0,0)}drawSingle(){const e=this.getSceneOverride(this.tlRender);this.drawTo(0,0,this.width,this.height,this.tlCam,e)}drawDouble=()=>{const e=this.getSceneOverride(this.tlRender),t=this.getSceneOverride(this.trRender),s=Math.floor(this.width/2),n=Math.floor(this.height/2),a=this.renderer instanceof tt;if(this.state.mode==="Side by Side")this.drawTo(0,0,s,this.height,this.tlCam,e),this.drawTo(s,0,s,this.height,this.trCam,t);else{const r=this.height-n;a?(this.drawTo(0,0,this.width,n,this.tlCam,e),this.drawTo(0,r,this.width,n,this.trCam,t)):(this.drawTo(0,r,this.width,n,this.tlCam,e),this.drawTo(0,0,this.width,n,this.trCam,t))}};drawQuad=()=>{const e=this.renderer instanceof tt,t=this.getSceneOverride(this.tlRender),s=this.getSceneOverride(this.trRender),n=this.getSceneOverride(this.blRender),a=this.getSceneOverride(this.brRender),r=Math.floor(this.width/2),o=Math.floor(this.height/2),c=this.height-o;let l=0,h=e?0:this.height-o;l=0,this.drawTo(l,h,r,o,this.tlCam,t),l=r,this.drawTo(l,h,r,o,this.trCam,s),h=e?c:0,l=0,this.scene.overrideMaterial=n,this.drawTo(l,h,r,o,this.blCam,n),l=r,this.drawTo(l,h,r,o,this.brCam,a)};get appID(){return this.props.three.name}get mode(){return this.state.mode}get three(){return this.props.three}get expandedCameraVisibility(){return`${this.appID}_multiviewCameraVisibility`}get expandedLightVisibility(){return`${this.appID}_multiviewLightVisibility`}get expandedGridVisibility(){return`${this.appID}_multiviewGridVisibility`}}class Je extends b.Component{static instance;matrix=new d.Matrix4;position=new d.Vector3;rotation=new d.Euler;scale=new d.Vector3;open=!1;constructor(e){super(e);const t=localStorage.getItem(this.expandedName),s=t!==null?t==="open":!1;this.open=s,this.saveExpanded(),this.state={lastUpdated:0,expanded:s},this.matrix.elements=e.object.matrix,e.object.uuid.length>0&&(this.position.setFromMatrixPosition(this.matrix),this.rotation.setFromRotationMatrix(this.matrix),this.scale.setFromMatrixScale(this.matrix)),Je.instance=this}update(){if(V.instance){const e=V.instance.selectedItem;if(e===void 0)return;this.position.x=K(e.position.x,3),this.position.y=K(e.position.y,3),this.position.z=K(e.position.z,3),this.rotation.copy(e.rotation),this.scale.x=K(e.scale.x,3),this.scale.y=K(e.scale.y,3),this.scale.z=K(e.scale.z,3),this.setState({lastUpdated:Date.now()})}}render(){return u.jsx(X,{three:this.props.three,title:"Transform",expanded:this.open,items:[{title:"Position",prop:"position",type:"grid3",step:.1,value:this.position,onChange:this.updateTransform},{title:"Rotation",prop:"rotation",type:"euler",value:this.rotation,onChange:this.updateTransform},{title:"Scale",prop:"scale",type:"grid3",value:this.scale,onChange:this.updateTransform},{title:"Visible",prop:"visible",type:"boolean",value:this.props.object.visible,onChange:this.updateTransform}],onToggle:e=>{this.open=e,this.saveExpanded()}},this.state.lastUpdated)}updateTransform=(e,t)=>{const s=e==="rotation"?{x:t._x,y:t._y,z:t._z}:t;this.props.three.updateObject(this.props.object.uuid,e,s);const n=this.props.three.getScene(this.props.object.uuid);if(n){const a=n.getObjectByProperty("uuid",this.props.object.uuid);B(a,e,s)}};saveExpanded(){localStorage.setItem(this.expandedName,this.open?"open":"closed")}get expandedName(){return`${this.props.three.name}_transform`}}function Wt(i){switch(i){case"color":return"Color";case"intensity":return"Intensity";case"decay":return"Decay";case"distance":return"Distance";case"angle":return"Angle";case"penumbra":return"Penumbra";case"groundColor":return"Ground Color";case"width":return"Width";case"height":return"Height"}return i}function xn(i,e){function t(){return`${e.name}_light`}const s=localStorage.getItem(t()),n=s!==null?s==="open":!1;function a(o){localStorage.setItem(t(),o?"open":"closed")}const r=[];if(i.lightInfo!==void 0)for(const o in i.lightInfo){const c=i.lightInfo[o];c!==void 0&&(c.isColor!==void 0?r.push({title:Wt(o),prop:o,type:"color",value:c,onChange:(l,h)=>{const p=new d.Color(h);e.updateObject(i.uuid,l,p);const m=e.getScene(i.uuid);if(m!==null){const g=m.getObjectByProperty("uuid",i.uuid);B(g,l,p)}}}):r.push({title:Wt(o),prop:o,type:typeof c,value:c,step:typeof c=="number"?.01:void 0,onChange:(l,h)=>{e.updateObject(i.uuid,l,h);const p=e.getScene(i.uuid);if(p!==null){const m=p.getObjectByProperty("uuid",i.uuid);B(m,l,h)}}}))}return u.jsx(X,{three:e,title:"Light",items:r,expanded:n,onToggle:o=>{a(o)}})}function On(i){const e=i.object,t=i.three;function s(){return`${t.name}_animation`}const n=localStorage.getItem(s()),a=n!==null?n==="open":!1;function r(m){localStorage.setItem(s(),m?"open":"closed")}const o=[],c=[];let l=0;e.animations.forEach(m=>{l=Math.max(l,m.duration),m.duration>0&&c.push({title:m.name,items:[{title:"Duration",type:"number",value:m.duration,disabled:!0},{title:"Blend Mode",type:"option",disabled:!0,options:[{title:"Normal",value:2500},{title:"Additive",value:2501}]}]})}),o.push({title:"Animations",items:c});let h;const p=t.getScene(e.uuid);if(p!==null){const m=p.getObjectByProperty("uuid",e.uuid);if(m!==void 0){const g=m.mixer;if(g!==void 0){const _=[{title:"Time Scale",type:"range",value:g.timeScale,step:.01,min:-1,max:2,onChange:(E,v)=>{g.timeScale=v,t.updateObject(e.uuid,"mixer.timeScale",v)}}];_.push({title:"Stop All",type:"button",onChange:()=>{g.stopAllAction(),t.requestMethod(e.uuid,"stopAllAction",void 0,"mixer")}}),o.push({title:"Mixer",items:_}),h=new d.SkeletonHelper(m),V.instance?.scene.add(h)}}}return b.useEffect(()=>()=>{h!==void 0&&ne(h)},[]),u.jsx(X,{three:i.three,title:"Animation",items:o,expanded:a,onToggle:m=>{r(m)}})}const ft={name:"",uuid:"",type:"",visible:!1,matrix:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],animations:[],material:void 0,perspectiveCameraInfo:void 0,orthographicCameraInfo:void 0,lightInfo:void 0,children:[]};function Ci(i){const[e,t]=b.useState(ft);b.useEffect(()=>{function r(c){t(c.value)}function o(){t(ft)}return i.three.addEventListener(I.CLEAR_OBJECT,o),i.three.addEventListener(I.SET_SCENE,o),i.three.addEventListener(I.SET_OBJECT,r),()=>{i.three.removeEventListener(I.CLEAR_OBJECT,o),i.three.removeEventListener(I.SET_SCENE,o),i.three.removeEventListener(I.SET_OBJECT,r)}},[]);const s=e.type.toLowerCase(),n=e.animations.length>0||e.mixer!==void 0,a=s.search("mesh")>-1||s.search("line")>-1||s.search("points")>-1;return a&&console.log(s,e),u.jsx(Te,{three:i.three,label:"Inspector",button:e.uuid.length>0?u.jsx("button",{className:"remove",onClick:()=>{G.instance.remove(e.name),t(ft)}}):void 0,children:u.jsx("div",{id:"Inspector",className:i.class,children:e.uuid.length>0&&u.jsxs(u.Fragment,{children:[u.jsxs(u.Fragment,{children:[u.jsx(Ze,{type:"string",title:"Name",prop:"name",value:e.name,disabled:!0}),u.jsx(Ze,{type:"string",title:"Type",prop:"type",value:e.type,disabled:!0}),u.jsx(Ze,{type:"string",title:"UUID",prop:"uuid",value:e.uuid,disabled:!0})]}),u.jsxs(u.Fragment,{children:[u.jsx(Je,{object:e,three:i.three}),n?u.jsx(On,{object:e,three:i.three}):null,s.search("camera")>-1?un(e,i.three):null,s.search("light")>-1?xn(e,i.three):null,a?cn(e,i.three):null]})]})})},"Inspector")}class wn extends b.Component{autoClear=!0;autoClearColor=!0;autoClearDepth=!0;autoClearStencil=!0;outputColorSpace=d.SRGBColorSpace;localClippingEnabled=!1;clearColor=new d.Color(0);clearAlpha=1;toneMapping=d.NoToneMapping;toneMappingExposure=1;type="";constructor(e){super(e);const t=localStorage.getItem(this.expandedName),s=t!==null?t==="open":!1;if(this.state={expanded:s,lastUpdated:Date.now()},this.saveExpanded(s),V.instance){const n=V.instance.renderer;n&&(this.autoClear=n.autoClear,this.autoClearColor=n.autoClearColor,this.autoClearDepth=n.autoClearDepth,this.autoClearStencil=n.autoClearStencil,this.clearAlpha=n.getClearAlpha(),this.toneMapping=n.toneMapping,this.toneMappingExposure=n.toneMappingExposure,n instanceof d.WebGLRenderer&&(this.localClippingEnabled=n.localClippingEnabled,n.getClearColor(this.clearColor)))}this.props.three.addEventListener(I.ADD_RENDERER,this.onAddRenderer)}componentwillunmount(){this.props.three.removeEventListener(I.ADD_RENDERER,this.onAddRenderer)}onAddRenderer=e=>{const t=e.value;if(this.autoClear=t.autoClear,this.autoClearColor=t.autoClearColor,this.autoClearDepth=t.autoClearDepth,this.autoClearStencil=t.autoClearStencil,this.outputColorSpace=t.outputColorSpace,this.localClippingEnabled=t.localClippingEnabled,this.clearAlpha=t.clearAlpha,this.type=t.type,this.toneMapping=t.toneMapping,this.toneMappingExposure=t.toneMappingExposure,this.clearColor.setStyle(t.clearColor,d.LinearSRGBColorSpace),d.ColorManagement.enabled=t.colorManagement,V.instance){const s=V.instance.renderer;s&&(s.autoClearColor=this.autoClearColor,s.outputColorSpace=this.outputColorSpace,s instanceof d.WebGLRenderer&&(s.localClippingEnabled=this.localClippingEnabled),s.toneMapping=this.toneMapping,s.toneMappingExposure=this.toneMappingExposure,s.setClearColor(t.clearColor,this.clearAlpha))}this.setState({lastUpdated:Date.now()})};render(){const e=()=>{if(V.instance){const t=V.instance.renderer;t&&(t.autoClearColor=this.autoClearColor,t.outputColorSpace=this.outputColorSpace,t instanceof d.WebGLRenderer&&(t.localClippingEnabled=this.localClippingEnabled),t.toneMapping=this.toneMapping,t.toneMappingExposure=this.toneMappingExposure,t.setClearColor(this.clearColor.getStyle(),this.clearAlpha),this.props.three.updateRenderer({autoClear:this.autoClear,autoClearColor:this.autoClearColor,autoClearDepth:this.autoClearDepth,autoClearStencil:this.autoClearStencil,outputColorSpace:this.outputColorSpace,localClippingEnabled:this.localClippingEnabled,clearAlpha:this.clearAlpha,clearColor:this.clearColor.getStyle(),colorManagement:d.ColorManagement.enabled,toneMapping:this.toneMapping,toneMappingExposure:this.toneMappingExposure}))}};return u.jsx(X,{three:this.props.three,title:"Renderer",expanded:this.state.expanded,items:[{type:"boolean",title:"Auto Clear",value:this.autoClear,onChange:(t,s)=>{this.autoClear=s}},{type:"boolean",title:"Auto Clear Color",value:this.autoClearColor,onChange:(t,s)=>{this.autoClearColor=s,e()}},{type:"boolean",title:"Auto Clear Depth",value:this.autoClearDepth,onChange:(t,s)=>{this.autoClearDepth=s,e()}},{type:"boolean",title:"Auto Clear Stencil",value:this.autoClearStencil,onChange:(t,s)=>{this.autoClearStencil=s,e()}},{type:"boolean",title:"Local Clipping",value:this.localClippingEnabled,onChange:(t,s)=>{this.localClippingEnabled=s,e()}},{type:"color",title:"Clear Color",value:`#${this.clearColor.getHexString()}`,onChange:(t,s)=>{this.clearColor.setStyle(s),e()}},{type:"range",title:"Clear Alpha",min:0,max:1,step:.01,value:this.clearAlpha,onChange:(t,s)=>{this.clearAlpha=s,e()}},{type:"boolean",title:"Color Management",value:d.ColorManagement.enabled,onChange:(t,s)=>{d.ColorManagement.enabled=s,e()}},{type:"option",title:"Color Space",value:this.outputColorSpace,options:[{title:"No Color Space",value:d.NoColorSpace},{title:"SRB Color Space",value:d.SRGBColorSpace},{title:"Linear SRB Color Space",value:d.LinearSRGBColorSpace}],onChange:(t,s)=>{this.outputColorSpace=s,e()}},{type:"option",title:"Tone Mapping",value:this.toneMapping,options:[{title:"None ",value:d.NoToneMapping},{title:"Linear ",value:d.LinearToneMapping},{title:"Reinhard",value:d.ReinhardToneMapping},{title:"Cineon ",value:d.CineonToneMapping},{title:"ACES Filmic",value:d.ACESFilmicToneMapping},{title:"AgX",value:d.AgXToneMapping},{title:"Neutral",value:d.NeutralToneMapping},{title:"Custom",value:d.CustomToneMapping}],onChange:(t,s)=>{this.toneMapping=s,e()}},{type:"range",title:"Tone Mapping Exposure",value:this.toneMappingExposure,min:0,max:2,step:.01,onChange:(t,s)=>{this.toneMappingExposure=s,e()}},{type:"string",title:"Type",value:this.type,disabled:!0},{type:"button",title:"Resize Scenes from Source",onChange:()=>{this.props.three.requestSize()}}],onToggle:t=>{this.setState({expanded:t}),this.saveExpanded(t)}},Math.random())}saveExpanded(e){localStorage.setItem(this.expandedName,e?"open":"closed")}get expandedName(){return`${this.props.three.name}_renderer`}}function yi(i){const[e]=b.useState([]),[t]=b.useState([]),[s,n]=b.useState(0),a=l=>{const h=l.value;e.push(h),t.push(u.jsx(Te,{three:i.three,label:`Scene: ${h.name}`,scene:h,open:!1,visible:!1,onRefresh:()=>{i.three.refreshScene(h.name)},children:u.jsx(Ye,{child:h,scene:h,three:i.three})},h.name)),n(Date.now())},r=l=>{const h=l.value;for(let p=0;p<e.length;p++)if(h.uuid===e[p].uuid){e[p]=h,t[p]=u.jsx(Te,{three:i.three,label:`Scene: ${h.name}`,scene:h,open:t[p].props.open,visible:t[p].props.visible,onRefresh:()=>{i.three.refreshScene(h.name)},children:u.jsx(Ye,{child:h,scene:h,three:i.three})},h.name),n(Date.now());return}},o=l=>{const h=l.value;for(let p=0;p<e.length;p++)if(h.uuid===e[p].uuid){e.splice(p,1),t.splice(p,1),n(Date.now());return}},c=l=>{const h=l.value.name;for(let p=0;p<e.length;p++){const m=e[p],g=m.name===h;t[p]=u.jsx(Te,{three:i.three,label:`Scene: ${m.name}`,scene:m,open:g,visible:g,onRefresh:()=>{i.three.refreshScene(m.name)},children:u.jsx(Ye,{child:m,scene:m,three:i.three})},m.name)}n(Date.now())};return b.useEffect(()=>(i.three.addEventListener(I.ADD_SCENE,a),i.three.addEventListener(I.SET_SCENE,c),i.three.addEventListener(I.REFRESH_SCENE,r),i.three.addEventListener(I.REMOVE_SCENE,o),()=>{i.three.removeEventListener(I.ADD_SCENE,a),i.three.removeEventListener(I.SET_SCENE,c),i.three.removeEventListener(I.REFRESH_SCENE,r),i.three.removeEventListener(I.REMOVE_SCENE,o)}),[]),u.jsxs("div",{id:"SidePanel",children:[u.jsx("div",{className:"scenes",children:t},s),u.jsx(Ci,{three:i.three}),u.jsx(wn,{three:i.three}),u.jsx(U,{three:i.three})]})}function bi(i){return u.jsxs("div",{className:"editor",ref:i.ref,style:i.style,children:[u.jsx("div",{className:"header",children:i.header}),i.children,u.jsx("div",{className:"footer",children:i.footer})]})}function Tn(i){return u.jsx(bi,{children:u.jsxs(u.Fragment,{children:[u.jsx(V,{three:i.three,scenes:i.scenes,onSceneAdd:i.onSceneAdd,onSceneResize:i.onSceneResize,onSceneUpdate:i.onSceneUpdate}),u.jsx(yi,{three:i.three})]})})}exports.Accordion=Te;exports.Application=Ls;exports.BaseRemote=Et;exports.ChildObject=xt;exports.ContainerObject=Ye;exports.DepthNodeMaterial=fi;exports.Draggable=ai;exports.DraggableItem=ri;exports.Dropdown=oi;exports.DropdownItem=li;exports.Editor=bi;exports.ElementProxy=Ps;exports.ElementProxyReceiver=si;exports.ExportTexture=oe;exports.InfiniteGridHelper=ui;exports.InfiniteGridHelperGPU=mi;exports.InfiniteGridMaterial=di;exports.InfiniteGridNodeMaterial=pi;exports.Inspector=Ci;exports.MultiView=V;exports.NavButton=St;exports.ProxyManager=Is;exports.RemoteTheatre=ks;exports.RemoteThree=Vs;exports.SidePanel=yi;exports.Spline=qe;exports.SplineEditor=_i;exports.ThreeEditor=Tn;exports.Transform=G;exports.UVMaterial=gi;exports.UVNodeMaterial=vi;exports.WebworkerEventHandlers=Rs;exports.anchorGeometry=ti;exports.anchorGeometryTL=hs;exports.animateObjectMaterial=as;exports.animateObjectTransform=ns;exports.applyObjectMaterial=ei;exports.capitalize=ze;exports.clamp=he;exports.clearComposerGroups=bs;exports.colorToHex=gt;exports.copyToClipboard=Zt;exports.createMask=ms;exports.cubicBezier=es;exports.customizeTheatreElements=ss;exports.damp=qi;exports.defaultTheatreCallback=Hi;exports.detectMaxFrameRate=Kt;exports.detectSettings=Xt;exports.dispose=ne;exports.disposeMaterial=yt;exports.disposeTexture=vt;exports.distance=Zi;exports.generateCubemap=Es;exports.getAngle=$i;exports.getObjectMaterialObject=Jt;exports.getObjectMaterialProps=Qt;exports.hierarchyUUID=we;exports.inspectComposer=ys;exports.inspectComposerPass=ii;exports.isColor=qt;exports.map=Yi;exports.mix=Me;exports.noop=Fe;exports.normalize=$e;exports.orthoCamera=os;exports.parseModelLite=ls;exports.randomID=W;exports.renderToTexture=cs;exports.resetThreeObjects=Ue;exports.rgbaToHex=ts;exports.roundTo=K;exports.setMaterialBlendAdd=vs;exports.setMaterialBlendMultiply=_s;exports.setMaterialBlendNormal=gs;exports.setMaterialBlendScreen=Cs;exports.supportsOffscreenCanvas=ps;exports.triangle=Xe;exports.updateCameraOrtho=ds;exports.updateCameraOrtho16x9=us;exports.useMask=fs;exports.useStudio=is;