@tomorrowevening/hermes 0.0.139 → 0.0.140
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/hermes.cjs.js +453 -20
- package/dist/hermes.es.js +38529 -3161
- package/package.json +10 -13
- package/types/core/Application.d.ts +62 -62
- package/types/core/remote/BaseRemote.d.ts +9 -9
- package/types/core/remote/RemoteComponents.d.ts +7 -7
- package/types/core/remote/RemoteTheatre.d.ts +2 -0
- package/types/core/remote/RemoteThree.d.ts +6 -4
- package/types/editor/multiView/MultiView.d.ts +2 -1
- package/types/editor/multiView/Toggle.d.ts +11 -11
- package/types/editor/sidePanel/SidePanel.d.ts +3 -3
- package/types/editor/sidePanel/inspector/utils/InspectRenderer.d.ts +32 -31
- package/types/utils/detectSettings.d.ts +18 -18
- package/dist/style.css +0 -1
package/dist/hermes.cjs.js
CHANGED
@@ -1,4 +1,4 @@
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const x=require("three"),W=require("react"),ua=()=>{},u0=()=>{};function da(a){return a.substring(0,1).toUpperCase()+a.substring(1)}function Yf(a){const e=JSON.stringify(a);return navigator.clipboard.writeText(e),e}function Xf(){return Math.round(Math.random()*1e6).toString()}function Zf(a){return a.r!==void 0&&a.g!==void 0&&a.b!==void 0}function nh(a){const e=Math.round(a.r*255),t=Math.round(a.g*255),s=Math.round(a.b*255),i=l=>{const c=l.toString(16);return c.length===1?"0"+c:c},n=i(e),r=i(t),o=i(s);return"#"+n+r+o}function Fl(a,e,t,s){return new(t||(t=Promise))(function(i,n){function r(c){try{l(s.next(c))}catch(h){n(h)}}function o(c){try{l(s.throw(c))}catch(h){n(h)}}function l(c){var h;c.done?i(c.value):(h=c.value,h instanceof t?h:new t(function(u){u(h)})).then(r,o)}l((s=s.apply(a,[])).next())})}const d0=["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 ud(a){return a=a.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 Qf=typeof window>"u",Fs=(()=>{if(Qf)return;const{userAgent:a,platform:e,maxTouchPoints:t}=window.navigator,s=/(iphone|ipod|ipad)/i.test(a),i=e==="iPad"||e==="MacIntel"&&t>0&&!window.MSStream;return{isIpad:i,isMobile:/android/i.test(a)||s||i,isSafari12:/Version\/12.+Safari/.test(a),isFirefox:/Firefox/.test(a)}})();function p0(a,e,t){if(!t)return[e];const s=function(c){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
|
-
`,
|
9
|
+
`,u=`
|
10
10
|
precision highp float;
|
11
11
|
varying float vvv;
|
12
12
|
void main() {
|
@@ -15,7 +15,7 @@
|
|
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
|
-
`,m=h.createShader(35633),g=h.createShader(35632),E=h.createProgram();if(!(g&&m&&E))return;h.shaderSource(m,u),h.shaderSource(g,f),h.compileShader(m),h.compileShader(g),h.attachShader(E,m),h.attachShader(E,g),h.linkProgram(E),h.detachShader(E,m),h.detachShader(E,g),h.deleteShader(m),h.deleteShader(g),h.useProgram(E);const y=h.createBuffer();h.bindBuffer(34962,y),h.bufferData(34962,new Float32Array([-1,-1,0,3,-1,0,-1,3,0]),35044);const O=h.getAttribLocation(E,"aPosition");h.vertexAttribPointer(O,3,5126,!1,0,0),h.enableVertexAttribArray(O),h.clearColor(1,1,1,1),h.clear(16384),h.viewport(0,0,1,1),h.drawArrays(4,0,3);const _=new Uint8Array(4);return h.readPixels(0,0,1,1,6408,5121,_),h.deleteProgram(E),h.deleteBuffer(y),_.join("")}(i),n="801621810",r="8016218135",a="80162181161",l=Te?.isIpad?[["a7",a,12],["a8",r,15],["a8x",r,15],["a9",r,15],["a9x",r,15],["a10",r,15],["a10x",r,15],["a12",n,15],["a12x",n,15],["a12z",n,15],["a14",n,15],["a15",n,15],["m1",n,15],["m2",n,15]]:[["a7",a,12],["a8",r,12],["a9",r,15],["a10",r,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=l.filter(([,,h])=>h>=14):(c=l.filter(([,h])=>h===s),c.length||(c=l)),c.map(([h])=>`apple ${h} gpu`)}class Hi extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}const Kt=[],Vi=[];function rn(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 r,a=0;for(;a<s&&i.charCodeAt(a)===e.charCodeAt(a);)a++;if(s-=a,n-=a,s===0)return n;let l,c,h=0,u=0,f=0;for(;u<s;)Vi[u]=i.charCodeAt(a+u),Kt[u]=++u;for(;f<n;)for(r=e.charCodeAt(a+f),l=f++,h=f,u=0;u<s;u++)c=r===Vi[u]?l:l+1,l=Kt[u],h=Kt[u]=l>h?c>h?h+1:c:c>l?l+1:c;return h}function on(i){return i!=null}const ln=({mobileTiers:i=[0,15,30,60],desktopTiers:e=[0,15,30,60],override:t={},glContext:s,failIfMajorPerformanceCaveat:n=!1,benchmarksURL:r="https://unpkg.com/detect-gpu@5.0.57/dist/benchmarks"}={})=>Qt(void 0,void 0,void 0,function*(){const a={};if(_s)return{tier:0,type:"SSR"};const{isIpad:l=!!Te?.isIpad,isMobile:c=!!Te?.isMobile,screenSize:h=window.screen,loadBenchmarks:u=x=>Qt(void 0,void 0,void 0,function*(){const M=yield fetch(`${r}/${x}`).then(D=>D.json());if(parseInt(M.shift().split(".")[0],10)<4)throw new Hi("Detect GPU benchmark data is out of date. Please update to version 4x");return M})}=t;let{renderer:f}=t;const m=(x,M,D,k,R)=>({device:R,fps:k,gpu:D,isMobile:c,tier:x,type:M});let g,E="";if(f)f=zi(f),g=[f];else{const x=s||function(D,k=!1){const R={alpha:!1,antialias:!1,depth:!1,failIfMajorPerformanceCaveat:k,powerPreference:"high-performance",stencil:!1};D&&delete R.powerPreference;const V=window.document.createElement("canvas"),ge=V.getContext("webgl",R)||V.getContext("experimental-webgl",R);return ge??void 0}(Te?.isSafari12,n);if(!x)return m(0,"WEBGL_UNSUPPORTED");const M=Te?.isFirefox?null:x.getExtension("WEBGL_debug_renderer_info");if(f=M?x.getParameter(M.UNMASKED_RENDERER_WEBGL):x.getParameter(x.RENDERER),!f)return m(1,"FALLBACK");E=f,f=zi(f),g=function(D,k,R){return k==="apple gpu"?an(D,k,R):[k]}(x,f,c)}const y=(yield Promise.all(g.map(function(x){var M;return Qt(this,void 0,void 0,function*(){const D=(G=>{const ae=c?["adreno","apple","mali-t","mali","nvidia","powervr","samsung"]:["intel","apple","amd","radeon","nvidia","geforce","adreno"];for(const Ce of ae)if(G.includes(Ce))return Ce})(x);if(!D)return;const k=`${c?"m":"d"}-${D}${l?"-ipad":""}.json`,R=a[k]=(M=a[k])!==null&&M!==void 0?M:u(k);let V;try{V=yield R}catch(G){if(G instanceof Hi)throw G;return}const ge=function(G){var ae;const Ce=(G=G.replace(/\([^)]+\)/,"")).match(/\d+/)||G.match(/(\W|^)([A-Za-z]{1,3})(\W|$)/g);return(ae=Ce?.join("").replace(/\W|amd/g,""))!==null&&ae!==void 0?ae:""}(x);let ue=V.filter(([,G])=>G===ge);ue.length||(ue=V.filter(([G])=>G.includes(x)));const se=ue.length;if(se===0)return;const Q=x.split(/[.,()\[\]/\s]/g).sort().filter((G,ae,Ce)=>ae===0||G!==Ce[ae-1]).join(" ");let X,[Ae,,,,le]=se>1?ue.map(G=>[G,rn(Q,G[2])]).sort(([,G],[,ae])=>G-ae)[0][0]:ue[0],fe=Number.MAX_VALUE;const{devicePixelRatio:te}=window,Pe=h.width*te*h.height*te;for(const G of le){const[ae,Ce]=G,it=ae*Ce,Be=Math.abs(Pe-it);Be<fe&&(fe=Be,X=G)}if(!X)return;const[,,Re,De]=X;return[fe,Re,Ae,De]})}))).filter(on).sort(([x=Number.MAX_VALUE,M],[D=Number.MAX_VALUE,k])=>x===D?M-k:x-D);if(!y.length){const x=nn.find(M=>f.includes(M));return x?m(0,"BLOCKLISTED",x):m(1,"FALLBACK",`${f} (${E})`)}const[,O,_,b]=y[0];if(O===-1)return m(0,"BLOCKLISTED",_,O,b);const S=c?i:e;let w=0;for(let x=0;x<S.length;x++)O>=S[x]&&(w=x);return m(w,"BENCHMARK",_,O,b)});var vs=(i=>(i[i.High=0]="High",i[i.Medium=1]="Medium",i[i.Low=2]="Low",i))(vs||{});function ys(i){let e=0;const t=performance.now();function s(){e++;const n=performance.now();if(n-t>=100){const r=e/((n-t)/1e3),a=Math.round(r/30)*30;i(a)}else requestAnimationFrame(s)}requestAnimationFrame(s)}function cn(i,e,t){return new Promise(s=>{ln().then(n=>{let r=!1;const a=/^((?!chrome|android).)*safari/i.test(navigator.userAgent);if(r="transferControlToOffscreen"in i,a){const c=navigator.userAgent.match(/version\/(\d+)/i);r=(c?parseInt(c[1]):0)>=17}const l={dpr:devicePixelRatio,fps:30,width:innerWidth,height:innerHeight,mobile:n.isMobile!==void 0?n.isMobile:!1,supportOffScreenCanvas:r,quality:2,dev:e,editor:t};n.tier===3?l.quality=0:n.tier===2&&(l.quality=1),ys(c=>{l.fps=c,s(l)}),s(l)})})}function Ue(i,e,t){return Math.min(e,Math.max(i,t))}function Nt(i,e,t){return(t-i)/(e-i)}function tt(i,e,t){return i*(1-t)+e*t}function hn(i,e,t,s,n){return tt(t,s,Nt(i,e,n))}function dn(i,e){const t=i-e;return Math.sqrt(t*t)}function ye(i,e=1){return Number(i.toFixed(e))}function un(i,e,t,s){return tt(i,e,1-Math.exp(-t*s))}function pn(i,e=1){return Number(i.toFixed(e))}function mn(i,e,t,s){return i===e&&t===s}function fn(i,e,t,s){return 1/(3*e*i*i+2*t*i+s)}function gn(i,e,t,s,n){return e*(i*i*i)+t*(i*i)+s*i+n}function _n(i,e,t,s,n){const r=i*i;return e*(r*i)+t*r+s*i+n}function vn(i,e,t,s,n){if(i<=0)return 0;if(i>=1)return 1;if(mn(e,t,s,n))return i;const r=0,a=0,l=e,c=t,h=s,u=n,f=1,m=1,g=f-3*h+3*l-r,E=3*h-6*l+3*r,y=3*l-3*r,O=r,_=m-3*u+3*c-a,b=3*u-6*c+3*a,S=3*c-3*a,w=a;let x=i;for(let M=0;M<5;M++){const D=gn(x,g,E,y,O);let k=fn(x,g,E,y);k===1/0&&(k=i),x-=(D-i)*k,x=Math.min(Math.max(x,0),1)}return _n(x,_,b,S,w)}const pi=i=>{i?.dispose()},Ci=i=>{if(i)if(Array.isArray(i))i.forEach(e=>Ci(e));else{for(const e in i){const t=i[e];t!==null&&t instanceof o.Texture&&pi(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 o.Texture&&pi(s.value)}}i.dispose()}},Me=i=>{if(i){for(;i.children.length>0;){const e=i.children[0];e.type==="Audio"?(e.pause(),e.parent&&e.parent.remove(e)):Me(e)}if(i.parent&&i.parent.remove(i),i.isMesh){const e=i;e.geometry?.dispose(),Ci(e.material)}i.dispose!==void 0&&i.dispose()}};exports.totalThreeObjects=0;const mi=()=>{exports.totalThreeObjects=0},Ft=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=>Ft(t))};class vt{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 r=this.canvas.width/n.width,a=this.renderToCanvas(e);this.context.drawImage(a,0,0,n.width*r,n.height*r)}}return e.repeat.copy(t),e.offset.copy(s),this.canvas.toDataURL("image/png")}static renderToCanvas(e){if(this.material===null){this.camera=new o.OrthographicCamera(-.5,.5,.5,-.5,0,100),this.scene=new o.Scene,this.material=new o.MeshBasicMaterial;const t=new o.BufferGeometry;t.setAttribute("position",new o.Float32BufferAttribute([-.5,-.5,0,1.5,-.5,0,-.5,1.5,0],3)),t.setAttribute("normal",new o.Float32BufferAttribute([0,0,1,0,0,1],3)),t.setAttribute("uv",new o.Float32BufferAttribute([0,0,2,0,0,2],2));const s=new o.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=o.LinearSRGBColorSpace,e.colorSpace=o.LinearSRGBColorSpace,this.material.map=e,this.renderer.render(this.scene,this.camera),this.renderer.outputColorSpace=t,e.colorSpace=s}return this.renderer.domElement}}function yn(i){return new Promise(e=>{const t=new o.ObjectLoader;t.parseAsync(i.scene).then(s=>{const n=new o.AnimationMixer(s);if(i.animations.length>0){const a=i.animations.map(c=>o.AnimationClip.parse(c));n.clipAction(a[0]).play(),n.getRoot().animations=i.animations,n.getRoot().mixer=n}const r=[];i.cameras&&i.cameras.length>0&&i.cameras.forEach(a=>{const l=t.parse(a);r.push(l)}),e({animations:i.animations,model:s,mixer:n,cameras:r})})})}const We=Ei(["ctrlKey","metaKey","shiftKey","button","pointerId","pointerType","clientX","clientY","pageX","pageY"]),bn=Ei(["clientX","clientY","deltaX","deltaY","deltaMode"]),Cn=Ei(["ctrlKey","metaKey","shiftKey","keyCode"]);function En(i,e){i.preventDefault(),bn(i,e)}function Sn(i){i.preventDefault()}function wn(i,e,t){for(const s of e)t[s]=i[s]}function Ei(i){return function(t,s){const n={type:t.type};wn(t,i,n),s(n)}}function $t(i,e){const t=[],s={type:i.type,touches:t};for(let n=0;n<i.touches.length;++n){const r=i.touches[n];t.push({pageX:r.pageX,pageY:r.pageY})}e(s)}const xn={37:!0,38:!0,39:!0,40:!0};function Tn(i,e){const{keyCode:t}=i;xn[t]&&(i.preventDefault(),Cn(i,e))}const On={contextmenu:Sn,mousedown:We,mousemove:We,mouseup:We,pointerdown:We,pointermove:We,pointerup:We,touchstart:$t,touchmove:$t,touchend:$t,wheel:En,keydown:Tn};let Mn=0;class An{id;worker;constructor(e,t,s){this.id=Mn++,this.worker=t;const n=a=>{this.worker.postMessage({type:"event",id:this.id,data:a})};t.postMessage({type:"makeProxy",id:this.id});for(const[a,l]of Object.entries(s))e.addEventListener(a,c=>{l(c,n)});function r(){n({type:"resize",left:0,top:0,width:innerWidth,height:innerHeight})}window.addEventListener("resize",r),r()}}class bs extends o.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=yt,e.stopPropagation=yt,this.dispatchEvent(e)}focus(){}getRootNode(){return this}}class Pn{targets={};constructor(){this.handleEvent=this.handleEvent.bind(this)}makeProxy(e){const{id:t}=e,s=new bs;this.targets[t]=s}getProxy(e){return this.targets[e]}handleEvent(e){this.targets[e.id]?.handleEvent(e.data)}}var P=(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.GET_OBJECT="ToolEvents::getObject",i.SET_OBJECT="ToolEvents::setObject",i.UPDATE_OBJECT="ToolEvents::updateObject",i.CREATE_TEXTURE="ToolEvents::createTexture",i.REQUEST_METHOD="ToolEvents::requestMethod",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))(P||{});class Rn extends o.EventDispatcher{components=new Map;appHandlers=[];editorHandlers=[];_appID="";_debugEnabled;_broadcastChannel=void 0;_webSocket=void 0;_mode="app";_connected=!1;_useBC=!1;constructor(e,t,s,n=!0){super(),this._appID=e,this._debugEnabled=t,this.editor=s,t&&(this._useBC=n,n?(this._broadcastChannel=new BroadcastChannel(e),this._broadcastChannel.addEventListener("message",this.messageHandler)):(this._webSocket=new WebSocket(e),this._webSocket.addEventListener("open",this.openHandler),this._webSocket.addEventListener("close",this.closeHandler),this._webSocket.addEventListener("message",this.messageHandler)))}addComponent(e,t){this.components.set(e,t)}dispose(){this._broadcastChannel!==void 0&&this._broadcastChannel.removeEventListener("message",this.messageHandler),this._webSocket!==void 0&&(this._webSocket.removeEventListener("open",this.openHandler),this._webSocket.removeEventListener("close",this.closeHandler),this._webSocket.removeEventListener("message",this.messageHandler)),this.components.forEach(e=>{e.dispose()}),this.components.clear()}send(e){this._mode!==e.target&&(this._useBC?this._broadcastChannel?.postMessage(e):this._connected&&this._webSocket?.send(JSON.stringify(e)))}messageHandler=e=>{let t=e.data;this._useBC||(t=JSON.parse(e.data)),t.target==="editor"?this.handleEditorBroadcast(t):this.handleAppBroadcast(t)};handleAppBroadcast(e){switch(this.appHandlers.forEach(t=>{t.callback(e)}),e.event){case"custom":this.dispatchEvent({type:"ToolEvents::custom",value:e.data});break}}handleEditorBroadcast(e){switch(this.editorHandlers.forEach(t=>{t.callback(e)}),e.event){case"custom":this.dispatchEvent({type:"ToolEvents::custom",value:e.data});break}}openHandler=()=>{this._connected=!0};closeHandler=()=>{this._connected=!1};get appID(){return this._appID}get connected(){return this._connected}get debugEnabled(){return this._debugEnabled}get mode(){return this._mode}get isApp(){return this._mode==="app"}get editor(){return this._mode==="editor"}set editor(e){e&&(this._mode="editor")}}class Dn{canvas;inputElement;settings;playing=!1;rafID=-1;constructor(e,t,s){this.canvas=e,this.inputElement=t,this.settings=s}dispose(){this.stop()}play(){this.playing||(this.playing=!0,this.onUpdate())}stop(){this.playing&&(this.playing=!1,cancelAnimationFrame(this.rafID),this.rafID=-1)}update(){}draw(){}resize(e,t){this.settings.supportOffScreenCanvas&&(this.inputElement.clientWidth=e,this.inputElement.clientHeight=t,this.inputElement.width=e,this.inputElement.height=t)}onResize=e=>{this.resize(e.width,e.height)};onUpdate=()=>{this.update(),this.draw(),this.rafID=requestAnimationFrame(this.onUpdate)}}class In extends o.Scene{clock;cameras;lights;world;constructor(e){super(),this.name=e,this.clock=new o.Clock,this.lights=new o.Group,this.lights.name="lights",this.add(this.lights),this.cameras=new o.Group,this.cameras.name="cameras",this.add(this.cameras),this.world=new o.Group,this.world.name="world",this.add(this.world)}init(){return new Promise(e=>{this.setupLights().then(()=>this.setupCameras()).then(()=>this.setupWorld()).then(()=>this.setupPost()).then(()=>this.setupAnimation()).then(()=>this.setupDebug()).then(()=>e())})}setupLights(){return new Promise(e=>{e()})}setupCameras(){return new Promise(e=>{e()})}setupWorld(){return new Promise(e=>{e()})}setupPost(){return new Promise(e=>{e()})}setupAnimation(){return new Promise(e=>{e()})}setupDebug(){return new Promise(e=>{e()})}dispose(){}update(){}draw(e){}postDraw(){}resize(e,t,s){}show(){this.clock.start(),this.showComplete()}showComplete(){this.enable()}hide(){this.disable(),this.hideComplete()}hideComplete(){this.clock.stop()}enable(){}disable(){}get deltaTime(){return Math.min(this.clock.getDelta(),1/30)}}class Ht{app;constructor(e){this.app=e,this.app.appHandlers.push({remote:this,callback:this.handleApp.bind(this)}),this.app.editorHandlers.push({remote:this,callback:this.handleEditor.bind(this)})}dispose(){const e=this.app.appHandlers.findIndex(t=>t.remote===this);e>-1&&(this.app.appHandlers.splice(e,1),this.app.editorHandlers.splice(e,1))}handleApp(e){}handleEditor(e){}}class Ln extends Ht{selectDropdown(e,t){this.app.send({event:"selectComponent",target:"app",data:{dropdown:e,value:t}})}updateDropdown(e,t){this.app.send({event:"draggableListUpdate",target:"app",data:{dropdown:e,value:t}})}handleApp(e){switch(e.event){case"selectComponent":this.app.dispatchEvent({type:P.SELECT_DROPDOWN,value:e.data});break;case"draggableListUpdate":this.app.dispatchEvent({type:P.DRAG_UPDATE,value:e.data});break}}}function kn(i,e,t){if(i.editor){t.ui.restore(),t.onSelectionChange(a=>{a.length<1||a.forEach(l=>{let c=l.address.sheetId,h="setSheet",u={};switch(l.type){case"Theatre_Sheet_PublicAPI":h="setSheet",u={sheet:l.address.sheetId},e.activeSheet=e.sheets.get(l.address.sheetId);break;case"Theatre_SheetObject_PublicAPI":h="setSheetObject",c+=`_${l.address.objectKey}`,u={id:c,sheet:l.address.sheetId,key:l.address.objectKey},e.activeSheet=e.sheets.get(l.address.sheetId);break}i.send({event:h,target:"app",data:u})})});let s=-1;const n=()=>{if(e.activeSheet!==void 0&&s!==e.activeSheet.sequence.position){s=e.activeSheet.sequence.position;const a=e.activeSheet;i.send({event:"updateTimeline",target:"app",data:{position:s,sheet:a.address.sheetId}})}},r=()=>{n(),requestAnimationFrame(r)};n(),r()}else t.ui.hide()}function Un(){setTimeout(()=>{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)return;const s=t.children[1];s.style.justifyContent="left";try{const n=s.children[1];for(n.style.transform="translateX(10px)";n.children.length>1;)n.removeChild(n.children[0])}catch{}try{const n=t.children[3];n.style.top="0",n.style.right="300px"}catch{}},1e3)}function jn(i,e,t,s,n){const r=1-i;return r*r*r*e+3*r*r*i*t+3*r*i*i*s+i*i*i*n}function Nn(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,r=(t-i.position)/(e.position-i.position);return jn(r,i.value,i.value+s,e.value+n,e.value)}class Fn extends Ht{project;sheets=new Map;sheetObjects=new Map;sheetObjectCBs=new Map;sheetObjectUnsubscribe=new Map;activeSheet;studio=void 0;dispose(){this.project=void 0,this.sheets=new Map,this.sheetObjects=new Map,this.sheetObjectCBs=new Map,this.sheetObjectUnsubscribe=new Map}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=>{const r=t!==void 0?{...t}:{};this.sheet(e,s)?.sequence.play(r).then(a=>n(a)),this.app.send({event:"playSheet",target:"editor",data:{sheet:e,instance:s,value:t}})})}pauseSheet(e,t){this.sheet(e,t)?.sequence.pause(),this.app.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,r){if(this.project===void 0){console.error("Theatre Project hasn't been created yet.");return}const a=this.sheet(e,r);if(a===void 0)return;const c=`${this.getSheetInstance(e,r)}_${t}`;let h=this.sheetObjects.get(c),u=s;h!==void 0&&(u={...s,...h.value}),h=a.object(t,u),this.sheetObjects.set(c,h),this.sheetObjectCBs.set(c,n!==void 0?n:yt);const f=h.onValuesChange(m=>{if(this.app.editor){for(const E in m){const y=m[E];typeof y=="object"&&gs(y)&&(m[E]={r:y.r,g:y.g,b:y.b,a:y.a})}this.app.send({event:"updateSheetObject",target:"app",data:{sheet:e,sheetObject:c,values:m}})}const g=this.sheetObjectCBs.get(c);g!==void 0&&g(m)});return this.sheetObjectUnsubscribe.set(c,f),h}getSheetObjectKeyframes(e,t,s){const n=this.sheet(e);if(n===void 0)return[];const r=`${e}_${t}`,a=this.sheetObjects.get(r);return a===void 0?[]:n.sequence.__experimental_getKeyframes(a.props[s])}getSheetObjectVectors(e,t){const s=this.sheet(e);if(s===void 0)return[];const n=`${e}_${t}`,r=this.sheetObjects.get(n);if(r===void 0)return[];const a=[],l=s.sequence.__experimental_getKeyframes(r.props.x),c=s.sequence.__experimental_getKeyframes(r.props.y),h=s.sequence.__experimental_getKeyframes(r.props.z),u=new Set;return l.forEach(m=>u.add(m.position)),c.forEach(m=>u.add(m.position)),h.forEach(m=>u.add(m.position)),Array.from(u).sort((m,g)=>m-g).forEach(m=>{const g=(E,y)=>{const O=E.find((S,w)=>S.position<=y&&(E[w+1]?.position||1/0)>y),_=E.find(S=>S.position>y);if(!O)return _?.value||0;if(!_||O.position===y)return O.value;if(O.type==="bezier")return Nn(O,_,y);const b=(y-O.position)/(_.position-O.position);return O.value+b*(_.value-O.value)};a.push({position:m,x:g(l,m),y:g(c,m),z:g(h,m)})}),a}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 r=`${t}_${s}`,a=this.sheetObjectUnsubscribe.get(r);a!==void 0&&(this.sheetObjects.delete(r),this.sheetObjectCBs.delete(r),this.sheetObjectUnsubscribe.delete(r),a())}handleApp(e){let t;switch(e.event){case"setSheet":t=this.sheets.get(e.data.sheet),t!==void 0&&(this.activeSheet=t,this.studio?.setSelection([t]));break;case"setSheetObject":t=this.sheetObjects.get(`${e.data.sheet}_${e.data.key}`),t!==void 0&&this.studio?.setSelection([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);break;case"updateTimeline":t=this.sheets.get(e.data.sheet),this.activeSheet!==void 0&&(this.activeSheet.sequence.position=e.data.position);break}}handleEditor(e){if(this.app.editor)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}}handleEditorApp(){if(this.app.editor){this.studio?.ui.restore(),this.studio?.onSelectionChange(n=>{n.length<1||n.forEach(r=>{let a=r.address.sheetId,l="setSheet",c={};switch(r.type){case"Theatre_Sheet_PublicAPI":l="setSheet",c={sheet:r.address.sheetId},this.activeSheet=this.sheets.get(r.address.sheetId);break;case"Theatre_SheetObject_PublicAPI":l="setSheetObject",a+=`_${r.address.objectKey}`,c={id:a,sheet:r.address.sheetId,key:r.address.objectKey},this.activeSheet=this.sheets.get(r.address.sheetId);break}this.app.send({event:l,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.app.send({event:"updateTimeline",target:"app",data:{position:e,sheet:n.address.sheetId}})}},s=()=>{t(),requestAnimationFrame(s)};t(),s()}else this.studio?.ui.hide()}}function zn(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 et(i){const e={name:i.name,type:i.type,uuid:i.uuid,children:[]};return i.children.forEach(t=>{e.children.push(et(t))}),e}function Hn(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 Vn(i){switch(i){case"blendSrcAlpha":case"blendDstAlpha":case"blendEquationAlpha":case"clippingPlanes":case"shadowSide":case"precision":return!0}return!1}function Ze(i){const e={};for(const t in i){if(t.substring(0,1)==="_"||t.substring(0,2)==="is"||Vn(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:vt.renderToBlob(n),offset:[n.offset.x,n.offset.y],repeat:[n.repeat.x,n.repeat.y]}:t==="uniforms"&&(e[t]=Hn(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 Jt(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(r=>{n.push(Ze(r))}),e.material=n}else e.material=Ze(s.material)}else if(t.search("points")>-1){const s=i;if(Array.isArray(s.material)){const n=[];s.material.forEach(r=>{n.push(Ze(r))}),e.material=n}else e.material=Ze(s.material)}else if(t.search("line")>-1){const s=i;if(Array.isArray(s.material)){const n=[];s.material.forEach(r=>{n.push(Ze(r))}),e.material=n}else e.material=Ze(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 Bn(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 Yn(i,e){for(const t in e)i[t]=e[t]}function ee(i,e,t){if(i===void 0)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 a;switch(n){case 1:a=i[s[0]];break;case 2:a=i[s[0]][s[1]];break;case 3:a=i[s[0]][s[1]][s[2]];break;case 4:a=i[s[0]][s[1]][s[2]][s[3]];break;case 5:a=i[s[0]][s[1]][s[2]][s[3]][s[4]];break}a!=null&&Yn(a,t)}}function Cs(i){return new Promise((e,t)=>{const s=new Image;s.onload=()=>{const n=new o.Texture(s);n.wrapS=o.RepeatWrapping,n.wrapT=o.RepeatWrapping,n.needsUpdate=!0,e(n)},s.onerror=t,s.src=i})}class Gn extends Ht{canvas=null;inputElement=null;scene=void 0;scenes=new Map;renderer=void 0;renderTargets=new Map;groups=new Map;dispose(){this.scenes.forEach(e=>{Me(e)}),this.scenes.clear(),this.scene&&Me(this.scene),this.renderTargets.forEach(e=>{e.dispose()}),this.renderTargets.clear(),this.renderer?.dispose()}getObject(e){this.app.debugEnabled&&(this.renderer!==void 0&&(vt.renderer=this.renderer),this.app.send({event:"getObject",target:"app",data:e}))}setObject(e){this.renderer!==void 0&&(vt.renderer=this.renderer);const t=Jt(e);this.app.send({event:"setObject",target:"editor",data:t})}requestMethod(e,t,s,n){this.app.send({event:"requestMethod",target:"app",data:{uuid:e,key:t,value:s,subitem:n}})}updateObject(e,t,s){this.app.send({event:"updateObject",target:"app",data:{uuid:e,key:t,value:s}})}createTexture(e,t,s){this.app.send({event:"createTexture",target:"app",data:{uuid:e,key:t,value:s}})}addGroup(e){this.groups.get(e.title)===void 0&&(this.groups.set(e.title,{title:e.title,onUpdate:e.onUpdate}),this.app.send({event:"addGroup",target:"editor",data:JSON.stringify(e)}))}removeGroup(e){this.groups.get(e)!==void 0&&(this.groups.delete(e),this.app.send({event:"removeGroup",target:"editor",data:e}))}updateGroup(e,t,s){this.app.send({event:"updateGroup",target:"app",data:JSON.stringify({group:e,prop:t,value:s})})}removeAllGroups(){this.groups.forEach(e=>{const t=e.title;this.groups.delete(t),this.app.send({event:"removeGroup",target:"editor",data:t})}),this.groups.clear()}addSpline(e){setTimeout(()=>{this.app.send({event:"addSpline",target:"editor",data:JSON.stringify(e.toJSON())})},1)}setRenderer(e,t=null){if(this.renderer=e,this.canvas=e.domElement,this.inputElement=t!==null?t:this.canvas,!this.app.debugEnabled)return;const s=`#${e.getClearColor(new o.Color).getHexString()}`;this.app.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:o.ColorManagement.enabled,toneMapping:e.toneMapping,toneMappingExposure:e.toneMappingExposure}})}updateRenderer(e){this.app.send({event:"updateRenderer",target:"app",data:e})}addScene(e){if(e===void 0||(this.scenes.set(e.name,e),!this.app.debugEnabled))return;mi(),Ft(e);const t=et(e);this.app.send({event:"addScene",target:"editor",data:t})}refreshScene(e){if(!this.app.debugEnabled)return;const t=this.scenes.get(e);if(t!==void 0){const s=et(t);this.app.send({event:"refreshScene",target:"app",data:s})}}removeScene(e){if(e===void 0||(this.scenes.delete(e.name),!this.app.debugEnabled))return;const t=et(e);this.app.send({event:"removeScene",target:"editor",data:t})}removeAllScenes(){this.scenes.forEach(e=>this.removeScene(e))}getScene(e){let t=null;return this.scenes.forEach((s,n)=>{e.search(n)>-1&&(t=s)}),t}setScene(e){if(e===void 0||(this.scene=e,!this.app.debugEnabled))return;this.renderer!==void 0&&(vt.renderer=this.renderer),mi(),Ft(e);const t=et(e);this.app.send({event:"setScene",target:"editor",data:t})}addCamera(e){if(!this.app.debugEnabled)return;const t=Jt(e);this.app.send({event:"addCamera",target:"editor",data:t})}removeCamera(e){if(!this.app.debugEnabled)return;const t=Jt(e);this.app.send({event:"removeCamera",target:"editor",data:t})}handleApp(e){switch(e.event){case"getObject":this.app.dispatchEvent({type:P.GET_OBJECT,value:e.data});break;case"updateObject":this.app.dispatchEvent({type:P.UPDATE_OBJECT,value:e.data});break;case"createTexture":this.app.dispatchEvent({type:P.CREATE_TEXTURE,value:e.data});break;case"requestMethod":this.app.dispatchEvent({type:P.REQUEST_METHOD,value:e.data});break;case"refreshScene":this.app.send({event:"refreshScene",target:"editor",data:et(this.scenes.get(e.data.name))});break;case"updateRenderer":this.renderer&&(this.renderer.autoClear=e.data.autoClear,this.renderer.autoClearColor=e.data.autoClearColor,this.renderer.autoClearDepth=e.data.autoClearDepth,this.renderer.autoClearStencil=e.data.autoClearStencil,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,o.ColorManagement.enabled=e.data.colorManagement);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"setObject":this.app.dispatchEvent({type:P.SET_OBJECT,value:e.data});break;case"addScene":this.app.dispatchEvent({type:P.ADD_SCENE,value:e.data});break;case"refreshScene":this.app.dispatchEvent({type:P.REFRESH_SCENE,value:e.data});break;case"removeScene":this.app.dispatchEvent({type:P.REMOVE_SCENE,value:e.data});break;case"setScene":this.app.dispatchEvent({type:P.SET_SCENE,value:e.data});break;case"addCamera":this.app.dispatchEvent({type:P.ADD_CAMERA,value:e.data});break;case"removeCamera":this.app.dispatchEvent({type:P.REMOVE_CAMERA,value:e.data});break;case"addGroup":this.app.dispatchEvent({type:P.ADD_GROUP,value:e.data});break;case"removeGroup":this.app.dispatchEvent({type:P.REMOVE_GROUP,value:e.data});break;case"addSpline":this.app.dispatchEvent({type:P.ADD_SPLINE,value:e.data});break;case"addRenderer":this.app.dispatchEvent({type:P.ADD_RENDERER,value:e.data})}}addRT(e,t){const s=new o.WebGLRenderTarget(32,32,t);s.texture.name=e,this.renderTargets.set(e,s)}resize(e,t){const s=this.dpr;this.renderTargets.forEach(r=>{r.setSize(e*s,t*s)});const n=!(this.renderer?.domElement instanceof OffscreenCanvas);this.renderer?.setSize(e,t,n)}set dpr(e){this.renderer?.setPixelRatio(Ue(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}}var fi={exports:{}},nt={};/**
|
18
|
+
`,d=c.createShader(35633),p=c.createShader(35632),f=c.createProgram();if(!(p&&d&&f))return;c.shaderSource(d,h),c.shaderSource(p,u),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 y=c.getAttribLocation(f,"aPosition");c.vertexAttribPointer(y,3,5126,!1,0,0),c.enableVertexAttribArray(y),c.clearColor(1,1,1,1),c.clear(16384),c.viewport(0,0,1,1),c.drawArrays(4,0,3);const g=new Uint8Array(4);return c.readPixels(0,0,1,1,6408,5121,g),c.deleteProgram(f),c.deleteBuffer(m),g.join("")}(a),i="801621810",n="8016218135",r="80162181161",o=Fs?.isIpad?[["a7",r,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",r,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 dd extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}const Dl=[],pd=[];function f0(a,e){if(a===e)return 0;const t=a;a.length>e.length&&(a=e,e=t);let s=a.length,i=e.length;for(;s>0&&a.charCodeAt(~-s)===e.charCodeAt(~-i);)s--,i--;let n,r=0;for(;r<s&&a.charCodeAt(r)===e.charCodeAt(r);)r++;if(s-=r,i-=r,s===0)return i;let o,l,c=0,h=0,u=0;for(;h<s;)pd[h]=a.charCodeAt(r+h),Dl[h]=++h;for(;u<i;)for(n=e.charCodeAt(r+u),o=u++,c=u,h=0;h<s;h++)l=n===pd[h]?o:o+1,o=Dl[h],c=Dl[h]=o>c?l>c?c+1:l:l>o?o+1:l;return c}function m0(a){return a!=null}const g0=({mobileTiers:a=[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"}={})=>Fl(void 0,void 0,void 0,function*(){const r={};if(Qf)return{tier:0,type:"SSR"};const{isIpad:o=!!Fs?.isIpad,isMobile:l=!!Fs?.isMobile,screenSize:c=window.screen,loadBenchmarks:h=T=>Fl(void 0,void 0,void 0,function*(){const M=yield fetch(`${n}/${T}`).then(w=>w.json());if(parseInt(M.shift().split(".")[0],10)<4)throw new dd("Detect GPU benchmark data is out of date. Please update to version 4x");return M})}=t;let{renderer:u}=t;const d=(T,M,w,R,P)=>({device:P,fps:R,gpu:w,isMobile:l,tier:T,type:M});let p,f="";if(u)u=ud(u),p=[u];else{const T=s||function(w,R=!1){const P={alpha:!1,antialias:!1,depth:!1,failIfMajorPerformanceCaveat:R,powerPreference:"high-performance",stencil:!1};w&&delete P.powerPreference;const z=window.document.createElement("canvas"),$=z.getContext("webgl",P)||z.getContext("experimental-webgl",P);return $??void 0}(Fs?.isSafari12,i);if(!T)return d(0,"WEBGL_UNSUPPORTED");const M=Fs?.isFirefox?null:T.getExtension("WEBGL_debug_renderer_info");if(u=M?T.getParameter(M.UNMASKED_RENDERER_WEBGL):T.getParameter(T.RENDERER),!u)return d(1,"FALLBACK");f=u,u=ud(u),p=function(w,R,P){return R==="apple gpu"?p0(w,R,P):[R]}(T,u,l)}const m=(yield Promise.all(p.map(function(T){var M;return Fl(this,void 0,void 0,function*(){const w=(_e=>{const rt=l?["adreno","apple","mali-t","mali","nvidia","powervr","samsung"]:["intel","apple","amd","radeon","nvidia","geforce","adreno"];for(const Dt of rt)if(_e.includes(Dt))return Dt})(T);if(!w)return;const R=`${l?"m":"d"}-${w}${o?"-ipad":""}.json`,P=r[R]=(M=r[R])!==null&&M!==void 0?M:h(R);let z;try{z=yield P}catch(_e){if(_e instanceof dd)throw _e;return}const $=function(_e){var rt;const Dt=(_e=_e.replace(/\([^)]+\)/,"")).match(/\d+/)||_e.match(/(\W|^)([A-Za-z]{1,3})(\W|$)/g);return(rt=Dt?.join("").replace(/\W|amd/g,""))!==null&&rt!==void 0?rt:""}(T);let q=z.filter(([,_e])=>_e===$);q.length||(q=z.filter(([_e])=>_e.includes(T)));const j=q.length;if(j===0)return;const X=T.split(/[.,()\[\]/\s]/g).sort().filter((_e,rt,Dt)=>rt===0||_e!==Dt[rt-1]).join(" ");let Z,[ve,,,,ue]=j>1?q.map(_e=>[_e,f0(X,_e[2])]).sort(([,_e],[,rt])=>_e-rt)[0][0]:q[0],ge=Number.MAX_VALUE;const{devicePixelRatio:ie}=window,we=c.width*ie*c.height*ie;for(const _e of ue){const[rt,Dt]=_e,yr=rt*Dt,mn=Math.abs(we-yr);mn<ge&&(ge=mn,Z=_e)}if(!Z)return;const[,,ke,nt]=Z;return[ge,ke,ve,nt]})}))).filter(m0).sort(([T=Number.MAX_VALUE,M],[w=Number.MAX_VALUE,R])=>T===w?M-R:T-w);if(!m.length){const T=d0.find(M=>u.includes(M));return T?d(0,"BLOCKLISTED",T):d(1,"FALLBACK",`${u} (${f})`)}const[,y,g,_]=m[0];if(y===-1)return d(0,"BLOCKLISTED",g,y,_);const b=l?a:e;let S=0;for(let T=0;T<b.length;T++)y>=b[T]&&(S=T);return d(S,"BENCHMARK",g,y,_)});var Kf=(a=>(a[a.High=0]="High",a[a.Medium=1]="Medium",a[a.Low=2]="Low",a))(Kf||{});function Jf(a){let e=0;const t=performance.now();function s(){e++;const i=performance.now();if(i-t>=100){const n=e/((i-t)/1e3),r=Math.round(n/30)*30;a(r)}else requestAnimationFrame(s)}requestAnimationFrame(s)}function y0(a,e,t){return new Promise(s=>{g0().then(i=>{let n=!1;const r=/^((?!chrome|android).)*safari/i.test(navigator.userAgent);if(n="transferControlToOffscreen"in a,r){const l=navigator.userAgent.match(/version\/(\d+)/i);n=(l?parseInt(l[1]):0)>=17}const o={dpr:devicePixelRatio,fps:30,width:innerWidth,height:innerHeight,mobile:i.isMobile!==void 0?i.isMobile:!1,supportOffScreenCanvas:n,quality:2,dev:e,editor:t};i.tier===3?o.quality=0:i.tier===2&&(o.quality=1),Jf(l=>{o.fps=l,s(o)}),s(o)})})}function Si(a,e,t){return Math.min(e,Math.max(a,t))}function Bo(a,e,t){return(t-a)/(e-a)}function ir(a,e,t){return a*(1-t)+e*t}function x0(a,e,t,s,i){return ir(t,s,Bo(a,e,i))}function _0(a,e){const t=a-e;return Math.sqrt(t*t)}function ss(a,e=1){return Number(a.toFixed(e))}function b0(a,e,t,s){return ir(a,e,1-Math.exp(-t*s))}function T0(a,e=1){return Number(a.toFixed(e))}function S0(a,e,t,s){return a===e&&t===s}function v0(a,e,t,s){return 1/(3*e*a*a+2*t*a+s)}function w0(a,e,t,s,i){return e*(a*a*a)+t*(a*a)+s*a+i}function E0(a,e,t,s,i){const n=a*a;return e*(n*a)+t*n+s*a+i}function M0(a,e,t,s,i){if(a<=0)return 0;if(a>=1)return 1;if(S0(e,t,s,i))return a;const n=0,r=0,o=e,l=t,c=s,h=i,u=1,d=1,p=u-3*c+3*o-n,f=3*c-6*o+3*n,m=3*o-3*n,y=n,g=d-3*h+3*l-r,_=3*h-6*l+3*r,b=3*l-3*r,S=r;let T=a;for(let M=0;M<5;M++){const w=w0(T,p,f,m,y);let R=v0(T,p,f,m);R===1/0&&(R=a),T-=(w-a)*R,T=Math.min(Math.max(T,0),1)}return E0(T,g,_,b,S)}const rh=a=>{a?.dispose()},Wh=a=>{if(a)if(Array.isArray(a))a.forEach(e=>Wh(e));else{for(const e in a){const t=a[e];t!==null&&t instanceof x.Texture&&rh(t)}if(a.isShaderMaterial===!0){const e=a;for(const t in e.uniforms){const s=e.uniforms[t];s.value!==null&&s.value instanceof x.Texture&&rh(s.value)}}a.dispose()}},Ls=a=>{if(a){for(;a.children.length>0;){const e=a.children[0];e.type==="Audio"?(e.pause(),e.parent&&e.parent.remove(e)):Ls(e)}if(a.parent&&a.parent.remove(a),a.isMesh){const e=a;e.geometry?.dispose(),Wh(e.material)}a.dispose!==void 0&&a.dispose()}};exports.totalThreeObjects=0;const ah=()=>{exports.totalThreeObjects=0},Io=a=>{if(!a)return;let e=a.name.replaceAll(" ","").replaceAll("/",".");if(e.length===0&&(e=`obj_${exports.totalThreeObjects}`,exports.totalThreeObjects++),a.parent!==null&&a.parent.uuid.length>0&&(e=`${a.parent.uuid}.${e}`),a.uuid=e,a.isMesh!==void 0){const t=a;if(Array.isArray(t.material))t.material.forEach((s,i)=>{s.uuid=`${e}.material.${i}`});else{const s=t.material;s.uuid=`${e}.material`}}a.children.forEach(t=>Io(t))};class sa{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,r=this.renderToCanvas(e);this.context.drawImage(r,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 x.OrthographicCamera(-.5,.5,.5,-.5,0,100),this.scene=new x.Scene,this.material=new x.MeshBasicMaterial;const t=new x.BufferGeometry;t.setAttribute("position",new x.Float32BufferAttribute([-.5,-.5,0,1.5,-.5,0,-.5,1.5,0],3)),t.setAttribute("normal",new x.Float32BufferAttribute([0,0,1,0,0,1],3)),t.setAttribute("uv",new x.Float32BufferAttribute([0,0,2,0,0,2],2));const s=new x.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=x.LinearSRGBColorSpace,e.colorSpace=x.LinearSRGBColorSpace,this.material.map=e,this.renderer.render(this.scene,this.camera),this.renderer.outputColorSpace=t,e.colorSpace=s}return this.renderer.domElement}}function C0(a){return new Promise(e=>{const t=new x.ObjectLoader;t.parseAsync(a.scene).then(s=>{const i=new x.AnimationMixer(s);if(a.animations.length>0){const r=a.animations.map(l=>x.AnimationClip.parse(l));i.clipAction(r[0]).play(),i.getRoot().animations=a.animations,i.getRoot().mixer=i}const n=[];a.cameras&&a.cameras.length>0&&a.cameras.forEach(r=>{const o=t.parse(r);n.push(o)}),e({animations:a.animations,model:s,mixer:i,cameras:n})})})}const xn=$h(["ctrlKey","metaKey","shiftKey","button","pointerId","pointerType","clientX","clientY","pageX","pageY"]),A0=$h(["clientX","clientY","deltaX","deltaY","deltaMode"]),R0=$h(["ctrlKey","metaKey","shiftKey","keyCode"]);function N0(a,e){a.preventDefault(),A0(a,e)}function P0(a){a.preventDefault()}function F0(a,e,t){for(const s of e)t[s]=a[s]}function $h(a){return function(t,s){const i={type:t.type};F0(t,a,i),s(i)}}function Ol(a,e){const t=[],s={type:a.type,touches:t};for(let i=0;i<a.touches.length;++i){const n=a.touches[i];t.push({pageX:n.pageX,pageY:n.pageY})}e(s)}const D0={37:!0,38:!0,39:!0,40:!0};function O0(a,e){const{keyCode:t}=a;D0[t]&&(a.preventDefault(),R0(a,e))}const B0={contextmenu:P0,mousedown:xn,mousemove:xn,mouseup:xn,pointerdown:xn,pointermove:xn,pointerup:xn,touchstart:Ol,touchmove:Ol,touchend:Ol,wheel:N0,keydown:O0};let I0=0;class L0{id;worker;constructor(e,t,s){this.id=I0++,this.worker=t;const i=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,l=>{o(l,i)});function n(){i({type:"resize",left:0,top:0,width:innerWidth,height:innerHeight})}window.addEventListener("resize",n),n()}}class em extends x.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=ua,e.stopPropagation=ua,this.dispatchEvent(e)}focus(){}getRootNode(){return this}}class U0{targets={};constructor(){this.handleEvent=this.handleEvent.bind(this)}makeProxy(e){const{id:t}=e,s=new em;this.targets[t]=s}getProxy(e){return this.targets[e]}handleEvent(e){this.targets[e.id]?.handleEvent(e.data)}}var Q=(a=>(a.CUSTOM="ToolEvents::custom",a.SELECT_DROPDOWN="ToolEvents::selectDropdown",a.DRAG_UPDATE="ToolEvents::dragUpdate",a.ADD_SCENE="ToolEvents::addScene",a.REFRESH_SCENE="ToolEvents::refreshScene",a.REMOVE_SCENE="ToolEvents::removeScene",a.SET_SCENE="ToolEvents::setScene",a.GET_OBJECT="ToolEvents::getObject",a.SET_OBJECT="ToolEvents::setObject",a.UPDATE_OBJECT="ToolEvents::updateObject",a.CREATE_TEXTURE="ToolEvents::createTexture",a.REQUEST_METHOD="ToolEvents::requestMethod",a.ADD_CAMERA="ToolEvents::addCamera",a.REMOVE_CAMERA="ToolEvents::removeCamera",a.ADD_GROUP="ToolEvents::addGroup",a.REMOVE_GROUP="ToolEvents::removeGroup",a.ADD_SPLINE="ToolEvents::addSpline",a.ADD_RENDERER="ToolEvents::addRenderer",a.UPDATE_RENDERER="ToolEvents::updateRenderer",a))(Q||{});class k0 extends x.EventDispatcher{components=new Map;appHandlers=[];editorHandlers=[];_appID="";_debugEnabled;_broadcastChannel=void 0;_webSocket=void 0;_mode="app";_connected=!1;_useBC=!1;constructor(e,t,s,i=!0){super(),this._appID=e,this._debugEnabled=t,this.editor=s,t&&(this._useBC=i,i?(this._broadcastChannel=new BroadcastChannel(e),this._broadcastChannel.addEventListener("message",this.messageHandler)):(this._webSocket=new WebSocket(e),this._webSocket.addEventListener("open",this.openHandler),this._webSocket.addEventListener("close",this.closeHandler),this._webSocket.addEventListener("message",this.messageHandler)))}addComponent(e,t){this.components.set(e,t)}dispose(){this._broadcastChannel!==void 0&&this._broadcastChannel.removeEventListener("message",this.messageHandler),this._webSocket!==void 0&&(this._webSocket.removeEventListener("open",this.openHandler),this._webSocket.removeEventListener("close",this.closeHandler),this._webSocket.removeEventListener("message",this.messageHandler)),this.components.forEach(e=>{e.dispose()}),this.components.clear()}send(e){this._mode!==e.target&&(this._useBC?this._broadcastChannel?.postMessage(e):this._connected&&this._webSocket?.send(JSON.stringify(e)))}messageHandler=e=>{let t=e.data;this._useBC||(t=JSON.parse(e.data)),t.target==="editor"?this.handleEditorBroadcast(t):this.handleAppBroadcast(t)};handleAppBroadcast(e){switch(this.appHandlers.forEach(t=>{t.callback(e)}),e.event){case"custom":this.dispatchEvent({type:"ToolEvents::custom",value:e.data});break}}handleEditorBroadcast(e){switch(this.editorHandlers.forEach(t=>{t.callback(e)}),e.event){case"custom":this.dispatchEvent({type:"ToolEvents::custom",value:e.data});break}}openHandler=()=>{this._connected=!0};closeHandler=()=>{this._connected=!1};get appID(){return this._appID}get connected(){return this._connected}get debugEnabled(){return this._debugEnabled}get mode(){return this._mode}get isApp(){return this._mode==="app"}get editor(){return this._mode==="editor"}set editor(e){e&&(this._mode="editor")}}class z0{canvas;inputElement;settings;playing=!1;rafID=-1;constructor(e,t,s){this.canvas=e,this.inputElement=t,this.settings=s}dispose(){this.stop()}play(){this.playing||(this.playing=!0,this.onUpdate())}stop(){this.playing&&(this.playing=!1,cancelAnimationFrame(this.rafID),this.rafID=-1)}update(){}draw(){}resize(e,t){this.settings.supportOffScreenCanvas&&(this.inputElement.clientWidth=e,this.inputElement.clientHeight=t,this.inputElement.width=e,this.inputElement.height=t)}onResize=e=>{this.resize(e.width,e.height)};onUpdate=()=>{this.update(),this.draw(),this.rafID=requestAnimationFrame(this.onUpdate)}}class G0 extends x.Scene{clock;cameras;lights;world;constructor(e){super(),this.name=e,this.clock=new x.Clock,this.lights=new x.Group,this.lights.name="lights",this.add(this.lights),this.cameras=new x.Group,this.cameras.name="cameras",this.add(this.cameras),this.world=new x.Group,this.world.name="world",this.add(this.world)}init(){return new Promise(e=>{this.setupLights().then(()=>this.setupCameras()).then(()=>this.setupWorld()).then(()=>this.setupPost()).then(()=>this.setupAnimation()).then(()=>this.setupDebug()).then(()=>e())})}setupLights(){return new Promise(e=>{e()})}setupCameras(){return new Promise(e=>{e()})}setupWorld(){return new Promise(e=>{e()})}setupPost(){return new Promise(e=>{e()})}setupAnimation(){return new Promise(e=>{e()})}setupDebug(){return new Promise(e=>{e()})}dispose(){}update(){}draw(e){}postDraw(){}resize(e,t,s){}show(){this.clock.start(),this.showComplete()}showComplete(){this.enable()}hide(){this.disable(),this.hideComplete()}hideComplete(){this.clock.stop()}enable(){}disable(){}get deltaTime(){return Math.min(this.clock.getDelta(),1/30)}}class nl{app;constructor(e){this.app=e,this.app.appHandlers.push({remote:this,callback:this.handleApp.bind(this)}),this.app.editorHandlers.push({remote:this,callback:this.handleEditor.bind(this)})}dispose(){const e=this.app.appHandlers.findIndex(t=>t.remote===this);e>-1&&(this.app.appHandlers.splice(e,1),this.app.editorHandlers.splice(e,1))}handleApp(e){}handleEditor(e){}}class V0 extends nl{selectDropdown(e,t){this.app.send({event:"selectComponent",target:"app",data:{dropdown:e,value:t}})}updateDropdown(e,t){this.app.send({event:"draggableListUpdate",target:"app",data:{dropdown:e,value:t}})}handleApp(e){switch(e.event){case"selectComponent":this.app.dispatchEvent({type:Q.SELECT_DROPDOWN,value:e.data});break;case"draggableListUpdate":this.app.dispatchEvent({type:Q.DRAG_UPDATE,value:e.data});break}}}function H0(a,e,t){if(a.editor){t.ui.restore(),t.onSelectionChange(r=>{r.length<1||r.forEach(o=>{let l=o.address.sheetId,c="setSheet",h={};switch(o.type){case"Theatre_Sheet_PublicAPI":c="setSheet",h={sheet:o.address.sheetId},e.activeSheet=e.sheets.get(o.address.sheetId);break;case"Theatre_SheetObject_PublicAPI":c="setSheetObject",l+=`_${o.address.objectKey}`,h={id:l,sheet:o.address.sheetId,key:o.address.objectKey},e.activeSheet=e.sheets.get(o.address.sheetId);break}a.send({event:c,target:"app",data:h})})});let s=-1;const i=()=>{if(e.activeSheet!==void 0&&s!==e.activeSheet.sequence.position){s=e.activeSheet.sequence.position;const r=e.activeSheet;a.send({event:"updateTimeline",target:"app",data:{position:s,sheet:r.address.sheetId}})}},n=()=>{i(),requestAnimationFrame(n)};i(),n()}else t.ui.hide()}function W0(){setTimeout(()=>{const a=document.getElementById("theatrejs-studio-root");if(a===null||a.shadowRoot===null)return;const e=a.shadowRoot.getElementById("pointer-root");if(e===null)return;const t=e.children[0];if(t===null)return;const s=t.children[1];s.style.justifyContent="left";try{const i=s.children[1];for(i.style.transform="translateX(10px)";i.children.length>1;)i.removeChild(i.children[0])}catch{}try{const i=t.children[3];i.style.top="0",i.style.right="300px"}catch{}},1e3)}function $0(a,e,t,s,i){const n=1-a;return n*n*n*e+3*n*n*a*t+3*n*a*a*s+a*a*a*i}function j0(a,e,t){if(a.type!=="bezier"||a.handles.length!==4)throw new Error("Invalid keyframe data for Bézier interpolation.");const[s,i]=a.handles,n=(t-a.position)/(e.position-a.position);return $0(n,a.value,a.value+s,e.value+i,e.value)}class q0 extends nl{project;sheets=new Map;sheetObjects=new Map;sheetObjectCBs=new Map;sheetObjectUnsubscribe=new Map;activeSheet;studio=void 0;constructor(e){super(e),window.RemoteTheatre=this}dispose(){this.project=void 0,this.sheets=new Map,this.sheetObjects=new Map,this.sheetObjectCBs=new Map,this.sheetObjectUnsubscribe=new Map}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=>{const n=t!==void 0?{...t}:{};this.sheet(e,s)?.sequence.play(n).then(r=>i(r)),this.app.send({event:"playSheet",target:"editor",data:{sheet:e,instance:s,value:t}})})}pauseSheet(e,t){this.sheet(e,t)?.sequence.pause(),this.app.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 r=this.sheet(e,n);if(r===void 0)return;const l=`${this.getSheetInstance(e,n)}_${t}`;let c=this.sheetObjects.get(l),h=s;c!==void 0&&(h={...s,...c.value}),c=r.object(t,h),this.sheetObjects.set(l,c),this.sheetObjectCBs.set(l,i!==void 0?i:ua);const u=c.onValuesChange(d=>{if(this.app.editor){for(const f in d){const m=d[f];typeof m=="object"&&Zf(m)&&(d[f]={r:m.r,g:m.g,b:m.b,a:m.a})}this.app.send({event:"updateSheetObject",target:"app",data:{sheet:e,sheetObject:l,values:d}})}const p=this.sheetObjectCBs.get(l);p!==void 0&&p(d)});return this.sheetObjectUnsubscribe.set(l,u),c}getSheetObjectKeyframes(e,t,s){const i=this.sheet(e);if(i===void 0)return[];const n=`${e}_${t}`,r=this.sheetObjects.get(n);return r===void 0?[]:i.sequence.__experimental_getKeyframes(r.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 r=[],o=s.sequence.__experimental_getKeyframes(n.props.x),l=s.sequence.__experimental_getKeyframes(n.props.y),c=s.sequence.__experimental_getKeyframes(n.props.z),h=new Set;return o.forEach(d=>h.add(d.position)),l.forEach(d=>h.add(d.position)),c.forEach(d=>h.add(d.position)),Array.from(h).sort((d,p)=>d-p).forEach(d=>{const p=(f,m)=>{const y=f.find((b,S)=>b.position<=m&&(f[S+1]?.position||1/0)>m),g=f.find(b=>b.position>m);if(!y)return g?.value||0;if(!g||y.position===m)return y.value;if(y.type==="bezier")return j0(y,g,m);const _=(m-y.position)/(g.position-y.position);return y.value+_*(g.value-y.value)};r.push({position:d,x:p(o,d),y:p(l,d),z:p(c,d)})}),r}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}`,r=this.sheetObjectUnsubscribe.get(n);r!==void 0&&(this.sheetObjects.delete(n),this.sheetObjectCBs.delete(n),this.sheetObjectUnsubscribe.delete(n),r())}handleApp(e){let t;switch(e.event){case"setSheet":t=this.sheets.get(e.data.sheet),t!==void 0&&(this.activeSheet=t,this.studio?.setSelection([t]));break;case"setSheetObject":t=this.sheetObjects.get(`${e.data.sheet}_${e.data.key}`),t!==void 0&&this.studio?.setSelection([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);break;case"updateTimeline":t=this.sheets.get(e.data.sheet),this.activeSheet!==void 0&&(this.activeSheet.sequence.position=e.data.position);break}}handleEditor(e){if(this.app.editor)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}}handleEditorApp(){if(this.app.editor){this.studio?.ui.restore(),this.studio?.onSelectionChange(i=>{i.length<1||i.forEach(n=>{let r=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",r+=`_${n.address.objectKey}`,l={id:r,sheet:n.address.sheetId,key:n.address.objectKey},this.activeSheet=this.sheets.get(n.address.sheetId);break}this.app.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.app.send({event:"updateTimeline",target:"app",data:{position:e,sheet:i.address.sheetId}})}},s=()=>{t(),requestAnimationFrame(s)};t(),s()}else this.studio?.ui.hide()}}function Y0(a){if(a.name==="cameras")return"camera";if(a.name==="interactive")return"interactive";if(a.name==="lights")return"light";if(a.name==="ui")return"ui";if(a.name==="utils")return"utils";const e=a.type;return e.search("Helper")>-1?"icon_utils":e.search("Camera")>-1?"camera":e.search("Light")>-1?"light":"obj3D"}function Gn(a){const e={name:a.name,type:a.type,uuid:a.uuid,children:[]};return a.children.forEach(t=>{e.children.push(Gn(t))}),e}function X0(a){const e={};for(const t in a){const s=a[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 Z0(a){switch(a){case"blendSrcAlpha":case"blendDstAlpha":case"blendEquationAlpha":case"clippingPlanes":case"shadowSide":case"precision":return!0}return!1}function _n(a){const e={};for(const t in a){if(t.substring(0,1)==="_"||t.substring(0,2)==="is"||Z0(t))continue;const s=typeof a[t],i=a[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:sa.renderToBlob(i),offset:[i.offset.x,i.offset.y],repeat:[i.repeat.x,i.repeat.y]}:t==="uniforms"&&(e[t]=X0(e[t]))):t==="glslVersion"?e[t]="":e[t]={src:"",offset:[0,0],repeat:[1,1]};break}}return a.anisotropy!==void 0&&(e.anisotropy=a.anisotropy),a.clearcoat!==void 0&&(e.clearcoat=a.clearcoat),a.iridescence!==void 0&&(e.iridescence=a.iridescence),a.dispersion!==void 0&&(e.dispersion=a.dispersion),a.sheen!==void 0&&(e.sheen=a.sheen),a.transmission!==void 0&&(e.transmission=a.transmission),a.transmission!==void 0&&(e.transmission=a.transmission),e}function Bl(a){a.updateMatrix();const e={name:a.name,type:a.type,uuid:a.uuid,visible:a.visible,matrix:a.matrix.elements,animations:[],material:void 0,perspectiveCameraInfo:void 0,orthographicCameraInfo:void 0,lightInfo:void 0,children:[]};a.animations.forEach(s=>{e.animations.push({name:s.name,duration:s.duration,blendMode:s.blendMode})});const t=a.type.toLowerCase();if(t.search("mesh")>-1){const s=a;if(Array.isArray(s.material)){const i=[];s.material.forEach(n=>{i.push(_n(n))}),e.material=i}else e.material=_n(s.material)}else if(t.search("points")>-1){const s=a;if(Array.isArray(s.material)){const i=[];s.material.forEach(n=>{i.push(_n(n))}),e.material=i}else e.material=_n(s.material)}else if(t.search("line")>-1){const s=a;if(Array.isArray(s.material)){const i=[];s.material.forEach(n=>{i.push(_n(n))}),e.material=i}else e.material=_n(s.material)}else t.search("camera")>-1?a.type==="PerspectiveCamera"?e.perspectiveCameraInfo={fov:a.fov,zoom:a.zoom,near:a.near,far:a.far,focus:a.focus,aspect:a.aspect,filmGauge:a.filmGauge,filmOffset:a.filmOffset}:a.type==="OrthographicCamera"&&(e.orthographicCameraInfo={zoom:a.zoom,near:a.near,far:a.far,left:a.left,right:a.right,top:a.top,bottom:a.bottom}):t.search("light")>-1&&(e.lightInfo={color:a.color,intensity:a.intensity,decay:a.decay,distance:a.distance,angle:a.angle,penumbra:a.penumbra,groundColor:a.groundColor,width:a.width,height:a.height});return e}function Q0(a,e){const t=e.split(".");switch(t.length){case 1:return a[t[0]];case 2:return a[t[0]][t[1]];case 3:return a[t[0]][t[1]][t[2]];case 4:return a[t[0]][t[1]][t[2]][t[3]];case 5:return a[t[0]][t[1]][t[2]][t[3]][t[4]];case 6:return a[t[0]][t[1]][t[2]][t[3]][t[4]][t[5]]}}function K0(a,e){for(const t in e)a[t]=e[t]}function qe(a,e,t){if(a===void 0)return;const s=e.split("."),i=s.length;if(typeof t!="object")switch(i){case 1:a[s[0]]=t;break;case 2:a[s[0]][s[1]]=t;break;case 3:a[s[0]][s[1]][s[2]]=t;break;case 4:a[s[0]][s[1]][s[2]][s[3]]=t;break;case 5:a[s[0]][s[1]][s[2]][s[3]][s[4]]=t;break}else{let r;switch(i){case 1:r=a[s[0]];break;case 2:r=a[s[0]][s[1]];break;case 3:r=a[s[0]][s[1]][s[2]];break;case 4:r=a[s[0]][s[1]][s[2]][s[3]];break;case 5:r=a[s[0]][s[1]][s[2]][s[3]][s[4]];break}r!=null&&K0(r,t)}}function tm(a){return new Promise((e,t)=>{const s=new Image;s.onload=()=>{const i=new x.Texture(s);i.wrapS=x.RepeatWrapping,i.wrapT=x.RepeatWrapping,i.needsUpdate=!0,e(i)},s.onerror=t,s.src=a})}class J0 extends nl{canvas=null;inputElement=null;scene=void 0;scenes=new Map;renderer=void 0;renderTargets=new Map;groups=new Map;constructor(e){super(e),window.RemoteThree=this}dispose(){this.scenes.forEach(e=>{Ls(e)}),this.scenes.clear(),this.scene&&Ls(this.scene),this.renderTargets.forEach(e=>{e.dispose()}),this.renderTargets.clear(),this.renderer?.dispose()}getObject(e){this.app.debugEnabled&&(this.renderer!==void 0&&(sa.renderer=this.renderer),this.app.send({event:"getObject",target:"app",data:e}))}setObject(e){this.renderer!==void 0&&(sa.renderer=this.renderer);const t=Bl(e);this.app.send({event:"setObject",target:"editor",data:t})}requestMethod(e,t,s,i){this.app.send({event:"requestMethod",target:"app",data:{uuid:e,key:t,value:s,subitem:i}})}updateObject(e,t,s){this.app.send({event:"updateObject",target:"app",data:{uuid:e,key:t,value:s}})}createTexture(e,t,s){this.app.send({event:"createTexture",target:"app",data:{uuid:e,key:t,value:s}})}addGroup(e){this.groups.get(e.title)===void 0&&(this.groups.set(e.title,{title:e.title,onUpdate:e.onUpdate}),this.app.send({event:"addGroup",target:"editor",data:JSON.stringify(e)}))}removeGroup(e){this.groups.get(e)!==void 0&&(this.groups.delete(e),this.app.send({event:"removeGroup",target:"editor",data:e}))}updateGroup(e,t,s){this.app.send({event:"updateGroup",target:"app",data:JSON.stringify({group:e,prop:t,value:s})})}removeAllGroups(){this.groups.forEach(e=>{const t=e.title;this.groups.delete(t),this.app.send({event:"removeGroup",target:"editor",data:t})}),this.groups.clear()}addSpline(e){setTimeout(()=>{this.app.send({event:"addSpline",target:"editor",data:JSON.stringify(e.toJSON())})},1)}setRenderer(e,t=null){if(this.renderer=e,this.canvas=e.domElement,this.inputElement=t!==null?t:this.canvas,!this.app.debugEnabled)return;const s=`#${e.getClearColor(new x.Color).getHexString()}`;this.app.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:x.ColorManagement.enabled,toneMapping:e.toneMapping,toneMappingExposure:e.toneMappingExposure,type:e.isWebGLRenderer?"WebGLRenderer":"WebGPURenderer"}})}updateRenderer(e){this.app.send({event:"updateRenderer",target:"app",data:e})}addScene(e){if(e===void 0||(this.scenes.set(e.name,e),!this.app.debugEnabled))return;ah(),Io(e);const t=Gn(e);this.app.send({event:"addScene",target:"editor",data:t})}refreshScene(e){if(!this.app.debugEnabled)return;const t=this.scenes.get(e);if(t!==void 0){const s=Gn(t);this.app.send({event:"refreshScene",target:"app",data:s})}}removeScene(e){if(e===void 0||(this.scenes.delete(e.name),!this.app.debugEnabled))return;const t=Gn(e);this.app.send({event:"removeScene",target:"editor",data:t})}removeAllScenes(){this.scenes.forEach(e=>this.removeScene(e))}getScene(e){let t=null;return this.scenes.forEach((s,i)=>{e.search(i)>-1&&(t=s)}),t}setScene(e){if(e===void 0||(this.scene=e,!this.app.debugEnabled))return;this.renderer!==void 0&&(sa.renderer=this.renderer),ah(),Io(e);const t=Gn(e);this.app.send({event:"setScene",target:"editor",data:t})}addCamera(e){if(!this.app.debugEnabled)return;const t=Bl(e);this.app.send({event:"addCamera",target:"editor",data:t})}removeCamera(e){if(!this.app.debugEnabled)return;const t=Bl(e);this.app.send({event:"removeCamera",target:"editor",data:t})}handleApp(e){switch(e.event){case"getObject":this.app.dispatchEvent({type:Q.GET_OBJECT,value:e.data});break;case"updateObject":this.app.dispatchEvent({type:Q.UPDATE_OBJECT,value:e.data});break;case"createTexture":this.app.dispatchEvent({type:Q.CREATE_TEXTURE,value:e.data});break;case"requestMethod":this.app.dispatchEvent({type:Q.REQUEST_METHOD,value:e.data});break;case"refreshScene":this.app.send({event:"refreshScene",target:"editor",data:Gn(this.scenes.get(e.data.name))});break;case"updateRenderer":this.renderer&&(this.renderer.autoClear=e.data.autoClear,this.renderer.autoClearColor=e.data.autoClearColor,this.renderer.autoClearDepth=e.data.autoClearDepth,this.renderer.autoClearStencil=e.data.autoClearStencil,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,x.ColorManagement.enabled=e.data.colorManagement);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"setObject":this.app.dispatchEvent({type:Q.SET_OBJECT,value:e.data});break;case"addScene":this.app.dispatchEvent({type:Q.ADD_SCENE,value:e.data});break;case"refreshScene":this.app.dispatchEvent({type:Q.REFRESH_SCENE,value:e.data});break;case"removeScene":this.app.dispatchEvent({type:Q.REMOVE_SCENE,value:e.data});break;case"setScene":this.app.dispatchEvent({type:Q.SET_SCENE,value:e.data});break;case"addCamera":this.app.dispatchEvent({type:Q.ADD_CAMERA,value:e.data});break;case"removeCamera":this.app.dispatchEvent({type:Q.REMOVE_CAMERA,value:e.data});break;case"addGroup":this.app.dispatchEvent({type:Q.ADD_GROUP,value:e.data});break;case"removeGroup":this.app.dispatchEvent({type:Q.REMOVE_GROUP,value:e.data});break;case"addSpline":this.app.dispatchEvent({type:Q.ADD_SPLINE,value:e.data});break;case"addRenderer":this.app.dispatchEvent({type:Q.ADD_RENDERER,value:e.data})}}addRT(e,t){const s=new x.RenderTarget(32,32,t);s.texture.name=e,this.renderTargets.set(e,s)}resize(e,t){const s=this.dpr;this.renderTargets.forEach(n=>{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(Si(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}}var Pa={exports:{}},_r={};/**
|
19
19
|
* @license React
|
20
20
|
* react-jsx-runtime.production.min.js
|
21
21
|
*
|
@@ -23,7 +23,7 @@
|
|
23
23
|
*
|
24
24
|
* This source code is licensed under the MIT license found in the
|
25
25
|
* LICENSE file in the root directory of this source tree.
|
26
|
-
*/var
|
26
|
+
*/var fd;function ex(){if(fd)return _r;fd=1;var a=W,e=Symbol.for("react.element"),t=Symbol.for("react.fragment"),s=Object.prototype.hasOwnProperty,i=a.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,n={key:!0,ref:!0,__self:!0,__source:!0};function r(o,l,c){var h,u={},d=null,p=null;c!==void 0&&(d=""+c),l.key!==void 0&&(d=""+l.key),l.ref!==void 0&&(p=l.ref);for(h in l)s.call(l,h)&&!n.hasOwnProperty(h)&&(u[h]=l[h]);if(o&&o.defaultProps)for(h in l=o.defaultProps,l)u[h]===void 0&&(u[h]=l[h]);return{$$typeof:e,type:o,key:d,ref:p,props:u,_owner:i.current}}return _r.Fragment=t,_r.jsx=r,_r.jsxs=r,_r}var br={};/**
|
27
27
|
* @license React
|
28
28
|
* react-jsx-runtime.development.js
|
29
29
|
*
|
@@ -31,25 +31,458 @@
|
|
31
31
|
*
|
32
32
|
* This source code is licensed under the MIT license found in the
|
33
33
|
* LICENSE file in the root directory of this source tree.
|
34
|
-
*/var
|
35
|
-
`+
|
36
|
-
`),
|
37
|
-
`),
|
38
|
-
`+
|
34
|
+
*/var md;function tx(){return md||(md=1,process.env.NODE_ENV!=="production"&&function(){var a=W,e=Symbol.for("react.element"),t=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),n=Symbol.for("react.profiler"),r=Symbol.for("react.provider"),o=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),h=Symbol.for("react.suspense_list"),u=Symbol.for("react.memo"),d=Symbol.for("react.lazy"),p=Symbol.for("react.offscreen"),f=Symbol.iterator,m="@@iterator";function y(v){if(v===null||typeof v!="object")return null;var G=f&&v[f]||v[m];return typeof G=="function"?G:null}var g=a.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function _(v){{for(var G=arguments.length,Y=new Array(G>1?G-1:0),te=1;te<G;te++)Y[te-1]=arguments[te];b("error",v,Y)}}function b(v,G,Y){{var te=g.ReactDebugCurrentFrame,Me=te.getStackAddendum();Me!==""&&(G+="%s",Y=Y.concat([Me]));var Fe=Y.map(function(ye){return String(ye)});Fe.unshift("Warning: "+G),Function.prototype.apply.call(console[v],console,Fe)}}var S=!1,T=!1,M=!1,w=!1,R=!1,P;P=Symbol.for("react.module.reference");function z(v){return!!(typeof v=="string"||typeof v=="function"||v===s||v===n||R||v===i||v===c||v===h||w||v===p||S||T||M||typeof v=="object"&&v!==null&&(v.$$typeof===d||v.$$typeof===u||v.$$typeof===r||v.$$typeof===o||v.$$typeof===l||v.$$typeof===P||v.getModuleId!==void 0))}function $(v,G,Y){var te=v.displayName;if(te)return te;var Me=G.displayName||G.name||"";return Me!==""?Y+"("+Me+")":Y}function q(v){return v.displayName||"Context"}function j(v){if(v==null)return null;if(typeof v.tag=="number"&&_("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof v=="function")return v.displayName||v.name||null;if(typeof v=="string")return v;switch(v){case s:return"Fragment";case t:return"Portal";case n:return"Profiler";case i:return"StrictMode";case c:return"Suspense";case h:return"SuspenseList"}if(typeof v=="object")switch(v.$$typeof){case o:var G=v;return q(G)+".Consumer";case r:var Y=v;return q(Y._context)+".Provider";case l:return $(v,v.render,"ForwardRef");case u:var te=v.displayName||null;return te!==null?te:j(v.type)||"Memo";case d:{var Me=v,Fe=Me._payload,ye=Me._init;try{return j(ye(Fe))}catch{return null}}}return null}var X=Object.assign,Z=0,ve,ue,ge,ie,we,ke,nt;function _e(){}_e.__reactDisabledLog=!0;function rt(){{if(Z===0){ve=console.log,ue=console.info,ge=console.warn,ie=console.error,we=console.group,ke=console.groupCollapsed,nt=console.groupEnd;var v={configurable:!0,enumerable:!0,value:_e,writable:!0};Object.defineProperties(console,{info:v,log:v,warn:v,error:v,group:v,groupCollapsed:v,groupEnd:v})}Z++}}function Dt(){{if(Z--,Z===0){var v={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:X({},v,{value:ve}),info:X({},v,{value:ue}),warn:X({},v,{value:ge}),error:X({},v,{value:ie}),group:X({},v,{value:we}),groupCollapsed:X({},v,{value:ke}),groupEnd:X({},v,{value:nt})})}Z<0&&_("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var yr=g.ReactCurrentDispatcher,mn;function Ca(v,G,Y){{if(mn===void 0)try{throw Error()}catch(Me){var te=Me.stack.trim().match(/\n( *(at )?)/);mn=te&&te[1]||""}return`
|
35
|
+
`+mn+v}}var Ml=!1,Aa;{var zy=typeof WeakMap=="function"?WeakMap:Map;Aa=new zy}function Zu(v,G){if(!v||Ml)return"";{var Y=Aa.get(v);if(Y!==void 0)return Y}var te;Ml=!0;var Me=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var Fe;Fe=yr.current,yr.current=null,rt();try{if(G){var ye=function(){throw Error()};if(Object.defineProperty(ye.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(ye,[])}catch(Ot){te=Ot}Reflect.construct(v,[],ye)}else{try{ye.call()}catch(Ot){te=Ot}v.call(ye.prototype)}}else{try{throw Error()}catch(Ot){te=Ot}v()}}catch(Ot){if(Ot&&te&&typeof Ot.stack=="string"){for(var fe=Ot.stack.split(`
|
36
|
+
`),vt=te.stack.split(`
|
37
|
+
`),je=fe.length-1,Ze=vt.length-1;je>=1&&Ze>=0&&fe[je]!==vt[Ze];)Ze--;for(;je>=1&&Ze>=0;je--,Ze--)if(fe[je]!==vt[Ze]){if(je!==1||Ze!==1)do if(je--,Ze--,Ze<0||fe[je]!==vt[Ze]){var Kt=`
|
38
|
+
`+fe[je].replace(" at new "," at ");return v.displayName&&Kt.includes("<anonymous>")&&(Kt=Kt.replace("<anonymous>",v.displayName)),typeof v=="function"&&Aa.set(v,Kt),Kt}while(je>=1&&Ze>=0);break}}}finally{Ml=!1,yr.current=Fe,Dt(),Error.prepareStackTrace=Me}var yn=v?v.displayName||v.name:"",Ui=yn?Ca(yn):"";return typeof v=="function"&&Aa.set(v,Ui),Ui}function Gy(v,G,Y){return Zu(v,!1)}function Vy(v){var G=v.prototype;return!!(G&&G.isReactComponent)}function Ra(v,G,Y){if(v==null)return"";if(typeof v=="function")return Zu(v,Vy(v));if(typeof v=="string")return Ca(v);switch(v){case c:return Ca("Suspense");case h:return Ca("SuspenseList")}if(typeof v=="object")switch(v.$$typeof){case l:return Gy(v.render);case u:return Ra(v.type,G,Y);case d:{var te=v,Me=te._payload,Fe=te._init;try{return Ra(Fe(Me),G,Y)}catch{}}}return""}var xr=Object.prototype.hasOwnProperty,Qu={},Ku=g.ReactDebugCurrentFrame;function Na(v){if(v){var G=v._owner,Y=Ra(v.type,v._source,G?G.type:null);Ku.setExtraStackFrame(Y)}else Ku.setExtraStackFrame(null)}function Hy(v,G,Y,te,Me){{var Fe=Function.call.bind(xr);for(var ye in v)if(Fe(v,ye)){var fe=void 0;try{if(typeof v[ye]!="function"){var vt=Error((te||"React class")+": "+Y+" type `"+ye+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof v[ye]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw vt.name="Invariant Violation",vt}fe=v[ye](G,ye,te,Y,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(je){fe=je}fe&&!(fe instanceof Error)&&(Na(Me),_("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",te||"React class",Y,ye,typeof fe),Na(null)),fe instanceof Error&&!(fe.message in Qu)&&(Qu[fe.message]=!0,Na(Me),_("Failed %s type: %s",Y,fe.message),Na(null))}}}var Wy=Array.isArray;function Cl(v){return Wy(v)}function $y(v){{var G=typeof Symbol=="function"&&Symbol.toStringTag,Y=G&&v[Symbol.toStringTag]||v.constructor.name||"Object";return Y}}function jy(v){try{return Ju(v),!1}catch{return!0}}function Ju(v){return""+v}function ed(v){if(jy(v))return _("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",$y(v)),Ju(v)}var td=g.ReactCurrentOwner,qy={key:!0,ref:!0,__self:!0,__source:!0},sd,id;function Yy(v){if(xr.call(v,"ref")){var G=Object.getOwnPropertyDescriptor(v,"ref").get;if(G&&G.isReactWarning)return!1}return v.ref!==void 0}function Xy(v){if(xr.call(v,"key")){var G=Object.getOwnPropertyDescriptor(v,"key").get;if(G&&G.isReactWarning)return!1}return v.key!==void 0}function Zy(v,G){typeof v.ref=="string"&&td.current}function Qy(v,G){{var Y=function(){sd||(sd=!0,_("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",G))};Y.isReactWarning=!0,Object.defineProperty(v,"key",{get:Y,configurable:!0})}}function Ky(v,G){{var Y=function(){id||(id=!0,_("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",G))};Y.isReactWarning=!0,Object.defineProperty(v,"ref",{get:Y,configurable:!0})}}var Jy=function(v,G,Y,te,Me,Fe,ye){var fe={$$typeof:e,type:v,key:G,ref:Y,props:ye,_owner:Fe};return fe._store={},Object.defineProperty(fe._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(fe,"_self",{configurable:!1,enumerable:!1,writable:!1,value:te}),Object.defineProperty(fe,"_source",{configurable:!1,enumerable:!1,writable:!1,value:Me}),Object.freeze&&(Object.freeze(fe.props),Object.freeze(fe)),fe};function e0(v,G,Y,te,Me){{var Fe,ye={},fe=null,vt=null;Y!==void 0&&(ed(Y),fe=""+Y),Xy(G)&&(ed(G.key),fe=""+G.key),Yy(G)&&(vt=G.ref,Zy(G,Me));for(Fe in G)xr.call(G,Fe)&&!qy.hasOwnProperty(Fe)&&(ye[Fe]=G[Fe]);if(v&&v.defaultProps){var je=v.defaultProps;for(Fe in je)ye[Fe]===void 0&&(ye[Fe]=je[Fe])}if(fe||vt){var Ze=typeof v=="function"?v.displayName||v.name||"Unknown":v;fe&&Qy(ye,Ze),vt&&Ky(ye,Ze)}return Jy(v,fe,vt,Me,te,td.current,ye)}}var Al=g.ReactCurrentOwner,nd=g.ReactDebugCurrentFrame;function gn(v){if(v){var G=v._owner,Y=Ra(v.type,v._source,G?G.type:null);nd.setExtraStackFrame(Y)}else nd.setExtraStackFrame(null)}var Rl;Rl=!1;function Nl(v){return typeof v=="object"&&v!==null&&v.$$typeof===e}function rd(){{if(Al.current){var v=j(Al.current.type);if(v)return`
|
39
39
|
|
40
|
-
Check the render method of \``+
|
40
|
+
Check the render method of \``+v+"`."}return""}}function t0(v){return""}var ad={};function s0(v){{var G=rd();if(!G){var Y=typeof v=="string"?v:v.displayName||v.name;Y&&(G=`
|
41
41
|
|
42
|
-
Check
|
43
|
-
|
44
|
-
|
42
|
+
Check the top-level render call using <`+Y+">.")}return G}}function od(v,G){{if(!v._store||v._store.validated||v.key!=null)return;v._store.validated=!0;var Y=s0(G);if(ad[Y])return;ad[Y]=!0;var te="";v&&v._owner&&v._owner!==Al.current&&(te=" It was passed a child from "+j(v._owner.type)+"."),gn(v),_('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',Y,te),gn(null)}}function ld(v,G){{if(typeof v!="object")return;if(Cl(v))for(var Y=0;Y<v.length;Y++){var te=v[Y];Nl(te)&&od(te,G)}else if(Nl(v))v._store&&(v._store.validated=!0);else if(v){var Me=y(v);if(typeof Me=="function"&&Me!==v.entries)for(var Fe=Me.call(v),ye;!(ye=Fe.next()).done;)Nl(ye.value)&&od(ye.value,G)}}}function i0(v){{var G=v.type;if(G==null||typeof G=="string")return;var Y;if(typeof G=="function")Y=G.propTypes;else if(typeof G=="object"&&(G.$$typeof===l||G.$$typeof===u))Y=G.propTypes;else return;if(Y){var te=j(G);Hy(Y,v.props,"prop",te,v)}else if(G.PropTypes!==void 0&&!Rl){Rl=!0;var Me=j(G);_("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",Me||"Unknown")}typeof G.getDefaultProps=="function"&&!G.getDefaultProps.isReactClassApproved&&_("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function n0(v){{for(var G=Object.keys(v.props),Y=0;Y<G.length;Y++){var te=G[Y];if(te!=="children"&&te!=="key"){gn(v),_("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",te),gn(null);break}}v.ref!==null&&(gn(v),_("Invalid attribute `ref` supplied to `React.Fragment`."),gn(null))}}var cd={};function hd(v,G,Y,te,Me,Fe){{var ye=z(v);if(!ye){var fe="";(v===void 0||typeof v=="object"&&v!==null&&Object.keys(v).length===0)&&(fe+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var vt=t0();vt?fe+=vt:fe+=rd();var je;v===null?je="null":Cl(v)?je="array":v!==void 0&&v.$$typeof===e?(je="<"+(j(v.type)||"Unknown")+" />",fe=" Did you accidentally export a JSX literal instead of a component?"):je=typeof v,_("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",je,fe)}var Ze=e0(v,G,Y,Me,Fe);if(Ze==null)return Ze;if(ye){var Kt=G.children;if(Kt!==void 0)if(te)if(Cl(Kt)){for(var yn=0;yn<Kt.length;yn++)ld(Kt[yn],v);Object.freeze&&Object.freeze(Kt)}else _("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else ld(Kt,v)}if(xr.call(G,"key")){var Ui=j(v),Ot=Object.keys(G).filter(function(h0){return h0!=="key"}),Pl=Ot.length>0?"{key: someKey, "+Ot.join(": ..., ")+": ...}":"{key: someKey}";if(!cd[Ui+Pl]){var c0=Ot.length>0?"{"+Ot.join(": ..., ")+": ...}":"{}";_(`A props object containing a "key" prop is being spread into JSX:
|
43
|
+
let props = %s;
|
44
|
+
<%s {...props} />
|
45
|
+
React keys must be passed directly to JSX without using spread:
|
46
|
+
let props = %s;
|
47
|
+
<%s key={someKey} {...props} />`,Pl,Ui,c0,Ui),cd[Ui+Pl]=!0}}return v===s?n0(Ze):i0(Ze),Ze}}function r0(v,G,Y){return hd(v,G,Y,!0)}function a0(v,G,Y){return hd(v,G,Y,!1)}var o0=a0,l0=r0;br.Fragment=s,br.jsx=o0,br.jsxs=l0}()),br}var gd;function sx(){return gd||(gd=1,process.env.NODE_ENV==="production"?Pa.exports=ex():Pa.exports=tx()),Pa.exports}var C=sx();function jh(a){return a.title.search("<")>-1?C.jsx("button",{className:"svg",dangerouslySetInnerHTML:{__html:a.title}}):C.jsx("button",{children:a.title})}const ix=C.jsxs("svg",{className:"closeIcon",width:"14",height:"14",fill:"none",stroke:"#666666",strokeMiterlimit:"10",children:[C.jsx("circle",{cx:"7",cy:"7",r:"6"}),C.jsx("line",{x1:"4",y1:"4",x2:"10",y2:"10"}),C.jsx("line",{x1:"4",y1:"10",x2:"10",y2:"4"})]}),nx=C.jsx("svg",{className:"dragIcon",width:"14",height:"14",fill:"#666666",stroke:"none",children:C.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
|
45
48
|
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
|
46
|
-
C11,8.22,10.74,8,10.43,8z`})});function Es(i){return p.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:p.jsxs("div",{children:[qn,p.jsx("span",{children:i.title}),p.jsx("button",{className:"closeIcon",onClick:()=>i.onDelete(i.index),children:Xn})]})})}function Ss(i){const[e,t]=T.useState(!1),[s,n]=T.useState(i.options),[r,a]=T.useState(null),l=g=>{i.onDragComplete(g),n(g)},c=g=>{const E=[...s];E.splice(g,1),l(E)},h=g=>{a(g)},u=g=>{if(r===g||r===null)return;const E=[...s],y=E.splice(r,1)[0];E.splice(g,0,y),a(g),n(E)},f=()=>{i.onDragComplete(s),a(null)};let m="dropdown draggable";return i.subdropdown&&(m+=" subdropdown"),p.jsxs("div",{className:m,onMouseEnter:()=>t(!0),onMouseLeave:()=>t(!1),children:[p.jsx(Si,{title:i.title}),p.jsx("ul",{className:"reorder-list",style:{display:e?"block":"none"},children:s.map((g,E)=>p.jsx(Es,{title:g,index:E,draggingIndex:r,onDelete:c,onDragStart:h,onDragOver:u,onDragEnd:f},g))})]})}function ws(i){const[e,t]=T.useState(!1),s=[];i.options.map((r,a)=>{i.onSelect!==void 0&&(r.onSelect=i.onSelect),s.push(p.jsx(xs,{option:r},a))});let n="dropdown";return i.subdropdown&&(n+=" subdropdown"),p.jsxs("div",{className:n,onMouseEnter:()=>t(!0),onMouseLeave:()=>t(!1),children:[p.jsx(Si,{title:i.title}),p.jsx("ul",{style:{visibility:e?"visible":"hidden"},children:s})]})}function xs(i){const{option:e}=i,[t,s]=T.useState("");let n;switch(e.type){case"draggable":n=p.jsx(Ss,{title:e.title,options:e.value,onDragComplete:r=>{e.onDragComplete!==void 0&&e.onDragComplete(r)},subdropdown:!0});break;case"dropdown":n=p.jsx(ws,{title:e.title,options:e.value,onSelect:e.onSelect,subdropdown:!0});break;case"option":n=p.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 p.jsx("li",{className:t===e.title?"selected":"",children:n},fs())}function Ct(i){const[e,t]=T.useState(i.open!==void 0?i.open:!0),s=!e||i.children===void 0,n=()=>{i.app.dispatchEvent({type:P.REMOVE_SCENE,value:i.scene})};return p.jsxs("div",{className:`accordion ${s?"hide":""}`,children:[p.jsxs("button",{className:"toggle",onClick:()=>{const r=!e;i.onToggle!==void 0&&i.onToggle(r),t(r)},children:[p.jsx("p",{className:`status ${e?"open":""}`,children:"Toggle"}),p.jsx("p",{className:"label",children:bt(i.label)})]}),i.onRefresh?p.jsxs(p.Fragment,{children:[p.jsx("button",{className:"refresh",onClick:i.onRefresh}),p.jsx("button",{className:"remove",onClick:n})]}):null,i.button,p.jsx("div",{className:e?"open":"",children:p.jsx("div",{children:i.children})},Math.random())]})}function wi(i){const e=T.useRef(null),[t,s]=T.useState(!1),n=i.child!==void 0&&i.child.children.length>0,r=[];return i.child!==void 0&&i.child.children.length>0&&i.child.children.map((a,l)=>{r.push(p.jsx(wi,{app:i.app,child:a,three:i.three},l))}),T.useEffect(()=>{if(i.child){const a=i.three.getScene(i.child.uuid);if(a!==null){const l=a.getObjectByProperty("uuid",i.child.uuid);l!==void 0&&(e.current.style.opacity=l.visible?"1":"0.25")}}},[t]),p.jsx(p.Fragment,{children:i.child!==void 0&&p.jsxs("div",{className:"childObject",children:[p.jsxs("div",{className:"child",children:[n?p.jsx("button",{className:"status",style:{backgroundPositionX:t?"-14px":"2px"},onClick:()=>{s(!t)}}):null,p.jsx("button",{className:"name",style:{left:n?"20px":"5px"},onClick:()=>{i.child!==void 0&&(i.three.getObject(i.child.uuid),t||s(!0))},children:i.child.name.length>0?`${i.child.name} (${i.child.type})`:`${i.child.type}::${i.child.uuid}`}),p.jsx("button",{className:"visibility",ref:e,onClick:()=>{if(i.child){const a=i.three.getScene(i.child.uuid);if(a!==null){const l=a.getObjectByProperty("uuid",i.child.uuid);if(l!==void 0){const c="visible",h=!l.visible;e.current.style.opacity=h?"1":"0.25",i.three.updateObject(i.child.uuid,c,h),ee(l,c,h)}}}}}),p.jsx("div",{className:`icon ${zn(i.child)}`})]}),p.jsx("div",{className:t?"open":"",children:p.jsx("div",{className:"container",children:r})})]},Math.random())})}function gi(i){const e=[];return i.child?.children.map((t,s)=>{e.push(p.jsx(wi,{app:i.app,child:t,scene:i.scene,three:i.three},s))}),p.jsx("div",{className:`scene ${i.class!==void 0?i.class:""}`,children:e})}function mt(i){const[e,t]=T.useState(i.defaultValue);return T.useEffect(()=>{let s=!1,n=-1,r=0,a=i.defaultValue,l=!1;const c=g=>{l=g.ctrlKey},h=g=>{s=!0,r=Number(i.input.current?.value),n=g.clientX,document.addEventListener("mouseup",f,!1),document.addEventListener("mousemove",u,!1),document.addEventListener("contextmenu",f,!1)},u=g=>{if(!s)return;const E=i.step!==void 0?i.step:1,y=(g.clientX-n)*E*(l?10:1);a=Number((r+y).toFixed(4)),i.min!==void 0&&(a=Math.max(a,i.min)),i.max!==void 0&&(a=Math.min(a,i.max)),i.onChange!==void 0&&i.onChange(a),t(a)},f=()=>{s=!1,document.removeEventListener("mouseup",f),document.removeEventListener("mousemove",u),document.removeEventListener("contextmenu",f)},m=g=>{const E=Number(g.target.value);i.onChange!==void 0&&i.onChange(E),t(E)};return i.label.current?.addEventListener("mousedown",h,!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",h),i.sliderRef!==void 0&&i.sliderRef.current?.removeEventListener("input",m),document.removeEventListener("mouseup",f),document.removeEventListener("mousemove",u),document.removeEventListener("contextmenu",f),document.removeEventListener("keydown",c),document.addEventListener("keyup",c,!1)}},[]),e}function Ve(i){const e=T.useRef(null),t=T.useRef(null),[s,n]=T.useState(i.value);return mt({label:i.labelRef,input:e,sliderRef:t,defaultValue:s,min:i.min,max:i.max,step:i.step,onChange:r=>{n(r),i.onChange!==void 0&&i.onChange(i.prop,r)}}),p.jsxs(p.Fragment,{children:[i.type==="number"&&p.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,onChange:r=>{if(n(r.target.value),r.target.value.length===0)return;const a=Number(r.target.value);isNaN(a)||i.onChange!==void 0&&i.onChange(i.prop,a)}}),i.type==="range"&&p.jsxs(p.Fragment,{children:[p.jsx("input",{type:"text",value:s.toString(),disabled:i.disabled,ref:e,className:"min",onChange:r=>{if(r.target.value.length===0)return;const a=Number(r.target.value);isNaN(a)||i.onChange!==void 0&&i.onChange(i.prop,a)}}),p.jsx("input",{disabled:i.disabled,type:"range",value:s,min:i.min,max:i.max,step:i.step,ref:t,onChange:yt})]})]})}function Qn(i){const e=T.useRef(null),t=T.useRef(null),s=T.useRef(null),n=T.useRef(null),r=T.useRef(null),a=T.useRef(null),l=T.useRef(null),c=T.useRef(null),h=T.useRef(null),u=T.useRef(null),[f,m]=T.useState(i.value.x),[g,E]=T.useState(i.value.y),[y,O]=T.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))}),[_,b]=T.useState(!1);mt({label:l,input:e,defaultValue:f,min:y.min,max:y.max,step:.01,onChange:R=>{m(R),i.onChange({target:{value:{x:R,y:g}}})}}),mt({label:c,input:t,defaultValue:g,min:y.min,max:y.max,step:.01,onChange:R=>{E(R),i.onChange({target:{value:{x:f,y:R}}})}}),mt({label:h,input:s,defaultValue:y.min,min:y.min-1,max:y.max+1,step:.01,onChange:R=>{O({min:R,max:y.max})}}),mt({label:u,input:n,defaultValue:y.max,min:y.min-1,max:y.max+1,step:.01,onChange:R=>{O({min:y.min,max:R})}});function S(){_||(window.addEventListener("mousemove",x),window.addEventListener("mouseup",w),b(!0))}function w(){window.removeEventListener("mousemove",x),window.removeEventListener("mouseup",w),b(!1)}function x(R){const V=r.current.getBoundingClientRect(),ge=Ue(0,99,R.clientX-V.left)/99,ue=1-Ue(0,99,R.clientY-V.top)/99,se=ye(tt(y.min,y.max,ge),3),Q=ye(tt(y.min,y.max,ue),3);i.onChange({target:{value:{x:se,y:Q}}}),m(se),E(Q)}function M(){const R=Number(s.current.value);O({min:R,max:y.max}),f<R&&m(Ue(R,y.max,f)),g<R&&E(Ue(R,y.max,g))}function D(){const R=Number(n.current.value);O({min:y.min,max:R}),f>R&&m(Ue(y.min,R,f)),g>R&&E(Ue(y.min,R,g))}T.useEffect(()=>{a.current.style.left=`${Nt(y.min,y.max,f)*100}%`,a.current.style.top=`${(1-Nt(y.min,y.max,g))*100}%`},[y,f,g]);const k=i.step!==void 0?i.step:.01;return p.jsxs("div",{className:"vector2",children:[p.jsxs("div",{className:"fields",children:[p.jsxs("div",{children:[p.jsx("label",{ref:l,children:"X"}),p.jsx("input",{ref:e,type:"number",value:f,min:y.min,max:y.max,step:k,onChange:R=>{if(m(R.target.value),R.target.value.length===0)return;const V=Number(R.target.value);isNaN(V)||(i.onChange({target:{value:{x:V,y:g}}}),V<y.min&&O({min:V,max:y.max}))}})]}),p.jsxs("div",{children:[p.jsx("label",{ref:c,children:"Y"}),p.jsx("input",{ref:t,type:"number",value:g,min:y.min,max:y.max,step:k,onChange:R=>{if(E(R.target.value),R.target.value.length===0)return;const V=Number(R.target.value);isNaN(V)||(i.onChange({target:{value:{x:f,y:V}}}),V>y.max&&O({min:y.min,max:V}))}})]}),p.jsxs("div",{children:[p.jsx("label",{ref:h,children:"Min"}),p.jsx("input",{ref:s,type:"number",value:y.min,step:k,onChange:M})]}),p.jsxs("div",{children:[p.jsx("label",{ref:u,children:"Max"}),p.jsx("input",{ref:n,type:"number",value:y.max,step:k,onChange:D})]})]}),p.jsxs("div",{className:"input",ref:r,onMouseDown:S,onMouseUp:w,children:[p.jsx("div",{className:"x"}),p.jsx("div",{className:"y"}),p.jsx("div",{className:"pt",ref:a})]})]})}const Kn=Math.PI/180,$n=180/Math.PI;function Xe(i,e,t,s,n){return s+(i-e)*(n-s)/(t-e)}function qe(i,e,t){return(1-t)*i+t*e}function _i(i){return i*Kn}function Jn(i){return i*$n}function Gi(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,r=[];if(t){const a=T.useMemo(()=>i.value,[]);["_x","_y","_z"].forEach(c=>{const h=T.useRef(null);r.push(p.jsxs("div",{children:[p.jsx("label",{ref:h,children:c.substring(1).toUpperCase()}),p.jsx(Ve,{value:Jn(a[c]),type:"number",prop:c,step:.1,labelRef:h,onChange:(u,f)=>{a[u]=_i(f),i.onChange({target:{value:a}})}})]},c))})}else if(e){const a=T.useMemo(()=>i.value,[]),l=(h,u)=>{a[h]=u,i.onChange({target:{value:a}})};["x","y","z"].forEach(h=>{const u=T.useRef(null);r.push(p.jsxs("div",{children:[p.jsx("label",{ref:u,children:h.toUpperCase()}),p.jsx(Ve,{value:a[h],type:"number",prop:h,step:n,labelRef:u,onChange:l})]},h))})}else if(s){const a=T.useMemo(()=>i.value,[]),l=(c,h)=>{const u=Number(c);a.elements[u]=h,i.onChange({target:{value:a}})};for(let c=0;c<9;c++){const h=T.useRef(null);r.push(p.jsxs("div",{children:[p.jsx("label",{ref:h,children:c+1}),p.jsx(Ve,{value:a.elements[c],type:"number",prop:c.toString(),step:n,labelRef:h,onChange:l})]},c.toString()))}}return p.jsx("div",{className:"grid3",children:r},Math.random().toString())}function ea(i){const e=i.value.x!==void 0,t=i.step!==void 0?i.step:.01,s=[];if(e){const n=T.useMemo(()=>i.value,[]),r=(l,c)=>{n[l]=c,i.onChange({target:{value:n}})};["x","y","z","w"].forEach(l=>{const c=T.useRef(null);s.push(p.jsxs("div",{children:[p.jsx("label",{ref:c,children:l.toUpperCase()}),p.jsx(Ve,{value:n[l],type:"number",prop:l,step:t,labelRef:c,onChange:r})]},l))})}else{const n=T.useMemo(()=>i.value,[]),r=(a,l)=>{const c=Number(a);n.elements[c]=l,i.onChange({target:{value:n}})};for(let a=0;a<16;a++){const l=T.useRef(null);s.push(p.jsxs("div",{children:[p.jsx("label",{ref:l,children:a+1}),p.jsx(Ve,{value:n.elements[a],type:"number",prop:a.toString(),step:t,labelRef:l,onChange:r})]},a.toString()))}}return p.jsx("div",{className:"grid4",children:s})}function ta(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 ia(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 Vt(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 Ts(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 sa(){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(r){e(r.target.result)},n.readAsDataURL(s)}}),i.click()})}const na=[{title:"Front",value:o.FrontSide},{title:"Back",value:o.BackSide},{title:"Double",value:o.DoubleSide}],aa=[{title:"No Blending",value:o.NoBlending},{title:"Normal",value:o.NormalBlending},{title:"Additive",value:o.AdditiveBlending},{title:"Subtractive",value:o.SubtractiveBlending},{title:"Multiply",value:o.MultiplyBlending},{title:"Custom",value:o.CustomBlending}],ra=[{title:"Add",value:o.AddEquation},{title:"Subtract",value:o.SubtractEquation},{title:"Reverse Subtract",value:o.ReverseSubtractEquation},{title:"Min",value:o.MinEquation},{title:"Max",value:o.MaxEquation}],oa=[{title:"Zero",value:o.ZeroFactor},{title:"One",value:o.OneFactor},{title:"Src Color",value:o.SrcColorFactor},{title:"One Minus Src Color",value:o.OneMinusSrcColorFactor},{title:"Src Alpha",value:o.SrcAlphaFactor},{title:"One Minus Src Alpha",value:o.OneMinusSrcAlphaFactor},{title:"Dst Alpha",value:o.DstAlphaFactor},{title:"One Minus Dst Alpha",value:o.OneMinusDstAlphaFactor},{title:"Dst Color",value:o.DstColorFactor},{title:"One Minus Dst Color",value:o.OneMinusDstColorFactor},{title:"Src Alpha Saturate",value:o.SrcAlphaSaturateFactor},{title:"Constant Color",value:o.ConstantColorFactor},{title:"One Minus Constant Color",value:o.OneMinusConstantColorFactor},{title:"Constant Alpha",value:o.ConstantAlphaFactor},{title:"One Minus Constant Alpha",value:o.OneMinusConstantAlphaFactor}],la=[{title:"Zero",value:o.ZeroFactor},{title:"One",value:o.OneFactor},{title:"Src Color",value:o.SrcColorFactor},{title:"One Minus Src Color",value:o.OneMinusSrcColorFactor},{title:"Src Alpha",value:o.SrcAlphaFactor},{title:"One Minus Src Alpha",value:o.OneMinusSrcAlphaFactor},{title:"Dst Alpha",value:o.DstAlphaFactor},{title:"One Minus Dst Alpha",value:o.OneMinusDstAlphaFactor},{title:"Dst Color",value:o.DstColorFactor},{title:"One Minus Dst Color",value:o.OneMinusDstColorFactor},{title:"Constant Color",value:o.ConstantColorFactor},{title:"One Minus Constant Color",value:o.OneMinusConstantColorFactor},{title:"Constant Alpha",value:o.ConstantAlphaFactor},{title:"One Minus Constant Alpha",value:o.OneMinusConstantAlphaFactor}];function rt(i,e){i.needsUpdate=!0,i.type="option",i.options=e}function ca(i,e,t,s){return{type:"boolean",title:Vt(i),prop:i,value:e,needsUpdate:!0,onChange:(n,r)=>{s.updateObject(t.uuid,`material.${i}`,r),s.updateObject(t.uuid,"material.needsUpdate",!0);const a=s.getScene(t.uuid);if(a!==null){const l=a.getObjectByProperty("uuid",t.uuid);ee(l,`material.${i}`,r)}}}}function ha(i,e,t,s){const n={type:"number",title:Vt(i),prop:i,value:e,min:void 0,max:void 0,step:.01,needsUpdate:!0,onChange:(r,a)=>{s.updateObject(t.uuid,`material.${i}`,a),s.updateObject(t.uuid,"material.needsUpdate",!0);const l=s.getScene(t.uuid);if(l!==null){const c=l.getObjectByProperty("uuid",t.uuid);ee(c,`material.${i}`,a)}}};switch(i){case"blending":rt(n,aa);break;case"blendDst":rt(n,la);break;case"blendEquation":rt(n,ra);break;case"blendSrc":rt(n,oa);break;case"side":rt(n,na);break}return Ts(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 da(i,e,t,s){const n={type:"string",title:Vt(i),prop:i,value:e,needsUpdate:!0,onChange:(a,l)=>{s.updateObject(t.uuid,`material.${i}`,l),s.updateObject(t.uuid,"material.needsUpdate",!0);const c=s.getScene(t.uuid);if(c!==null){const h=c.getObjectByProperty("uuid",t.uuid);ee(h,`material.${i}`,l)}},onKeyDown:a=>{}};return(i==="vertexShader"||i==="fragmentShader")&&(n.disabled=!1,n.latest=n.value,n.onChange=(a,l)=>{n.latest=l,s.updateObject(t.uuid,`material.${i}`,l);const c=s.getScene(t.uuid);if(c!==null){const h=c.getObjectByProperty("uuid",t.uuid);ee(h,`material.${i}`,l)}},n.onKeyDown=a=>{if(a.key==="Enter"&&(a.altKey||a.metaKey)){s.updateObject(t.uuid,"material.needsUpdate",!0);const l=s.getScene(t.uuid);if(l!==null){const c=l.getObjectByProperty("uuid",t.uuid);ee(c,"material.needsUpdate",!0)}}}),n}function ua(i){return i.x!==void 0&&i.y!==void 0&&i.z===void 0}function pa(i){return i.x!==void 0&&i.y!==void 0&&i.z!==void 0&&i.w===void 0}function ma(i){return i.x!==void 0&&i.y!==void 0&&i.z!==void 0&&i.w!==void 0}function vi(i){i.sort((e,t)=>e.title<t.title?-1:e.title>t.title?1:0)}function ft(i,e,t,s,n="",r=!1){const a=Vt(i).split(".")[0].replaceAll("[","").replaceAll("]",""),l=n.length>0?`${n}.${i}`:i,c=typeof e;if(c==="boolean"||c==="string")return{title:a,prop:l,type:c,value:e,disabled:r,onChange:(h,u)=>{s.updateObject(t.uuid,`material.${l}`,u);const f=s.getScene(t.uuid);if(f!==null){const m=f.getObjectByProperty("uuid",t.uuid);ee(m,`material.${l}`,u)}}};if(c==="number"){const h={title:a,prop:l,type:"number",value:e,step:.01,disabled:r,onChange:(u,f)=>{s.updateObject(t.uuid,`material.${l}`,f);const m=s.getScene(t.uuid);if(m!==null){const g=m.getObjectByProperty("uuid",t.uuid);ee(g,`material.${l}`,f)}}};return Ts(a)&&(h.type="range",h.min=0,h.max=1),h}else{if(e.isColor)return{title:a,prop:l,type:"color",value:e,disabled:r,onChange:(h,u)=>{const f=new o.Color(u);s.updateObject(t.uuid,`material.${l}`,f);const m=s.getScene(t.uuid);if(m!==null){const g=m.getObjectByProperty("uuid",t.uuid);ee(g,`material.${l}`,f)}}};if(Array.isArray(e)){const h=[];for(const u in e){const f=e[u],m=`[${u.toString()}]`;if(f.value!==void 0){const g=ft(`${m}.value`,f.value,t,s,l,r);g!==void 0&&h.push(g)}else{const g=ft(m,f,t,s,l,r);g!==void 0&&h.push(g)}}if(h.length>0)return vi(h),{title:a,items:h}}else{if(ua(e))return{title:a,prop:l,type:"vector2",value:e,disabled:r,onChange:(h,u)=>{s.updateObject(t.uuid,`material.${l}`,u);const f=s.getScene(t.uuid);if(f!==null){const m=f.getObjectByProperty("uuid",t.uuid);ee(m,`material.${l}`,u)}}};if(pa(e))return{title:a,prop:l,type:"grid3",value:e,disabled:r,onChange:(h,u)=>{s.updateObject(t.uuid,`material.${l}`,u);const f=s.getScene(t.uuid);if(f!==null){const m=f.getObjectByProperty("uuid",t.uuid);ee(m,`material.${l}`,u)}}};if(ma(e))return{title:a,prop:l,type:"grid4",value:e,disabled:r,onChange:(h,u)=>{s.updateObject(t.uuid,`material.${l}`,u);const f=s.getScene(t.uuid);if(f!==null){const m=f.getObjectByProperty("uuid",t.uuid);ee(m,`material.${l}`,u)}}};if(e.isEuler)return{title:a,prop:l,type:"euler",value:e,disabled:r,onChange:(h,u)=>{s.updateObject(t.uuid,`material.${l}`,u);const f=s.getScene(t.uuid);if(f!==null){const m=f.getObjectByProperty("uuid",t.uuid);ee(m,`material.${l}`,u)}}};if(e.src!==void 0)return{title:a,type:"image",value:e,disabled:r,onChange:(h,u)=>{const f=ia(i),m=n.length>0?`${n}.${f}`:f;s.createTexture(t.uuid,`material.${m}`,u);const g=s.getScene(t.uuid);if(g!==null){const E=g.getObjectByProperty("uuid",t.uuid);if(E!==void 0){const y=O=>{const _=E.material,b=m.split(".");switch(b.length){case 1:_[b[0]]=O;break;case 2:_[b[0]][b[1]]=O;break;case 3:_[b[0]][b[1]][b[2]]=O;break;case 4:_[b[0]][b[1]][b[2]][b[3]]=O;break;case 5:_[b[0]][b[1]][b[2]][b[3]][b[4]]=O;break}_.needsUpdate=!0};u.src.length>0?Cs(u.src).then(O=>{O.offset.set(u.offset[0],u.offset[1]),O.repeat.set(u.repeat[0],u.repeat[1]),y(O)}):y(null)}}}};if(e.elements!==void 0)return{title:a,prop:l,type:e.elements.length>9?"grid4":"grid3",value:e,disabled:r,onChange:(h,u)=>{s.updateObject(t.uuid,`material.${l}`,u);const f=s.getScene(t.uuid);if(f!==null){const m=f.getObjectByProperty("uuid",t.uuid);ee(m,`material.${l}`,u)}}};{const h=[],u=i==="defines"||i==="extensions";try{for(const f in e){const m=e[f];if(m!==void 0)if(m.value!==void 0){const g=ft(`${f}.value`,m.value,t,s,l,u);g!==void 0&&h.push(g)}else{const g=ft(f,m,t,s,l,u);g!==void 0&&h.push(g)}}}catch{console.log("Issue cycling through material object:",i,e)}if(h.length>0)return vi(h),{title:a,items:h}}}}}function Wi(i,e,t){const s=[];for(const n in i){if(!ta(n))continue;const r=typeof i[n],a=i[n];if(r==="boolean")s.push(ca(n,a,e,t));else if(r==="number")s.push(ha(n,a,e,t));else if(r==="string")s.push(da(n,a,e,t));else if(r==="object"){const l=ft(n,a,e,t);l!==void 0&&s.push(l)}else a!==void 0&&console.log("other:",n,r,a)}return vi(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 r=n.getObjectByProperty("uuid",e.uuid);ee(r,"material.needsUpdate",!0)}}}),s}function fa(i,e,t){function s(){return`${t.app.appID}_material`}const n=localStorage.getItem(s()),r=n!==null?n==="open":!1;function a(c){localStorage.setItem(s(),c?"open":"closed")}const l=i.material;if(Array.isArray(l)){const c=[],h=l.length;for(let u=0;u<h;u++)c.push(p.jsx(be,{app:e,title:`Material ${u}`,items:Wi(l[u],i,t)},`Material ${u}`));return p.jsx(p.Fragment,{children:c})}else return p.jsx(be,{app:e,title:"Material",items:Wi(l,i,t),expanded:r,onToggle:c=>{a(c)}})}const Zi="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 ga(i){const e=i.step!==void 0?i.step:.01,t=T.useRef(null),s=T.useRef(null),n=T.useRef(null),r=T.useRef(null),a=T.useRef(null),[l]=T.useState(i.value),[c,h]=T.useState(i.value.offset[0]),[u,f]=T.useState(i.value.offset[1]),[m,g]=T.useState(i.value.repeat[0]),[E,y]=T.useState(i.value.repeat[1]);function O(b,S,w,x,M){if(i.onChange!==void 0){const D=i.prop!==void 0?i.prop:i.title;i.onChange(D,{src:b,offset:[S,w],repeat:[x,M]})}}function _(b){const S=t.current.src,w=b.target.value;switch(b.target){case s.current:h(w),O(S,w,u,m,E);break;case n.current:f(w),O(S,c,w,m,E);break;case r.current:g(w),O(S,c,u,w,E);break;case a.current:y(w),O(S,c,u,m,w);break}}return p.jsxs("div",{className:"imageField",children:[p.jsx("img",{alt:i.title,ref:t,onClick:()=>{sa().then(b=>{t.current.src=b,O(b,c,u,m,E)})},src:l.src.length>0?l.src:Zi}),p.jsxs("div",{className:"fields",children:[p.jsxs("div",{children:[p.jsx("label",{children:"Offset:"}),p.jsx("input",{ref:s,type:"number",value:c,step:e,onChange:_}),p.jsx("input",{ref:n,type:"number",value:u,step:e,onChange:_})]}),p.jsxs("div",{children:[p.jsx("label",{children:"Repeat:"}),p.jsx("input",{ref:r,type:"number",value:m,step:e,onChange:_}),p.jsx("input",{ref:a,type:"number",value:E,step:e,onChange:_})]}),p.jsx("button",{onClick:()=>{O("",c,u,m,E),t.current.src=Zi},children:"Clear"})]})]})}function Ut(i){let e=i.value;e!==void 0&&(e.isColor!==void 0?e=ui(i.value):i.type==="color"&&(e=ui(new o.Color().setStyle(i.value,o.LinearSRGBColorSpace))));const[t,s]=T.useState(e),n=T.useRef(null),r=h=>{let u=h.target.value;if(i.type==="boolean")u=h.target.checked;else if(i.type==="option"&&(typeof i.value=="number"?u=Number(u):typeof i.value=="boolean"?u=!!u:typeof i.value=="object"&&(u=JSON.parse(u)),i.options!==void 0)){const f=i.options.length;for(let m=0;m<f&&i.options[m].value!==u;m++);}s(u),i.onChange!==void 0&&i.onChange(i.prop!==void 0?i.prop:i.title,u)},a={};i.disabled&&(a.opacity=.8);const l=i.type==="string"&&(t.length>100||t.search(`
|
47
|
-
`)>-1),c=l||i.type==="image"||i.type==="vector2";return p.jsxs("div",{className:`field ${c?"block":""}`,style:a,children:[i.type!=="button"&&p.jsx("label",{ref:n,children:bt(i.title)},"fieldLabel"),i.type==="string"&&!l&&p.jsx("input",{type:"text",disabled:i.disabled,onChange:r,value:t}),i.type==="string"&&l&&p.jsx("textarea",{cols:50,rows:10,disabled:i.disabled!==void 0?i.disabled:!0,onChange:r,onKeyDown:h=>{i.onKeyDown!==void 0&&i.onKeyDown(h)},value:t}),i.type==="boolean"&&p.jsx("input",{type:"checkbox",disabled:i.disabled,onChange:r,checked:t}),i.type==="number"&&p.jsx(Ve,{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"&&p.jsx(Ve,{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"&&p.jsxs(p.Fragment,{children:[p.jsx("input",{type:"text",value:t.toString(),onChange:r,disabled:i.disabled,className:"color"}),p.jsx("input",{type:"color",value:t,onChange:r,disabled:i.disabled})]}),i.type==="button"&&p.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"&&p.jsx(ga,{title:i.title,prop:i.prop,value:i.value,onChange:i.onChange}),i.type==="option"&&p.jsx(p.Fragment,{children:p.jsx("select",{onChange:r,disabled:i.disabled,defaultValue:i.value,children:i.options?.map((h,u)=>p.jsx("option",{value:h.value,children:bt(h.title)},u))})}),i.type==="vector2"&&p.jsx(Qn,{step:i.step,value:t,min:0,max:1,onChange:r}),i.type==="grid3"&&p.jsx(Gi,{step:i.step,value:t,onChange:r}),i.type==="grid4"&&p.jsx(ea,{step:i.step,value:t,onChange:r}),i.type==="euler"&&p.jsx(Gi,{step:i.step,value:t,onChange:r})]})}function _a(i){return"items"in i}class be extends T.Component{subgroupNames=[];subgroupElements=[];valueOverrides=new Map;app;constructor(e){super(e),this.app=e.app,this.state={lastUpdated:Date.now()}}addGroup(e){const t=[];e.items.forEach(r=>{t.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:(a,l)=>{e.onUpdate(a,l)}})});const s=T.createRef(),n=p.jsx(be,{app:this.app,ref:s,title:e.title,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(_a(t))e.push(p.jsx(be,{app:this.app,title:bt(t.title),items:t.items},Math.random()));else{const s=this.valueOverrides.get(t.title),n=s!==void 0?s:t.value;e.push(p.jsx(Ut,{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:(r,a)=>{t.onChange!==void 0&&(this.valueOverrides.delete(t.title),t.onChange(r,a))},onKeyDown:r=>{t.onKeyDown!==void 0&&t.onKeyDown(r)}},Math.random()))}}),this.subgroupElements.forEach(t=>e.push(t)),p.jsx(Ct,{app:this.app,label:this.props.title,open:this.props.expanded===!0,onToggle:t=>{this.props.onToggle&&this.props?.onToggle(t)},children:e})}}class B extends T.Component{static instance;static groups=[];static groupsRefs=[];static groupTitles=[];static app;constructor(e){super(e),this.state={lastUpdate:Date.now()},B.app=e.app,B.instance=this,B.app.addEventListener(P.ADD_GROUP,this.addGroup),B.app.addEventListener(P.REMOVE_GROUP,this.removeGroup)}componentWillUnmount(){B.app.removeEventListener(P.ADD_GROUP,this.addGroup),B.app.removeEventListener(P.REMOVE_GROUP,this.removeGroup)}render(){return p.jsx("div",{className:"customGroups",children:B.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:(r,a)=>{this.props.three.updateGroup(t.title,r,a)}})}),B.groups.push(p.jsx(be,{app:B.app,title:t.title,items:s},Math.random())),B.groupTitles.push(t.title),this.setState({lastUpdate:Date.now()})};removeGroup=e=>{const t=e.value,s=B.groupTitles.length;for(let n=0;n<s;n++)if(t===B.groupTitles[n]){B.groups.splice(n,1),B.groupTitles.splice(n,1),this.setState({lastUpdate:Date.now()});return}};static addEditorGroup(e){const t=[];e.items.forEach(r=>{t.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:(a,l)=>{e.onUpdate(a,l)}})});const s=T.createRef(),n=p.jsx(be,{app:B.app,ref:s,title:e.title,items:t},Math.random());return B.groups.push(n),B.groupsRefs.push(s),B.groupTitles.push(e.title),s}static removeEditorGroup(e){const t=B.groupTitles.length;for(let s=0;s<t;s++)if(e===B.groupTitles[s]){B.groups.splice(s,1),B.groupTitles.splice(s,1),B.instance.setState({lastUpdate:Date.now()});return}}}function Xi(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 va(i,e,t){function s(){return`${t.app.appID}_camera`}const n=localStorage.getItem(s()),r=n!==null?n==="open":!1;function a(c){localStorage.setItem(s(),c?"open":"closed")}const l=[];if(i.perspectiveCameraInfo!==void 0)for(const c in i.perspectiveCameraInfo)l.push({title:Xi(c),prop:c,type:"number",step:.01,value:i.perspectiveCameraInfo[c],onChange:(h,u)=>{t.updateObject(i.uuid,h,u),t.requestMethod(i.uuid,"updateProjectionMatrix");const f=t.getScene(i.uuid);if(f!==null){const m=f.getObjectByProperty("uuid",i.uuid);m!==void 0&&(ee(m,h,u),m.updateProjectionMatrix())}}});else if(i.orthographicCameraInfo!==void 0)for(const c in i.orthographicCameraInfo)l.push({title:Xi(c),prop:c,type:"number",step:.01,value:i.orthographicCameraInfo[c],onChange:(h,u)=>{t.updateObject(i.uuid,h,u),t.requestMethod(i.uuid,"updateProjectionMatrix");const f=t.getScene(i.uuid);if(f!==null){const m=f.getObjectByProperty("uuid",i.uuid);m!==void 0&&(ee(m,h,u),m.updateProjectionMatrix())}}});return p.jsx(be,{app:e,title:"Camera",items:l,expanded:r,onToggle:c=>{a(c)}})}class ya extends o.Line{constructor(e,t){const s=[1,1,0,-1,1,0,-1,-1,0,1,-1,0,1,1,0],n=new o.BufferGeometry;n.setAttribute("position",new o.Float32BufferAttribute(s,3)),n.computeBoundingSphere();const r=new o.LineBasicMaterial({fog:!1});super(n,r),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],l=new o.BufferGeometry;l.setAttribute("position",new o.Float32BufferAttribute(a,3)),l.computeBoundingSphere(),this.add(new o.Mesh(l,new o.MeshBasicMaterial({side:o.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 qi={type:"change"},xi={type:"start"},Os={type:"end"},Ot=new o.Ray,Qi=new o.Plane,ba=Math.cos(70*o.MathUtils.DEG2RAD),ne=new o.Vector3,pe=2*Math.PI,Y={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},ei=1e-6;class Ca extends o.Controls{constructor(e,t=null){super(e,t),this.state=Y.NONE,this.enabled=!0,this.target=new o.Vector3,this.cursor=new o.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.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:o.MOUSE.ROTATE,MIDDLE:o.MOUSE.DOLLY,RIGHT:o.MOUSE.PAN},this.touches={ONE:o.TOUCH.ROTATE,TWO:o.TOUCH.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this._lastPosition=new o.Vector3,this._lastQuaternion=new o.Quaternion,this._lastTargetPosition=new o.Vector3,this._quat=new o.Quaternion().setFromUnitVectors(e.up,new o.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new o.Spherical,this._sphericalDelta=new o.Spherical,this._scale=1,this._panOffset=new o.Vector3,this._rotateStart=new o.Vector2,this._rotateEnd=new o.Vector2,this._rotateDelta=new o.Vector2,this._panStart=new o.Vector2,this._panEnd=new o.Vector2,this._panDelta=new o.Vector2,this._dollyStart=new o.Vector2,this._dollyEnd=new o.Vector2,this._dollyDelta=new o.Vector2,this._dollyDirection=new o.Vector3,this._mouse=new o.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=Sa.bind(this),this._onPointerDown=Ea.bind(this),this._onPointerUp=wa.bind(this),this._onContextMenu=Ra.bind(this),this._onMouseWheel=Oa.bind(this),this._onKeyDown=Ma.bind(this),this._onTouchStart=Aa.bind(this),this._onTouchMove=Pa.bind(this),this._onMouseDown=xa.bind(this),this._onMouseMove=Ta.bind(this),this._interceptControlDown=Da.bind(this),this._interceptControlUp=Ia.bind(this),this.domElement!==null&&this.connect(),this.update()}connect(){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.removeEventListener("pointermove",this._onPointerMove),this.domElement.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(qi),this.update(),this.state=Y.NONE}update(e=null){const t=this.object.position;ne.copy(t).sub(this.target),ne.applyQuaternion(this._quat),this._spherical.setFromVector3(ne),this.autoRotate&&this.state===Y.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,n=this.maxAzimuthAngle;isFinite(s)&&isFinite(n)&&(s<-Math.PI?s+=pe:s>Math.PI&&(s-=pe),n<-Math.PI?n+=pe:n>Math.PI&&(n-=pe),s<=n?this._spherical.theta=Math.max(s,Math.min(n,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(s+n)/2?Math.max(s,this._spherical.theta):Math.min(n,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),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 r=!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),r=a!=this._spherical.radius}if(ne.setFromSpherical(this._spherical),ne.applyQuaternion(this._quatInverse),t.copy(this.target).add(ne),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 l=ne.length();a=this._clampDistance(l*this._scale);const c=l-a;this.object.position.addScaledVector(this._dollyDirection,c),this.object.updateMatrixWorld(),r=!!c}else if(this.object.isOrthographicCamera){const l=new o.Vector3(this._mouse.x,this._mouse.y,0);l.unproject(this.object);const c=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),r=c!==this.object.zoom;const h=new o.Vector3(this._mouse.x,this._mouse.y,0);h.unproject(this.object),this.object.position.sub(h).add(l),this.object.updateMatrixWorld(),a=ne.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):(Ot.origin.copy(this.object.position),Ot.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(Ot.direction))<ba?this.object.lookAt(this.target):(Qi.setFromNormalAndCoplanarPoint(this.object.up,this.target),Ot.intersectPlane(Qi,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(),r=!0)}return this._scale=1,this._performCursorZoom=!1,r||this._lastPosition.distanceToSquared(this.object.position)>ei||8*(1-this._lastQuaternion.dot(this.object.quaternion))>ei||this._lastTargetPosition.distanceToSquared(this.target)>ei?(this.dispatchEvent(qi),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?pe/60*this.autoRotateSpeed*e:pe/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){ne.setFromMatrixColumn(t,0),ne.multiplyScalar(-e),this._panOffset.add(ne)}_panUp(e,t){this.screenSpacePanning===!0?ne.setFromMatrixColumn(t,1):(ne.setFromMatrixColumn(t,0),ne.crossVectors(this.object.up,ne)),ne.multiplyScalar(e),this._panOffset.add(ne)}_pan(e,t){const s=this.domElement;if(this.object.isPerspectiveCamera){const n=this.object.position;ne.copy(n).sub(this.target);let r=ne.length();r*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*r/s.clientHeight,this.object.matrix),this._panUp(2*t*r/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(),n=e-s.left,r=t-s.top,a=s.width,l=s.height;this._mouse.x=n/a*2-1,this._mouse.y=-(r/l)*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(pe*this._rotateDelta.x/t.clientHeight),this._rotateUp(pe*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._rotateUp(pe*this.rotateSpeed/this.domElement.clientHeight):this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this._rotateUp(-pe*this.rotateSpeed/this.domElement.clientHeight):this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this._rotateLeft(pe*this.rotateSpeed/this.domElement.clientHeight):this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this._rotateLeft(-pe*this.rotateSpeed/this.domElement.clientHeight):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),n=.5*(e.pageY+t.y);this._rotateStart.set(s,n)}}_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),n=.5*(e.pageY+t.y);this._panStart.set(s,n)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),s=e.pageX-t.x,n=e.pageY-t.y,r=Math.sqrt(s*s+n*n);this._dollyStart.set(0,r)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const s=this._getSecondPointerPosition(e),n=.5*(e.pageX+s.x),r=.5*(e.pageY+s.y);this._rotateEnd.set(n,r)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(pe*this._rotateDelta.x/t.clientHeight),this._rotateUp(pe*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),n=.5*(e.pageY+t.y);this._panEnd.set(s,n)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),s=e.pageX-t.x,n=e.pageY-t.y,r=Math.sqrt(s*s+n*n);this._dollyEnd.set(0,r),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const a=(e.pageX+t.x)*.5,l=(e.pageY+t.y)*.5;this._updateZoomParameters(a,l)}_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 o.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 Ea(i){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(i.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(i)&&(this._addPointer(i),i.pointerType==="touch"?this._onTouchStart(i):this._onMouseDown(i)))}function Sa(i){this.enabled!==!1&&(i.pointerType==="touch"?this._onTouchMove(i):this._onMouseMove(i))}function wa(i){switch(this._removePointer(i),this._pointers.length){case 0:this.domElement.releasePointerCapture(i.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(Os),this.state=Y.NONE;break;case 1:const e=this._pointers[0],t=this._pointerPositions[e];this._onTouchStart({pointerId:e,pageX:t.x,pageY:t.y});break}}function xa(i){let e;switch(i.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 o.MOUSE.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(i),this.state=Y.DOLLY;break;case o.MOUSE.ROTATE:if(i.ctrlKey||i.metaKey||i.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(i),this.state=Y.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(i),this.state=Y.ROTATE}break;case o.MOUSE.PAN:if(i.ctrlKey||i.metaKey||i.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(i),this.state=Y.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(i),this.state=Y.PAN}break;default:this.state=Y.NONE}this.state!==Y.NONE&&this.dispatchEvent(xi)}function Ta(i){switch(this.state){case Y.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(i);break;case Y.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(i);break;case Y.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(i);break}}function Oa(i){this.enabled===!1||this.enableZoom===!1||this.state!==Y.NONE||(i.preventDefault(),this.dispatchEvent(xi),this._handleMouseWheel(this._customWheelEvent(i)),this.dispatchEvent(Os))}function Ma(i){this.enabled===!1||this.enablePan===!1||this._handleKeyDown(i)}function Aa(i){switch(this._trackPointer(i),this._pointers.length){case 1:switch(this.touches.ONE){case o.TOUCH.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(i),this.state=Y.TOUCH_ROTATE;break;case o.TOUCH.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(i),this.state=Y.TOUCH_PAN;break;default:this.state=Y.NONE}break;case 2:switch(this.touches.TWO){case o.TOUCH.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(i),this.state=Y.TOUCH_DOLLY_PAN;break;case o.TOUCH.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(i),this.state=Y.TOUCH_DOLLY_ROTATE;break;default:this.state=Y.NONE}break;default:this.state=Y.NONE}this.state!==Y.NONE&&this.dispatchEvent(xi)}function Pa(i){switch(this._trackPointer(i),this.state){case Y.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(i),this.update();break;case Y.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(i),this.update();break;case Y.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(i),this.update();break;case Y.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(i),this.update();break;default:this.state=Y.NONE}}function Ra(i){this.enabled!==!1&&i.preventDefault()}function Da(i){i.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function Ia(i){i.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}/*!
|
49
|
+
C11,8.22,10.74,8,10.43,8z`})});function sm(a){return C.jsx("li",{className:`reorder-item ${a.draggingIndex===a.index?"dragging":""}`,draggable:!0,onDragStart:()=>a.onDragStart(a.index),onDragOver:e=>{e.preventDefault(),a.onDragOver(a.index)},onDragEnd:a.onDragEnd,children:C.jsxs("div",{children:[nx,C.jsx("span",{children:a.title}),C.jsx("button",{className:"closeIcon",onClick:()=>a.onDelete(a.index),children:ix})]})})}function im(a){const[e,t]=W.useState(!1),[s,i]=W.useState(a.options),[n,r]=W.useState(null),o=p=>{a.onDragComplete(p),i(p)},l=p=>{const f=[...s];f.splice(p,1),o(f)},c=p=>{r(p)},h=p=>{if(n===p||n===null)return;const f=[...s],m=f.splice(n,1)[0];f.splice(p,0,m),r(p),i(f)},u=()=>{a.onDragComplete(s),r(null)};let d="dropdown draggable";return a.subdropdown&&(d+=" subdropdown"),C.jsxs("div",{className:d,onMouseEnter:()=>t(!0),onMouseLeave:()=>t(!1),children:[C.jsx(jh,{title:a.title}),C.jsx("ul",{className:"reorder-list",style:{display:e?"block":"none"},children:s.map((p,f)=>C.jsx(sm,{title:p,index:f,draggingIndex:n,onDelete:l,onDragStart:c,onDragOver:h,onDragEnd:u},p))})]})}function nm(a){const[e,t]=W.useState(!1),s=[];a.options.map((n,r)=>{a.onSelect!==void 0&&(n.onSelect=a.onSelect),s.push(C.jsx(rm,{option:n},r))});let i="dropdown";return a.subdropdown&&(i+=" subdropdown"),C.jsxs("div",{className:i,onMouseEnter:()=>t(!0),onMouseLeave:()=>t(!1),children:[C.jsx(jh,{title:a.title}),C.jsx("ul",{style:{visibility:e?"visible":"hidden"},children:s})]})}function rm(a){const{option:e}=a,[t,s]=W.useState("");let i;switch(e.type){case"draggable":i=C.jsx(im,{title:e.title,options:e.value,onDragComplete:n=>{e.onDragComplete!==void 0&&e.onDragComplete(n)},subdropdown:!0});break;case"dropdown":i=C.jsx(nm,{title:e.title,options:e.value,onSelect:e.onSelect,subdropdown:!0});break;case"option":i=C.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 C.jsx("li",{className:t===e.title?"selected":"",children:i},Xf())}function pa(a){const[e,t]=W.useState(a.open!==void 0?a.open:!0),s=!e||a.children===void 0,i=()=>{a.app.dispatchEvent({type:Q.REMOVE_SCENE,value:a.scene})};return C.jsxs("div",{className:`accordion ${s?"hide":""}`,children:[C.jsxs("button",{className:"toggle",onClick:()=>{const n=!e;a.onToggle!==void 0&&a.onToggle(n),t(n)},children:[C.jsx("p",{className:`status ${e?"open":""}`,children:"Toggle"}),C.jsx("p",{className:"label",children:da(a.label)})]}),a.onRefresh?C.jsxs(C.Fragment,{children:[C.jsx("button",{className:"refresh",onClick:a.onRefresh}),C.jsx("button",{className:"remove",onClick:i})]}):null,a.button,C.jsx("div",{className:e?"open":"",children:C.jsx("div",{children:a.children})},Math.random())]})}function qh(a){const e=W.useRef(null),[t,s]=W.useState(!1),i=a.child!==void 0&&a.child.children.length>0,n=[];return a.child!==void 0&&a.child.children.length>0&&a.child.children.map((r,o)=>{n.push(C.jsx(qh,{app:a.app,child:r,three:a.three},o))}),W.useEffect(()=>{if(a.child){const r=a.three.getScene(a.child.uuid);if(r!==null){const o=r.getObjectByProperty("uuid",a.child.uuid);o!==void 0&&(e.current.style.opacity=o.visible?"1":"0.25")}}},[t]),C.jsx(C.Fragment,{children:a.child!==void 0&&C.jsxs("div",{className:"childObject",children:[C.jsxs("div",{className:"child",children:[i?C.jsx("button",{className:"status",style:{backgroundPositionX:t?"-14px":"2px"},onClick:()=>{s(!t)}}):null,C.jsx("button",{className:"name",style:{left:i?"20px":"5px"},onClick:()=>{a.child!==void 0&&(a.three.getObject(a.child.uuid),t||s(!0))},children:a.child.name.length>0?`${a.child.name} (${a.child.type})`:`${a.child.type}::${a.child.uuid}`}),C.jsx("button",{className:"visibility",ref:e,onClick:()=>{if(a.child){const r=a.three.getScene(a.child.uuid);if(r!==null){const o=r.getObjectByProperty("uuid",a.child.uuid);if(o!==void 0){const l="visible",c=!o.visible;e.current.style.opacity=c?"1":"0.25",a.three.updateObject(a.child.uuid,l,c),qe(o,l,c)}}}}}),C.jsx("div",{className:`icon ${Y0(a.child)}`})]}),C.jsx("div",{className:t?"open":"",children:C.jsx("div",{className:"container",children:n})})]},Math.random())})}function oh(a){const e=[];return a.child?.children.map((t,s)=>{e.push(C.jsx(qh,{app:a.app,child:t,scene:a.scene,three:a.three},s))}),C.jsx("div",{className:`scene ${a.class!==void 0?a.class:""}`,children:e})}function qr(a){const[e,t]=W.useState(a.defaultValue);return W.useEffect(()=>{let s=!1,i=-1,n=0,r=a.defaultValue,o=!1;const l=p=>{o=p.ctrlKey},c=p=>{s=!0,n=Number(a.input.current?.value),i=p.clientX,document.addEventListener("mouseup",u,!1),document.addEventListener("mousemove",h,!1),document.addEventListener("contextmenu",u,!1)},h=p=>{if(!s)return;const f=a.step!==void 0?a.step:1,m=(p.clientX-i)*f*(o?10:1);r=Number((n+m).toFixed(4)),a.min!==void 0&&(r=Math.max(r,a.min)),a.max!==void 0&&(r=Math.min(r,a.max)),a.onChange!==void 0&&a.onChange(r),t(r)},u=()=>{s=!1,document.removeEventListener("mouseup",u),document.removeEventListener("mousemove",h),document.removeEventListener("contextmenu",u)},d=p=>{const f=Number(p.target.value);a.onChange!==void 0&&a.onChange(f),t(f)};return a.label.current?.addEventListener("mousedown",c,!1),a.sliderRef!==void 0&&a.sliderRef.current?.addEventListener("input",d),document.addEventListener("keydown",l,!1),document.addEventListener("keyup",l,!1),()=>{a.label.current?.removeEventListener("mousedown",c),a.sliderRef!==void 0&&a.sliderRef.current?.removeEventListener("input",d),document.removeEventListener("mouseup",u),document.removeEventListener("mousemove",h),document.removeEventListener("contextmenu",u),document.removeEventListener("keydown",l),document.addEventListener("keyup",l,!1)}},[]),e}function ln(a){const e=W.useRef(null),t=W.useRef(null),[s,i]=W.useState(a.value);return qr({label:a.labelRef,input:e,sliderRef:t,defaultValue:s,min:a.min,max:a.max,step:a.step,onChange:n=>{i(n),a.onChange!==void 0&&a.onChange(a.prop,n)}}),C.jsxs(C.Fragment,{children:[a.type==="number"&&C.jsx("input",{alt:a.alt,className:a.className,ref:e,type:"number",value:s,min:a.min,max:a.max,step:a.step,disabled:a.disabled,onChange:n=>{if(i(n.target.value),n.target.value.length===0)return;const r=Number(n.target.value);isNaN(r)||a.onChange!==void 0&&a.onChange(a.prop,r)}}),a.type==="range"&&C.jsxs(C.Fragment,{children:[C.jsx("input",{type:"text",value:s.toString(),disabled:a.disabled,ref:e,className:"min",onChange:n=>{if(n.target.value.length===0)return;const r=Number(n.target.value);isNaN(r)||a.onChange!==void 0&&a.onChange(a.prop,r)}}),C.jsx("input",{disabled:a.disabled,type:"range",value:s,min:a.min,max:a.max,step:a.step,ref:t,onChange:ua})]})]})}function rx(a){const e=W.useRef(null),t=W.useRef(null),s=W.useRef(null),i=W.useRef(null),n=W.useRef(null),r=W.useRef(null),o=W.useRef(null),l=W.useRef(null),c=W.useRef(null),h=W.useRef(null),[u,d]=W.useState(a.value.x),[p,f]=W.useState(a.value.y),[m,y]=W.useState({min:Math.min(a.min,Math.min(a.value.x,a.value.y)),max:Math.max(a.max,Math.max(a.value.x,a.value.y))}),[g,_]=W.useState(!1);qr({label:o,input:e,defaultValue:u,min:m.min,max:m.max,step:.01,onChange:P=>{d(P),a.onChange({target:{value:{x:P,y:p}}})}}),qr({label:l,input:t,defaultValue:p,min:m.min,max:m.max,step:.01,onChange:P=>{f(P),a.onChange({target:{value:{x:u,y:P}}})}}),qr({label:c,input:s,defaultValue:m.min,min:m.min-1,max:m.max+1,step:.01,onChange:P=>{y({min:P,max:m.max})}}),qr({label:h,input:i,defaultValue:m.max,min:m.min-1,max:m.max+1,step:.01,onChange:P=>{y({min:m.min,max:P})}});function b(){g||(window.addEventListener("mousemove",T),window.addEventListener("mouseup",S),_(!0))}function S(){window.removeEventListener("mousemove",T),window.removeEventListener("mouseup",S),_(!1)}function T(P){const z=n.current.getBoundingClientRect(),$=Si(0,99,P.clientX-z.left)/99,q=1-Si(0,99,P.clientY-z.top)/99,j=ss(ir(m.min,m.max,$),3),X=ss(ir(m.min,m.max,q),3);a.onChange({target:{value:{x:j,y:X}}}),d(j),f(X)}function M(){const P=Number(s.current.value);y({min:P,max:m.max}),u<P&&d(Si(P,m.max,u)),p<P&&f(Si(P,m.max,p))}function w(){const P=Number(i.current.value);y({min:m.min,max:P}),u>P&&d(Si(m.min,P,u)),p>P&&f(Si(m.min,P,p))}W.useEffect(()=>{r.current.style.left=`${Bo(m.min,m.max,u)*100}%`,r.current.style.top=`${(1-Bo(m.min,m.max,p))*100}%`},[m,u,p]);const R=a.step!==void 0?a.step:.01;return C.jsxs("div",{className:"vector2",children:[C.jsxs("div",{className:"fields",children:[C.jsxs("div",{children:[C.jsx("label",{ref:o,children:"X"}),C.jsx("input",{ref:e,type:"number",value:u,min:m.min,max:m.max,step:R,onChange:P=>{if(d(P.target.value),P.target.value.length===0)return;const z=Number(P.target.value);isNaN(z)||(a.onChange({target:{value:{x:z,y:p}}}),z<m.min&&y({min:z,max:m.max}))}})]}),C.jsxs("div",{children:[C.jsx("label",{ref:l,children:"Y"}),C.jsx("input",{ref:t,type:"number",value:p,min:m.min,max:m.max,step:R,onChange:P=>{if(f(P.target.value),P.target.value.length===0)return;const z=Number(P.target.value);isNaN(z)||(a.onChange({target:{value:{x:u,y:z}}}),z>m.max&&y({min:m.min,max:z}))}})]}),C.jsxs("div",{children:[C.jsx("label",{ref:c,children:"Min"}),C.jsx("input",{ref:s,type:"number",value:m.min,step:R,onChange:M})]}),C.jsxs("div",{children:[C.jsx("label",{ref:h,children:"Max"}),C.jsx("input",{ref:i,type:"number",value:m.max,step:R,onChange:w})]})]}),C.jsxs("div",{className:"input",ref:n,onMouseDown:b,onMouseUp:S,children:[C.jsx("div",{className:"x"}),C.jsx("div",{className:"y"}),C.jsx("div",{className:"pt",ref:r})]})]})}const mt=["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 yd=1234567;const ia=Math.PI/180,nr=180/Math.PI;function Qs(){const a=Math.random()*4294967295|0,e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,s=Math.random()*4294967295|0;return(mt[a&255]+mt[a>>8&255]+mt[a>>16&255]+mt[a>>24&255]+"-"+mt[e&255]+mt[e>>8&255]+"-"+mt[e>>16&15|64]+mt[e>>24&255]+"-"+mt[t&63|128]+mt[t>>8&255]+"-"+mt[t>>16&255]+mt[t>>24&255]+mt[s&255]+mt[s>>8&255]+mt[s>>16&255]+mt[s>>24&255]).toLowerCase()}function de(a,e,t){return Math.max(e,Math.min(t,a))}function Yh(a,e){return(a%e+e)%e}function Qi(a,e,t,s,i){return s+(a-e)*(i-s)/(t-e)}function ax(a,e,t){return a!==e?(t-a)/(e-a):0}function xs(a,e,t){return(1-t)*a+t*e}function ox(a,e,t,s){return xs(a,e,1-Math.exp(-t*s))}function lx(a,e=1){return e-Math.abs(Yh(a,e*2)-e)}function cx(a,e,t){return a<=e?0:a>=t?1:(a=(a-e)/(t-e),a*a*(3-2*a))}function hx(a,e,t){return a<=e?0:a>=t?1:(a=(a-e)/(t-e),a*a*a*(a*(a*6-15)+10))}function ux(a,e){return a+Math.floor(Math.random()*(e-a+1))}function dx(a,e){return a+Math.random()*(e-a)}function px(a){return a*(.5-Math.random())}function fx(a){a!==void 0&&(yd=a);let e=yd+=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 Lo(a){return a*ia}function am(a){return a*nr}function mx(a){return(a&a-1)===0&&a!==0}function gx(a){return Math.pow(2,Math.ceil(Math.log(a)/Math.LN2))}function yx(a){return Math.pow(2,Math.floor(Math.log(a)/Math.LN2))}function xx(a,e,t,s,i){const n=Math.cos,r=Math.sin,o=n(t/2),l=r(t/2),c=n((e+s)/2),h=r((e+s)/2),u=n((e-s)/2),d=r((e-s)/2),p=n((s-e)/2),f=r((s-e)/2);switch(i){case"XYX":a.set(o*h,l*u,l*d,o*c);break;case"YZY":a.set(l*d,o*h,l*u,o*c);break;case"ZXZ":a.set(l*u,l*d,o*h,o*c);break;case"XZX":a.set(o*h,l*f,l*p,o*c);break;case"YXY":a.set(l*p,o*h,l*f,o*c);break;case"ZYZ":a.set(l*f,l*p,o*h,o*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+i)}}function At(a,e){switch(e.constructor){case Float32Array:return a;case Uint32Array:return a/4294967295;case Uint16Array:return a/65535;case Uint8Array:return a/255;case Int32Array:return Math.max(a/2147483647,-1);case Int16Array:return Math.max(a/32767,-1);case Int8Array:return Math.max(a/127,-1);default:throw new Error("Invalid component type.")}}function oe(a,e){switch(e.constructor){case Float32Array:return a;case Uint32Array:return Math.round(a*4294967295);case Uint16Array:return Math.round(a*65535);case Uint8Array:return Math.round(a*255);case Int32Array:return Math.round(a*2147483647);case Int16Array:return Math.round(a*32767);case Int8Array:return Math.round(a*127);default:throw new Error("Invalid component type.")}}const _x={DEG2RAD:ia,RAD2DEG:nr,generateUUID:Qs,clamp:de,euclideanModulo:Yh,mapLinear:Qi,inverseLerp:ax,lerp:xs,damp:ox,pingpong:lx,smoothstep:cx,smootherstep:hx,randInt:ux,randFloat:dx,randFloatSpread:px,seededRandom:fx,degToRad:Lo,radToDeg:am,isPowerOfTwo:mx,ceilPowerOfTwo:gx,floorPowerOfTwo:yx,setQuaternionFromProperEuler:xx,normalize:oe,denormalize:At};function xd(a){const e=a.value.x!==void 0&&a.value.y!==void 0&&a.value.z!==void 0,t=a.value.isEuler!==void 0,s=a.value.elements!==void 0,i=a.step!==void 0?a.step:.01,n=[];if(t){const r=W.useMemo(()=>a.value,[]);["_x","_y","_z"].forEach(l=>{const c=W.useRef(null);n.push(C.jsxs("div",{children:[C.jsx("label",{ref:c,children:l.substring(1).toUpperCase()}),C.jsx(ln,{value:am(r[l]),type:"number",prop:l,step:.1,labelRef:c,onChange:(h,u)=>{r[h]=Lo(u),a.onChange({target:{value:r}})}})]},l))})}else if(e){const r=W.useMemo(()=>a.value,[]),o=(c,h)=>{r[c]=h,a.onChange({target:{value:r}})};["x","y","z"].forEach(c=>{const h=W.useRef(null);n.push(C.jsxs("div",{children:[C.jsx("label",{ref:h,children:c.toUpperCase()}),C.jsx(ln,{value:r[c],type:"number",prop:c,step:i,labelRef:h,onChange:o})]},c))})}else if(s){const r=W.useMemo(()=>a.value,[]),o=(l,c)=>{const h=Number(l);r.elements[h]=c,a.onChange({target:{value:r}})};for(let l=0;l<9;l++){const c=W.useRef(null);n.push(C.jsxs("div",{children:[C.jsx("label",{ref:c,children:l+1}),C.jsx(ln,{value:r.elements[l],type:"number",prop:l.toString(),step:i,labelRef:c,onChange:o})]},l.toString()))}}return C.jsx("div",{className:"grid3",children:n},Math.random().toString())}function bx(a){const e=a.value.x!==void 0,t=a.step!==void 0?a.step:.01,s=[];if(e){const i=W.useMemo(()=>a.value,[]),n=(o,l)=>{i[o]=l,a.onChange({target:{value:i}})};["x","y","z","w"].forEach(o=>{const l=W.useRef(null);s.push(C.jsxs("div",{children:[C.jsx("label",{ref:l,children:o.toUpperCase()}),C.jsx(ln,{value:i[o],type:"number",prop:o,step:t,labelRef:l,onChange:n})]},o))})}else{const i=W.useMemo(()=>a.value,[]),n=(r,o)=>{const l=Number(r);i.elements[l]=o,a.onChange({target:{value:i}})};for(let r=0;r<16;r++){const o=W.useRef(null);s.push(C.jsxs("div",{children:[C.jsx("label",{ref:o,children:r+1}),C.jsx(ln,{value:i.elements[r],type:"number",prop:r.toString(),step:t,labelRef:o,onChange:n})]},r.toString()))}}return C.jsx("div",{className:"grid4",children:s})}function Tx(a){return!(a==="defaultAttributeValues"||a==="forceSinglePass"||a==="linecap"||a==="linejoin"||a==="linewidth"||a==="normalMapType"||a==="precision"||a==="shadowSide"||a==="uniformsGroups"||a==="uniformsNeedUpdate"||a==="userData"||a==="version"||a==="wireframeLinecap"||a==="wireframeLinejoin"||a==="wireframeLinewidth"||a.slice(0,4)==="clip"||a.slice(0,7)==="polygon"||a.slice(0,7)==="stencil"||a.slice(0,2)==="is")}function Sx(a){switch(a){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 a}function rl(a){switch(a){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 a}function om(a){const e=a.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 vx(){const a=document.createElement("input");return a.type="file",new Promise((e,t)=>{a.addEventListener("change",function(){if(a.files===null)t();else{const s=a.files[0],i=new FileReader;i.onload=function(n){e(n.target.result)},i.readAsDataURL(s)}}),a.click()})}const wx=[{title:"Front",value:x.FrontSide},{title:"Back",value:x.BackSide},{title:"Double",value:x.DoubleSide}],Ex=[{title:"No Blending",value:x.NoBlending},{title:"Normal",value:x.NormalBlending},{title:"Additive",value:x.AdditiveBlending},{title:"Subtractive",value:x.SubtractiveBlending},{title:"Multiply",value:x.MultiplyBlending},{title:"Custom",value:x.CustomBlending}],Mx=[{title:"Add",value:x.AddEquation},{title:"Subtract",value:x.SubtractEquation},{title:"Reverse Subtract",value:x.ReverseSubtractEquation},{title:"Min",value:x.MinEquation},{title:"Max",value:x.MaxEquation}],Cx=[{title:"Zero",value:x.ZeroFactor},{title:"One",value:x.OneFactor},{title:"Src Color",value:x.SrcColorFactor},{title:"One Minus Src Color",value:x.OneMinusSrcColorFactor},{title:"Src Alpha",value:x.SrcAlphaFactor},{title:"One Minus Src Alpha",value:x.OneMinusSrcAlphaFactor},{title:"Dst Alpha",value:x.DstAlphaFactor},{title:"One Minus Dst Alpha",value:x.OneMinusDstAlphaFactor},{title:"Dst Color",value:x.DstColorFactor},{title:"One Minus Dst Color",value:x.OneMinusDstColorFactor},{title:"Src Alpha Saturate",value:x.SrcAlphaSaturateFactor},{title:"Constant Color",value:x.ConstantColorFactor},{title:"One Minus Constant Color",value:x.OneMinusConstantColorFactor},{title:"Constant Alpha",value:x.ConstantAlphaFactor},{title:"One Minus Constant Alpha",value:x.OneMinusConstantAlphaFactor}],Ax=[{title:"Zero",value:x.ZeroFactor},{title:"One",value:x.OneFactor},{title:"Src Color",value:x.SrcColorFactor},{title:"One Minus Src Color",value:x.OneMinusSrcColorFactor},{title:"Src Alpha",value:x.SrcAlphaFactor},{title:"One Minus Src Alpha",value:x.OneMinusSrcAlphaFactor},{title:"Dst Alpha",value:x.DstAlphaFactor},{title:"One Minus Dst Alpha",value:x.OneMinusDstAlphaFactor},{title:"Dst Color",value:x.DstColorFactor},{title:"One Minus Dst Color",value:x.OneMinusDstColorFactor},{title:"Constant Color",value:x.ConstantColorFactor},{title:"One Minus Constant Color",value:x.OneMinusConstantColorFactor},{title:"Constant Alpha",value:x.ConstantAlphaFactor},{title:"One Minus Constant Alpha",value:x.OneMinusConstantAlphaFactor}];function Tr(a,e){a.needsUpdate=!0,a.type="option",a.options=e}function Rx(a,e,t,s){return{type:"boolean",title:rl(a),prop:a,value:e,needsUpdate:!0,onChange:(i,n)=>{s.updateObject(t.uuid,`material.${a}`,n),s.updateObject(t.uuid,"material.needsUpdate",!0);const r=s.getScene(t.uuid);if(r!==null){const o=r.getObjectByProperty("uuid",t.uuid);qe(o,`material.${a}`,n)}}}}function Nx(a,e,t,s){const i={type:"number",title:rl(a),prop:a,value:e,min:void 0,max:void 0,step:.01,needsUpdate:!0,onChange:(n,r)=>{s.updateObject(t.uuid,`material.${a}`,r),s.updateObject(t.uuid,"material.needsUpdate",!0);const o=s.getScene(t.uuid);if(o!==null){const l=o.getObjectByProperty("uuid",t.uuid);qe(l,`material.${a}`,r)}}};switch(a){case"blending":Tr(i,Ex);break;case"blendDst":Tr(i,Ax);break;case"blendEquation":Tr(i,Mx);break;case"blendSrc":Tr(i,Cx);break;case"side":Tr(i,wx);break}return om(a)&&(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 Px(a,e,t,s){const i={type:"string",title:rl(a),prop:a,value:e,needsUpdate:!0,onChange:(r,o)=>{s.updateObject(t.uuid,`material.${a}`,o),s.updateObject(t.uuid,"material.needsUpdate",!0);const l=s.getScene(t.uuid);if(l!==null){const c=l.getObjectByProperty("uuid",t.uuid);qe(c,`material.${a}`,o)}},onKeyDown:r=>{}};return(a==="vertexShader"||a==="fragmentShader")&&(i.disabled=!1,i.latest=i.value,i.onChange=(r,o)=>{i.latest=o,s.updateObject(t.uuid,`material.${a}`,o);const l=s.getScene(t.uuid);if(l!==null){const c=l.getObjectByProperty("uuid",t.uuid);qe(c,`material.${a}`,o)}},i.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 l=o.getObjectByProperty("uuid",t.uuid);qe(l,"material.needsUpdate",!0)}}}),i}function Fx(a){return a.x!==void 0&&a.y!==void 0&&a.z===void 0}function Dx(a){return a.x!==void 0&&a.y!==void 0&&a.z!==void 0&&a.w===void 0}function Ox(a){return a.x!==void 0&&a.y!==void 0&&a.z!==void 0&&a.w!==void 0}function lh(a){a.sort((e,t)=>e.title<t.title?-1:e.title>t.title?1:0)}function Yr(a,e,t,s,i="",n=!1){const r=rl(a).split(".")[0].replaceAll("[","").replaceAll("]",""),o=i.length>0?`${i}.${a}`:a,l=typeof e;if(l==="boolean"||l==="string")return{title:r,prop:o,type:l,value:e,disabled:n,onChange:(c,h)=>{s.updateObject(t.uuid,`material.${o}`,h);const u=s.getScene(t.uuid);if(u!==null){const d=u.getObjectByProperty("uuid",t.uuid);qe(d,`material.${o}`,h)}}};if(l==="number"){const c={title:r,prop:o,type:"number",value:e,step:.01,disabled:n,onChange:(h,u)=>{s.updateObject(t.uuid,`material.${o}`,u);const d=s.getScene(t.uuid);if(d!==null){const p=d.getObjectByProperty("uuid",t.uuid);qe(p,`material.${o}`,u)}}};return om(r)&&(c.type="range",c.min=0,c.max=1),c}else{if(e.isColor)return{title:r,prop:o,type:"color",value:e,disabled:n,onChange:(c,h)=>{const u=new x.Color(h);s.updateObject(t.uuid,`material.${o}`,u);const d=s.getScene(t.uuid);if(d!==null){const p=d.getObjectByProperty("uuid",t.uuid);qe(p,`material.${o}`,u)}}};if(Array.isArray(e)){const c=[];for(const h in e){const u=e[h],d=`[${h.toString()}]`;if(u.value!==void 0){const p=Yr(`${d}.value`,u.value,t,s,o,n);p!==void 0&&c.push(p)}else{const p=Yr(d,u,t,s,o,n);p!==void 0&&c.push(p)}}if(c.length>0)return lh(c),{title:r,items:c}}else{if(Fx(e))return{title:r,prop:o,type:"vector2",value:e,disabled:n,onChange:(c,h)=>{s.updateObject(t.uuid,`material.${o}`,h);const u=s.getScene(t.uuid);if(u!==null){const d=u.getObjectByProperty("uuid",t.uuid);qe(d,`material.${o}`,h)}}};if(Dx(e))return{title:r,prop:o,type:"grid3",value:e,disabled:n,onChange:(c,h)=>{s.updateObject(t.uuid,`material.${o}`,h);const u=s.getScene(t.uuid);if(u!==null){const d=u.getObjectByProperty("uuid",t.uuid);qe(d,`material.${o}`,h)}}};if(Ox(e))return{title:r,prop:o,type:"grid4",value:e,disabled:n,onChange:(c,h)=>{s.updateObject(t.uuid,`material.${o}`,h);const u=s.getScene(t.uuid);if(u!==null){const d=u.getObjectByProperty("uuid",t.uuid);qe(d,`material.${o}`,h)}}};if(e.isEuler)return{title:r,prop:o,type:"euler",value:e,disabled:n,onChange:(c,h)=>{s.updateObject(t.uuid,`material.${o}`,h);const u=s.getScene(t.uuid);if(u!==null){const d=u.getObjectByProperty("uuid",t.uuid);qe(d,`material.${o}`,h)}}};if(e.src!==void 0)return{title:r,type:"image",value:e,disabled:n,onChange:(c,h)=>{const u=Sx(a),d=i.length>0?`${i}.${u}`:u;s.createTexture(t.uuid,`material.${d}`,h);const p=s.getScene(t.uuid);if(p!==null){const f=p.getObjectByProperty("uuid",t.uuid);if(f!==void 0){const m=y=>{const g=f.material,_=d.split(".");switch(_.length){case 1:g[_[0]]=y;break;case 2:g[_[0]][_[1]]=y;break;case 3:g[_[0]][_[1]][_[2]]=y;break;case 4:g[_[0]][_[1]][_[2]][_[3]]=y;break;case 5:g[_[0]][_[1]][_[2]][_[3]][_[4]]=y;break}g.needsUpdate=!0};h.src.length>0?tm(h.src).then(y=>{y.offset.set(h.offset[0],h.offset[1]),y.repeat.set(h.repeat[0],h.repeat[1]),m(y)}):m(null)}}}};if(e.elements!==void 0)return{title:r,prop:o,type:e.elements.length>9?"grid4":"grid3",value:e,disabled:n,onChange:(c,h)=>{s.updateObject(t.uuid,`material.${o}`,h);const u=s.getScene(t.uuid);if(u!==null){const d=u.getObjectByProperty("uuid",t.uuid);qe(d,`material.${o}`,h)}}};{const c=[],h=a==="defines"||a==="extensions";try{for(const u in e){const d=e[u];if(d!==void 0)if(d.value!==void 0){const p=Yr(`${u}.value`,d.value,t,s,o,h);p!==void 0&&c.push(p)}else{const p=Yr(u,d,t,s,o,h);p!==void 0&&c.push(p)}}}catch{console.log("Issue cycling through material object:",a,e)}if(c.length>0)return lh(c),{title:r,items:c}}}}}function _d(a,e,t){const s=[];for(const i in a){if(!Tx(i))continue;const n=typeof a[i],r=a[i];if(n==="boolean")s.push(Rx(i,r,e,t));else if(n==="number")s.push(Nx(i,r,e,t));else if(n==="string")s.push(Px(i,r,e,t));else if(n==="object"){const o=Yr(i,r,e,t);o!==void 0&&s.push(o)}else r!==void 0&&console.log("other:",i,n,r)}return lh(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);qe(n,"material.needsUpdate",!0)}}}),s}function Bx(a,e,t){function s(){return`${t.app.appID}_material`}const i=localStorage.getItem(s()),n=i!==null?i==="open":!1;function r(l){localStorage.setItem(s(),l?"open":"closed")}const o=a.material;if(Array.isArray(o)){const l=[],c=o.length;for(let h=0;h<c;h++)l.push(C.jsx(cs,{app:e,title:`Material ${h}`,items:_d(o[h],a,t)},`Material ${h}`));return C.jsx(C.Fragment,{children:l})}else return C.jsx(cs,{app:e,title:"Material",items:_d(o,a,t),expanded:n,onToggle:l=>{r(l)}})}const bd="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 Ix(a){const e=a.step!==void 0?a.step:.01,t=W.useRef(null),s=W.useRef(null),i=W.useRef(null),n=W.useRef(null),r=W.useRef(null),[o]=W.useState(a.value),[l,c]=W.useState(a.value.offset[0]),[h,u]=W.useState(a.value.offset[1]),[d,p]=W.useState(a.value.repeat[0]),[f,m]=W.useState(a.value.repeat[1]);function y(_,b,S,T,M){if(a.onChange!==void 0){const w=a.prop!==void 0?a.prop:a.title;a.onChange(w,{src:_,offset:[b,S],repeat:[T,M]})}}function g(_){const b=t.current.src,S=_.target.value;switch(_.target){case s.current:c(S),y(b,S,h,d,f);break;case i.current:u(S),y(b,l,S,d,f);break;case n.current:p(S),y(b,l,h,S,f);break;case r.current:m(S),y(b,l,h,d,S);break}}return C.jsxs("div",{className:"imageField",children:[C.jsx("img",{alt:a.title,ref:t,onClick:()=>{vx().then(_=>{t.current.src=_,y(_,l,h,d,f)})},src:o.src.length>0?o.src:bd}),C.jsxs("div",{className:"fields",children:[C.jsxs("div",{children:[C.jsx("label",{children:"Offset:"}),C.jsx("input",{ref:s,type:"number",value:l,step:e,onChange:g}),C.jsx("input",{ref:i,type:"number",value:h,step:e,onChange:g})]}),C.jsxs("div",{children:[C.jsx("label",{children:"Repeat:"}),C.jsx("input",{ref:n,type:"number",value:d,step:e,onChange:g}),C.jsx("input",{ref:r,type:"number",value:f,step:e,onChange:g})]}),C.jsx("button",{onClick:()=>{y("",l,h,d,f),t.current.src=bd},children:"Clear"})]})]})}function vo(a){let e=a.value;e!==void 0&&(e.isColor!==void 0?e=nh(a.value):a.type==="color"&&(e=nh(new x.Color().setStyle(a.value,x.LinearSRGBColorSpace))));const[t,s]=W.useState(e),i=W.useRef(null),n=c=>{let h=c.target.value;if(a.type==="boolean")h=c.target.checked;else if(a.type==="option"&&(typeof a.value=="number"?h=Number(h):typeof a.value=="boolean"?h=!!h:typeof a.value=="object"&&(h=JSON.parse(h)),a.options!==void 0)){const u=a.options.length;for(let d=0;d<u&&a.options[d].value!==h;d++);}s(h),a.onChange!==void 0&&a.onChange(a.prop!==void 0?a.prop:a.title,h)},r={};a.disabled&&(r.opacity=.8);const o=a.type==="string"&&(t.length>100||t.search(`
|
50
|
+
`)>-1),l=o||a.type==="image"||a.type==="vector2";return C.jsxs("div",{className:`field ${l?"block":""}`,style:r,children:[a.type!=="button"&&C.jsx("label",{ref:i,children:da(a.title)},"fieldLabel"),a.type==="string"&&!o&&C.jsx("input",{type:"text",disabled:a.disabled,onChange:n,value:t}),a.type==="string"&&o&&C.jsx("textarea",{cols:50,rows:10,disabled:a.disabled!==void 0?a.disabled:!0,onChange:n,onKeyDown:c=>{a.onKeyDown!==void 0&&a.onKeyDown(c)},value:t}),a.type==="boolean"&&C.jsx("input",{type:"checkbox",disabled:a.disabled,onChange:n,checked:t}),a.type==="number"&&C.jsx(ln,{value:t,type:a.type,prop:a.prop!==void 0?a.prop:a.title,min:a.min,max:a.max,step:a.step,disabled:a.disabled,labelRef:i,onChange:a.onChange}),a.type==="range"&&C.jsx(ln,{value:t,type:a.type,prop:a.prop!==void 0?a.prop:a.title,min:a.min,max:a.max,step:a.step,disabled:a.disabled,labelRef:i,onChange:a.onChange}),a.type==="color"&&C.jsxs(C.Fragment,{children:[C.jsx("input",{type:"text",value:t.toString(),onChange:n,disabled:a.disabled,className:"color"}),C.jsx("input",{type:"color",value:t,onChange:n,disabled:a.disabled})]}),a.type==="button"&&C.jsx("button",{disabled:a.disabled,onClick:()=>{a.onChange!==void 0&&a.onChange(a.prop!==void 0?a.prop:a.title,!0)},children:a.title}),a.type==="image"&&C.jsx(Ix,{title:a.title,prop:a.prop,value:a.value,onChange:a.onChange}),a.type==="option"&&C.jsx(C.Fragment,{children:C.jsx("select",{onChange:n,disabled:a.disabled,defaultValue:a.value,children:a.options?.map((c,h)=>C.jsx("option",{value:c.value,children:da(c.title)},h))})}),a.type==="vector2"&&C.jsx(rx,{step:a.step,value:t,min:0,max:1,onChange:n}),a.type==="grid3"&&C.jsx(xd,{step:a.step,value:t,onChange:n}),a.type==="grid4"&&C.jsx(bx,{step:a.step,value:t,onChange:n}),a.type==="euler"&&C.jsx(xd,{step:a.step,value:t,onChange:n})]})}function Lx(a){return"items"in a}class cs extends W.Component{subgroupNames=[];subgroupElements=[];valueOverrides=new Map;app;constructor(e){super(e),this.app=e.app,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:(r,o)=>{e.onUpdate(r,o)}})});const s=W.createRef(),i=C.jsx(cs,{app:this.app,ref:s,title:e.title,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(Lx(t))e.push(C.jsx(cs,{app:this.app,title:da(t.title),items:t.items},Math.random()));else{const s=this.valueOverrides.get(t.title),i=s!==void 0?s:t.value;e.push(C.jsx(vo,{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,r)=>{t.onChange!==void 0&&(this.valueOverrides.delete(t.title),t.onChange(n,r))},onKeyDown:n=>{t.onKeyDown!==void 0&&t.onKeyDown(n)}},Math.random()))}}),this.subgroupElements.forEach(t=>e.push(t)),C.jsx(pa,{app:this.app,label:this.props.title,open:this.props.expanded===!0,onToggle:t=>{this.props.onToggle&&this.props?.onToggle(t)},children:e})}}class Re extends W.Component{static instance;static groups=[];static groupsRefs=[];static groupTitles=[];static app;constructor(e){super(e),this.state={lastUpdate:Date.now()},Re.app=e.app,Re.instance=this,Re.app.addEventListener(Q.ADD_GROUP,this.addGroup),Re.app.addEventListener(Q.REMOVE_GROUP,this.removeGroup)}componentWillUnmount(){Re.app.removeEventListener(Q.ADD_GROUP,this.addGroup),Re.app.removeEventListener(Q.REMOVE_GROUP,this.removeGroup)}render(){return C.jsx("div",{className:"customGroups",children:Re.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,r)=>{this.props.three.updateGroup(t.title,n,r)}})}),Re.groups.push(C.jsx(cs,{app:Re.app,title:t.title,items:s},Math.random())),Re.groupTitles.push(t.title),this.setState({lastUpdate:Date.now()})};removeGroup=e=>{const t=e.value,s=Re.groupTitles.length;for(let i=0;i<s;i++)if(t===Re.groupTitles[i]){Re.groups.splice(i,1),Re.groupTitles.splice(i,1),this.setState({lastUpdate:Date.now()});return}};static addEditorGroup(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:(r,o)=>{e.onUpdate(r,o)}})});const s=W.createRef(),i=C.jsx(cs,{app:Re.app,ref:s,title:e.title,items:t},Math.random());return Re.groups.push(i),Re.groupsRefs.push(s),Re.groupTitles.push(e.title),s}static removeEditorGroup(e){const t=Re.groupTitles.length;for(let s=0;s<t;s++)if(e===Re.groupTitles[s]){Re.groups.splice(s,1),Re.groupTitles.splice(s,1),Re.instance.setState({lastUpdate:Date.now()});return}}}function Td(a){switch(a){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 a}function Ux(a,e,t){function s(){return`${t.app.appID}_camera`}const i=localStorage.getItem(s()),n=i!==null?i==="open":!1;function r(l){localStorage.setItem(s(),l?"open":"closed")}const o=[];if(a.perspectiveCameraInfo!==void 0)for(const l in a.perspectiveCameraInfo)o.push({title:Td(l),prop:l,type:"number",step:.01,value:a.perspectiveCameraInfo[l],onChange:(c,h)=>{t.updateObject(a.uuid,c,h),t.requestMethod(a.uuid,"updateProjectionMatrix");const u=t.getScene(a.uuid);if(u!==null){const d=u.getObjectByProperty("uuid",a.uuid);d!==void 0&&(qe(d,c,h),d.updateProjectionMatrix())}}});else if(a.orthographicCameraInfo!==void 0)for(const l in a.orthographicCameraInfo)o.push({title:Td(l),prop:l,type:"number",step:.01,value:a.orthographicCameraInfo[l],onChange:(c,h)=>{t.updateObject(a.uuid,c,h),t.requestMethod(a.uuid,"updateProjectionMatrix");const u=t.getScene(a.uuid);if(u!==null){const d=u.getObjectByProperty("uuid",a.uuid);d!==void 0&&(qe(d,c,h),d.updateProjectionMatrix())}}});return C.jsx(cs,{app:e,title:"Camera",items:o,expanded:n,onToggle:l=>{r(l)}})}class kx{constructor(e,t){this.nodes=e,this.info=t,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._animationLoop!==null&&this._animationLoop(t,s)};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 vs{constructor(){this.weakMap=new WeakMap}get(e){let t=this.weakMap;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.weakMap;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.weakMap;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])}}const lm="177",zx=0,Gx=1,Vx=2,Hx=0,Wx=1,wo=3,Ks=0,zt=1,Yn=2,rr=0,Js=1,Uo=2,ko=3,zo=4,na=5,bs=100,cm=101,hm=102,$x=103,jx=104,vi=200,um=201,dm=202,pm=203,Go=204,Vo=205,fm=206,mm=207,gm=208,ym=209,xm=210,_m=0,bm=1,Tm=2,Ho=3,Sm=4,vm=5,wm=6,Em=7,al=0,qx=1,Yx=2,Xn=0,Xx=1,Zx=2,Qx=3,Kx=4,Jx=6,e_=7,Xh=300,fa=301,Wo=302,Zh=303,Qh=304,ch=306,ar=1e3,Ri=1001,or=1002,lt=1003,Mm=1004,ma=1005,Qt=1006,hh=1007,ei=1008,Rt=1009,ra=1010,aa=1011,Vn=1012,Mt=1013,Ye=1014,Zt=1015,ns=1016,t_=1017,s_=1018,Ni=1020,Cm=35902,i_=1021,Kh=1022,rs=1023,Bs=1026,ti=1027,Jh=1028,eu=1029,on=1030,tu=1031,n_=1032,su=1033,Il=33776,Eo=33777,Mo=33778,Co=33779,Sd=35840,vd=35841,wd=35842,Ed=35843,Md=36196,uh=37492,dh=37496,ph=37808,fh=37809,mh=37810,gh=37811,yh=37812,xh=37813,_h=37814,bh=37815,Th=37816,Sh=37817,vh=37818,wh=37819,Eh=37820,Mh=37821,Ll=36492,r_=36283,Cd=36284,Ad=36285,Rd=36286,Pi=0,a_=1,ri="",Yt="srgb",Zn="srgb-linear",$o="linear",se="srgb",o_=0,Ki=7680,l_=7681,c_=7682,h_=7683,u_=34055,d_=34056,p_=5386,f_=512,m_=513,g_=514,y_=515,x_=516,__=517,b_=518,Ch=519,Am=512,iu=513,Rm=514,Nm=515,Pm=516,Fm=517,Dm=518,Om=519,jo=35044,Hn=35048,Lt=2e3,Fi=2001;class Vt{constructor(e,t,s,i,n,r,o,l,c){Vt.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,s,i,n,r,o,l,c)}set(e,t,s,i,n,r,o,l,c){const h=this.elements;return h[0]=e,h[1]=i,h[2]=o,h[3]=t,h[4]=n,h[5]=l,h[6]=s,h[7]=r,h[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,r=s[0],o=s[3],l=s[6],c=s[1],h=s[4],u=s[7],d=s[2],p=s[5],f=s[8],m=i[0],y=i[3],g=i[6],_=i[1],b=i[4],S=i[7],T=i[2],M=i[5],w=i[8];return n[0]=r*m+o*_+l*T,n[3]=r*y+o*b+l*M,n[6]=r*g+o*S+l*w,n[1]=c*m+h*_+u*T,n[4]=c*y+h*b+u*M,n[7]=c*g+h*S+u*w,n[2]=d*m+p*_+f*T,n[5]=d*y+p*b+f*M,n[8]=d*g+p*S+f*w,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],r=e[4],o=e[5],l=e[6],c=e[7],h=e[8];return t*r*h-t*o*c-s*n*h+s*o*l+i*n*c-i*r*l}invert(){const e=this.elements,t=e[0],s=e[1],i=e[2],n=e[3],r=e[4],o=e[5],l=e[6],c=e[7],h=e[8],u=h*r-o*c,d=o*l-h*n,p=c*n-r*l,f=t*u+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]=u*m,e[1]=(i*c-h*s)*m,e[2]=(o*s-i*r)*m,e[3]=d*m,e[4]=(h*t-i*l)*m,e[5]=(i*n-o*t)*m,e[6]=p*m,e[7]=(s*l-c*t)*m,e[8]=(r*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,r,o){const l=Math.cos(n),c=Math.sin(n);return this.set(s*l,s*c,-s*(l*r+c*o)+r+e,-i*c,i*l,-i*(-c*r+l*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(Ul.makeScale(e,t)),this}rotate(e){return this.premultiply(Ul.makeRotation(-e)),this}translate(e,t){return this.premultiply(Ul.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 Ul=new Vt;function Bm(a){for(let e=a.length-1;e>=0;--e)if(a[e]>=65535)return!0;return!1}function Ah(a){return document.createElementNS("http://www.w3.org/1999/xhtml",a)}function T_(){const a=Ah("canvas");return a.style.display="block",a}const Nd={};function ai(a){a in Nd||(Nd[a]=!0,console.warn(a))}const Pd=new Vt().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),Fd=new Vt().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function S_(){const a={enabled:!0,workingColorSpace:Zn,spaces:{},convert:function(i,n,r){return this.enabled===!1||n===r||!n||!r||(this.spaces[n].transfer===se&&(i.r=si(i.r),i.g=si(i.g),i.b=si(i.b)),this.spaces[n].primaries!==this.spaces[r].primaries&&(i.applyMatrix3(this.spaces[n].toXYZ),i.applyMatrix3(this.spaces[r].fromXYZ)),this.spaces[r].transfer===se&&(i.r=Qn(i.r),i.g=Qn(i.g),i.b=Qn(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===ri?$o:this.spaces[i].transfer},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,r){return i.copy(this.spaces[n].toXYZ).multiply(this.spaces[r].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 ai("THREE.ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),a.workingToColorSpace(i,n)},toWorkingColorSpace:function(i,n){return ai("THREE.ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),a.colorSpaceToWorking(i,n)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],s=[.3127,.329];return a.define({[Zn]:{primaries:e,whitePoint:s,transfer:$o,toXYZ:Pd,fromXYZ:Fd,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:Yt},outputColorSpaceConfig:{drawingBufferColorSpace:Yt}},[Yt]:{primaries:e,whitePoint:s,transfer:se,toXYZ:Pd,fromXYZ:Fd,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:Yt}}}),a}const Le=S_();function si(a){return a<.04045?a*.0773993808:Math.pow(a*.9478672986+.0521327014,2.4)}function Qn(a){return a<.0031308?a*12.92:1.055*Math.pow(a,.41666)-.055}const Im={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},di={h:0,s:0,l:0},Fa={h:0,s:0,l:0};function kl(a,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?a+(e-a)*6*t:t<1/2?e:t<2/3?a+(e-a)*6*(2/3-t):a}class Se{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=Yt){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,Le.colorSpaceToWorking(this,t),this}setRGB(e,t,s,i=Le.workingColorSpace){return this.r=e,this.g=t,this.b=s,Le.colorSpaceToWorking(this,i),this}setHSL(e,t,s,i=Le.workingColorSpace){if(e=Yh(e,1),t=de(t,0,1),s=de(s,0,1),t===0)this.r=this.g=this.b=s;else{const n=s<=.5?s*(1+t):s+t-s*t,r=2*s-n;this.r=kl(r,n,e+1/3),this.g=kl(r,n,e),this.b=kl(r,n,e-1/3)}return Le.colorSpaceToWorking(this,i),this}setStyle(e,t=Yt){function s(n){n!==void 0&&parseFloat(n)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let n;const r=i[1],o=i[2];switch(r){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:console.warn("THREE.Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const n=i[1],r=n.length;if(r===3)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,t);if(r===6)return this.setHex(parseInt(n,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Yt){const s=Im[e.toLowerCase()];return s!==void 0?this.setHex(s,t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=si(e.r),this.g=si(e.g),this.b=si(e.b),this}copyLinearToSRGB(e){return this.r=Qn(e.r),this.g=Qn(e.g),this.b=Qn(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Yt){return Le.workingToColorSpace(gt.copy(this),e),Math.round(de(gt.r*255,0,255))*65536+Math.round(de(gt.g*255,0,255))*256+Math.round(de(gt.b*255,0,255))}getHexString(e=Yt){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Le.workingColorSpace){Le.workingToColorSpace(gt.copy(this),t);const s=gt.r,i=gt.g,n=gt.b,r=Math.max(s,i,n),o=Math.min(s,i,n);let l,c;const h=(o+r)/2;if(o===r)l=0,c=0;else{const u=r-o;switch(c=h<=.5?u/(r+o):u/(2-r-o),r){case s:l=(i-n)/u+(i<n?6:0);break;case i:l=(n-s)/u+2;break;case n:l=(s-i)/u+4;break}l/=6}return e.h=l,e.s=c,e.l=h,e}getRGB(e,t=Le.workingColorSpace){return Le.workingToColorSpace(gt.copy(this),t),e.r=gt.r,e.g=gt.g,e.b=gt.b,e}getStyle(e=Yt){Le.workingToColorSpace(gt.copy(this),e);const t=gt.r,s=gt.g,i=gt.b;return e!==Yt?`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(di),this.setHSL(di.h+e,di.s+t,di.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(di),e.getHSL(Fa);const s=xs(di.h,Fa.h,t),i=xs(di.s,Fa.s,t),n=xs(di.l,Fa.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 gt=new Se;Se.NAMES=Im;class ol{constructor(e,t,s,i){ol.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}}class pr{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,r,o){let l=s[i+0],c=s[i+1],h=s[i+2],u=s[i+3];const d=n[r+0],p=n[r+1],f=n[r+2],m=n[r+3];if(o===0){e[t+0]=l,e[t+1]=c,e[t+2]=h,e[t+3]=u;return}if(o===1){e[t+0]=d,e[t+1]=p,e[t+2]=f,e[t+3]=m;return}if(u!==m||l!==d||c!==p||h!==f){let y=1-o;const g=l*d+c*p+h*f+u*m,_=g>=0?1:-1,b=1-g*g;if(b>Number.EPSILON){const T=Math.sqrt(b),M=Math.atan2(T,g*_);y=Math.sin(y*M)/T,o=Math.sin(o*M)/T}const S=o*_;if(l=l*y+d*S,c=c*y+p*S,h=h*y+f*S,u=u*y+m*S,y===1-o){const T=1/Math.sqrt(l*l+c*c+h*h+u*u);l*=T,c*=T,h*=T,u*=T}}e[t]=l,e[t+1]=c,e[t+2]=h,e[t+3]=u}static multiplyQuaternionsFlat(e,t,s,i,n,r){const o=s[i],l=s[i+1],c=s[i+2],h=s[i+3],u=n[r],d=n[r+1],p=n[r+2],f=n[r+3];return e[t]=o*f+h*u+l*p-c*d,e[t+1]=l*f+h*d+c*u-o*p,e[t+2]=c*f+h*p+o*d-l*u,e[t+3]=h*f-o*u-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,r=e._order,o=Math.cos,l=Math.sin,c=o(s/2),h=o(i/2),u=o(n/2),d=l(s/2),p=l(i/2),f=l(n/2);switch(r){case"XYZ":this._x=d*h*u+c*p*f,this._y=c*p*u-d*h*f,this._z=c*h*f+d*p*u,this._w=c*h*u-d*p*f;break;case"YXZ":this._x=d*h*u+c*p*f,this._y=c*p*u-d*h*f,this._z=c*h*f-d*p*u,this._w=c*h*u+d*p*f;break;case"ZXY":this._x=d*h*u-c*p*f,this._y=c*p*u+d*h*f,this._z=c*h*f+d*p*u,this._w=c*h*u-d*p*f;break;case"ZYX":this._x=d*h*u-c*p*f,this._y=c*p*u+d*h*f,this._z=c*h*f-d*p*u,this._w=c*h*u+d*p*f;break;case"YZX":this._x=d*h*u+c*p*f,this._y=c*p*u+d*h*f,this._z=c*h*f-d*p*u,this._w=c*h*u-d*p*f;break;case"XZY":this._x=d*h*u-c*p*f,this._y=c*p*u-d*h*f,this._z=c*h*f+d*p*u,this._w=c*h*u+d*p*f;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+r)}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],r=t[1],o=t[5],l=t[9],c=t[2],h=t[6],u=t[10],d=s+o+u;if(d>0){const p=.5/Math.sqrt(d+1);this._w=.25/p,this._x=(h-l)*p,this._y=(n-c)*p,this._z=(r-i)*p}else if(s>o&&s>u){const p=2*Math.sqrt(1+s-o-u);this._w=(h-l)/p,this._x=.25*p,this._y=(i+r)/p,this._z=(n+c)/p}else if(o>u){const p=2*Math.sqrt(1+o-s-u);this._w=(n-c)/p,this._x=(i+r)/p,this._y=.25*p,this._z=(l+h)/p}else{const p=2*Math.sqrt(1+u-s-o);this._w=(r-i)/p,this._x=(n+c)/p,this._y=(l+h)/p,this._z=.25*p}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let s=e.dot(t)+1;return s<Number.EPSILON?(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(de(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,r=e._w,o=t._x,l=t._y,c=t._z,h=t._w;return this._x=s*h+r*o+i*c-n*l,this._y=i*h+r*l+n*o-s*c,this._z=n*h+r*c+s*l-i*o,this._w=r*h-s*o-i*l-n*c,this._onChangeCallback(),this}slerp(e,t){if(t===0)return this;if(t===1)return this.copy(e);const s=this._x,i=this._y,n=this._z,r=this._w;let o=r*e._w+s*e._x+i*e._y+n*e._z;if(o<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,o=-o):this.copy(e),o>=1)return this._w=r,this._x=s,this._y=i,this._z=n,this;const l=1-o*o;if(l<=Number.EPSILON){const p=1-t;return this._w=p*r+t*this._w,this._x=p*s+t*this._x,this._y=p*i+t*this._y,this._z=p*n+t*this._z,this.normalize(),this}const c=Math.sqrt(l),h=Math.atan2(c,o),u=Math.sin((1-t)*h)/c,d=Math.sin(t*h)/c;return this._w=r*u+this._w*d,this._x=s*u+this._x*d,this._y=i*u+this._y*d,this._z=n*u+this._z*d,this._onChangeCallback(),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 N{constructor(e=0,t=0,s=0){N.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(Dd.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Dd.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,r=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])*r,this.y=(n[1]*t+n[5]*s+n[9]*i+n[13])*r,this.z=(n[2]*t+n[6]*s+n[10]*i+n[14])*r,this}applyQuaternion(e){const t=this.x,s=this.y,i=this.z,n=e.x,r=e.y,o=e.z,l=e.w,c=2*(r*i-o*s),h=2*(o*t-n*i),u=2*(n*s-r*t);return this.x=t+l*c+r*u-o*h,this.y=s+l*h+o*c-n*u,this.z=i+l*u+n*h-r*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=de(this.x,e.x,t.x),this.y=de(this.y,e.y,t.y),this.z=de(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=de(this.x,e,t),this.y=de(this.y,e,t),this.z=de(this.z,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(de(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,r=t.x,o=t.y,l=t.z;return this.x=i*l-n*o,this.y=n*r-s*l,this.z=s*o-i*r,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 zl.copy(this).projectOnVector(e),this.sub(zl)}reflect(e){return this.sub(zl.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(de(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 zl=new N,Dd=new pr;class Be{constructor(e,t,s,i,n,r,o,l,c,h,u,d,p,f,m,y){Be.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,r,o,l,c,h,u,d,p,f,m,y)}set(e,t,s,i,n,r,o,l,c,h,u,d,p,f,m,y){const g=this.elements;return g[0]=e,g[4]=t,g[8]=s,g[12]=i,g[1]=n,g[5]=r,g[9]=o,g[13]=l,g[2]=c,g[6]=h,g[10]=u,g[14]=d,g[3]=p,g[7]=f,g[11]=m,g[15]=y,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 Be().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 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){const t=this.elements,s=e.elements,i=1/bn.setFromMatrixColumn(e,0).length(),n=1/bn.setFromMatrixColumn(e,1).length(),r=1/bn.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]*r,t[9]=s[9]*r,t[10]=s[10]*r,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,r=Math.cos(s),o=Math.sin(s),l=Math.cos(i),c=Math.sin(i),h=Math.cos(n),u=Math.sin(n);if(e.order==="XYZ"){const d=r*h,p=r*u,f=o*h,m=o*u;t[0]=l*h,t[4]=-l*u,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]=r*l}else if(e.order==="YXZ"){const d=l*h,p=l*u,f=c*h,m=c*u;t[0]=d+m*o,t[4]=f*o-p,t[8]=r*c,t[1]=r*u,t[5]=r*h,t[9]=-o,t[2]=p*o-f,t[6]=m+d*o,t[10]=r*l}else if(e.order==="ZXY"){const d=l*h,p=l*u,f=c*h,m=c*u;t[0]=d-m*o,t[4]=-r*u,t[8]=f+p*o,t[1]=p+f*o,t[5]=r*h,t[9]=m-d*o,t[2]=-r*c,t[6]=o,t[10]=r*l}else if(e.order==="ZYX"){const d=r*h,p=r*u,f=o*h,m=o*u;t[0]=l*h,t[4]=f*c-p,t[8]=d*c+m,t[1]=l*u,t[5]=m*c+d,t[9]=p*c-f,t[2]=-c,t[6]=o*l,t[10]=r*l}else if(e.order==="YZX"){const d=r*l,p=r*c,f=o*l,m=o*c;t[0]=l*h,t[4]=m-d*u,t[8]=f*u+p,t[1]=u,t[5]=r*h,t[9]=-o*h,t[2]=-c*h,t[6]=p*u+f,t[10]=d-m*u}else if(e.order==="XZY"){const d=r*l,p=r*c,f=o*l,m=o*c;t[0]=l*h,t[4]=-u,t[8]=c*h,t[1]=d*u+m,t[5]=r*h,t[9]=p*u-f,t[2]=f*u-p,t[6]=o*h,t[10]=m*u+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(v_,e,w_)}lookAt(e,t,s){const i=this.elements;return Ht.subVectors(e,t),Ht.lengthSq()===0&&(Ht.z=1),Ht.normalize(),pi.crossVectors(s,Ht),pi.lengthSq()===0&&(Math.abs(s.z)===1?Ht.x+=1e-4:Ht.z+=1e-4,Ht.normalize(),pi.crossVectors(s,Ht)),pi.normalize(),Da.crossVectors(Ht,pi),i[0]=pi.x,i[4]=Da.x,i[8]=Ht.x,i[1]=pi.y,i[5]=Da.y,i[9]=Ht.y,i[2]=pi.z,i[6]=Da.z,i[10]=Ht.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,r=s[0],o=s[4],l=s[8],c=s[12],h=s[1],u=s[5],d=s[9],p=s[13],f=s[2],m=s[6],y=s[10],g=s[14],_=s[3],b=s[7],S=s[11],T=s[15],M=i[0],w=i[4],R=i[8],P=i[12],z=i[1],$=i[5],q=i[9],j=i[13],X=i[2],Z=i[6],ve=i[10],ue=i[14],ge=i[3],ie=i[7],we=i[11],ke=i[15];return n[0]=r*M+o*z+l*X+c*ge,n[4]=r*w+o*$+l*Z+c*ie,n[8]=r*R+o*q+l*ve+c*we,n[12]=r*P+o*j+l*ue+c*ke,n[1]=h*M+u*z+d*X+p*ge,n[5]=h*w+u*$+d*Z+p*ie,n[9]=h*R+u*q+d*ve+p*we,n[13]=h*P+u*j+d*ue+p*ke,n[2]=f*M+m*z+y*X+g*ge,n[6]=f*w+m*$+y*Z+g*ie,n[10]=f*R+m*q+y*ve+g*we,n[14]=f*P+m*j+y*ue+g*ke,n[3]=_*M+b*z+S*X+T*ge,n[7]=_*w+b*$+S*Z+T*ie,n[11]=_*R+b*q+S*ve+T*we,n[15]=_*P+b*j+S*ue+T*ke,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],r=e[1],o=e[5],l=e[9],c=e[13],h=e[2],u=e[6],d=e[10],p=e[14],f=e[3],m=e[7],y=e[11],g=e[15];return f*(+n*l*u-i*c*u-n*o*d+s*c*d+i*o*p-s*l*p)+m*(+t*l*p-t*c*d+n*r*d-i*r*p+i*c*h-n*l*h)+y*(+t*c*u-t*o*p-n*r*u+s*r*p+n*o*h-s*c*h)+g*(-i*o*h-t*l*u+t*o*d+i*r*u-s*r*d+s*l*h)}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],r=e[4],o=e[5],l=e[6],c=e[7],h=e[8],u=e[9],d=e[10],p=e[11],f=e[12],m=e[13],y=e[14],g=e[15],_=u*y*c-m*d*c+m*l*p-o*y*p-u*l*g+o*d*g,b=f*d*c-h*y*c-f*l*p+r*y*p+h*l*g-r*d*g,S=h*m*c-f*u*c+f*o*p-r*m*p-h*o*g+r*u*g,T=f*u*l-h*m*l-f*o*d+r*m*d+h*o*y-r*u*y,M=t*_+s*b+i*S+n*T;if(M===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const w=1/M;return e[0]=_*w,e[1]=(m*d*n-u*y*n-m*i*p+s*y*p+u*i*g-s*d*g)*w,e[2]=(o*y*n-m*l*n+m*i*c-s*y*c-o*i*g+s*l*g)*w,e[3]=(u*l*n-o*d*n-u*i*c+s*d*c+o*i*p-s*l*p)*w,e[4]=b*w,e[5]=(h*y*n-f*d*n+f*i*p-t*y*p-h*i*g+t*d*g)*w,e[6]=(f*l*n-r*y*n-f*i*c+t*y*c+r*i*g-t*l*g)*w,e[7]=(r*d*n-h*l*n+h*i*c-t*d*c-r*i*p+t*l*p)*w,e[8]=S*w,e[9]=(f*u*n-h*m*n-f*s*p+t*m*p+h*s*g-t*u*g)*w,e[10]=(r*m*n-f*o*n+f*s*c-t*m*c-r*s*g+t*o*g)*w,e[11]=(h*o*n-r*u*n-h*s*c+t*u*c+r*s*p-t*o*p)*w,e[12]=T*w,e[13]=(h*m*i-f*u*i+f*s*d-t*m*d-h*s*y+t*u*y)*w,e[14]=(f*o*i-r*m*i-f*s*l+t*m*l+r*s*y-t*o*y)*w,e[15]=(r*u*i-h*o*i+h*s*l-t*u*l-r*s*d+t*o*d)*w,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,r=e.x,o=e.y,l=e.z,c=n*r,h=n*o;return this.set(c*r+s,c*o-i*l,c*l+i*o,0,c*o+i*l,h*o+s,h*l-i*r,0,c*l-i*o,h*l+i*r,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,r){return this.set(1,s,n,0,e,1,r,0,t,i,1,0,0,0,0,1),this}compose(e,t,s){const i=this.elements,n=t._x,r=t._y,o=t._z,l=t._w,c=n+n,h=r+r,u=o+o,d=n*c,p=n*h,f=n*u,m=r*h,y=r*u,g=o*u,_=l*c,b=l*h,S=l*u,T=s.x,M=s.y,w=s.z;return i[0]=(1-(m+g))*T,i[1]=(p+S)*T,i[2]=(f-b)*T,i[3]=0,i[4]=(p-S)*M,i[5]=(1-(d+g))*M,i[6]=(y+_)*M,i[7]=0,i[8]=(f+b)*w,i[9]=(y-_)*w,i[10]=(1-(d+m))*w,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;let n=bn.set(i[0],i[1],i[2]).length();const r=bn.set(i[4],i[5],i[6]).length(),o=bn.set(i[8],i[9],i[10]).length();this.determinant()<0&&(n=-n),e.x=i[12],e.y=i[13],e.z=i[14],ds.copy(this);const c=1/n,h=1/r,u=1/o;return ds.elements[0]*=c,ds.elements[1]*=c,ds.elements[2]*=c,ds.elements[4]*=h,ds.elements[5]*=h,ds.elements[6]*=h,ds.elements[8]*=u,ds.elements[9]*=u,ds.elements[10]*=u,t.setFromRotationMatrix(ds),s.x=n,s.y=r,s.z=o,this}makePerspective(e,t,s,i,n,r,o=Lt){const l=this.elements,c=2*n/(t-e),h=2*n/(s-i),u=(t+e)/(t-e),d=(s+i)/(s-i);let p,f;if(o===Lt)p=-(r+n)/(r-n),f=-2*r*n/(r-n);else if(o===Fi)p=-r/(r-n),f=-r*n/(r-n);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return l[0]=c,l[4]=0,l[8]=u,l[12]=0,l[1]=0,l[5]=h,l[9]=d,l[13]=0,l[2]=0,l[6]=0,l[10]=p,l[14]=f,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(e,t,s,i,n,r,o=Lt){const l=this.elements,c=1/(t-e),h=1/(s-i),u=1/(r-n),d=(t+e)*c,p=(s+i)*h;let f,m;if(o===Lt)f=(r+n)*u,m=-2*u;else if(o===Fi)f=n*u,m=-1*u;else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return l[0]=2*c,l[4]=0,l[8]=0,l[12]=-d,l[1]=0,l[5]=2*h,l[9]=0,l[13]=-p,l[2]=0,l[6]=0,l[10]=m,l[14]=-f,l[3]=0,l[7]=0,l[11]=0,l[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 bn=new N,ds=new Be,v_=new N(0,0,0),w_=new N(1,1,1),pi=new N,Da=new N,Ht=new N;class ce{constructor(e=0,t=0){ce.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=de(this.x,e.x,t.x),this.y=de(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=de(this.x,e,t),this.y=de(this.y,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(de(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(de(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,r=this.y-e.y;return this.x=n*s-r*i+e.x,this.y=n*i+r*s+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class me{constructor(e=0,t=0,s=0,i=1){me.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,r=e.elements;return this.x=r[0]*t+r[4]*s+r[8]*i+r[12]*n,this.y=r[1]*t+r[5]*s+r[9]*i+r[13]*n,this.z=r[2]*t+r[6]*s+r[10]*i+r[14]*n,this.w=r[3]*t+r[7]*s+r[11]*i+r[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],h=l[4],u=l[8],d=l[1],p=l[5],f=l[9],m=l[2],y=l[6],g=l[10];if(Math.abs(h-d)<.01&&Math.abs(u-m)<.01&&Math.abs(f-y)<.01){if(Math.abs(h+d)<.1&&Math.abs(u+m)<.1&&Math.abs(f+y)<.1&&Math.abs(c+p+g-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const b=(c+1)/2,S=(p+1)/2,T=(g+1)/2,M=(h+d)/4,w=(u+m)/4,R=(f+y)/4;return b>S&&b>T?b<.01?(s=0,i=.707106781,n=.707106781):(s=Math.sqrt(b),i=M/s,n=w/s):S>T?S<.01?(s=.707106781,i=0,n=.707106781):(i=Math.sqrt(S),s=M/i,n=R/i):T<.01?(s=.707106781,i=.707106781,n=0):(n=Math.sqrt(T),s=w/n,i=R/n),this.set(s,i,n,t),this}let _=Math.sqrt((y-f)*(y-f)+(u-m)*(u-m)+(d-h)*(d-h));return Math.abs(_)<.001&&(_=1),this.x=(y-f)/_,this.y=(u-m)/_,this.z=(d-h)/_,this.w=Math.acos((c+p+g-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=de(this.x,e.x,t.x),this.y=de(this.y,e.y,t.y),this.z=de(this.z,e.z,t.z),this.w=de(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=de(this.x,e,t),this.y=de(this.y,e,t),this.z=de(this.z,e,t),this.w=de(this.w,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(de(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}}function ga(a,e=0){let t=3735928559^e,s=1103547991^e;if(a instanceof Array)for(let i=0,n;i<a.length;i++)n=a[i],t=Math.imul(t^n,2654435761),s=Math.imul(s^n,1597334677);else for(let i=0,n;i<a.length;i++)n=a.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 E_=a=>ga(a),nu=a=>ga(a),qo=(...a)=>ga(a);function Lm(a,e=!1){const t=[];a.isNode===!0&&(t.push(a.id),a=a.getSelf());for(const{property:s,childNode:i}of Yo(a))t.push(ga(s.slice(0,-4)),i.getCacheKey(e));return ga(t)}function*Yo(a,e=!1){for(const t in a){if(t.startsWith("_")===!0)continue;const s=a[t];if(Array.isArray(s)===!0)for(let i=0;i<s.length;i++){const n=s[i];n&&(n.isNode===!0||e&&typeof n.toJSON=="function")&&(yield{property:t,index:i,childNode:n})}else if(s&&s.isNode===!0)yield{property:t,childNode:s};else if(typeof s=="object")for(const i in s){const n=s[i];n&&(n.isNode===!0||e&&typeof n.toJSON=="function")&&(yield{property:t,index:i,childNode:n})}}}const M_=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),Od=new WeakMap;function C_(a){return M_.get(a)}function Xo(a){if(a==null)return null;const e=typeof a;return a.isNode===!0?"node":e==="number"?"float":e==="boolean"?"bool":e==="string"?"string":e==="function"?"shader":a.isVector2===!0?"vec2":a.isVector3===!0?"vec3":a.isVector4===!0?"vec4":a.isMatrix2===!0?"mat2":a.isMatrix3===!0?"mat3":a.isMatrix4===!0?"mat4":a.isColor===!0?"color":a instanceof ArrayBuffer?"ArrayBuffer":null}function Um(a,...e){const t=a?a.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]])),a==="color"?new Se(...e):t==="vec2"?new ce(...e):t==="vec3"?new N(...e):t==="vec4"?new me(...e):t==="mat2"?new ol(...e):t==="mat3"?new Vt(...e):t==="mat4"?new Be(...e):a==="bool"?e[0]||!1:a==="float"||a==="int"||a==="uint"?e[0]||0:a==="string"?e[0]||"":a==="ArrayBuffer"?R_(e[0]):null}function km(a){let e=Od.get(a);return e===void 0&&(e={},Od.set(a,e)),e}function A_(a){let e="";const t=new Uint8Array(a);for(let s=0;s<t.length;s++)e+=String.fromCharCode(t[s]);return btoa(e)}function R_(a){return Uint8Array.from(atob(a),e=>e.charCodeAt(0)).buffer}let N_=0;function P_(a){const e=Object.keys(a);let t=Object.getPrototypeOf(a);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 F_{constructor(e,t,s,i,n,r,o,l,c,h){this.id=N_++,this._nodes=e,this._geometries=t,this.renderer=s,this.object=i,this.material=n,this.scene=r,this.camera=o,this.lightsNode=l,this.context=c,this.geometry=i.geometry,this.version=n.version,this.drawRange=null,this.attributes=null,this.pipeline=null,this.group=null,this.vertexBuffers=null,this.drawParams=null,this.bundle=null,this.clippingContext=h,this.clippingContextCacheKey=h!==null?h.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.material.addEventListener("dispose",this.onMaterialDispose)}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)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}setGeometry(e){this.geometry=e,this.attributes=null}getAttributes(){if(this.attributes!==null)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,s=[],i=new Set;for(const n of e){const r=n.node&&n.node.attribute?n.node.attribute:t.getAttribute(n.name);if(r===void 0)continue;s.push(r);const o=r.isInterleavedBufferAttribute?r.data:r;i.add(o)}return this.attributes=s,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,r=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(r.instanceCount=c,e.isBatchedMesh===!0)return r;let h=1;t.wireframe===!0&&!e.isPoints&&!e.isLineSegments&&!e.isLine&&!e.isLineLoop&&(h=2);let u=n.start*h,d=(n.start+n.count)*h;i!==null&&(u=Math.max(u,i.start*h),d=Math.min(d,(i.start+i.count)*h));const p=s.attributes.position;let f=1/0;l?f=o.count:p!=null&&(f=p.count),u=Math.max(u,0),d=Math.min(d,f);const m=d-u;return m<0||m===1/0?null:(r.vertexCount=m,r.firstVertex=u,r)}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,r=i.length;n<r;n++){const o=i[n];t+=o.id+","}}return e.index&&(t+="index,"),t}getMaterialCacheKey(){const{object:e,material:t}=this;let s=t.customProgramCacheKey();for(const i of P_(t)){if(/^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test(i))continue;const n=t[i];let r;if(n!==null){const o=typeof n;o==="number"?r=n!==0?"1":"0":o==="object"?(r="{",n.isTexture&&(r+=n.mapping),r+="}"):r=String(n)}else r=String(n);s+=r+","}return s+=this.clippingContextCacheKey+",",e.geometry&&(s+=this.getGeometryCacheKey()),e.skeleton&&(s+=e.skeleton.bones.length+","),e.isBatchedMesh&&(s+=e._matricesTexture.uuid+",",e._colorsTexture!==null&&(s+=e._colorsTexture.uuid+",")),e.count>1&&(s+=e.uuid+","),s+=e.receiveShadow+",",E_(s)}get needsGeometryUpdate(){return this.geometry.id!==this.object.geometry.id}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=qo(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=qo(e,1)),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.onDispose()}}const ki=[];class D_{constructor(e,t,s,i,n,r){this.renderer=e,this.nodes=t,this.geometries=s,this.pipelines=i,this.bindings=n,this.info=r,this.chainMaps={}}get(e,t,s,i,n,r,o,l){const c=this.getChainMap(l);ki[0]=e,ki[1]=t,ki[2]=r,ki[3]=n;let h=c.get(ki);return h===void 0?(h=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,s,i,n,r,o,l),c.set(ki,h)):(h.updateClipping(o),h.needsGeometryUpdate&&h.setGeometry(e.geometry),(h.version!==t.version||h.needsUpdate)&&(h.initialCacheKey!==h.getCacheKey()?(h.dispose(),h=this.get(e,t,s,i,n,r,o,l)):h.version=t.version)),ki.length=0,h}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new vs)}dispose(){this.chainMaps={}}createRenderObject(e,t,s,i,n,r,o,l,c,h,u){const d=this.getChainMap(u),p=new F_(e,t,s,i,n,r,o,l,c,h);return p.onDispose=()=>{this.pipelines.delete(p),this.bindings.delete(p),this.nodes.delete(p),d.delete(p.getChainArray())},p}}class Bi{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 as={VERTEX:1,INDEX:2,STORAGE:3,INDIRECT:4},Mi=16,O_=211,B_=212;class I_ extends Bi{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===as.VERTEX?this.backend.createAttribute(e):t===as.INDEX?this.backend.createIndexAttribute(e):t===as.STORAGE?this.backend.createStorageAttribute(e):t===as.INDIRECT&&this.backend.createIndirectStorageAttribute(e),s.version=this._getBufferAttribute(e).version;else{const i=this._getBufferAttribute(e);(s.version<i.version||i.usage===Hn)&&(this.backend.updateAttribute(e),s.version=i.version)}}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}const Ys=L_();function L_(){const a=new ArrayBuffer(4),e=new Float32Array(a),t=new Uint32Array(a),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),r=new Uint32Array(64),o=new Uint32Array(64);for(let l=1;l<1024;++l){let c=l<<13,h=0;for(;(c&8388608)===0;)c<<=1,h-=8388608;c&=-8388609,h+=947912704,n[l]=c|h}for(let l=1024;l<2048;++l)n[l]=939524096+(l-1024<<13);for(let l=1;l<31;++l)r[l]=l<<23;r[31]=1199570944,r[32]=2147483648;for(let l=33;l<63;++l)r[l]=2147483648+(l-32<<23);r[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:r,offsetTable:o}}function Wt(a){Math.abs(a)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),a=de(a,-65504,65504),Ys.floatView[0]=a;const e=Ys.uint32View[0],t=e>>23&511;return Ys.baseTable[t]+((e&8388607)>>Ys.shiftTable[t])}function Oa(a){const e=a>>10;return Ys.uint32View[0]=Ys.mantissaTable[Ys.offsetTable[e]+(a&1023)]+Ys.exponentTable[e],Ys.floatView[0]}const Qe=new N,Ba=new ce;let U_=0;class os{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:U_++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=s,this.usage=jo,this.updateRanges=[],this.gpuType=Zt,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++)Ba.fromBufferAttribute(this,t),Ba.applyMatrix3(e),this.setXY(t,Ba.x,Ba.y);else if(this.itemSize===3)for(let t=0,s=this.count;t<s;t++)Qe.fromBufferAttribute(this,t),Qe.applyMatrix3(e),this.setXYZ(t,Qe.x,Qe.y,Qe.z);return this}applyMatrix4(e){for(let t=0,s=this.count;t<s;t++)Qe.fromBufferAttribute(this,t),Qe.applyMatrix4(e),this.setXYZ(t,Qe.x,Qe.y,Qe.z);return this}applyNormalMatrix(e){for(let t=0,s=this.count;t<s;t++)Qe.fromBufferAttribute(this,t),Qe.applyNormalMatrix(e),this.setXYZ(t,Qe.x,Qe.y,Qe.z);return this}transformDirection(e){for(let t=0,s=this.count;t<s;t++)Qe.fromBufferAttribute(this,t),Qe.transformDirection(e),this.setXYZ(t,Qe.x,Qe.y,Qe.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=At(s,this.array)),s}setComponent(e,t,s){return this.normalized&&(s=oe(s,this.array)),this.array[e*this.itemSize+t]=s,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=At(t,this.array)),t}setX(e,t){return this.normalized&&(t=oe(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=At(t,this.array)),t}setY(e,t){return this.normalized&&(t=oe(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=At(t,this.array)),t}setZ(e,t){return this.normalized&&(t=oe(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=At(t,this.array)),t}setW(e,t){return this.normalized&&(t=oe(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,s){return e*=this.itemSize,this.normalized&&(t=oe(t,this.array),s=oe(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=oe(t,this.array),s=oe(s,this.array),i=oe(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=oe(t,this.array),s=oe(s,this.array),i=oe(i,this.array),n=oe(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!==jo&&(e.usage=this.usage),e}}class zm extends os{constructor(e,t,s){super(new Uint16Array(e),t,s)}}class Gm extends os{constructor(e,t,s){super(new Uint32Array(e),t,s)}}class Vm extends os{constructor(e,t,s){super(new Uint16Array(e),t,s),this.isFloat16BufferAttribute=!0}getX(e){let t=Oa(this.array[e*this.itemSize]);return this.normalized&&(t=At(t,this.array)),t}setX(e,t){return this.normalized&&(t=oe(t,this.array)),this.array[e*this.itemSize]=Wt(t),this}getY(e){let t=Oa(this.array[e*this.itemSize+1]);return this.normalized&&(t=At(t,this.array)),t}setY(e,t){return this.normalized&&(t=oe(t,this.array)),this.array[e*this.itemSize+1]=Wt(t),this}getZ(e){let t=Oa(this.array[e*this.itemSize+2]);return this.normalized&&(t=At(t,this.array)),t}setZ(e,t){return this.normalized&&(t=oe(t,this.array)),this.array[e*this.itemSize+2]=Wt(t),this}getW(e){let t=Oa(this.array[e*this.itemSize+3]);return this.normalized&&(t=At(t,this.array)),t}setW(e,t){return this.normalized&&(t=oe(t,this.array)),this.array[e*this.itemSize+3]=Wt(t),this}setXY(e,t,s){return e*=this.itemSize,this.normalized&&(t=oe(t,this.array),s=oe(s,this.array)),this.array[e+0]=Wt(t),this.array[e+1]=Wt(s),this}setXYZ(e,t,s,i){return e*=this.itemSize,this.normalized&&(t=oe(t,this.array),s=oe(s,this.array),i=oe(i,this.array)),this.array[e+0]=Wt(t),this.array[e+1]=Wt(s),this.array[e+2]=Wt(i),this}setXYZW(e,t,s,i,n){return e*=this.itemSize,this.normalized&&(t=oe(t,this.array),s=oe(s,this.array),i=oe(i,this.array),n=oe(n,this.array)),this.array[e+0]=Wt(t),this.array[e+1]=Wt(s),this.array[e+2]=Wt(i),this.array[e+3]=Wt(n),this}}class Nt extends os{constructor(e,t,s){super(new Float32Array(e),t,s)}}function Hm(a){return a.index!==null?a.index.version:a.attributes.position.version}function Bd(a){const e=[],t=a.index,s=a.attributes.position;if(t!==null){const n=t.array;for(let r=0,o=n.length;r<o;r+=3){const l=n[r+0],c=n[r+1],h=n[r+2];e.push(l,c,c,h,h,l)}}else{const n=s.array;for(let r=0,o=n.length/3-1;r<o;r+=3){const l=r+0,c=r+1,h=r+2;e.push(l,c,c,h,h,l)}}const i=new(Bm(e)?Gm:zm)(e,1);return i.version=Hm(a),i}class k_ extends Bi{constructor(e,t){super(),this.attributes=e,this.info=t,this.wireframes=new WeakMap,this.attributeCall=new WeakMap}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,r=e.getAttributes();n!==null&&this.attributes.delete(n);for(const l of r)this.attributes.delete(l);const o=this.wireframes.get(t);o!==void 0&&this.attributes.delete(o),t.removeEventListener("dispose",i)};t.addEventListener("dispose",i)}updateAttributes(e){const t=e.getAttributes();for(const n of t)n.isStorageBufferAttribute||n.isStorageInstancedBufferAttribute?this.updateAttribute(n,as.STORAGE):this.updateAttribute(n,as.VERTEX);const s=this.getIndex(e);s!==null&&this.updateAttribute(s,as.INDEX);const i=e.geometry.indirect;i!==null&&this.updateAttribute(i,as.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}getIndex(e){const{geometry:t,material:s}=e;let i=t.index;if(s.wireframe===!0){const n=this.wireframes;let r=n.get(t);r===void 0?(r=Bd(t),n.set(t,r)):r.version!==Hm(t)&&(this.attributes.delete(r),r=Bd(t),n.set(t,r)),i=r}return i}}class z_{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):console.error("THREE.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 Wm{constructor(e){this.cacheKey=e,this.usedTimes=0}}class G_ extends Wm{constructor(e,t,s){super(e),this.vertexProgram=t,this.fragmentProgram=s}}class V_ extends Wm{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let H_=0;class Gl{constructor(e,t,s,i=null,n=null){this.id=H_++,this.code=e,this.stage=t,this.name=s,this.transforms=i,this.attributes=n,this.usedTimes=0}}class W_ extends Bi{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 r=this.nodes.getForCompute(e);let o=this.programs.compute.get(r.computeShader);o===void 0&&(n&&n.computeProgram.usedTimes===0&&this._releaseProgram(n.computeProgram),o=new Gl(r.computeShader,"compute",e.name,r.transforms,r.nodeAttributes),this.programs.compute.set(r.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 r=e.getNodeBuilderState(),o=e.material?e.material.name:"";let l=this.programs.vertex.get(r.vertexShader);l===void 0&&(n&&n.vertexProgram.usedTimes===0&&this._releaseProgram(n.vertexProgram),l=new Gl(r.vertexShader,"vertex",o),this.programs.vertex.set(r.vertexShader,l),s.createProgram(l));let c=this.programs.fragment.get(r.fragmentShader);c===void 0&&(n&&n.fragmentProgram.usedTimes===0&&this._releaseProgram(n.fragmentProgram),c=new Gl(r.fragmentShader,"fragment",o),this.programs.fragment.set(r.fragmentShader,c),s.createProgram(c));const h=this._getRenderCacheKey(e,l,c);let u=this.caches.get(h);u===void 0?(n&&n.usedTimes===0&&this._releasePipeline(n),u=this._getRenderPipeline(e,l,c,h,t)):e.pipeline=u,u.usedTimes++,l.usedTimes++,c.usedTimes++,i.pipeline=u}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 V_(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 r=this.caches.get(i);return r===void 0&&(r=new G_(i,t,s),this.caches.set(i,r),e.pipeline=r,this.backend.createRenderPipeline(e,n)),r}_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 $_ extends Bi{constructor(e,t,s,i,n,r){super(),this.backend=e,this.textures=s,this.pipelines=n,this.attributes=i,this.nodes=t,this.info=r,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))}_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.isStorageBuffer){const s=t.attribute,i=s.isIndirectStorageBufferAttribute?as.INDIRECT:as.STORAGE;this.attributes.update(s,i)}}_update(e,t){const{backend:s}=this;let i=!1,n=!0,r=0,o=0;for(const l of e.bindings)if(!(l.isNodeUniformsGroup&&this.nodes.updateGroup(l)===!1)){if(l.isStorageBuffer){const c=l.attribute,h=c.isIndirectStorageBufferAttribute?as.INDIRECT:as.STORAGE;this.attributes.update(c,h)}if(l.isUniformBuffer)l.update()&&s.updateBinding(l);else if(l.isSampler)l.update();else if(l.isSampledTexture){const c=this.textures.get(l.texture);l.needsBindingsUpdate(c.generation)&&(i=!0);const h=l.update(),u=l.texture;h&&this.textures.updateTexture(u);const d=s.get(u);if(d.externalTexture!==void 0||c.isDefaultTexture?n=!1:(r=r*10+u.id,o+=u.version),s.isWebGPUBackend===!0&&d.texture===void 0&&d.externalTexture===void 0&&(console.error("Bindings._update: binding should be available:",l,h,u,l.textureNode.value,i),this.textures.updateTexture(u),i=!0),u.isStorageTexture===!0){const p=this.get(u);l.store===!0?p.needsMipmap=!0:this.textures.needsMipmaps(u)&&p.needsMipmap===!0&&(this.backend.generateMipmaps(u),p.needsMipmap=!1)}}}i===!0&&this.backend.updateBindings(e,t,n?r:0,o)}}function j_(a,e){return a.groupOrder!==e.groupOrder?a.groupOrder-e.groupOrder:a.renderOrder!==e.renderOrder?a.renderOrder-e.renderOrder:a.z!==e.z?a.z-e.z:a.id-e.id}function Id(a,e){return a.groupOrder!==e.groupOrder?a.groupOrder-e.groupOrder:a.renderOrder!==e.renderOrder?a.renderOrder-e.renderOrder:a.z!==e.z?e.z-a.z:a.id-e.id}function Ld(a){return(a.transmission>0||a.transmissionNode)&&a.side===Yn&&a.forceSinglePass===!1}class q_{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,r,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:r,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=r,l.clippingContext=o),this.renderItemsIndex++,l}push(e,t,s,i,n,r,o){const l=this.getNextRenderItem(e,t,s,i,n,r,o);e.occlusionTest===!0&&this.occlusionQueryCount++,s.transparent===!0||s.transmission>0?(Ld(s)&&this.transparentDoublePass.push(l),this.transparent.push(l)):this.opaque.push(l)}unshift(e,t,s,i,n,r,o){const l=this.getNextRenderItem(e,t,s,i,n,r,o);s.transparent===!0||s.transmission>0?(Ld(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||j_),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||Id),this.transparent.length>1&&this.transparent.sort(t||Id)}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 Sr=[];class Y_{constructor(e){this.lighting=e,this.lists=new vs}get(e,t){const s=this.lists;Sr[0]=e,Sr[1]=t;let i=s.get(Sr);return i===void 0&&(i=new q_(this.lighting,e,t),s.set(Sr,i)),Sr.length=0,i}dispose(){this.lists=new vs}}let X_=0;class Z_{constructor(){this.id=X_++,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 me,this.scissor=!1,this.scissorValue=new me,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.isRenderContext=!0}getCacheKey(){return $m(this)}}function $m(a){const{textures:e,activeCubeFace:t}=a,s=[t];for(const i of e)s.push(i.id);return nu(s)}let un=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,r=i.length;n<r;n++)i[n].call(this,e);e.target=null}}};const Ud=new Be,kd=new pr;class hs{constructor(e=0,t=0,s=0,i=hs.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],r=i[4],o=i[8],l=i[1],c=i[5],h=i[9],u=i[2],d=i[6],p=i[10];switch(t){case"XYZ":this._y=Math.asin(de(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-h,p),this._z=Math.atan2(-r,n)):(this._x=Math.atan2(d,c),this._z=0);break;case"YXZ":this._x=Math.asin(-de(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(o,p),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-u,n),this._z=0);break;case"ZXY":this._x=Math.asin(de(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,p),this._z=Math.atan2(-r,c)):(this._y=0,this._z=Math.atan2(l,n));break;case"ZYX":this._y=Math.asin(-de(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,p),this._z=Math.atan2(l,n)):(this._x=0,this._z=Math.atan2(-r,c));break;case"YZX":this._z=Math.asin(de(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-h,c),this._y=Math.atan2(-u,n)):(this._x=0,this._y=Math.atan2(o,p));break;case"XZY":this._z=Math.asin(-de(r,-1,1)),Math.abs(r)<.9999999?(this._x=Math.atan2(d,c),this._y=Math.atan2(o,n)):(this._x=Math.atan2(-h,p),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,s===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,s){return Ud.makeRotationFromQuaternion(e),this.setFromRotationMatrix(Ud,t,s)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return kd.setFromEuler(this),this.setFromQuaternion(kd,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}}hs.DEFAULT_ORDER="XYZ";class Q_{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 K_=0;const zd=new N,Tn=new pr,Vs=new Be,Ia=new N,vr=new N,J_=new N,eb=new pr,Gd=new N(1,0,0),Vd=new N(0,1,0),Hd=new N(0,0,1),Wd={type:"added"},tb={type:"removed"},Sn={type:"childadded",child:null},Vl={type:"childremoved",child:null};class ct extends un{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:K_++}),this.uuid=Qs(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=ct.DEFAULT_UP.clone();const e=new N,t=new hs,s=new pr,i=new N(1,1,1);function n(){s.setFromEuler(t,!1)}function r(){t.setFromQuaternion(s,void 0,!1)}t._onChange(n),s._onChange(r),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 Be},normalMatrix:{value:new Vt}}),this.matrix=new Be,this.matrixWorld=new Be,this.matrixAutoUpdate=ct.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=ct.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new Q_,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.userData={}}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 Tn.setFromAxisAngle(e,t),this.quaternion.multiply(Tn),this}rotateOnWorldAxis(e,t){return Tn.setFromAxisAngle(e,t),this.quaternion.premultiply(Tn),this}rotateX(e){return this.rotateOnAxis(Gd,e)}rotateY(e){return this.rotateOnAxis(Vd,e)}rotateZ(e){return this.rotateOnAxis(Hd,e)}translateOnAxis(e,t){return zd.copy(e).applyQuaternion(this.quaternion),this.position.add(zd.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(Gd,e)}translateY(e){return this.translateOnAxis(Vd,e)}translateZ(e){return this.translateOnAxis(Hd,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(Vs.copy(this.matrixWorld).invert())}lookAt(e,t,s){e.isVector3?Ia.copy(e):Ia.set(e,t,s);const i=this.parent;this.updateWorldMatrix(!0,!1),vr.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Vs.lookAt(vr,Ia,this.up):Vs.lookAt(Ia,vr,this.up),this.quaternion.setFromRotationMatrix(Vs),i&&(Vs.extractRotation(i.matrixWorld),Tn.setFromRotationMatrix(Vs),this.quaternion.premultiply(Tn.invert()))}add(e){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return e===this?(console.error("THREE.Object3D.add: object can't be added as a child of itself.",e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(Wd),Sn.child=e,this.dispatchEvent(Sn),Sn.child=null):console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let 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(tb),Vl.child=e,this.dispatchEvent(Vl),Vl.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),Vs.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),Vs.multiply(e.parent.matrixWorld)),e.applyMatrix4(Vs),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(Wd),Sn.child=e,this.dispatchEvent(Sn),Sn.child=null,this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let s=0,i=this.children.length;s<i;s++){const r=this.children[s].getObjectByProperty(e,t);if(r!==void 0)return r}}getObjectsByProperty(e,t,s=[]){this[e]===t&&s.push(this);const i=this.children;for(let n=0,r=i.length;n<r;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(vr,e,J_),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(vr,eb,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),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,r=i.length;n<r;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),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.matrixAutoUpdate===!1&&(i.matrixAutoUpdate=!1),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,h=l.length;c<h;c++){const u=l[c];n(e.shapes,u)}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=r(e.geometries),l=r(e.materials),c=r(e.textures),h=r(e.images),u=r(e.shapes),d=r(e.skeletons),p=r(e.animations),f=r(e.nodes);o.length>0&&(s.geometries=o),l.length>0&&(s.materials=l),c.length>0&&(s.textures=c),h.length>0&&(s.images=h),u.length>0&&(s.shapes=u),d.length>0&&(s.skeletons=d),p.length>0&&(s.animations=p),f.length>0&&(s.nodes=f)}return s.object=i,s;function r(o){const l=[];for(const c in o){const h=o[c];delete h.metadata,l.push(h)}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),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=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}}ct.DEFAULT_UP=new N(0,1,0);ct.DEFAULT_MATRIX_AUTO_UPDATE=!0;ct.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;class ru extends ct{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 hs,this.environmentIntensity=1,this.environmentRotation=new hs,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}}class au extends ct{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Be,this.projectionMatrix=new Be,this.projectionMatrixInverse=new Be,this.coordinateSystem=Lt}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const wr=[],sb=new ru,ib=new au;class nb{constructor(){this.chainMaps={}}get(e,t,s=null){wr[0]=e,wr[1]=t;let i;if(s===null)i="default";else{const o=s.texture.format;i=`${s.textures.length}:${o}:${s.samples}:${s.depthBuffer}:${s.stencilBuffer}`}const n=this._getChainMap(i);let r=n.get(wr);return r===void 0&&(r=new Z_,n.set(wr,r)),wr.length=0,s!==null&&(r.sampleCount=s.samples===0?1:s.samples),r}getForClear(e=null){return this.get(sb,ib,e)}_getChainMap(e){return this.chainMaps[e]||(this.chainMaps[e]=new vs)}dispose(){this.chainMaps={}}}let vn;class rb{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{vn===void 0&&(vn=Ah("canvas")),vn.width=e.width,vn.height=e.height;const i=vn.getContext("2d");e instanceof ImageData?i.putImageData(e,0,0):i.drawImage(e,0,0,e.width,e.height),s=vn}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=Ah("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 r=0;r<n.length;r++)n[r]=si(n[r]/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(si(t[s]/255)*255):t[s]=si(t[s]);return{data:t,width:e.width,height:e.height}}else return console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let ab=0;class ou{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:ab++}),this.uuid=Qs(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){const t=this.data;return t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight):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 r=0,o=i.length;r<o;r++)i[r].isDataTexture?n.push(Hl(i[r].image)):n.push(Hl(i[r]))}else n=Hl(i);s.url=n}return t||(e.images[this.uuid]=s),s}}function Hl(a){return typeof HTMLImageElement<"u"&&a instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&a instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&a instanceof ImageBitmap?rb.getDataURL(a):a.data?{data:Array.from(a.data),width:a.width,height:a.height,type:a.data.constructor.name}:(console.warn("THREE.Texture: Unable to serialize Texture."),{})}let ob=0;const Wl=new N;class Tt extends un{constructor(e=Tt.DEFAULT_IMAGE,t=Tt.DEFAULT_MAPPING,s=Ri,i=Ri,n=Qt,r=ei,o=rs,l=Rt,c=Tt.DEFAULT_ANISOTROPY,h=ri){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:ob++}),this.uuid=Qs(),this.name="",this.source=new ou(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=s,this.wrapT=i,this.magFilter=n,this.minFilter=r,this.anisotropy=c,this.format=o,this.internalFormat=null,this.type=l,this.offset=new ce(0,0),this.repeat=new ce(1,1),this.center=new ce(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new Vt,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=h,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(Wl).x}get height(){return this.source.getSize(Wl).y}get depth(){return this.source.getSize(Wl).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){console.warn(`THREE.Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const i=this[t];if(i===void 0){console.warn(`THREE.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!==Xh)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case ar:e.x=e.x-Math.floor(e.x);break;case Ri:e.x=e.x<0?0:1;break;case or: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 ar:e.y=e.y-Math.floor(e.y);break;case Ri:e.y=e.y<0?0:1;break;case or: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++}}Tt.DEFAULT_IMAGE=null;Tt.DEFAULT_MAPPING=Xh;Tt.DEFAULT_ANISOTROPY=1;class Is extends Tt{constructor(e,t,s=Ye,i,n,r,o=lt,l=lt,c,h=Bs,u=1){if(h!==Bs&&h!==ti)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const d={width:e,height:t,depth:u};super(d,i,n,r,o,l,h,s,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new ou(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}}const lb=new N;class cb extends Bi{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={}),r=e.textures,o=this.getSize(r[0]),l=o.width>>t,c=o.height>>t;let h=e.depthTexture||n[t];const u=e.depthBuffer===!0||e.stencilBuffer===!0;let d=!1;h===void 0&&u&&(h=new Is,h.format=e.stencilBuffer?ti:Bs,h.type=e.stencilBuffer?Ni:Ye,h.image.width=l,h.image.height=c,h.image.depth=o.depth,h.isArrayTexture=e.multiview===!0&&o.depth>1,n[t]=h),(s.width!==o.width||o.height!==s.height)&&(d=!0,h&&(h.needsUpdate=!0,h.image.width=l,h.image.height=c,h.image.depth=h.isArrayTexture?h.image.depth:1)),s.width=o.width,s.height=o.height,s.textures=r,s.depthTexture=h||null,s.depth=e.depthBuffer,s.stencil=e.stencilBuffer,s.renderTarget=e,s.sampleCount!==i&&(d=!0,h&&(h.needsUpdate=!0),s.sampleCount=i);const p={sampleCount:i};if(e.isXRRenderTarget!==!0){for(let f=0;f<r.length;f++){const m=r[f];d&&(m.needsUpdate=!0),this.updateTexture(m,p)}h&&this.updateTexture(h,p)}if(s.initialized!==!0){s.initialized=!0;const f=()=>{e.removeEventListener("dispose",f);for(let m=0;m<r.length;m++)this._destroyTexture(r[m]);h&&this._destroyTexture(h),this.delete(e)};e.addEventListener("dispose",f)}}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.destroySampler(e),n.destroyTexture(e)),e.isFramebufferTexture){const c=this.renderer.getRenderTarget();c?e.type=c.texture.type:e.type=Rt}const{width:r,height:o,depth:l}=this.getSize(e);if(t.width=r,t.height=o,t.depth=l,t.needsMipmaps=this.needsMipmaps(e),t.levels=t.needsMipmaps?this.getMipLevels(e,r,o):1,i||e.isStorageTexture===!0)n.createSampler(e),n.createTexture(e,t),s.generation=e.version;else if(s.initialized!==!0&&n.createSampler(e),e.version>0){const h=e.image;if(h===void 0)console.warn("THREE.Renderer: Texture marked for update but image is undefined.");else if(h.complete===!1)console.warn("THREE.Renderer: Texture marked for update but image is incomplete.");else{if(e.images){const u=[];for(const d of e.images)u.push(d);t.images=u}else t.image=h;(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),t.needsMipmaps&&e.mipmaps.length===0&&n.generateMipmaps(e)}}else n.createDefaultTexture(e),s.isDefaultTexture=!0,s.generation=e.version;if(s.initialized!==!0){s.initialized=!0,s.generation=e.version,this.info.memory.textures++;const c=()=>{e.removeEventListener("dispose",c),this._destroyTexture(e)};e.addEventListener("dispose",c)}s.version=e.version}getSize(e,t=lb){let s=e.images?e.images[0]:e.image;return s?(s.image!==void 0&&(s=s.image),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.isCompressedTexture?e.mipmaps?i=e.mipmaps.length:i=1:i=Math.floor(Math.log2(Math.max(t,s)))+1,i}needsMipmaps(e){return e.isCompressedTexture===!0||e.generateMipmaps}_destroyTexture(e){this.has(e)===!0&&(this.backend.destroySampler(e),this.backend.destroyTexture(e),this.delete(e),this.info.memory.textures--)}}class lu extends Se{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)}}const La={VERTEX:"vertex"},he={NONE:"none",FRAME:"frame",RENDER:"render",OBJECT:"object"},Zs={READ_ONLY:"readOnly",WRITE_ONLY:"writeOnly",READ_WRITE:"readWrite"},hb=["fragment","vertex"],$d=["setup","analyze","generate"],jd=[...hb,"compute"],fr=["x","y","z","w"],ub={analyze:"setup",generate:"analyze"};let db=0;class ae extends un{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=he.NONE,this.updateBeforeType=he.NONE,this.updateAfterType=he.NONE,this.uuid=_x.generateUUID(),this.version=0,this.global=!1,this.parents=!1,this.isNode=!0,this._cacheKey=null,this._cacheKeyVersion=0,Object.defineProperty(this,"id",{value:db++})}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.getSelf()),this}onFrameUpdate(e){return this.onUpdate(e,he.FRAME)}onRenderUpdate(e){return this.onUpdate(e,he.RENDER)}onObjectUpdate(e){return this.onUpdate(e,he.OBJECT)}onReference(e){return this.updateReference=e.bind(this.getSelf()),this}getSelf(){return this.self||this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(const{childNode:e}of Yo(this))yield e}dispose(){this.dispatchEvent({type:"dispose"})}traverse(e){e(this);for(const t of this.getChildren())t.traverse(e)}getCacheKey(e=!1){return e=e||this.version!==this._cacheKeyVersion,(e===!0||this._cacheKey===null)&&(this._cacheKey=qo(Lm(this,e),this.customCacheKey()),this._cacheKeyVersion=this.version),this._cacheKey}customCacheKey(){return 0}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}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(){console.warn("Abstract function.")}updateAfter(){console.warn("Abstract function.")}update(){console.warn("Abstract function.")}build(e,t=null){const s=this.getShared(e);if(this!==s)return s.build(e,t);const i=e.getDataFromNode(this);i.buildStages=i.buildStages||{},i.buildStages[e.buildStage]=!0;const n=ub[e.buildStage];if(n&&i.buildStages[n]!==!0){const l=e.getBuildStage();e.setBuildStage(n),this.build(e),e.setBuildStage(l)}e.addNode(this),e.addChain(this);let r=null;const o=e.getBuildStage();if(o==="setup"){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 h=e.getNodeProperties(c);h.parents=h.parents||[],h.parents.push(this)}c.build(e)}}r=l.outputNode}else if(o==="analyze")this.analyze(e,t);else if(o==="generate")if(this.generate.length===1){const c=this.getNodeType(e),h=e.getDataFromNode(this);r=h.snippet,r===void 0?h.generated===void 0?(h.generated=!0,r=this.generate(e)||"",h.snippet=r):(console.warn("THREE.Node: Recursion detected.",this),r=""):h.flowCodes!==void 0&&e.context.nodeBlock!==void 0&&e.addFlowCodeHierarchy(this,e.context.nodeBlock),r=e.format(r,c,t)}else r=this.generate(e,t)||"";return e.removeChain(this),e.addSequentialNode(this),r}getSerializeChildren(){return Yo(this)}serialize(e){const t=this.getSerializeChildren(),s={};for(const{property:i,index:n,childNode:r}of t)n!==void 0?(s[i]===void 0&&(s[i]=Number.isInteger(n)?[]:{}),s[i][n]=r.toJSON(e.meta).uuid):s[i]=r.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 r=e.inputNodes[s][n];i[n]=t[r]}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 r(o){const l=[];for(const c in o){const h=o[c];delete h.metadata,l.push(h)}return l}if(i){const o=r(e.textures),l=r(e.images),c=r(e.nodes);o.length>0&&(n.textures=o),l.length>0&&(n.images=l),c.length>0&&(n.nodes=c)}return n}}class st extends ae{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 r=super.build(e,i),o=e.getVarFromNode(this,null,i),l=e.getPropertyName(o);return e.addLineFlowCode(`${l} = ${r}`,this),n.snippet=r,n.propertyName=l,e.format(n.propertyName,i,t)}}return super.build(e,t)}}class Sa extends ae{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)}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 jm extends ae{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 pb extends st{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,r=e.getComponentType(s),o=[];let l=0;for(const h of n){if(l>=i){console.error(`THREE.TSL: Length of parameters exceeds maximum length of function '${s}()' type.`);break}let u=h.getNodeType(e),d=e.getTypeLength(u),p;l+d>i&&(console.error(`THREE.TSL: Length of '${s}()' data exceeds maximum length of output type.`),d=i-l,u=e.getTypeFromLength(d)),l+=d,p=h.build(e,u);const f=e.getComponentType(u);f!==r&&(p=e.format(p,f,r)),o.push(p)}const c=`${e.getType(s)}( ${o.join(", ")} )`;return e.format(c,s,t)}}const fb=fr.join("");class qd extends ae{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(fr.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))}generate(e,t){const s=this.node,i=e.getTypeLength(s.getNodeType(e));let n=null;if(i>1){let r=null;this.getVectorLength()>=i&&(r=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const l=s.build(e,r);this.components.length===i&&this.components===fb.slice(0,this.components.length)?n=e.format(l,r,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 mb extends st{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),r=e.getComponentType(i.getNodeType(e)),o=e.getTypeFromLength(s.length,r),l=i.build(e,o),c=t.build(e,n),h=e.getTypeLength(n),u=[];for(let d=0;d<h;d++){const p=fr[d];p===s[0]?(u.push(l),d+=s.length-1):u.push(c+"."+p)}return`${e.getType(n)}( ${u.join(", ")} )`}}class gb extends st{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),r=e.getVarFromNode(this),o=e.getPropertyName(r);e.addLineFlowCode(o+" = "+n,this);const l=e.getTypeLength(i),c=[];let h=0;for(let u=0;u<l;u++){const d=fr[u];d===t[h]?(c.push("1.0 - "+(o+"."+d)),h++):c.push(o+"."+d)}return`${e.getType(i)}( ${c.join(", ")} )`}}class cu extends ae{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?Xo(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=Xo(this.value),e.nodeType=this.nodeType,e.valueType==="ArrayBuffer"&&(e.value=A_(e.value)),e.precision=this.precision}deserialize(e){super.deserialize(e),this.nodeType=e.nodeType,this.value=Array.isArray(e.value)?Um(e.valueType,...e.value):e.value,this.precision=e.precision||null,this.value&&this.value.fromArray&&(this.value=this.value.fromArray(e.value))}generate(){console.warn("Abstract function.")}}const Yd=/float|u?int/;class ci extends cu{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 Yd.test(s)&&Yd.test(t)?e.generateConst(t,this.value):e.format(this.generateConst(e),s,t)}}class yb extends ae{static get type(){return"MemberNode"}constructor(e,t){super(),this.node=e,this.property=t,this.isMemberNode=!0}getNodeType(e){return this.node.getMemberType(e,this.property)}generate(e){return this.node.build(e)+"."+this.property}}let lr=null;const Wn=new Map;function O(a,e){if(Wn.has(a)){console.warn(`THREE.TSL: Redefinition of method chaining '${a}'.`);return}if(typeof e!="function")throw new Error(`THREE.TSL: Node element ${a} is not a function`);Wn.set(a,e)}const qm=a=>a.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"),Xd=a=>qm(a).split("").sort().join(""),Ym={setup(a,e){const t=e.shift();return a(hl(t),...e)},get(a,e,t){if(typeof e=="string"&&a[e]===void 0){if(a.isStackNode!==!0&&e==="assign")return(...s)=>(lr.assign(t,...s),t);if(Wn.has(e)){const s=Wn.get(e);return a.isStackNode?(...i)=>t.add(s(...i)):(...i)=>s(t,...i)}else{if(e==="self")return a;if(e.endsWith("Assign")&&Wn.has(e.slice(0,e.length-6))){const s=Wn.get(e.slice(0,e.length-6));return a.isStackNode?(...i)=>t.assign(i[0],s(...i)):(...i)=>t.assign(s(t,...i))}else{if(/^[xyzwrgbastpq]{1,4}$/.test(e)===!0)return e=qm(e),k(new qd(t,e));if(/^set[XYZWRGBASTPQ]{1,4}$/.test(e)===!0)return e=Xd(e.slice(3).toLowerCase()),s=>k(new mb(a,e,k(s)));if(/^flip[XYZWRGBASTPQ]{1,4}$/.test(e)===!0)return e=Xd(e.slice(4).toLowerCase()),()=>k(new gb(k(a),e));if(e==="width"||e==="height"||e==="depth")return e==="width"?e="x":e==="height"?e="y":e==="depth"&&(e="z"),k(new qd(a,e));if(/^\d+$/.test(e)===!0)return k(new Sa(t,new ci(Number(e),"uint")));if(/^get$/.test(e)===!0)return s=>k(new yb(t,s))}}}return Reflect.get(a,e,t)},set(a,e,t,s){return typeof e=="string"&&a[e]===void 0&&(/^[xyzwrgbastpq]{1,4}$/.test(e)===!0||e==="width"||e==="height"||e==="depth"||/^\d+$/.test(e)===!0)?(s[e].assign(t),!0):Reflect.set(a,e,t,s)}},$l=new WeakMap,Zd=new WeakMap,xb=function(a,e=null){const t=Xo(a);if(t==="node"){let s=$l.get(a);return s===void 0&&(s=new Proxy(a,Ym),$l.set(a,s),$l.set(s,s)),s}else{if(e===null&&(t==="float"||t==="boolean")||t&&t!=="shader"&&t!=="string")return k(Rh(a,e));if(t==="shader")return L(a)}return a},_b=function(a,e=null){for(const t in a)a[t]=k(a[t],e);return a},bb=function(a,e=null){const t=a.length;for(let s=0;s<t;s++)a[s]=k(a[s],e);return a},Tb=function(a,e=null,t=null,s=null){const i=h=>k(s!==null?Object.assign(h,s):h);let n,r=e,o,l;function c(h){let u;return r?u=/[a-z]/i.test(r)?r+"()":r:u=a.type,o!==void 0&&h.length<o?(console.error(`THREE.TSL: "${u}" parameter length is less than minimum required.`),h.concat(new Array(o-h.length).fill(0))):l!==void 0&&h.length>l?(console.error(`THREE.TSL: "${u}" parameter length exceeds limit.`),h.slice(0,l)):h}return e===null?n=(...h)=>i(new a(...Kn(c(h)))):t!==null?(t=k(t),n=(...h)=>i(new a(e,...Kn(c(h)),t))):n=(...h)=>i(new a(e,...Kn(c(h)))),n.setParameterLength=(...h)=>(h.length===1?o=l=h[0]:h.length===2&&([o,l]=h),n),n.setName=h=>(r=h,n),n},Sb=function(a,...e){return k(new a(...Kn(e)))};class vb extends ae{constructor(e,t){super(),this.shaderNode=e,this.inputNodes=t,this.isShaderCallNodeInternal=!0}getNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}getMemberType(e,t){return this.getOutputNode(e).getMemberType(e,t)}call(e){const{shaderNode:t,inputNodes:s}=this,i=e.getNodeProperties(t),n=t.namespace&&t.namespace===e.namespace?e.getNamespace("once"):"once";if(i[n])return i[n];let r=null;if(t.layout){let o=Zd.get(e.constructor);o===void 0&&(o=new WeakMap,Zd.set(e.constructor,o));let l=o.get(t);l===void 0&&(l=k(e.buildFunctionNode(t)),o.set(t,l)),e.addInclude(l),r=k(l.call(s))}else{const o=t.jsFunc,l=s!==null||o.length>1?o(s||[],e):o(e);r=k(l)}return t.once&&(i[n]=r),r}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}getOutputNode(e){const t=e.getNodeProperties(this),s=e.getOutputNamespace();return t[s]=t[s]||this.setupOutput(e),t[s]}build(e,t=null){let s=null;const i=e.getBuildStage(),n=e.getNodeProperties(this),r=e.getOutputNamespace(),o=this.getOutputNode(e);if(i==="setup"){const l=e.getNamespace("initialized");n[l]!==!0&&(n[l]=!0,n[r]=this.getOutputNode(e),n[r].build(e)),s=n[r]}else i==="analyze"?o.build(e,t):i==="generate"&&(s=o.build(e,t)||"");return s}}class wb extends ae{constructor(e,t){super(t),this.jsFunc=e,this.layout=null,this.global=!0,this.once=!1,this.namespace=null}setLayout(e){return this.layout=e,this}call(e=null){return hl(e),k(new vb(this,e))}setup(){return this.call()}}const Eb=[!1,!0],Mb=[0,1,2,3],Cb=[-1,-2],Xm=[.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],hu=new Map;for(const a of Eb)hu.set(a,new ci(a));const uu=new Map;for(const a of Mb)uu.set(a,new ci(a,"uint"));const du=new Map([...uu].map(a=>new ci(a.value,"int")));for(const a of Cb)du.set(a,new ci(a,"int"));const ll=new Map([...du].map(a=>new ci(a.value)));for(const a of Xm)ll.set(a,new ci(a));for(const a of Xm)ll.set(-a,new ci(-a));const cl={bool:hu,uint:uu,ints:du,float:ll},Qd=new Map([...hu,...ll]),Rh=(a,e)=>Qd.has(a)?Qd.get(a):a.isNode===!0?a:new ci(a,e),Ab=a=>{try{return a.getNodeType()}catch{return}},it=function(a,e=null){return(...t)=>{if((t.length===0||!["bool","float","int","uint"].includes(a)&&t.every(i=>typeof i!="object"))&&(t=[Um(a,...t)]),t.length===1&&e!==null&&e.has(t[0]))return k(e.get(t[0]));if(t.length===1){const i=Rh(t[0],a);return Ab(i)===a?k(i):k(new jm(i,a))}const s=t.map(i=>Rh(i));return k(new pb(s,a))}},Kd=a=>typeof a=="object"&&a!==null?a.value:a,Rb=a=>a!=null?a.nodeType||a.convertTo||(typeof a=="string"?a:null):null;function Xr(a,e){return new Proxy(new wb(a,e),Ym)}const k=(a,e=null)=>xb(a,e),hl=(a,e=null)=>new _b(a,e),Kn=(a,e=null)=>new bb(a,e),U=(...a)=>new Tb(...a),V=(...a)=>new Sb(...a);let Nb=0;const L=(a,e=null)=>{let t=null;e!==null&&(typeof e=="object"?t=e.return:(typeof e=="string"?t=e:console.error("THREE.TSL: Invalid layout type."),e=null));const s=new Xr(a,t),i=(...n)=>{let r;hl(n),n[0]&&(n[0].isNode||Object.getPrototypeOf(n[0])!==Object.prototype)?r=[...n]:r=n[0];const l=s.call(r);return t==="void"&&l.toStack(),l};if(i.shaderNode=s,i.id=s.id,i.getNodeType=(...n)=>s.getNodeType(...n),i.getCacheKey=(...n)=>s.getCacheKey(...n),i.setLayout=n=>(s.setLayout(n),i),i.once=(n=null)=>(s.once=!0,s.namespace=n,i),e!==null){if(typeof e.inputs!="object"){const n={name:"fn"+Nb++,type:t,inputs:[]};for(const r in e)r!=="return"&&n.inputs.push({name:r,type:e[r]});e=n}i.setLayout(e)}return i},Zo=a=>{lr=a},Zm=()=>lr,Xe=(...a)=>lr.If(...a);function Qm(a){return lr&&lr.add(a),a}O("toStack",Qm);const Pb=new it("color"),B=new it("float",cl.float),Ue=new it("int",cl.ints),Fb=new it("uint",cl.uint),pu=new it("bool",cl.bool),H=new it("vec2"),qs=new it("ivec2"),Db=new it("uvec2"),Ob=new it("bvec2"),I=new it("vec3"),Bb=new it("ivec3"),Ib=new it("uvec3"),Lb=new it("bvec3"),re=new it("vec4"),Ub=new it("ivec4"),kb=new it("uvec4"),zb=new it("bvec4"),fu=new it("mat2"),Pt=new it("mat3"),Jn=new it("mat4");O("toColor",Pb);O("toFloat",B);O("toInt",Ue);O("toUint",Fb);O("toBool",pu);O("toVec2",H);O("toIVec2",qs);O("toUVec2",Db);O("toBVec2",Ob);O("toVec3",I);O("toIVec3",Bb);O("toUVec3",Ib);O("toBVec3",Lb);O("toVec4",re);O("toIVec4",Ub);O("toUVec4",kb);O("toBVec4",zb);O("toMat2",fu);O("toMat3",Pt);O("toMat4",Jn);const Gb=U(Sa).setParameterLength(2),Vb=(a,e)=>k(new jm(k(a),e));O("element",Gb);O("convert",Vb);O("append",a=>(console.warn("THREE.TSL: .append() has been renamed to .toStack()."),Qm(a)));class Hb extends st{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 fr.join("").slice(0,s)!==t.components}return!1}setup(e){const{targetNode:t,sourceNode:s}=this,i=e.getNodeProperties(this);i.sourceNode=s,i.targetNode=t.context({assign:!0})}generate(e,t){const{targetNode:s,sourceNode:i}=e.getNodeProperties(this),n=this.needsSplitAssign(e),r=s.getNodeType(e),o=s.build(e),l=i.build(e,r),c=i.getNodeType(e),h=e.getDataFromNode(this);let u;if(h.initialized===!0)t!=="void"&&(u=o);else if(n){const d=e.getVarFromNode(this,null,r),p=e.getPropertyName(d);e.addLineFlowCode(`${p} = ${l}`,this);const f=s.node,y=f.node.context({assign:!0}).build(e);for(let g=0;g<f.components.length;g++){const _=f.components[g];e.addLineFlowCode(`${y}.${_} = ${p}[ ${g} ]`,this)}t!=="void"&&(u=o)}else u=`${o} = ${l}`,(t==="void"||c==="void")&&(e.addLineFlowCode(u,this),t!=="void"&&(u=o));return h.initialized=!0,e.format(u,r,t)}}const Wb=U(Hb).setParameterLength(2);O("assign",Wb);class Jd extends st{static get type(){return"ArrayNode"}constructor(e,t,s=null){super(e),this.count=t,this.values=s,this.isArrayNode=!0}getNodeType(e){return this.nodeType===null&&(this.nodeType=this.values[0].getNodeType(e)),this.nodeType}getElementType(e){return this.getNodeType(e)}generate(e){const t=this.getNodeType(e);return e.generateArray(t,this.count,this.values)}}const $b=(...a)=>{let e;if(a.length===1){const t=a[0];e=new Jd(null,t.length,t)}else{const t=a[0],s=a[1];e=new Jd(t,s)}return k(e)};O("toArray",(a,e)=>$b(Array(e).fill(a)));class Km extends ae{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 jb=a=>new Km(a),mu=(a,e=0)=>new Km(a,!0,e),qb=mu("frame"),K=mu("render"),Jm=jb("object");class va extends cu{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=Jm}label(e){return this.name=e,this}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){const s=this.getSelf();return e=e.bind(s),super.onUpdate(i=>{const n=e(i,s);n!==void 0&&(this.value=n)},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 r=n.getInputType(e),o=e.getUniformFromNode(n,r,e.shaderStage,this.name||e.context.label),l=e.getPropertyName(o);return e.context.label!==void 0&&delete e.context.label,e.format(l,s,t)}}const J=(a,e)=>{const t=Rb(e||a),s=a&&a.isNode===!0?a.node&&a.node.value||a.value:a;return k(new va(s,t))};class Ae extends ae{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}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 eg=(a,e)=>k(new Ae(a,e)),Qo=(a,e)=>k(new Ae(a,e,!0)),Te=V(Ae,"vec4","DiffuseColor"),ep=V(Ae,"vec3","EmissiveColor"),Xs=V(Ae,"float","Roughness"),Ko=V(Ae,"float","Metalness"),Nh=V(Ae,"float","Clearcoat"),Jo=V(Ae,"float","ClearcoatRoughness"),$n=V(Ae,"vec3","Sheen"),gu=V(Ae,"float","SheenRoughness"),yu=V(Ae,"float","Iridescence"),tg=V(Ae,"float","IridescenceIOR"),sg=V(Ae,"float","IridescenceThickness"),Ph=V(Ae,"float","AlphaT"),Ji=V(Ae,"float","Anisotropy"),Ao=V(Ae,"vec3","AnisotropyT"),er=V(Ae,"vec3","AnisotropyB"),qt=V(Ae,"color","SpecularColor"),el=V(Ae,"float","SpecularF90"),Fh=V(Ae,"float","Shininess"),oa=V(Ae,"vec4","Output"),jl=V(Ae,"float","dashSize"),tp=V(Ae,"float","gapSize"),Ro=V(Ae,"float","IOR"),Dh=V(Ae,"float","Transmission"),ig=V(Ae,"float","Thickness"),ng=V(Ae,"float","AttenuationDistance"),rg=V(Ae,"color","AttenuationColor"),ag=V(Ae,"float","Dispersion");class Yb extends st{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)}generate(e){const t=[],s=this.functionNode,i=s.getInputs(e),n=this.parameters,r=(l,c)=>{const h=c.type,u=h==="pointer";let d;return u?d="&"+l.build(e):d=l.build(e,h),d};if(Array.isArray(n)){if(n.length>i.length)console.error("THREE.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(console.error("THREE.TSL: The number of provided parameters is less than the expected number of inputs in 'Fn()'.");n.length<i.length;)n.push(B(0));for(let l=0;l<n.length;l++)t.push(r(n[l],i[l]))}else for(const l of i){const c=n[l.name];c!==void 0?t.push(r(c,l)):(console.error(`THREE.TSL: Input '${l.name}' not found in 'Fn()'.`),t.push(r(B(0),l)))}return`${s.build(e,"property")}( ${t.join(", ")} )`}}const Xb=(a,...e)=>(e=e.length>1||e[0]&&e[0].isNode===!0?Kn(e):hl(e[0]),k(new Yb(k(a),e)));O("call",Xb);const Zb={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class He extends st{static get type(){return"OperatorNode"}constructor(e,t,s,...i){if(super(),i.length>0){let n=new He(e,t,s);for(let r=0;r<i.length-1;r++)n=new He(e,n,i[r]);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(Zb[this.op],t)}getNodeType(e){const t=this.op,s=this.aNode,i=this.bNode,n=s.getNodeType(e),r=i?i.getNodeType(e):null;if(n==="void"||r==="void")return"void";if(t==="%")return n;if(t==="~"||t==="&"||t==="|"||t==="^"||t===">>"||t==="<<")return e.getIntegerType(n);if(t==="!"||t==="&&"||t==="||"||t==="^^")return"bool";if(t==="=="||t==="!="||t==="<"||t===">"||t==="<="||t===">="){const o=Math.max(e.getTypeLength(n),e.getTypeLength(r));return o>1?`bvec${o}`:"bool"}else{if(e.isMatrix(n)){if(r==="float")return n;if(e.isVector(r))return e.getVectorFromMatrix(n);if(e.isMatrix(r))return n}else if(e.isMatrix(r)){if(n==="float")return r;if(e.isVector(n))return e.getVectorFromMatrix(r)}return e.getTypeLength(r)>e.getTypeLength(n)?r:n}}generate(e,t){const s=this.op,{aNode:i,bNode:n}=this,r=this.getNodeType(e);let o=null,l=null;r!=="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=r,l=e.changeComponentType(l,"uint")):s==="%"?(o=r,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=r):e.isMatrix(l)?o==="float"?o="float":e.isVector(o)?o=e.getVectorFromMatrix(l):o=l=r:o=l=r):o=l=r;const c=i.build(e,o),h=n?n.build(e,l):null,u=e.getFunctionOperator(s);if(t!=="void"){const d=e.renderer.coordinateSystem===Lt;if(s==="=="||s==="!="||s==="<"||s===">"||s==="<="||s===">=")return d?e.isVector(o)?e.format(`${this.getOperatorMethod(e,t)}( ${c}, ${h} )`,r,t):e.format(`( ${c} ${s} ${h} )`,r,t):e.format(`( ${c} ${s} ${h} )`,r,t);if(s==="%")return e.isInteger(l)?e.format(`( ${c} % ${h} )`,r,t):e.format(`${this.getOperatorMethod(e,r)}( ${c}, ${h} )`,r,t);if(s==="!"||s==="~")return e.format(`(${s}${c})`,o,t);if(u)return e.format(`${u}( ${c}, ${h} )`,r,t);if(e.isMatrix(o)&&l==="float")return e.format(`( ${h} ${s} ${c} )`,r,t);if(o==="float"&&e.isMatrix(l))return e.format(`${c} ${s} ${h}`,r,t);{let p=`( ${c} ${s} ${h} )`;return!d&&r==="bool"&&e.isVector(o)&&e.isVector(l)&&(p=`all${p}`),e.format(p,r,t)}}else if(o!=="void")return u?e.format(`${u}( ${c}, ${h} )`,r,t):e.isMatrix(o)&&l==="float"?e.format(`${h} ${s} ${c}`,r,t):e.format(`${c} ${s} ${h}`,r,t)}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const Ft=U(He,"+").setParameterLength(2,1/0).setName("add"),Ct=U(He,"-").setParameterLength(2,1/0).setName("sub"),pe=U(He,"*").setParameterLength(2,1/0).setName("mul"),Us=U(He,"/").setParameterLength(2,1/0).setName("div"),ul=U(He,"%").setParameterLength(2).setName("mod"),og=U(He,"==").setParameterLength(2).setName("equal"),Qb=U(He,"!=").setParameterLength(2).setName("notEqual"),Kb=U(He,"<").setParameterLength(2).setName("lessThan"),Jb=U(He,">").setParameterLength(2).setName("greaterThan"),eT=U(He,"<=").setParameterLength(2).setName("lessThanEqual"),tT=U(He,">=").setParameterLength(2).setName("greaterThanEqual"),sT=U(He,"&&").setParameterLength(2,1/0).setName("and"),iT=U(He,"||").setParameterLength(2,1/0).setName("or"),nT=U(He,"!").setParameterLength(1).setName("not"),rT=U(He,"^^").setParameterLength(2).setName("xor"),aT=U(He,"&").setParameterLength(2).setName("bitAnd"),oT=U(He,"~").setParameterLength(2).setName("bitNot"),lT=U(He,"|").setParameterLength(2).setName("bitOr"),cT=U(He,"^").setParameterLength(2).setName("bitXor"),hT=U(He,"<<").setParameterLength(2).setName("shiftLeft"),uT=U(He,">>").setParameterLength(2).setName("shiftRight"),dT=L(([a])=>(a.addAssign(1),a)),pT=L(([a])=>(a.subAssign(1),a)),fT=L(([a])=>{const e=Ue(a).toConst();return a.addAssign(1),e}),mT=L(([a])=>{const e=Ue(a).toConst();return a.subAssign(1),e});O("add",Ft);O("sub",Ct);O("mul",pe);O("div",Us);O("mod",ul);O("equal",og);O("notEqual",Qb);O("lessThan",Kb);O("greaterThan",Jb);O("lessThanEqual",eT);O("greaterThanEqual",tT);O("and",sT);O("or",iT);O("not",nT);O("xor",rT);O("bitAnd",aT);O("bitNot",oT);O("bitOr",lT);O("bitXor",cT);O("shiftLeft",hT);O("shiftRight",uT);O("incrementBefore",dT);O("decrementBefore",pT);O("increment",fT);O("decrement",mT);const gT=(a,e)=>(console.warn('THREE.TSL: "remainder()" is deprecated. Use "mod( int( ... ) )" instead.'),ul(a,e)),yT=(a,e)=>(console.warn('THREE.TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.'),ul(Ue(a),Ue(e)));O("remainder",gT);O("modInt",yT);class A extends st{static get type(){return"MathNode"}constructor(e,t,s=null,i=null){if(super(),(e===A.MAX||e===A.MIN)&&arguments.length>3){let n=new A(e,t,s);for(let r=2;r<arguments.length-1;r++)n=new A(e,n,arguments[r]);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),r=e.isMatrix(s)?0:e.getTypeLength(s),o=e.isMatrix(i)?0:e.getTypeLength(i);return n>r&&n>o?t:r>o?s:o>n?i:t}getNodeType(e){const t=this.method;return t===A.LENGTH||t===A.DISTANCE||t===A.DOT?"float":t===A.CROSS?"vec3":t===A.ALL||t===A.ANY?"bool":t===A.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===A.ONE_MINUS)n=Ct(1,t);else if(i===A.RECIPROCAL)n=Us(1,t);else if(i===A.DIFFERENCE)n=is(Ct(t,s));else if(i===A.TRANSFORM_DIRECTION){let r=t,o=s;e.isMatrix(r.getNodeType(e))?o=re(I(o),0):r=re(I(r),0);const l=pe(r,o).xyz;n=xa(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),r=this.getInputType(e),o=this.aNode,l=this.bNode,c=this.cNode,h=e.renderer.coordinateSystem;if(i===A.NEGATE)return e.format("( - "+o.build(e,r)+" )",n,t);{const u=[];return i===A.CROSS?u.push(o.build(e,n),l.build(e,n)):h===Lt&&i===A.STEP?u.push(o.build(e,e.getTypeLength(o.getNodeType(e))===1?"float":r),l.build(e,r)):h===Lt&&(i===A.MIN||i===A.MAX)?u.push(o.build(e,r),l.build(e,e.getTypeLength(l.getNodeType(e))===1?"float":r)):i===A.REFRACT?u.push(o.build(e,r),l.build(e,r),c.build(e,"float")):i===A.MIX?u.push(o.build(e,r),l.build(e,r),c.build(e,e.getTypeLength(c.getNodeType(e))===1?"float":r)):(h===Fi&&i===A.ATAN&&l!==null&&(i="atan2"),e.shaderStage!=="fragment"&&(i===A.DFDX||i===A.DFDY)&&(console.warn(`THREE.TSL: '${i}' is not supported in the ${e.shaderStage} stage.`),i="/*"+i+"*/"),u.push(o.build(e,r)),l!==null&&u.push(l.build(e,r)),c!==null&&u.push(c.build(e,r))),e.format(`${e.getMethod(i,n)}( ${u.join(", ")} )`,n,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}A.ALL="all";A.ANY="any";A.RADIANS="radians";A.DEGREES="degrees";A.EXP="exp";A.EXP2="exp2";A.LOG="log";A.LOG2="log2";A.SQRT="sqrt";A.INVERSE_SQRT="inversesqrt";A.FLOOR="floor";A.CEIL="ceil";A.NORMALIZE="normalize";A.FRACT="fract";A.SIN="sin";A.COS="cos";A.TAN="tan";A.ASIN="asin";A.ACOS="acos";A.ATAN="atan";A.ABS="abs";A.SIGN="sign";A.LENGTH="length";A.NEGATE="negate";A.ONE_MINUS="oneMinus";A.DFDX="dFdx";A.DFDY="dFdy";A.ROUND="round";A.RECIPROCAL="reciprocal";A.TRUNC="trunc";A.FWIDTH="fwidth";A.TRANSPOSE="transpose";A.BITCAST="bitcast";A.EQUALS="equals";A.MIN="min";A.MAX="max";A.STEP="step";A.REFLECT="reflect";A.DISTANCE="distance";A.DIFFERENCE="difference";A.DOT="dot";A.CROSS="cross";A.POW="pow";A.TRANSFORM_DIRECTION="transformDirection";A.MIX="mix";A.CLAMP="clamp";A.REFRACT="refract";A.SMOOTHSTEP="smoothstep";A.FACEFORWARD="faceforward";const xT=B(1e-6),_T=B(Math.PI),bT=U(A,A.ALL).setParameterLength(1),TT=U(A,A.ANY).setParameterLength(1),ST=U(A,A.RADIANS).setParameterLength(1),vT=U(A,A.DEGREES).setParameterLength(1),lg=U(A,A.EXP).setParameterLength(1),ya=U(A,A.EXP2).setParameterLength(1),cg=U(A,A.LOG).setParameterLength(1),ii=U(A,A.LOG2).setParameterLength(1),xu=U(A,A.SQRT).setParameterLength(1),wT=U(A,A.INVERSE_SQRT).setParameterLength(1),cn=U(A,A.FLOOR).setParameterLength(1),_u=U(A,A.CEIL).setParameterLength(1),xa=U(A,A.NORMALIZE).setParameterLength(1),Ii=U(A,A.FRACT).setParameterLength(1),_s=U(A,A.SIN).setParameterLength(1),wi=U(A,A.COS).setParameterLength(1),ET=U(A,A.TAN).setParameterLength(1),MT=U(A,A.ASIN).setParameterLength(1),hg=U(A,A.ACOS).setParameterLength(1),ug=U(A,A.ATAN).setParameterLength(1,2),is=U(A,A.ABS).setParameterLength(1),tl=U(A,A.SIGN).setParameterLength(1),ni=U(A,A.LENGTH).setParameterLength(1),CT=U(A,A.NEGATE).setParameterLength(1),AT=U(A,A.ONE_MINUS).setParameterLength(1),dg=U(A,A.DFDX).setParameterLength(1),pg=U(A,A.DFDY).setParameterLength(1),RT=U(A,A.ROUND).setParameterLength(1),NT=U(A,A.RECIPROCAL).setParameterLength(1),PT=U(A,A.TRUNC).setParameterLength(1),FT=U(A,A.FWIDTH).setParameterLength(1),DT=U(A,A.TRANSPOSE).setParameterLength(1),OT=(a,e)=>(console.warn('THREE.TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"'),og(a,e)),cr=U(A,A.MIN).setParameterLength(2,1/0),St=U(A,A.MAX).setParameterLength(2,1/0),fg=U(A,A.STEP).setParameterLength(2),BT=U(A,A.REFLECT).setParameterLength(2),IT=U(A,A.DISTANCE).setParameterLength(2),LT=U(A,A.DIFFERENCE).setParameterLength(2),bu=U(A,A.DOT).setParameterLength(2),mg=U(A,A.CROSS).setParameterLength(2),dl=U(A,A.POW).setParameterLength(2),gg=U(A,A.POW,2).setParameterLength(1),UT=U(A,A.POW,3).setParameterLength(1),kT=U(A,A.POW,4).setParameterLength(1),zT=U(A,A.TRANSFORM_DIRECTION).setParameterLength(2),GT=a=>pe(tl(a),dl(is(a),1/3)),yg=a=>bu(a,a),ze=U(A,A.MIX).setParameterLength(3),oi=(a,e=0,t=1)=>k(new A(A.CLAMP,k(a),k(e),k(t))),xg=a=>oi(a),_g=U(A,A.REFRACT).setParameterLength(3),Di=U(A,A.SMOOTHSTEP).setParameterLength(3),VT=U(A,A.FACEFORWARD).setParameterLength(3),HT=L(([a])=>{const s=43758.5453,i=bu(a.xy,H(12.9898,78.233)),n=ul(i,_T);return Ii(_s(n).mul(s))}),WT=(a,e,t)=>ze(e,t,a),$T=(a,e,t)=>Di(e,t,a),jT=(a,e)=>(console.warn('THREE.TSL: "atan2" is overloaded. Use "atan" instead.'),ug(a,e));O("all",bT);O("any",TT);O("equals",OT);O("radians",ST);O("degrees",vT);O("exp",lg);O("exp2",ya);O("log",cg);O("log2",ii);O("sqrt",xu);O("inverseSqrt",wT);O("floor",cn);O("ceil",_u);O("normalize",xa);O("fract",Ii);O("sin",_s);O("cos",wi);O("tan",ET);O("asin",MT);O("acos",hg);O("atan",ug);O("abs",is);O("sign",tl);O("length",ni);O("lengthSq",yg);O("negate",CT);O("oneMinus",AT);O("dFdx",dg);O("dFdy",pg);O("round",RT);O("reciprocal",NT);O("trunc",PT);O("fwidth",FT);O("atan2",jT);O("min",cr);O("max",St);O("step",fg);O("reflect",BT);O("distance",IT);O("dot",bu);O("cross",mg);O("pow",dl);O("pow2",gg);O("pow3",UT);O("pow4",kT);O("transformDirection",zT);O("mix",WT);O("clamp",oi);O("refract",_g);O("smoothstep",$T);O("faceForward",VT);O("difference",LT);O("saturate",xg);O("cbrt",GT);O("transpose",DT);O("rand",HT);class qT extends ae{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 this.setup(e),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.cache(),s=this.ifNode.cache(),i=this.elseNode?this.elseNode.cache():null,n=e.context.nodeBlock;e.getDataFromNode(s).parentNodeBlock=n,i!==null&&(e.getDataFromNode(i).parentNodeBlock=n);const r=e.getNodeProperties(this);r.condNode=t,r.ifNode=s.context({nodeBlock:s}),r.elseNode=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:r,elseNode:o}=e.getNodeProperties(this),l=e.currentFunctionNode,c=t!=="void",h=c?eg(s).build(e):"";i.nodeProperty=h;const u=n.build(e,"bool");e.addFlowCode(`
|
51
|
+
${e.tab}if ( ${u} ) {
|
52
|
+
|
53
|
+
`).addFlowTab();let d=r.build(e,s);if(d&&(c?d=h+" = "+d+";":(d="return "+d+";",l===null&&(console.warn("THREE.TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values."),d="// "+d))),e.removeFlowTab().addFlowCode(e.tab+" "+d+`
|
54
|
+
|
55
|
+
`+e.tab+"}"),o!==null){e.addFlowCode(` else {
|
56
|
+
|
57
|
+
`).addFlowTab();let p=o.build(e,s);p&&(c?p=h+" = "+p+";":(p="return "+p+";",l===null&&(console.warn("THREE.TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values."),p="// "+p))),e.removeFlowTab().addFlowCode(e.tab+" "+p+`
|
58
|
+
|
59
|
+
`+e.tab+`}
|
60
|
+
|
61
|
+
`)}else e.addFlowCode(`
|
62
|
+
|
63
|
+
`);return e.format(h,s,t)}}const bt=U(qT).setParameterLength(2,3);O("select",bt);const YT=(...a)=>(console.warn("THREE.TSL: cond() has been renamed to select()."),bt(...a));O("cond",YT);class bg extends ae{static get type(){return"ContextNode"}constructor(e,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}getNodeType(e){return this.node.getNodeType(e)}analyze(e){const t=e.getContext();e.setContext({...e.context,...this.value}),this.node.build(e),e.setContext(t)}setup(e){const t=e.getContext();e.setContext({...e.context,...this.value}),this.node.build(e),e.setContext(t)}generate(e,t){const s=e.getContext();e.setContext({...e.context,...this.value});const i=this.node.build(e,t);return e.setContext(s),i}}const Tu=U(bg).setParameterLength(1,2),XT=(a,e)=>Tu(a,{label:e});O("context",Tu);O("label",XT);class No extends ae{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}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}getNodeType(e){return this.node.getNodeType(e)}generate(e){const{node:t,name:s,readOnly:i}=this,{renderer:n}=e,r=n.backend.isWebGPUBackend===!0;let o=!1,l=!1;i&&(o=e.isDeterministic(t),l=r?i:o);const c=e.getVectorType(this.getNodeType(e)),h=t.build(e,c),u=e.getVarFromNode(this,s,c,void 0,l),d=e.getPropertyName(u);let p=d;if(l)if(r)p=o?`const ${d}`:`let ${d}`;else{const f=e.getArrayCount(t);p=`const ${e.getVar(u.type,d,f)}`}return e.addLineFlowCode(`${p} = ${h}`,this),d}}const Su=U(No),ZT=(a,e=null)=>Su(a,e).toStack(),QT=(a,e=null)=>Su(a,e,!0).toStack();O("toVar",ZT);O("toConst",QT);const KT=a=>(console.warn('TSL: "temp( node )" is deprecated. Use "Var( node )" or "node.toVar()" instead.'),Su(a));O("temp",KT);class JT extends ae{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=e,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),r=this.interpolationType,o=this.interpolationSampling;t.varying=s=e.getVaryingFromNode(this,i,n,r,o),t.node=this.node}return s.needsInterpolation||(s.needsInterpolation=e.shaderStage==="fragment"),s}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(La.VERTEX,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(La.VERTEX,this.node)}generate(e){const t=e.getNodeProperties(this),s=this.setupVarying(e);if(t.propertyName===void 0){const i=this.getNodeType(e),n=e.getPropertyName(s,La.VERTEX);e.flowNodeFromShaderStage(La.VERTEX,this.node,i,n),t.propertyName=n}return e.getPropertyName(s)}}const ws=U(JT).setParameterLength(1,2),eS=a=>ws(a);O("toVarying",ws);O("toVertexStage",eS);O("varying",(...a)=>(console.warn("THREE.TSL: .varying() has been renamed to .toVarying()."),ws(...a)));O("vertexStage",(...a)=>(console.warn("THREE.TSL: .vertexStage() has been renamed to .toVertexStage()."),ws(...a)));const tS=L(([a])=>{const e=a.mul(.9478672986).add(.0521327014).pow(2.4),t=a.mul(.0773993808),s=a.lessThanEqual(.04045);return ze(e,t,s)}).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),sS=L(([a])=>{const e=a.pow(.41666).mul(1.055).sub(.055),t=a.mul(12.92),s=a.lessThanEqual(.0031308);return ze(e,t,s)}).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),vu="WorkingColorSpace",iS="OutputColorSpace";class Tg extends st{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===vu?Le.workingColorSpace:t===iS?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 Le.enabled===!1||s===i||!s||!i||(Le.getTransfer(s)===se&&(n=re(tS(n.rgb),n.a)),Le.getPrimaries(s)!==Le.getPrimaries(i)&&(n=re(Pt(Le._getMatrix(new Vt,s,i)).mul(n.rgb),n.a)),Le.getTransfer(i)===se&&(n=re(sS(n.rgb),n.a))),n}}const nS=(a,e)=>k(new Tg(k(a),vu,e)),wu=(a,e)=>k(new Tg(k(a),e,vu));O("workingToColorSpace",nS);O("colorSpaceToWorking",wu);let rS=class extends Sa{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 Sg extends ae{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=he.OBJECT}setGroup(e){return this.group=e,this}element(e){return k(new rS(this,k(e)))}setNodeType(e){const t=J(null,e).getSelf();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 aS=(a,e,t)=>k(new Sg(a,e,t));class oS extends Sg{static get type(){return"RendererReferenceNode"}constructor(e,t,s=null){super(e,t,s),this.renderer=s,this.setGroup(K)}updateReference(e){return this.reference=this.renderer!==null?this.renderer:e.renderer,this.reference}}const lS=(a,e,t=null)=>k(new oS(a,e,t));class cS extends st{static get type(){return"ToneMappingNode"}constructor(e,t=uS,s=null){super("vec3"),this.toneMapping=e,this.exposureNode=t,this.colorNode=s}customCacheKey(){return qo(this.toneMapping)}setup(e){const t=this.colorNode||e.context.color,s=this.toneMapping;if(s===Xn)return t;let i=null;const n=e.renderer.library.getToneMappingFunction(s);return n!==null?i=re(n(t.rgb,this.exposureNode),t.a):(console.error("ToneMappingNode: Unsupported Tone Mapping configuration.",s),i=t),i}}const hS=(a,e,t)=>k(new cS(a,k(e),k(t))),uS=lS("toneMappingExposure","float");O("toneMapping",(a,e,t)=>hS(e,t,a));const wt=new N;class Eu{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=At(s,this.array)),s}setComponent(e,t,s){return this.normalized&&(s=oe(s,this.array)),this.data.array[e*this.data.stride+this.offset+t]=s,this}setX(e,t){return this.normalized&&(t=oe(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=oe(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=oe(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=oe(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=At(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=At(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=At(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=At(t,this.array)),t}setXY(e,t,s){return e=e*this.data.stride+this.offset,this.normalized&&(t=oe(t,this.array),s=oe(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=oe(t,this.array),s=oe(s,this.array),i=oe(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=oe(t,this.array),s=oe(s,this.array),i=oe(i,this.array),n=oe(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){console.log("THREE.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 os(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 Eu(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(e===void 0){console.log("THREE.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}}}class vg{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e!==void 0?e.length/t:0,this.usage=jo,this.updateRanges=[],this.version=0,this.uuid=Qs()}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=Qs()),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=Qs()),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}}}class dS extends cu{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=jo,this.instanced=!1,this.attribute=null,this.global=!0,e&&e.isBufferAttribute===!0&&(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=this.value,i=e.getTypeLength(t),n=this.bufferStride||i,r=this.bufferOffset,o=s.isInterleavedBuffer===!0?s:new vg(s,n),l=new Eu(o,i,r);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=ws(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}}const Mu=(a,e=null,t=0,s=0)=>k(new dS(a,e,t,s)),pS=(a,e=null,t=0,s=0)=>Mu(a,e,t,s).setUsage(Hn),sp=(a,e=null,t=0,s=0)=>Mu(a,e,t,s).setInstanced(!0),ip=(a,e=null,t=0,s=0)=>pS(a,e,t,s).setInstanced(!0);O("toAttribute",a=>Mu(a.value));class fS extends ae{static get type(){return"ComputeNode"}constructor(e,t,s=[64]){super("void"),this.isComputeNode=!0,this.computeNode=e,this.count=t,this.workgroupSize=s,this.dispatchCount=0,this.version=1,this.name="",this.updateBeforeType=he.OBJECT,this.onInitFunction=null,this.updateDispatchCount()}dispose(){this.dispatchEvent({type:"dispose"})}label(e){return this.name=e,this}updateDispatchCount(){const{count:e,workgroupSize:t}=this;let s=t[0];for(let i=1;i<t.length;i++)s*=t[i];this.dispatchCount=Math.ceil(e/s)}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 mS=(a,e,t)=>k(new fS(k(a),e,t));O("compute",mS);class gS extends ae{static get type(){return"CacheNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isCacheNode=!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}}const Po=(a,e)=>k(new gS(k(a),e)),yS=(a,e)=>a.context({namespace:e});O("cache",Po);class xS extends ae{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 _S=U(xS).setParameterLength(2);O("bypass",_S);class wg extends ae{static get type(){return"RemapNode"}constructor(e,t,s,i=B(0),n=B(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:r}=this;let o=e.sub(t).div(s.sub(t));return r===!0&&(o=o.clamp()),o.mul(n.sub(i)).add(i)}}const bS=U(wg,null,null,{doClamp:!1}).setParameterLength(3,5),TS=U(wg).setParameterLength(3,5);O("remap",bS);O("remapClamp",TS);class Fo extends ae{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 hr=U(Fo).setParameterLength(1,2),SS=a=>(a?bt(a,hr("discard")):hr("discard")).toStack();O("discard",SS);class vS extends st{static get type(){return"RenderOutputNode"}constructor(e,t,s){super("vec4"),this.colorNode=e,this.toneMapping=t,this.outputColorSpace=s,this.isRenderOutputNode=!0}setup({context:e}){let t=this.colorNode||e.color;const s=(this.toneMapping!==null?this.toneMapping:e.toneMapping)||Xn,i=(this.outputColorSpace!==null?this.outputColorSpace:e.outputColorSpace)||ri;return s!==Xn&&(t=t.toneMapping(s)),i!==ri&&i!==Le.workingColorSpace&&(t=t.workingToColorSpace(i)),t}}const wS=(a,e=null,t=null)=>k(new vS(k(a),e,t));O("renderOutput",wS);class ES extends st{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),i="--- TSL debug - "+e.shaderStage+" shader ---",n="-".repeat(i.length);let r="";return r+="// #"+i+`#
|
64
|
+
`,r+=e.flow.code.replace(/^\t/mg,"")+`
|
65
|
+
`,r+="/* ... */ "+s+` /* ... */
|
66
|
+
`,r+="// #"+n+`#
|
67
|
+
`,t!==null?t(e,r):console.log(r),s}}const MS=(a,e=null)=>k(new ES(k(a),e));O("debug",MS);class Eg extends ae{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),r=e.getTypeFromAttribute(n),o=e.getAttribute(t,r);return e.shaderStage==="vertex"?e.format(o.name,r,s):ws(this).build(e,s)}else return console.warn(`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 Oi=(a,e=null)=>k(new Eg(a,e));class Ge extends ae{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===Ge.VERTEX)i=e.getVertexIndex();else if(s===Ge.INSTANCE)i=e.getInstanceIndex();else if(s===Ge.DRAW)i=e.getDrawIndex();else if(s===Ge.INVOCATION_LOCAL)i=e.getInvocationLocalIndex();else if(s===Ge.INVOCATION_SUBGROUP)i=e.getInvocationSubgroupIndex();else if(s===Ge.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=ws(this).build(e,t),n}}Ge.VERTEX="vertex";Ge.INSTANCE="instance";Ge.SUBGROUP="subgroup";Ge.INVOCATION_LOCAL="invocationLocal";Ge.INVOCATION_SUBGROUP="invocationSubgroup";Ge.DRAW="draw";const CS=V(Ge,Ge.VERTEX),Cu=V(Ge,Ge.INSTANCE);Ge.SUBGROUP;Ge.INVOCATION_SUBGROUP;Ge.INVOCATION_LOCAL;const AS=V(Ge,Ge.DRAW);class RS extends Ae{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getHash(){return this.uuid}generate(){return this.name}}class NS extends ae{static get type(){return"StackNode"}constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this._expressionNode=null,this.isStackNode=!0}getNodeType(e){return this.outputNode?this.outputNode.getNodeType(e):"void"}getMemberType(e,t){return this.outputNode?this.outputNode.getMemberType(e,t):"void"}add(e){return this.nodes.push(e),this}If(e,t){const s=new Xr(t);return this._currentCond=bt(e,s),this.add(this._currentCond)}ElseIf(e,t){const s=new Xr(t),i=bt(e,s);return this._currentCond.elseNode=i,this._currentCond=i,this}Else(e){return this._currentCond.elseNode=new Xr(e),this}Switch(e){return this._expressionNode=k(e),this}Case(...e){const t=[];if(e.length>=2)for(let o=0;o<e.length-1;o++)t.push(this._expressionNode.equal(k(e[o])));else throw new Error("TSL: Invalid parameter length. Case() requires at least two parameters.");const s=e[e.length-1],i=new Xr(s);let n=t[0];for(let o=1;o<t.length;o++)n=n.or(t[o]);const r=bt(n,i);return this._currentCond===null?(this._currentCond=r,this.add(this._currentCond)):(this._currentCond.elseNode=r,this._currentCond=r,this)}Default(e){return this.Else(e),this}build(e,...t){const s=Zm();Zo(this);const i=e.buildStage;for(const n of this.nodes)if(i==="setup")n.build(e);else if(i==="analyze")n.build(e,this);else if(i==="generate"){const r=e.getDataFromNode(n,"any").stages,o=r&&r[e.shaderStage];if(n.isVarNode&&o&&o.length===1&&o[0]&&o[0].isStackNode)continue;n.build(e,"void")}return Zo(s),this.outputNode?this.outputNode.build(e,...t):super.build(e,...t)}else(...e){return console.warn("THREE.TSL: .else() has been renamed to .Else()."),this.Else(...e)}elseif(...e){return console.warn("THREE.TSL: .elseif() has been renamed to .ElseIf()."),this.ElseIf(...e)}}const ql=U(NS).setParameterLength(0,1);class PS extends ae{static get type(){return"LoopNode"}constructor(e=[]){super(),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 r=0,o=this.params.length-1;r<o;r++){const l=this.params[r],c=l.isNode!==!0&&l.name||this.getVarName(r),h=l.isNode!==!0&&l.type||"int";s[c]=hr(c,h)}const i=e.addStack();t.returnsNode=this.params[this.params.length-1](s,e),t.stackNode=i;const n=this.params[0];return n.isNode!==!0&&typeof n.update=="function"&&(t.updateNode=L(this.params[0].update)(s)),e.removeStack(),t}getNodeType(e){const{returnsNode:t}=this.getProperties(e);return t?t.getNodeType(e):"void"}setup(e){this.getProperties(e)}generate(e){const t=this.getProperties(e),s=this.params,i=t.stackNode;for(let o=0,l=s.length-1;o<l;o++){const c=s[o];let h=!1,u=null,d=null,p=null,f=null,m=null,y=null;c.isNode?c.getNodeType(e)==="bool"?(h=!0,f="bool",d=c.build(e,f)):(f="int",p=this.getVarName(o),u="0",d=c.build(e,f),m="<"):(f=c.type||"int",p=c.name||this.getVarName(o),u=c.start,d=c.end,m=c.condition,y=c.update,typeof u=="number"?u=e.generateConst(f,u):u&&u.isNode&&(u=u.build(e,f)),typeof d=="number"?d=e.generateConst(f,d):d&&d.isNode&&(d=d.build(e,f)),u!==void 0&&d===void 0?(u=u+" - 1",d="0",m=">="):d!==void 0&&u===void 0&&(u="0",m="<"),m===void 0&&(Number(u)>Number(d)?m=">=":m="<"));let g;if(h)g=`while ( ${d} )`;else{const _={start:u,end:d},b=_.start,S=_.end;let T;const M=()=>m.includes("<")?"+=":"-=";if(y!=null)switch(typeof y){case"function":T=e.flowStagesNode(t.updateNode,"void").code.replace(/\t|;/g,"");break;case"number":T=p+" "+M()+" "+e.generateConst(f,y);break;case"string":T=p+" "+y;break;default:y.isNode?T=p+" "+M()+" "+y.build(e):(console.error("THREE.TSL: 'Loop( { update: ... } )' is not a function, string or number."),T="break /* invalid update */")}else f==="int"||f==="uint"?y=m.includes("<")?"++":"--":y=M()+" 1.",T=p+" "+y;const w=e.getVar(f,p)+" = "+b,R=p+" "+m+" "+S;g=`for ( ${w}; ${R}; ${T} )`}e.addFlowCode((o===0?`
|
68
|
+
`:"")+e.tab+g+` {
|
69
|
+
|
70
|
+
`).addFlowTab()}const n=i.build(e,"void"),r=t.returnsNode?t.returnsNode.build(e):"";e.removeFlowTab().addFlowCode(`
|
71
|
+
`+e.tab+n);for(let o=0,l=this.params.length-1;o<l;o++)e.addFlowCode((o===0?"":e.tab)+`}
|
72
|
+
|
73
|
+
`).removeFlowTab();return e.addFlowTab(),r}}const Ts=(...a)=>k(new PS(Kn(a,"int"))).toStack(),FS=()=>hr("break").toStack();class wa{constructor(e=new N(1/0,1/0,1/0),t=new N(-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(ps.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,s=e.count;t<s;t++)this.expandByPoint(ps.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=ps.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 r=0,o=n.count;r<o;r++)e.isMesh===!0?e.getVertexPosition(r,ps):ps.fromBufferAttribute(n,r),ps.applyMatrix4(e.matrixWorld),this.expandByPoint(ps);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),Ua.copy(e.boundingBox)):(s.boundingBox===null&&s.computeBoundingBox(),Ua.copy(s.boundingBox)),Ua.applyMatrix4(e.matrixWorld),this.union(Ua)}const i=e.children;for(let n=0,r=i.length;n<r;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,ps),ps.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(Er),ka.subVectors(this.max,Er),wn.subVectors(e.a,Er),En.subVectors(e.b,Er),Mn.subVectors(e.c,Er),fi.subVectors(En,wn),mi.subVectors(Mn,En),zi.subVectors(wn,Mn);let t=[0,-fi.z,fi.y,0,-mi.z,mi.y,0,-zi.z,zi.y,fi.z,0,-fi.x,mi.z,0,-mi.x,zi.z,0,-zi.x,-fi.y,fi.x,0,-mi.y,mi.x,0,-zi.y,zi.x,0];return!Yl(t,wn,En,Mn,ka)||(t=[1,0,0,0,1,0,0,0,1],!Yl(t,wn,En,Mn,ka))?!1:(za.crossVectors(fi,mi),t=[za.x,za.y,za.z],Yl(t,wn,En,Mn,ka))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,ps).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(ps).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:(Hs[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Hs[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Hs[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Hs[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Hs[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Hs[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Hs[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Hs[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Hs),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 Hs=[new N,new N,new N,new N,new N,new N,new N,new N],ps=new N,Ua=new wa,wn=new N,En=new N,Mn=new N,fi=new N,mi=new N,zi=new N,Er=new N,ka=new N,za=new N,Gi=new N;function Yl(a,e,t,s,i){for(let n=0,r=a.length-3;n<=r;n+=3){Gi.fromArray(a,n);const o=i.x*Math.abs(Gi.x)+i.y*Math.abs(Gi.y)+i.z*Math.abs(Gi.z),l=e.dot(Gi),c=t.dot(Gi),h=s.dot(Gi);if(Math.max(-Math.max(l,c,h),Math.min(l,c,h))>o)return!1}return!0}const DS=new wa,Mr=new N,Xl=new N;class pl{constructor(e=new N,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):DS.setFromPoints(e).getCenter(s);let i=0;for(let n=0,r=e.length;n<r;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;Mr.subVectors(e,this.center);const t=Mr.lengthSq();if(t>this.radius*this.radius){const s=Math.sqrt(t),i=(s-this.radius)*.5;this.center.addScaledVector(Mr,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):(Xl.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Mr.copy(e.center).add(Xl)),this.expandByPoint(Mr.copy(e.center).sub(Xl))),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}}const np=new pl;class Ne extends ae{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=he.OBJECT,this.uniformNode=new va(null)}getNodeType(){const e=this.scope;if(e===Ne.WORLD_MATRIX)return"mat4";if(e===Ne.POSITION||e===Ne.VIEW_POSITION||e===Ne.DIRECTION||e===Ne.SCALE)return"vec3";if(e===Ne.RADIUS)return"float"}update(e){const t=this.object3d,s=this.uniformNode,i=this.scope;if(i===Ne.WORLD_MATRIX)s.value=t.matrixWorld;else if(i===Ne.POSITION)s.value=s.value||new N,s.value.setFromMatrixPosition(t.matrixWorld);else if(i===Ne.SCALE)s.value=s.value||new N,s.value.setFromMatrixScale(t.matrixWorld);else if(i===Ne.DIRECTION)s.value=s.value||new N,t.getWorldDirection(s.value);else if(i===Ne.VIEW_POSITION){const n=e.camera;s.value=s.value||new N,s.value.setFromMatrixPosition(t.matrixWorld),s.value.applyMatrix4(n.matrixWorldInverse)}else if(i===Ne.RADIUS){const n=e.object.geometry;n.boundingSphere===null&&n.computeBoundingSphere(),np.copy(n.boundingSphere).applyMatrix4(t.matrixWorld),s.value=np.radius}}generate(e){const t=this.scope;return t===Ne.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===Ne.POSITION||t===Ne.VIEW_POSITION||t===Ne.DIRECTION||t===Ne.SCALE?this.uniformNode.nodeType="vec3":t===Ne.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}}Ne.WORLD_MATRIX="worldMatrix";Ne.POSITION="position";Ne.SCALE="scale";Ne.VIEW_POSITION="viewPosition";Ne.DIRECTION="direction";Ne.RADIUS="radius";const OS=U(Ne,Ne.POSITION).setParameterLength(1);class Mg extends va{static get type(){return"BufferNode"}constructor(e,t,s=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=s}getElementType(e){return this.getNodeType(e)}getInputType(){return"buffer"}}const Cg=(a,e,t)=>k(new Mg(a,e,t));class BS extends Sa{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 IS extends Mg{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=t===null?Xo(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=he.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,r=e[i];t[n]=r.r,t[n+1]=r.g,t[n+2]=r.b||0}else if(s==="mat2")for(let i=0;i<e.length;i++){const n=i*4,r=e[i];t[n]=r.elements[0],t[n+1]=r.elements[1],t[n+2]=r.elements[2],t[n+3]=r.elements[3]}else if(s==="mat3")for(let i=0;i<e.length;i++){const n=i*16,r=e[i];t[n]=r.elements[0],t[n+1]=r.elements[1],t[n+2]=r.elements[2],t[n+4]=r.elements[3],t[n+5]=r.elements[4],t[n+6]=r.elements[5],t[n+8]=r.elements[6],t[n+9]=r.elements[7],t[n+10]=r.elements[8],t[n+15]=1}else if(s==="mat4")for(let i=0;i<e.length;i++){const n=i*16,r=e[i];for(let o=0;o<r.elements.length;o++)t[n+o]=r.elements[o]}else for(let i=0;i<e.length;i++){const n=i*4,r=e[i];t[n]=r.x,t[n+1]=r.y,t[n+2]=r.z||0,t[n+3]=r.w||0}}setup(e){const t=this.array.length,s=this.elementType;let i=Float32Array;const n=this.paddedType,r=e.getTypeLength(n);return s.charAt(0)==="i"&&(i=Int32Array),s.charAt(0)==="u"&&(i=Uint32Array),this.value=new i(t*r),this.bufferCount=t,this.bufferType=n,super.setup(e)}element(e){return k(new BS(this,k(e)))}}const Os=(a,e)=>k(new IS(a,e));class LS extends ae{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}const fl=U(LS).setParameterLength(1),Ag=J(0,"uint").label("u_cameraIndex").setGroup(mu("cameraIndex")).toVarying("v_cameraIndex"),sn=J("float").label("cameraNear").setGroup(K).onRenderUpdate(({camera:a})=>a.near),nn=J("float").label("cameraFar").setGroup(K).onRenderUpdate(({camera:a})=>a.far),Au=L(({camera:a})=>{let e;if(a.isArrayCamera&&a.cameras.length>0){const t=[];for(const i of a.cameras)t.push(i.projectionMatrix);e=Os(t).setGroup(K).label("cameraProjectionMatrices").element(a.isMultiViewCamera?fl("gl_ViewID_OVR"):Ag).toVar("cameraProjectionMatrix")}else e=J("mat4").label("cameraProjectionMatrix").setGroup(K).onRenderUpdate(({camera:t})=>t.projectionMatrix);return e}).once()(),hi=L(({camera:a})=>{let e;if(a.isArrayCamera&&a.cameras.length>0){const t=[];for(const i of a.cameras)t.push(i.matrixWorldInverse);e=Os(t).setGroup(K).label("cameraViewMatrices").element(a.isMultiViewCamera?fl("gl_ViewID_OVR"):Ag).toVar("cameraViewMatrix")}else e=J("mat4").label("cameraViewMatrix").setGroup(K).onRenderUpdate(({camera:t})=>t.matrixWorldInverse);return e}).once()(),US=J(new N).label("cameraPosition").setGroup(K).onRenderUpdate(({camera:a},e)=>e.value.setFromMatrixPosition(a.matrixWorld));class us extends Ne{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}us.DIRECTION;const hn=V(us,us.WORLD_MATRIX);us.POSITION;us.SCALE;us.VIEW_POSITION;us.RADIUS;const kS=J(new Vt).onObjectUpdate(({object:a},e)=>e.value.getNormalMatrix(a.matrixWorld)),ml=L(a=>a.renderer.overrideNodes.modelViewMatrix||zS).once()().toVar("modelViewMatrix"),zS=hi.mul(hn),rp=L(a=>(a.context.isHighPrecisionModelViewMatrix=!0,J("mat4").onObjectUpdate(({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))).once()().toVar("highpModelViewMatrix"),ap=L(a=>{const e=a.context.isHighPrecisionModelViewMatrix;return J("mat3").onObjectUpdate(({object:t,camera:s})=>(e!==!0&&t.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,t.matrixWorld),t.normalMatrix.getNormalMatrix(t.modelViewMatrix)))}).once()().toVar("highpModelNormalViewMatrix"),gl=Oi("position","vec3"),_t=gl.toVarying("positionLocal"),op=gl.toVarying("positionPrevious"),_a=L(a=>hn.mul(_t).xyz.toVarying(a.getNamespace("v_positionWorld")),"vec3").once("POSITION")(),Rg=L(a=>_t.transformDirection(hn).toVarying(a.getNamespace("v_positionWorldDirection")).normalize().toVar("positionWorldDirection"),"vec3").once("POSITION")(),et=L(a=>a.context.setupPositionView().toVarying(a.getNamespace("v_positionView")),"vec3").once("POSITION")(),$e=et.negate().toVarying("v_positionViewDirection").normalize().toVar("positionViewDirection");class GS extends st{static get type(){return"EquirectUVNode"}constructor(e=Rg){super("vec2"),this.dirNode=e}setup(){const e=this.dirNode,t=e.z.atan(e.x).mul(1/(Math.PI*2)).add(.5),s=e.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5);return H(t,s)}}const Ng=U(GS).setParameterLength(0,1);class VS extends ae{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){const{renderer:t,material:s}=e;return t.coordinateSystem===Lt&&s.side===zt?"false":e.getFrontFacing()}}const HS=V(VS),yl=B(HS).mul(2).sub(1),Pg=Oi("normal","vec3"),ks=L(a=>a.geometry.hasAttribute("normal")===!1?(console.warn('THREE.TSL: Vertex attribute "normal" not found on geometry.'),I(0,1,0)):Pg,"vec3").once()().toVar("normalLocal"),WS=et.dFdx().cross(et.dFdy()).normalize().toVar("normalFlat"),zs=L(a=>{let e;return a.material.flatShading===!0?e=WS:e=ws(Fg(ks),"v_normalView").normalize(),e},"vec3").once()().toVar("normalView"),Ru=L(a=>{let e=zs.transformDirection(hi);return a.material.flatShading!==!0&&(e=ws(e,"v_normalWorld")),e},"vec3").once()().normalize().toVar("normalWorld"),Je=L(a=>{let e=a.context.setupNormal().context({getUV:null});return a.material.flatShading!==!0&&(e=e.mul(yl)),e},"vec3").once()().toVar("transformedNormalView"),Nu=Je.transformDirection(hi).toVar("transformedNormalWorld"),Zr=L(a=>{let e=a.context.setupClearcoatNormal().context({getUV:null});return a.material.flatShading!==!0&&(e=e.mul(yl)),e},"vec3").once()().toVar("transformedClearcoatNormalView"),$S=L(([a,e=hn])=>{const t=Pt(e),s=a.div(I(t[0].dot(t[0]),t[1].dot(t[1]),t[2].dot(t[2])));return t.mul(s).xyz}),Fg=L(([a],e)=>{const t=e.renderer.overrideNodes.modelNormalViewMatrix;if(t!==null)return t.transformDirection(a);const s=kS.mul(a);return hi.transformDirection(s)});class jS extends st{static get type(){return"MatcapUVNode"}constructor(){super("vec2")}setup(){const e=I($e.z,0,$e.x.negate()).normalize(),t=$e.cross(e);return H(e.dot(Je),t.dot(Je)).mul(.495).add(.5)}}const qS=V(jS);class YS extends va{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=he.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 XS=U(YS).setParameterLength(1),ZS=a=>k(a).mul(.5).add(.5);class QS extends st{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(),r=t.sin();return fu(n,r,r.negate(),n).mul(s)}else{const n=t,r=Jn(re(1,0,0,0),re(0,wi(n.x),_s(n.x).negate(),0),re(0,_s(n.x),wi(n.x),0),re(0,0,0,1)),o=Jn(re(wi(n.y),0,_s(n.y),0),re(0,1,0,0),re(_s(n.y).negate(),0,wi(n.y),0),re(0,0,0,1)),l=Jn(re(wi(n.z),_s(n.z).negate(),0,0),re(_s(n.z),wi(n.z),0,0),re(0,0,1,0),re(0,0,0,1));return r.mul(o).mul(l).mul(re(s,1)).xyz}}}const Dg=U(QS).setParameterLength(2);let Cr,Ar;class Ke extends ae{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this.isViewportNode=!0}getNodeType(){return this.scope===Ke.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=he.NONE;return(this.scope===Ke.SIZE||this.scope===Ke.VIEWPORT)&&(e=he.RENDER),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===Ke.VIEWPORT?t!==null?Ar.copy(t.viewport):(e.getViewport(Ar),Ar.multiplyScalar(e.getPixelRatio())):t!==null?(Cr.width=t.width,Cr.height=t.height):e.getDrawingBufferSize(Cr)}setup(){const e=this.scope;let t=null;return e===Ke.SIZE?t=J(Cr||(Cr=new ce)):e===Ke.VIEWPORT?t=J(Ar||(Ar=new me)):t=H(xl.div(Oh)),t}generate(e){if(this.scope===Ke.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const s=e.getNodeProperties(Oh).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${s}.y - ${t}.y )`}return t}return super.generate(e)}}Ke.COORDINATE="coordinate";Ke.VIEWPORT="viewport";Ke.SIZE="size";Ke.UV="uv";const tr=V(Ke,Ke.UV),Oh=V(Ke,Ke.SIZE),xl=V(Ke,Ke.COORDINATE),la=V(Ke,Ke.VIEWPORT);la.zw;la.xy;const Ea=(a=0)=>Oi("uv"+(a>0?a:""),"vec2");class KS extends ae{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 sr=U(KS).setParameterLength(1,2),Og=new Tt;class mr extends va{static get type(){return"TextureNode"}constructor(e=Og,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.sampler=!0,this.updateMatrix=!1,this.updateType=he.NONE,this.referenceNode=null,this._value=e,this._matrixUniform=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===Ye?"uvec4":this.value.type===Mt?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return Ea(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return this._matrixUniform===null&&(this._matrixUniform=J(this.value.matrix)),this._matrixUniform.mul(I(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this.updateType=e?he.OBJECT:he.NONE,this}setupUV(e,t){const s=this.value;return e.isFlipY()&&(s.image instanceof ImageBitmap&&s.flipY===!0||s.isRenderTargetTexture===!0||s.isFramebufferTexture===!0||s.isDepthTexture===!0)&&(this.sampler?t=t.flipY():t=t.setY(Ue(sr(this,this.levelNode).y).sub(t.y).sub(1))),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;const s=this.value;if(!s||s.isTexture!==!0)throw new Error("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().");let i=this.uvNode;(i===null||e.context.forceUVContext===!0)&&e.context.getUV&&(i=e.context.getUV(this,e)),i||(i=this.getDefaultUV()),this.updateMatrix===!0&&(i=this.getTransformedUV(i)),i=this.setupUV(e,i);let n=this.levelNode;n===null&&e.context.getTextureLevel&&(n=e.context.getTextureLevel(this)),t.uvNode=i,t.levelNode=n,t.biasNode=this.biasNode,t.compareNode=this.compareNode,t.gradNode=this.gradNode,t.depthNode=this.depthNode}generateUV(e,t){return t.build(e,this.sampler===!0?"vec2":"ivec2")}generateSnippet(e,t,s,i,n,r,o,l){const c=this.value;let h;return i?h=e.generateTextureLevel(c,t,s,i,r):n?h=e.generateTextureBias(c,t,s,n,r):l?h=e.generateTextureGrad(c,t,s,l,r):o?h=e.generateTextureCompare(c,t,s,o,r):this.sampler===!1?h=e.generateTextureLoad(c,t,s,r):h=e.generateTexture(c,t,s,r),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 r=e.getDataFromNode(this);let o=r.propertyName;if(o===void 0){const{uvNode:h,levelNode:u,biasNode:d,compareNode:p,depthNode:f,gradNode:m}=i,y=this.generateUV(e,h),g=u?u.build(e,"float"):null,_=d?d.build(e,"float"):null,b=f?f.build(e,"int"):null,S=p?p.build(e,"float"):null,T=m?[m[0].build(e,"vec2"),m[1].build(e,"vec2")]:null,M=e.getVarFromNode(this);o=e.getPropertyName(M);const w=this.generateSnippet(e,n,y,g,_,b,S,T);e.addLineFlowCode(`${o} = ${w}`,this),r.snippet=w,r.propertyName=o}let l=o;const c=this.getNodeType(e);return e.needsToWorkingColorSpace(s)&&(l=wu(hr(l,c),s.colorSpace).setup(e).build(e,c)),e.format(l,c,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}uv(e){return console.warn("THREE.TextureNode: .uv() has been renamed. Use .sample() instead."),this.sample(e)}sample(e){const t=this.clone();return t.uvNode=k(e),t.referenceNode=this.getSelf(),k(t)}blur(e){const t=this.clone();t.biasNode=k(e).mul(XS(t)),t.referenceNode=this.getSelf();const s=t.value;return t.generateMipmaps===!1&&(s&&s.generateMipmaps===!1||s.minFilter===lt||s.magFilter===lt)&&(console.warn("THREE.TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),k(t)}level(e){const t=this.clone();return t.levelNode=k(e),t.referenceNode=this.getSelf(),k(t)}size(e){return sr(this,e)}bias(e){const t=this.clone();return t.biasNode=k(e),t.referenceNode=this.getSelf(),k(t)}compare(e){const t=this.clone();return t.compareNode=k(e),t.referenceNode=this.getSelf(),k(t)}grad(e,t){const s=this.clone();return s.gradNode=[k(e),k(t)],s.referenceNode=this.getSelf(),k(s)}depth(e){const t=this.clone();return t.depthNode=k(e),t.referenceNode=this.getSelf(),k(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()}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}}const JS=U(mr).setParameterLength(1,4).setName("texture"),xe=(a=Og,e=null,t=null,s=null)=>{let i;return a&&a.isTextureNode===!0?(i=k(a.clone()),i.referenceNode=a.getSelf(),e!==null&&(i.uvNode=k(e)),t!==null&&(i.levelNode=k(t)),s!==null&&(i.biasNode=k(s))):i=JS(a,e,t,s),i},ys=(...a)=>xe(...a).setSampler(!1);class ev extends Tt{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=lt,this.minFilter=lt,this.generateMipmaps=!1,this.needsUpdate=!0}}const Rr=new ce;class Bg extends mr{static get type(){return"ViewportTextureNode"}constructor(e=tr,t=null,s=null){s===null&&(s=new ev,s.minFilter=ei),super(s,e,t),this.generateMipmaps=!1,this.isOutputTextureNode=!0,this.updateBeforeType=he.FRAME}updateBefore(e){const t=e.renderer;t.getDrawingBufferSize(Rr);const s=this.value;(s.image.width!==Rr.width||s.image.height!==Rr.height)&&(s.image.width=Rr.width,s.image.height=Rr.height,s.needsUpdate=!0);const i=s.generateMipmaps;s.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(s),s.generateMipmaps=i}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const Ig=U(Bg,null,null,{generateMipmaps:!0}).setParameterLength(0,3);let Zl=null;class tv extends Bg{static get type(){return"ViewportDepthTextureNode"}constructor(e=tr,t=null){Zl===null&&(Zl=new Is),super(e,t,Zl)}}const sv=U(tv).setParameterLength(0,2);class Ut extends ae{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===Ut.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,s=this.valueNode;let i=null;if(t===Ut.DEPTH_BASE)s!==null&&(i=kg().assign(s));else if(t===Ut.DEPTH)e.isPerspectiveCamera?i=iv(et.z,sn,nn):i=ca(et.z,sn,nn);else if(t===Ut.LINEAR_DEPTH)if(s!==null)if(e.isPerspectiveCamera){const n=Lg(s,sn,nn);i=ca(n,sn,nn)}else i=s;else i=ca(et.z,sn,nn);return i}}Ut.DEPTH_BASE="depthBase";Ut.DEPTH="depth";Ut.LINEAR_DEPTH="linearDepth";const ca=(a,e,t)=>a.add(e).div(e.sub(t)),iv=(a,e,t)=>e.add(a).mul(t).div(t.sub(e).mul(a)),Lg=(a,e,t)=>e.mul(t).div(t.sub(e).mul(a).sub(t)),Ug=(a,e,t)=>{e=e.max(1e-6).toVar();const s=ii(a.negate().div(e)),i=ii(t.div(e));return s.div(i)},kg=U(Ut,Ut.DEPTH_BASE),zg=V(Ut,Ut.DEPTH),nv=U(Ut,Ut.LINEAR_DEPTH).setParameterLength(0,1);sv();zg.assign=a=>kg(a);const Ql=new N,rv=new N,av=new Vt;class Ei{constructor(e=new N(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=Ql.subVectors(s,t).cross(rv.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(Ql),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||av.getNormalMatrix(e),i=this.coplanarPoint(Ql).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)}}class dn extends un{constructor(e=1,t=1,s={}){super(),s=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Qt,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 me(0,0,e,t),this.scissorTest=!1,this.viewport=new me(0,0,e,t);const i={width:e,height:t,depth:s.depth},n=new Tt(i);this.textures=[];const r=s.count;for(let o=0;o<r;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:Qt,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].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 ou(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"})}}new Ei;new N;new N;new N;new Be;new N(0,0,-1);new me;new N;new N;new me;new ce;const ov=new dn;tr.flipX();ov.depthTexture=new Is(1,1);let lv=0;class Gt extends un{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:lv++}),this.uuid=Qs(),this.name="",this.type="Material",this.blending=Js,this.side=Ks,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=Go,this.blendDst=Vo,this.blendEquation=bs,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Se(0,0,0),this.blendAlpha=0,this.depthFunc=Ho,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=Ch,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Ki,this.stencilZFail=Ki,this.stencilZPass=Ki,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){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}const i=this[t];if(i===void 0){console.warn(`THREE.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.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!==Js&&(s.blending=this.blending),this.side!==Ks&&(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!==Go&&(s.blendSrc=this.blendSrc),this.blendDst!==Vo&&(s.blendDst=this.blendDst),this.blendEquation!==bs&&(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!==Ho&&(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!==Ch&&(s.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(s.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(s.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Ki&&(s.stencilFail=this.stencilFail),this.stencilZFail!==Ki&&(s.stencilZFail=this.stencilZFail),this.stencilZPass!==Ki&&(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.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 r=[];for(const o in n){const l=n[o];delete l.metadata,r.push(l)}return r}if(t){const n=i(e.textures),r=i(e.images);n.length>0&&(s.textures=n),r.length>0&&(s.images=r)}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.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++}}const lp=new hs,Kl=new Be,cv=J(0).onReference(({material:a})=>a).onObjectUpdate(({material:a})=>a.refractionRatio),Jl=J(1).onReference(({material:a})=>a).onObjectUpdate(function({material:a,scene:e}){return a.envMap?a.envMapIntensity:e.environmentIntensity}),Gg=J(new Be).onReference(function(a){return a.material}).onObjectUpdate(function({material:a,scene:e}){const t=e.environment!==null&&a.envMap===null?e.environmentRotation:a.envMapRotation;return t?(lp.copy(t),Kl.makeRotationFromEuler(lp)):Kl.identity(),Kl}),hv=$e.negate().reflect(Je),uv=$e.negate().refract(Je,cv),dv=hv.transformDirection(hi).toVar("reflectVector"),pv=uv.transformDirection(hi).toVar("reflectVector");class _l extends Tt{constructor(e=[],t=fa,s,i,n,r,o,l,c,h){super(e,t,s,i,n,r,o,l,c,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}const fv=new _l;class mv extends mr{static get type(){return"CubeTextureNode"}constructor(e,t=null,s=null,i=null){super(e,t,s,i),this.isCubeTextureNode=!0}getInputType(){return"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===fa?dv:e.mapping===Wo?pv:(console.error('THREE.CubeTextureNode: Mapping "%s" not supported.',e.mapping),I(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const s=this.value;return(e.renderer.coordinateSystem===Fi||!s.isRenderTargetTexture)&&(t=I(t.x.negate(),t.yz)),Gg.mul(t)}generateUV(e,t){return t.build(e,"vec3")}}const gv=U(mv).setParameterLength(1,4).setName("cubeTexture"),ba=(a=fv,e=null,t=null,s=null)=>{let i;return a&&a.isCubeTextureNode===!0?(i=k(a.clone()),i.referenceNode=a.getSelf(),e!==null&&(i.uvNode=k(e)),t!==null&&(i.levelNode=k(t)),s!==null&&(i.biasNode=k(s))):i=gv(a,e,t,s),i};class yv extends Sa{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 Pu extends ae{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=he.OBJECT}element(e){return k(new yv(this,k(e)))}setGroup(e){return this.group=e,this}label(e){return this.name=e,this}setNodeType(e){let t=null;this.count!==null?t=Cg(null,e,this.count):Array.isArray(this.getValueFromReference())?t=Os(null,e):e==="texture"?t=xe(null):e==="cubeTexture"?t=ba(null):t=J(null,e),this.group!==null&&t.setGroup(this.group),this.name!==null&&t.label(this.name),this.node=t.getSelf()}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 Oe=(a,e,t)=>k(new Pu(a,e,t)),cp=(a,e,t,s)=>k(new Pu(a,e,s,t));class xv extends Pu{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 Ci=(a,e,t=null)=>k(new xv(a,e,t)),Vg=L(a=>(a.geometry.hasAttribute("tangent")===!1&&a.geometry.computeTangents(),Oi("tangent","vec4")))(),Fu=Vg.xyz.toVar("tangentLocal"),Hg=ml.mul(re(Fu,0)).xyz.toVarying("v_tangentView").normalize().toVar("tangentView"),_v=L(([a,e],t)=>{let s=a.mul(Vg.w).xyz;return t.material.flatShading!==!0&&(s=ws(s,e)),s}).once(),bv=_v(zs.cross(Hg),"v_bitangentView").normalize().toVar("bitangentView"),Qr=Pt(Hg,bv,zs),Tv=(()=>{let a=er.cross($e);return a=a.cross(er).normalize(),a=ze(a,Je,Ji.mul(Xs.oneMinus()).oneMinus().pow2().pow2()).normalize(),a})(),Sv=L(a=>{const{eye_pos:e,surf_norm:t,mapN:s,uv:i}=a,n=e.dFdx(),r=e.dFdy(),o=i.dFdx(),l=i.dFdy(),c=t,h=r.cross(c),u=c.cross(n),d=h.mul(o.x).add(u.mul(l.x)),p=h.mul(o.y).add(u.mul(l.y)),f=d.dot(d).max(p.dot(p)),m=yl.mul(f.inverseSqrt());return Ft(d.mul(s.x,m),p.mul(s.y,m),c.mul(s.z)).normalize()});class vv extends st{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=Pi}setup(e){const{normalMapType:t,scaleNode:s}=this;let i=this.node.mul(2).sub(1);s!==null&&(i=I(i.xy.mul(s),i.z));let n=null;return t===a_?n=Fg(i):t===Pi&&(e.hasGeometryAttribute("tangent")===!0?n=Qr.mul(i).normalize():n=Sv({eye_pos:et,surf_norm:zs,mapN:i,uv:Ea()})),n}}const hp=U(vv).setParameterLength(1,2),wv=L(({textureNode:a,bumpScale:e})=>{const t=i=>a.cache().context({getUV:n=>i(n.uvNode||Ea()),forceUVContext:!0}),s=B(t(i=>i));return H(B(t(i=>i.add(i.dFdx()))).sub(s),B(t(i=>i.add(i.dFdy()))).sub(s)).mul(e)}),Ev=L(a=>{const{surf_pos:e,surf_norm:t,dHdxy:s}=a,i=e.dFdx().normalize(),n=e.dFdy().normalize(),r=t,o=n.cross(r),l=r.cross(i),c=i.dot(o).mul(yl),h=c.sign().mul(s.x.mul(o).add(s.y.mul(l)));return c.abs().mul(t).sub(h).normalize()});class Mv extends st{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=wv({textureNode:this.textureNode,bumpScale:e});return Ev({surf_pos:et,surf_norm:zs,dHdxy:t})}}const Cv=U(Mv).setParameterLength(1,2),up=new Map;class D extends ae{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let s=up.get(e);return s===void 0&&(s=Ci(e,t),up.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===D.COLOR){const n=t.color!==void 0?this.getColor(s):I();t.map&&t.map.isTexture===!0?i=n.mul(this.getTexture("map")):i=n}else if(s===D.OPACITY){const n=this.getFloat(s);t.alphaMap&&t.alphaMap.isTexture===!0?i=n.mul(this.getTexture("alpha")):i=n}else if(s===D.SPECULAR_STRENGTH)t.specularMap&&t.specularMap.isTexture===!0?i=this.getTexture("specular").r:i=B(1);else if(s===D.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===D.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===D.ROUGHNESS){const n=this.getFloat(s);t.roughnessMap&&t.roughnessMap.isTexture===!0?i=n.mul(this.getTexture(s).g):i=n}else if(s===D.METALNESS){const n=this.getFloat(s);t.metalnessMap&&t.metalnessMap.isTexture===!0?i=n.mul(this.getTexture(s).b):i=n}else if(s===D.EMISSIVE){const n=this.getFloat("emissiveIntensity"),r=this.getColor(s).mul(n);t.emissiveMap&&t.emissiveMap.isTexture===!0?i=r.mul(this.getTexture(s)):i=r}else if(s===D.NORMAL)t.normalMap?(i=hp(this.getTexture("normal"),this.getCache("normalScale","vec2")),i.normalMapType=t.normalMapType):t.bumpMap?i=Cv(this.getTexture("bump").r,this.getFloat("bumpScale")):i=zs;else if(s===D.CLEARCOAT){const n=this.getFloat(s);t.clearcoatMap&&t.clearcoatMap.isTexture===!0?i=n.mul(this.getTexture(s).r):i=n}else if(s===D.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===D.CLEARCOAT_NORMAL)t.clearcoatNormalMap?i=hp(this.getTexture(s),this.getCache(s+"Scale","vec2")):i=zs;else if(s===D.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===D.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(.07,1)}else if(s===D.ANISOTROPY)if(t.anisotropyMap&&t.anisotropyMap.isTexture===!0){const n=this.getTexture(s);i=fu(Nr.x,Nr.y,Nr.y.negate(),Nr.x).mul(n.rg.mul(2).sub(H(1)).normalize().mul(n.b))}else i=Nr;else if(s===D.IRIDESCENCE_THICKNESS){const n=Oe("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const r=Oe("0","float",t.iridescenceThicknessRange);i=n.sub(r).mul(this.getTexture(s).g).add(r)}else i=n}else if(s===D.TRANSMISSION){const n=this.getFloat(s);t.transmissionMap?i=n.mul(this.getTexture(s).r):i=n}else if(s===D.THICKNESS){const n=this.getFloat(s);t.thicknessMap?i=n.mul(this.getTexture(s).g):i=n}else if(s===D.IOR)i=this.getFloat(s);else if(s===D.LIGHT_MAP)i=this.getTexture(s).rgb.mul(this.getFloat("lightMapIntensity"));else if(s===D.AO)i=this.getTexture(s).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else if(s===D.LINE_DASH_OFFSET)i=t.dashOffset?this.getFloat(s):B(0);else{const n=this.getNodeType(e);i=this.getCache(s,n)}return i}}D.ALPHA_TEST="alphaTest";D.COLOR="color";D.OPACITY="opacity";D.SHININESS="shininess";D.SPECULAR="specular";D.SPECULAR_STRENGTH="specularStrength";D.SPECULAR_INTENSITY="specularIntensity";D.SPECULAR_COLOR="specularColor";D.REFLECTIVITY="reflectivity";D.ROUGHNESS="roughness";D.METALNESS="metalness";D.NORMAL="normal";D.CLEARCOAT="clearcoat";D.CLEARCOAT_ROUGHNESS="clearcoatRoughness";D.CLEARCOAT_NORMAL="clearcoatNormal";D.EMISSIVE="emissive";D.ROTATION="rotation";D.SHEEN="sheen";D.SHEEN_ROUGHNESS="sheenRoughness";D.ANISOTROPY="anisotropy";D.IRIDESCENCE="iridescence";D.IRIDESCENCE_IOR="iridescenceIOR";D.IRIDESCENCE_THICKNESS="iridescenceThickness";D.IOR="ior";D.TRANSMISSION="transmission";D.THICKNESS="thickness";D.ATTENUATION_DISTANCE="attenuationDistance";D.ATTENUATION_COLOR="attenuationColor";D.LINE_SCALE="scale";D.LINE_DASH_SIZE="dashSize";D.LINE_GAP_SIZE="gapSize";D.LINE_WIDTH="linewidth";D.LINE_DASH_OFFSET="dashOffset";D.POINT_SIZE="size";D.DISPERSION="dispersion";D.LIGHT_MAP="light";D.AO="ao";const Av=V(D,D.ALPHA_TEST),Rv=V(D,D.COLOR),Nv=V(D,D.SHININESS),Pv=V(D,D.EMISSIVE),Wg=V(D,D.OPACITY),Fv=V(D,D.SPECULAR),dp=V(D,D.SPECULAR_INTENSITY),Dv=V(D,D.SPECULAR_COLOR),Do=V(D,D.SPECULAR_STRENGTH),ec=V(D,D.REFLECTIVITY),Ov=V(D,D.ROUGHNESS),Bv=V(D,D.METALNESS),Iv=V(D,D.NORMAL),Lv=V(D,D.CLEARCOAT),Uv=V(D,D.CLEARCOAT_ROUGHNESS),kv=V(D,D.CLEARCOAT_NORMAL),zv=V(D,D.ROTATION),Gv=V(D,D.SHEEN),Vv=V(D,D.SHEEN_ROUGHNESS),Hv=V(D,D.ANISOTROPY),Wv=V(D,D.IRIDESCENCE),$v=V(D,D.IRIDESCENCE_IOR),jv=V(D,D.IRIDESCENCE_THICKNESS),qv=V(D,D.TRANSMISSION),Yv=V(D,D.THICKNESS),Xv=V(D,D.IOR),Zv=V(D,D.ATTENUATION_DISTANCE),Qv=V(D,D.ATTENUATION_COLOR),Kv=V(D,D.LINE_SCALE),Jv=V(D,D.LINE_DASH_SIZE),ew=V(D,D.LINE_GAP_SIZE);D.LINE_WIDTH;const tw=V(D,D.LINE_DASH_OFFSET),sw=V(D,D.POINT_SIZE),iw=V(D,D.DISPERSION),$g=V(D,D.LIGHT_MAP),nw=V(D,D.AO),Nr=J(new ce).onReference(function(a){return a.material}).onRenderUpdate(function({material:a}){this.value.set(a.anisotropy*Math.cos(a.anisotropyRotation),a.anisotropy*Math.sin(a.anisotropyRotation))}),jg=L(a=>a.context.setupModelViewProjection(),"vec4").once()().toVarying("v_modelViewProjection");class rw extends vg{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 aw extends os{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}}class ow extends ae{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=he.FRAME,this.buffer=null,this.bufferColor=null}setup(e){const{count:t,instanceMatrix:s,instanceColor:i}=this;let{instanceMatrixNode:n,instanceColorNode:r}=this;if(n===null){if(t<=1e3)n=Cg(s.array,"mat4",Math.max(t,1)).element(Cu);else{const l=new rw(s.array,16,1);this.buffer=l;const c=s.usage===Hn?ip:sp,h=[c(l,"vec4",16,0),c(l,"vec4",16,4),c(l,"vec4",16,8),c(l,"vec4",16,12)];n=Jn(...h)}this.instanceMatrixNode=n}if(i&&r===null){const l=new aw(i.array,3),c=i.usage===Hn?ip:sp;this.bufferColor=l,r=I(c(l,"vec3",3,0)),this.instanceColorNode=r}const o=n.mul(_t).xyz;if(_t.assign(o),e.hasGeometryAttribute("normal")){const l=$S(ks,n);ks.assign(l)}this.instanceColorNode!==null&&Qo("vec3","vInstanceColor").assign(this.instanceColorNode)}update(){this.instanceMatrix.usage!==Hn&&this.buffer!==null&&this.instanceMatrix.version!==this.buffer.version&&(this.buffer.version=this.instanceMatrix.version),this.instanceColor&&this.instanceColor.usage!==Hn&&this.bufferColor!==null&&this.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceColor.version)}}class lw extends ow{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:s,instanceColor:i}=e;super(t,s,i),this.instancedMesh=e}}const cw=U(lw).setParameterLength(1);class hw extends ae{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=Cu:this.batchingIdNode=AS);const s=L(([f])=>{const m=Ue(sr(ys(this.batchMesh._indirectTexture),0).x),y=Ue(f).mod(m),g=Ue(f).div(m);return ys(this.batchMesh._indirectTexture,qs(y,g)).x}).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]})(Ue(this.batchingIdNode)),i=this.batchMesh._matricesTexture,n=Ue(sr(ys(i),0).x),r=B(s).mul(4).toInt().toVar(),o=r.mod(n),l=r.div(n),c=Jn(ys(i,qs(o,l)),ys(i,qs(o.add(1),l)),ys(i,qs(o.add(2),l)),ys(i,qs(o.add(3),l))),h=this.batchMesh._colorsTexture;if(h!==null){const m=L(([y])=>{const g=Ue(sr(ys(h),0).x),_=y,b=_.mod(g),S=_.div(g);return ys(h,qs(b,S)).rgb}).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]})(s);Qo("vec3","vBatchColor").assign(m)}const u=Pt(c);_t.assign(c.mul(_t));const d=ks.div(I(u[0].dot(u[0]),u[1].dot(u[1]),u[2].dot(u[2]))),p=u.mul(d).xyz;ks.assign(p),e.hasGeometryAttribute("tangent")&&Fu.mulAssign(u)}}const uw=U(hw).setParameterLength(1),pp=new WeakMap;class dw extends ae{static get type(){return"SkinningNode"}constructor(e){super("void"),this.skinnedMesh=e,this.updateType=he.OBJECT,this.skinIndexNode=Oi("skinIndex","uvec4"),this.skinWeightNode=Oi("skinWeight","vec4"),this.bindMatrixNode=Oe("bindMatrix","mat4"),this.bindMatrixInverseNode=Oe("bindMatrixInverse","mat4"),this.boneMatricesNode=cp("skeleton.boneMatrices","mat4",e.skeleton.bones.length),this.positionNode=_t,this.toPositionNode=_t,this.previousBoneMatricesNode=null}getSkinnedPosition(e=this.boneMatricesNode,t=this.positionNode){const{skinIndexNode:s,skinWeightNode:i,bindMatrixNode:n,bindMatrixInverseNode:r}=this,o=e.element(s.x),l=e.element(s.y),c=e.element(s.z),h=e.element(s.w),u=n.mul(t),d=Ft(o.mul(i.x).mul(u),l.mul(i.y).mul(u),c.mul(i.z).mul(u),h.mul(i.w).mul(u));return r.mul(d).xyz}getSkinnedNormal(e=this.boneMatricesNode,t=ks){const{skinIndexNode:s,skinWeightNode:i,bindMatrixNode:n,bindMatrixInverseNode:r}=this,o=e.element(s.x),l=e.element(s.y),c=e.element(s.z),h=e.element(s.w);let u=Ft(i.x.mul(o),i.y.mul(l),i.z.mul(c),i.w.mul(h));return u=r.mul(u).mul(n),u.transformDirection(t).xyz}getPreviousSkinnedPosition(e){const t=e.object;return this.previousBoneMatricesNode===null&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=cp("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,op)}needsPreviousBoneMatrices(e){const t=e.renderer.getMRT();return t&&t.has("velocity")||km(e.object).useVelocity===!0}setup(e){this.needsPreviousBoneMatrices(e)&&op.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(this.toPositionNode&&this.toPositionNode.assign(t),e.hasGeometryAttribute("normal")){const s=this.getSkinnedNormal();ks.assign(s),e.hasGeometryAttribute("tangent")&&Fu.assign(s)}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;pp.get(t)!==e.frameId&&(pp.set(t,e.frameId),this.previousBoneMatricesNode!==null&&t.previousBoneMatrices.set(t.boneMatrices),t.update())}}const pw=a=>k(new dw(a));class fw extends Tt{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=lt,this.minFilter=lt,this.wrapR=Ri,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}const tc=new WeakMap,$t=new me,fp=L(({bufferMap:a,influence:e,stride:t,width:s,depth:i,offset:n})=>{const r=Ue(CS).mul(t).add(n),o=r.div(s),l=r.sub(o.mul(s));return ys(a,qs(l,o)).depth(i).xyz.mul(e)});function mw(a){const e=a.morphAttributes.position!==void 0,t=a.morphAttributes.normal!==void 0,s=a.morphAttributes.color!==void 0,i=a.morphAttributes.position||a.morphAttributes.normal||a.morphAttributes.color,n=i!==void 0?i.length:0;let r=tc.get(a);if(r===void 0||r.count!==n){let g=function(){m.dispose(),tc.delete(a),a.removeEventListener("dispose",g)};r!==void 0&&r.texture.dispose();const o=a.morphAttributes.position||[],l=a.morphAttributes.normal||[],c=a.morphAttributes.color||[];let h=0;e===!0&&(h=1),t===!0&&(h=2),s===!0&&(h=3);let u=a.attributes.position.count*h,d=1;const p=4096;u>p&&(d=Math.ceil(u/p),u=p);const f=new Float32Array(u*d*4*n),m=new fw(f,u,d,n);m.type=Zt,m.needsUpdate=!0;const y=h*4;for(let _=0;_<n;_++){const b=o[_],S=l[_],T=c[_],M=u*d*4*_;for(let w=0;w<b.count;w++){const R=w*y;e===!0&&($t.fromBufferAttribute(b,w),f[M+R+0]=$t.x,f[M+R+1]=$t.y,f[M+R+2]=$t.z,f[M+R+3]=0),t===!0&&($t.fromBufferAttribute(S,w),f[M+R+4]=$t.x,f[M+R+5]=$t.y,f[M+R+6]=$t.z,f[M+R+7]=0),s===!0&&($t.fromBufferAttribute(T,w),f[M+R+8]=$t.x,f[M+R+9]=$t.y,f[M+R+10]=$t.z,f[M+R+11]=T.itemSize===4?$t.w:1)}}r={count:n,texture:m,stride:h,size:new ce(u,d)},tc.set(a,r),a.addEventListener("dispose",g)}return r}class gw extends ae{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=J(1),this.updateType=he.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,r=n!==void 0?n.length:0,{texture:o,stride:l,size:c}=mw(t);s===!0&&_t.mulAssign(this.morphBaseInfluence),i===!0&&ks.mulAssign(this.morphBaseInfluence);const h=Ue(c.width);Ts(r,({i:u})=>{const d=B(0).toVar();this.mesh.count>1&&this.mesh.morphTexture!==null&&this.mesh.morphTexture!==void 0?d.assign(ys(this.mesh.morphTexture,qs(Ue(u).add(1),Ue(Cu))).r):d.assign(Oe("morphTargetInfluences","float").element(u).toVar()),Xe(d.notEqual(0),()=>{s===!0&&_t.addAssign(fp({bufferMap:o,influence:d,stride:l,width:h,depth:u,offset:Ue(0)})),i===!0&&ks.addAssign(fp({bufferMap:o,influence:d,stride:l,width:h,depth:u,offset:Ue(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 yw=U(gw).setParameterLength(1);class gr extends ae{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class xw extends gr{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class _w extends bg{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=I().toVar("directDiffuse"),i=I().toVar("directSpecular"),n=I().toVar("indirectDiffuse"),r=I().toVar("indirectSpecular"),o={directDiffuse:s,directSpecular:i,indirectDiffuse:n,indirectSpecular:r};return{radiance:I().toVar("radiance"),irradiance:I().toVar("irradiance"),iblIrradiance:I().toVar("iblIrradiance"),ambientOcclusion:B(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 bw=U(_w);class Tw extends gr{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}class ls extends ae{static get type(){return"ClippingNode"}constructor(e=ls.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===ls.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(s,i):this.scope===ls.HARDWARE?this.setupHardwareClipping(i,e):this.setupDefault(s,i)}setupAlphaToCoverage(e,t){return L(()=>{const s=B().toVar("distanceToPlane"),i=B().toVar("distanceToGradient"),n=B(1).toVar("clipOpacity"),r=t.length;if(this.hardwareClipping===!1&&r>0){const l=Os(t);Ts(r,({i:c})=>{const h=l.element(c);s.assign(et.dot(h.xyz).negate().add(h.w)),i.assign(s.fwidth().div(2)),n.mulAssign(Di(i.negate(),i,s))})}const o=e.length;if(o>0){const l=Os(e),c=B(1).toVar("intersectionClipOpacity");Ts(o,({i:h})=>{const u=l.element(h);s.assign(et.dot(u.xyz).negate().add(u.w)),i.assign(s.fwidth().div(2)),c.mulAssign(Di(i.negate(),i,s).oneMinus())}),n.mulAssign(c.oneMinus())}Te.a.mulAssign(n),Te.a.equal(0).discard()})()}setupDefault(e,t){return L(()=>{const s=t.length;if(this.hardwareClipping===!1&&s>0){const n=Os(t);Ts(s,({i:r})=>{const o=n.element(r);et.dot(o.xyz).greaterThan(o.w).discard()})}const i=e.length;if(i>0){const n=Os(e),r=pu(!0).toVar("clipped");Ts(i,({i:o})=>{const l=n.element(o);r.assign(et.dot(l.xyz).greaterThan(l.w).and(r))}),r.discard()}})()}setupHardwareClipping(e,t){const s=e.length;return t.enableHardwareClipping(s),L(()=>{const i=Os(e),n=fl(t.getClipDistance());Ts(s,({i:r})=>{const o=i.element(r),l=et.dot(o.xyz).sub(o.w).negate();n.element(r).assign(l)})})()}}ls.ALPHA_TO_COVERAGE="alphaToCoverage";ls.DEFAULT="default";ls.HARDWARE="hardware";const Sw=()=>k(new ls),vw=()=>k(new ls(ls.ALPHA_TO_COVERAGE)),ww=()=>k(new ls(ls.HARDWARE)),Ew=["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"];class Mw{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=e.object.isSkinnedMesh===!0,this.refreshUniforms=Ew,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),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:r,height:o}=e.context;t.bufferWidth=r,t.bufferHeight=o}this.renderObjects.set(e,t)}return t}getAttributesData(e){const t={};for(const s in e){const i=e[s];t[s]={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.renderer.overrideNodes.modelViewMatrix!==null||e.renderer.overrideNodes.modelNormalViewMatrix!==null}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){const{object:t,material:s,geometry:i}=e,n=this.getRenderObjectData(e);if(n.worldMatrix.equals(t.matrixWorld)!==!0)return n.worldMatrix.copy(t.matrixWorld),!1;const r=n.material;for(const m in r){const y=r[m],g=s[m];if(y.equals!==void 0){if(y.equals(g)===!1)return y.copy(g),!1}else if(g.isTexture===!0){if(y.id!==g.id||y.version!==g.version)return y.id=g.id,y.version=g.version,!1}else if(y!==g)return r[m]=g,!1}if(r.transmission>0){const{width:m,height:y}=e.context;if(n.bufferWidth!==m||n.bufferHeight!==y)return n.bufferWidth=m,n.bufferHeight=y,!1}const o=n.geometry,l=i.attributes,c=o.attributes,h=Object.keys(c),u=Object.keys(l);if(o.id!==i.id)return o.id=i.id,!1;if(h.length!==u.length)return n.geometry.attributes=this.getAttributesData(l),!1;for(const m of h){const y=c[m],g=l[m];if(g===void 0)return delete c[m],!1;if(y.version!==g.version)return y.version=g.version,!1}const d=i.index,p=o.indexVersion,f=d?d.version:null;if(p!==f)return o.indexVersion=f,!1;if(o.drawRange.start!==i.drawRange.start||o.drawRange.count!==i.drawRange.count)return o.drawRange.start=i.drawRange.start,o.drawRange.count=i.drawRange.count,!1;if(n.morphTargetInfluences){let m=!1;for(let y=0;y<n.morphTargetInfluences.length;y++)n.morphTargetInfluences[y]!==t.morphTargetInfluences[y]&&(m=!0);if(m)return!0}return n.center&&n.center.equals(t.center)===!1?(n.center.copy(t.center),!0):(e.bundle!==null&&(n.version=e.bundle.version),!0)}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;return i||n?!1:this.equals(e)!==!0}}const Cw=.05,mp=L(([a])=>Ii(pe(1e4,_s(pe(17,a.x).add(pe(.1,a.y)))).mul(Ft(.1,is(_s(pe(13,a.y).add(a.x))))))),gp=L(([a])=>mp(H(mp(a.xy),a.z))),Aw=L(([a])=>{const e=St(ni(dg(a.xyz)),ni(pg(a.xyz))),t=B(1).div(B(Cw).mul(e)).toVar("pixScale"),s=H(ya(cn(ii(t))),ya(_u(ii(t)))),i=H(gp(cn(s.x.mul(a.xyz))),gp(cn(s.y.mul(a.xyz)))),n=Ii(ii(t)),r=Ft(pe(n.oneMinus(),i.x),pe(n,i.y)),o=cr(n,n.oneMinus()),l=I(r.mul(r).div(pe(2,o).mul(Ct(1,o))),r.sub(pe(.5,o)).div(Ct(1,o)),Ct(1,Ct(1,r).mul(Ct(1,r)).div(pe(2,o).mul(Ct(1,o))))),c=r.lessThan(o.oneMinus()).select(r.lessThan(o).select(l.x,l.y),l.z);return oi(c,1e-6,1)}).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class Rw extends Eg{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 me(1,1,1,1)),i}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const Nw=(a=0)=>k(new Rw(a));class tt extends Gt{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.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,Object.defineProperty(this,"shadowPositionNode",{get:()=>this.receivedShadowPositionNode,set:e=>{console.warn('THREE.NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".'),this.receivedShadowPositionNode=e}})}customProgramCacheKey(){return this.type+Lm(this)}build(e){this.setup(e)}setupObserver(e){return new Mw(e)}setup(e){e.context.setupNormal=()=>this.setupNormal(e),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);const t=e.renderer,s=t.getRenderTarget();e.addStack();const i=this.setupVertex(e),n=this.vertexNode||i;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 r;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.add(o);const c=re(l,Te.a).max(0);r=this.setupOutput(e,c),oa.assign(r);const h=this.outputNode!==null;if(h&&(r=this.outputNode),s!==null){const u=t.getMRT(),d=this.mrtNode;u!==null?(h&&oa.assign(r),r=u,d!==null&&(r=u.merge(d))):d!==null&&(r=d)}}else{let l=this.fragmentNode;l.isOutputStructNode!==!0&&(l=re(l)),r=this.setupOutput(e,l)}e.stack.outputNode=r,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.samples;this.alphaToCoverage&&n>1?i=vw():e.stack.add(Sw())}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.add(ww()),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=Ug(et.z,sn,nn):i=ca(et.z,sn,nn))}i!==null&&zg.assign(i).toStack()}setupPositionView(){return ml.mul(_t).xyz}setupModelViewProjection(){return Au.mul(et)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.vertex=e.removeStack(),jg}setupPosition(e){const{object:t,geometry:s}=e;if((s.morphAttributes.position||s.morphAttributes.normal||s.morphAttributes.color)&&yw(t).toStack(),t.isSkinnedMesh===!0&&pw(t).toStack(),this.displacementMap){const i=Ci("displacementMap","texture"),n=Ci("displacementScale","float"),r=Ci("displacementBias","float");_t.addAssign(ks.normalize().mul(i.x.mul(n).add(r)))}return t.isBatchedMesh&&uw(t).toStack(),t.isInstancedMesh&&t.instanceMatrix&&t.instanceMatrix.isInstancedBufferAttribute===!0&&cw(t).toStack(),this.positionNode!==null&&_t.assign(yS(this.positionNode,"POSITION")),_t}setupDiffuseColor({object:e,geometry:t}){this.maskNode!==null&&pu(this.maskNode).not().discard();let s=this.colorNode?re(this.colorNode):Rv;this.vertexColors===!0&&t.hasAttribute("color")&&(s=s.mul(Nw())),e.instanceColor&&(s=Qo("vec3","vInstanceColor").mul(s)),e.isBatchedMesh&&e._colorsTexture&&(s=Qo("vec3","vBatchColor").mul(s)),Te.assign(s);const i=this.opacityNode?B(this.opacityNode):Wg;Te.a.assign(Te.a.mul(i));let n=null;(this.alphaTestNode!==null||this.alphaTest>0)&&(n=this.alphaTestNode!==null?B(this.alphaTestNode):Av,Te.a.lessThanEqual(n).discard()),this.alphaHash===!0&&Te.a.lessThan(Aw(_t)).discard(),this.transparent===!1&&this.blending===Js&&this.alphaToCoverage===!1?Te.a.assign(1):n===null&&Te.a.lessThanEqual(0).discard()}setupVariants(){}setupOutgoingLight(){return this.lights===!0?I(0):Te.rgb}setupNormal(){return this.normalNode?I(this.normalNode):Iv}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?Ci("envMap","cubeTexture"):Ci("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Tw($g)),t}setupLights(e){const t=[],s=this.setupEnvironment(e);s&&s.isLightingNode&&t.push(s);const i=this.setupLightMap(e);if(i&&i.isLightingNode&&t.push(i),this.aoNode!==null||e.material.aoMap){const r=this.aoNode!==null?this.aoNode:nw;t.push(new xw(r))}let n=this.lightsNode||e.lightsNode;return t.length>0&&(n=e.renderer.lighting.createNode([...n.getLights(),...t])),n}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=bw(o,c,s,i)}else s!==null&&(l=I(i!==null?ze(l,s,i):s));return(n&&n.isNode===!0||t.emissive&&t.emissive.isColor===!0)&&(ep.assign(I(n||Pv)),l=l.add(ep)),l}setupFog(e,t){const s=e.fogNode;return s&&(oa.assign(t),t=re(s)),t}setupOutput(e,t){return this.fog===!0&&(t=this.setupFog(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=Gt.prototype.toJSON.call(this,e),i=Yo(this);s.inputNodes={};for(const{property:r,childNode:o}of i)s.inputNodes[r]=o.toJSON(e).uuid;function n(r){const o=[];for(const l in r){const c=r[l];delete c.metadata,o.push(c)}return o}if(t){const r=n(e.textures),o=n(e.images),l=n(e.nodes);r.length>0&&(s.textures=r),o.length>0&&(s.images=o),l.length>0&&(s.nodes=l)}return s}copy(e){return this.lightsNode=e.lightsNode,this.envNode=e.envNode,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.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,super.copy(e)}}let Pw=0;const Jt=new Be,sc=new ct,Cn=new N,jt=new wa,Pr=new wa,ht=new N;class ui extends un{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:Pw++}),this.uuid=Qs(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(Bm(e)?Gm:zm)(e,1):this.index=e,this}setIndirect(e){return this.indirect=e,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 Vt().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 Jt.makeRotationFromQuaternion(e),this.applyMatrix4(Jt),this}rotateX(e){return Jt.makeRotationX(e),this.applyMatrix4(Jt),this}rotateY(e){return Jt.makeRotationY(e),this.applyMatrix4(Jt),this}rotateZ(e){return Jt.makeRotationZ(e),this.applyMatrix4(Jt),this}translate(e,t,s){return Jt.makeTranslation(e,t,s),this.applyMatrix4(Jt),this}scale(e,t,s){return Jt.makeScale(e,t,s),this.applyMatrix4(Jt),this}lookAt(e){return sc.lookAt(e),sc.updateMatrix(),this.applyMatrix4(sc.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Cn).negate(),this.translate(Cn.x,Cn.y,Cn.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 r=e[i];s.push(r.x,r.y,r.z||0)}this.setAttribute("position",new Nt(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&&console.warn("THREE.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 wa);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new N(-1/0,-1/0,-1/0),new N(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];jt.setFromBufferAttribute(n),this.morphTargetsRelative?(ht.addVectors(this.boundingBox.min,jt.min),this.boundingBox.expandByPoint(ht),ht.addVectors(this.boundingBox.max,jt.max),this.boundingBox.expandByPoint(ht)):(this.boundingBox.expandByPoint(jt.min),this.boundingBox.expandByPoint(jt.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new pl);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new N,1/0);return}if(e){const s=this.boundingSphere.center;if(jt.setFromBufferAttribute(e),t)for(let n=0,r=t.length;n<r;n++){const o=t[n];Pr.setFromBufferAttribute(o),this.morphTargetsRelative?(ht.addVectors(jt.min,Pr.min),jt.expandByPoint(ht),ht.addVectors(jt.max,Pr.max),jt.expandByPoint(ht)):(jt.expandByPoint(Pr.min),jt.expandByPoint(Pr.max))}jt.getCenter(s);let i=0;for(let n=0,r=e.count;n<r;n++)ht.fromBufferAttribute(e,n),i=Math.max(i,s.distanceToSquared(ht));if(t)for(let n=0,r=t.length;n<r;n++){const o=t[n],l=this.morphTargetsRelative;for(let c=0,h=o.count;c<h;c++)ht.fromBufferAttribute(o,c),l&&(Cn.fromBufferAttribute(e,c),ht.add(Cn)),i=Math.max(i,s.distanceToSquared(ht))}this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius)&&console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){console.error("THREE.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 os(new Float32Array(4*s.count),4));const r=this.getAttribute("tangent"),o=[],l=[];for(let R=0;R<s.count;R++)o[R]=new N,l[R]=new N;const c=new N,h=new N,u=new N,d=new ce,p=new ce,f=new ce,m=new N,y=new N;function g(R,P,z){c.fromBufferAttribute(s,R),h.fromBufferAttribute(s,P),u.fromBufferAttribute(s,z),d.fromBufferAttribute(n,R),p.fromBufferAttribute(n,P),f.fromBufferAttribute(n,z),h.sub(c),u.sub(c),p.sub(d),f.sub(d);const $=1/(p.x*f.y-f.x*p.y);isFinite($)&&(m.copy(h).multiplyScalar(f.y).addScaledVector(u,-p.y).multiplyScalar($),y.copy(u).multiplyScalar(p.x).addScaledVector(h,-f.x).multiplyScalar($),o[R].add(m),o[P].add(m),o[z].add(m),l[R].add(y),l[P].add(y),l[z].add(y))}let _=this.groups;_.length===0&&(_=[{start:0,count:e.count}]);for(let R=0,P=_.length;R<P;++R){const z=_[R],$=z.start,q=z.count;for(let j=$,X=$+q;j<X;j+=3)g(e.getX(j+0),e.getX(j+1),e.getX(j+2))}const b=new N,S=new N,T=new N,M=new N;function w(R){T.fromBufferAttribute(i,R),M.copy(T);const P=o[R];b.copy(P),b.sub(T.multiplyScalar(T.dot(P))).normalize(),S.crossVectors(M,P);const $=S.dot(l[R])<0?-1:1;r.setXYZW(R,b.x,b.y,b.z,$)}for(let R=0,P=_.length;R<P;++R){const z=_[R],$=z.start,q=z.count;for(let j=$,X=$+q;j<X;j+=3)w(e.getX(j+0)),w(e.getX(j+1)),w(e.getX(j+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 os(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 N,n=new N,r=new N,o=new N,l=new N,c=new N,h=new N,u=new N;if(e)for(let d=0,p=e.count;d<p;d+=3){const f=e.getX(d+0),m=e.getX(d+1),y=e.getX(d+2);i.fromBufferAttribute(t,f),n.fromBufferAttribute(t,m),r.fromBufferAttribute(t,y),h.subVectors(r,n),u.subVectors(i,n),h.cross(u),o.fromBufferAttribute(s,f),l.fromBufferAttribute(s,m),c.fromBufferAttribute(s,y),o.add(h),l.add(h),c.add(h),s.setXYZ(f,o.x,o.y,o.z),s.setXYZ(m,l.x,l.y,l.z),s.setXYZ(y,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),r.fromBufferAttribute(t,d+2),h.subVectors(r,n),u.subVectors(i,n),h.cross(u),s.setXYZ(d+0,h.x,h.y,h.z),s.setXYZ(d+1,h.x,h.y,h.z),s.setXYZ(d+2,h.x,h.y,h.z);this.normalizeNormals(),s.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,s=e.count;t<s;t++)ht.fromBufferAttribute(e,t),ht.normalize(),e.setXYZ(t,ht.x,ht.y,ht.z)}toNonIndexed(){function e(o,l){const c=o.array,h=o.itemSize,u=o.normalized,d=new c.constructor(l.length*h);let p=0,f=0;for(let m=0,y=l.length;m<y;m++){o.isInterleavedBufferAttribute?p=l[m]*o.data.stride+o.offset:p=l[m]*h;for(let g=0;g<h;g++)d[f++]=c[p++]}return new os(d,h,u)}if(this.index===null)return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new ui,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 h=0,u=c.length;h<u;h++){const d=c[h],p=e(d,s);l.push(p)}t.morphAttributes[o]=l}t.morphTargetsRelative=this.morphTargetsRelative;const r=this.groups;for(let o=0,l=r.length;o<l;o++){const c=r[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],h=[];for(let u=0,d=c.length;u<d;u++){const p=c[u];h.push(p.toJSON(e.data))}h.length>0&&(i[l]=h,n=!0)}n&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const r=this.groups;r.length>0&&(e.data.groups=JSON.parse(JSON.stringify(r)));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 h=i[c];this.setAttribute(c,h.clone(t))}const n=e.morphAttributes;for(const c in n){const h=[],u=n[c];for(let d=0,p=u.length;d<p;d++)h.push(u[d].clone(t));this.morphAttributes[c]=h}this.morphTargetsRelative=e.morphTargetsRelative;const r=e.groups;for(let c=0,h=r.length;c<h;c++){const u=r[c];this.addGroup(u.start,u.count,u.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"})}}const Ws=new N,ic=new N,Ga=new N,gi=new N,nc=new N,Va=new N,rc=new N;class Fw{constructor(e=new N,t=new N(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,Ws)),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=Ws.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Ws.copy(this.origin).addScaledVector(this.direction,t),Ws.distanceToSquared(e))}distanceSqToSegment(e,t,s,i){ic.copy(e).add(t).multiplyScalar(.5),Ga.copy(t).sub(e).normalize(),gi.copy(this.origin).sub(ic);const n=e.distanceTo(t)*.5,r=-this.direction.dot(Ga),o=gi.dot(this.direction),l=-gi.dot(Ga),c=gi.lengthSq(),h=Math.abs(1-r*r);let u,d,p,f;if(h>0)if(u=r*l-o,d=r*o-l,f=n*h,u>=0)if(d>=-f)if(d<=f){const m=1/h;u*=m,d*=m,p=u*(u+r*d+2*o)+d*(r*u+d+2*l)+c}else d=n,u=Math.max(0,-(r*d+o)),p=-u*u+d*(d+2*l)+c;else d=-n,u=Math.max(0,-(r*d+o)),p=-u*u+d*(d+2*l)+c;else d<=-f?(u=Math.max(0,-(-r*n+o)),d=u>0?-n:Math.min(Math.max(-n,-l),n),p=-u*u+d*(d+2*l)+c):d<=f?(u=0,d=Math.min(Math.max(-n,-l),n),p=d*(d+2*l)+c):(u=Math.max(0,-(r*n+o)),d=u>0?n:Math.min(Math.max(-n,-l),n),p=-u*u+d*(d+2*l)+c);else d=r>0?-n:n,u=Math.max(0,-(r*d+o)),p=-u*u+d*(d+2*l)+c;return s&&s.copy(this.origin).addScaledVector(this.direction,u),i&&i.copy(ic).addScaledVector(Ga,d),p}intersectSphere(e,t){Ws.subVectors(e.center,this.origin);const s=Ws.dot(this.direction),i=Ws.dot(Ws)-s*s,n=e.radius*e.radius;if(i>n)return null;const r=Math.sqrt(n-i),o=s-r,l=s+r;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,r,o,l;const c=1/this.direction.x,h=1/this.direction.y,u=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),h>=0?(n=(e.min.y-d.y)*h,r=(e.max.y-d.y)*h):(n=(e.max.y-d.y)*h,r=(e.min.y-d.y)*h),s>r||n>i||((n>s||isNaN(s))&&(s=n),(r<i||isNaN(i))&&(i=r),u>=0?(o=(e.min.z-d.z)*u,l=(e.max.z-d.z)*u):(o=(e.max.z-d.z)*u,l=(e.min.z-d.z)*u),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,Ws)!==null}intersectTriangle(e,t,s,i,n){nc.subVectors(t,e),Va.subVectors(s,e),rc.crossVectors(nc,Va);let r=this.direction.dot(rc),o;if(r>0){if(i)return null;o=1}else if(r<0)o=-1,r=-r;else return null;gi.subVectors(this.origin,e);const l=o*this.direction.dot(Va.crossVectors(gi,Va));if(l<0)return null;const c=o*this.direction.dot(nc.cross(gi));if(c<0||l+c>r)return null;const h=-o*gi.dot(rc);return h<0?null:this.at(h/r,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)}}const fs=new N,$s=new N,ac=new N,js=new N,An=new N,Rn=new N,yp=new N,oc=new N,lc=new N,cc=new N,hc=new me,uc=new me,dc=new me;class Ss{constructor(e=new N,t=new N,s=new N){this.a=e,this.b=t,this.c=s}static getNormal(e,t,s,i){i.subVectors(s,t),fs.subVectors(e,t),i.cross(fs);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){fs.subVectors(i,t),$s.subVectors(s,t),ac.subVectors(e,t);const r=fs.dot(fs),o=fs.dot($s),l=fs.dot(ac),c=$s.dot($s),h=$s.dot(ac),u=r*c-o*o;if(u===0)return n.set(0,0,0),null;const d=1/u,p=(c*l-o*h)*d,f=(r*h-o*l)*d;return n.set(1-p-f,f,p)}static containsPoint(e,t,s,i){return this.getBarycoord(e,t,s,i,js)===null?!1:js.x>=0&&js.y>=0&&js.x+js.y<=1}static getInterpolation(e,t,s,i,n,r,o,l){return this.getBarycoord(e,t,s,i,js)===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,js.x),l.addScaledVector(r,js.y),l.addScaledVector(o,js.z),l)}static getInterpolatedAttribute(e,t,s,i,n,r){return hc.setScalar(0),uc.setScalar(0),dc.setScalar(0),hc.fromBufferAttribute(e,t),uc.fromBufferAttribute(e,s),dc.fromBufferAttribute(e,i),r.setScalar(0),r.addScaledVector(hc,n.x),r.addScaledVector(uc,n.y),r.addScaledVector(dc,n.z),r}static isFrontFacing(e,t,s,i){return fs.subVectors(s,t),$s.subVectors(e,t),fs.cross($s).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 fs.subVectors(this.c,this.b),$s.subVectors(this.a,this.b),fs.cross($s).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Ss.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Ss.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,s,i,n){return Ss.getInterpolation(e,this.a,this.b,this.c,t,s,i,n)}containsPoint(e){return Ss.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Ss.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 r,o;An.subVectors(i,s),Rn.subVectors(n,s),oc.subVectors(e,s);const l=An.dot(oc),c=Rn.dot(oc);if(l<=0&&c<=0)return t.copy(s);lc.subVectors(e,i);const h=An.dot(lc),u=Rn.dot(lc);if(h>=0&&u<=h)return t.copy(i);const d=l*u-h*c;if(d<=0&&l>=0&&h<=0)return r=l/(l-h),t.copy(s).addScaledVector(An,r);cc.subVectors(e,n);const p=An.dot(cc),f=Rn.dot(cc);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(Rn,o);const y=h*f-p*u;if(y<=0&&u-h>=0&&p-f>=0)return yp.subVectors(n,i),o=(u-h)/(u-h+(p-f)),t.copy(i).addScaledVector(yp,o);const g=1/(y+m+d);return r=m*g,o=d*g,t.copy(s).addScaledVector(An,r).addScaledVector(Rn,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}class Ai extends Gt{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Se(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 hs,this.combine=al,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 xp=new Be,Vi=new Fw,Ha=new pl,_p=new N,Wa=new N,$a=new N,ja=new N,pc=new N,qa=new N,bp=new N,Ya=new N;class li extends ct{constructor(e=new ui,t=new Ai){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,r=i.length;n<r;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,r=s.morphTargetsRelative;t.fromBufferAttribute(i,e);const o=this.morphTargetInfluences;if(n&&o){qa.set(0,0,0);for(let l=0,c=n.length;l<c;l++){const h=o[l],u=n[l];h!==0&&(pc.fromBufferAttribute(u,e),r?qa.addScaledVector(pc,h):qa.addScaledVector(pc.sub(t),h))}t.add(qa)}return t}raycast(e,t){const s=this.geometry,i=this.material,n=this.matrixWorld;i!==void 0&&(s.boundingSphere===null&&s.computeBoundingSphere(),Ha.copy(s.boundingSphere),Ha.applyMatrix4(n),Vi.copy(e.ray).recast(e.near),!(Ha.containsPoint(Vi.origin)===!1&&(Vi.intersectSphere(Ha,_p)===null||Vi.origin.distanceToSquared(_p)>(e.far-e.near)**2))&&(xp.copy(n).invert(),Vi.copy(e.ray).applyMatrix4(xp),!(s.boundingBox!==null&&Vi.intersectsBox(s.boundingBox)===!1)&&this._computeIntersections(e,t,Vi)))}_computeIntersections(e,t,s){let i;const n=this.geometry,r=this.material,o=n.index,l=n.attributes.position,c=n.attributes.uv,h=n.attributes.uv1,u=n.attributes.normal,d=n.groups,p=n.drawRange;if(o!==null)if(Array.isArray(r))for(let f=0,m=d.length;f<m;f++){const y=d[f],g=r[y.materialIndex],_=Math.max(y.start,p.start),b=Math.min(o.count,Math.min(y.start+y.count,p.start+p.count));for(let S=_,T=b;S<T;S+=3){const M=o.getX(S),w=o.getX(S+1),R=o.getX(S+2);i=Xa(this,g,e,s,c,h,u,M,w,R),i&&(i.faceIndex=Math.floor(S/3),i.face.materialIndex=y.materialIndex,t.push(i))}}else{const f=Math.max(0,p.start),m=Math.min(o.count,p.start+p.count);for(let y=f,g=m;y<g;y+=3){const _=o.getX(y),b=o.getX(y+1),S=o.getX(y+2);i=Xa(this,r,e,s,c,h,u,_,b,S),i&&(i.faceIndex=Math.floor(y/3),t.push(i))}}else if(l!==void 0)if(Array.isArray(r))for(let f=0,m=d.length;f<m;f++){const y=d[f],g=r[y.materialIndex],_=Math.max(y.start,p.start),b=Math.min(l.count,Math.min(y.start+y.count,p.start+p.count));for(let S=_,T=b;S<T;S+=3){const M=S,w=S+1,R=S+2;i=Xa(this,g,e,s,c,h,u,M,w,R),i&&(i.faceIndex=Math.floor(S/3),i.face.materialIndex=y.materialIndex,t.push(i))}}else{const f=Math.max(0,p.start),m=Math.min(l.count,p.start+p.count);for(let y=f,g=m;y<g;y+=3){const _=y,b=y+1,S=y+2;i=Xa(this,r,e,s,c,h,u,_,b,S),i&&(i.faceIndex=Math.floor(y/3),t.push(i))}}}}function Dw(a,e,t,s,i,n,r,o){let l;if(e.side===zt?l=s.intersectTriangle(r,n,i,!0,o):l=s.intersectTriangle(i,n,r,e.side===Ks,o),l===null)return null;Ya.copy(o),Ya.applyMatrix4(a.matrixWorld);const c=t.ray.origin.distanceTo(Ya);return c<t.near||c>t.far?null:{distance:c,point:Ya.clone(),object:a}}function Xa(a,e,t,s,i,n,r,o,l,c){a.getVertexPosition(o,Wa),a.getVertexPosition(l,$a),a.getVertexPosition(c,ja);const h=Dw(a,e,t,s,Wa,$a,ja,bp);if(h){const u=new N;Ss.getBarycoord(bp,Wa,$a,ja,u),i&&(h.uv=Ss.getInterpolatedAttribute(i,o,l,c,u,new ce)),n&&(h.uv1=Ss.getInterpolatedAttribute(n,o,l,c,u,new ce)),r&&(h.normal=Ss.getInterpolatedAttribute(r,o,l,c,u,new N),h.normal.dot(s.direction)>0&&h.normal.multiplyScalar(-1));const d={a:o,b:l,c,normal:new N,materialIndex:0};Ss.getNormal(Wa,$a,ja,d.normal),h.face=d,h.barycoord=u}return h}class Du extends au{constructor(e=-1,t=1,s=1,i=-1,n=.1,r=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=r,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,r){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=r,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,r=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,h=(this.top-this.bottom)/this.view.fullHeight/this.zoom;n+=c*this.view.offsetX,r=n+c*this.view.width,o-=h*this.view.offsetY,l=o-h*this.view.height}this.projectionMatrix.makeOrthographic(n,r,o,l,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}}const fc=new Du(-1,1,1,-1,0,1);class Ow extends ui{constructor(e=!1){super();const t=e===!1?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new Nt([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new Nt(t,2))}}const Bw=new Ow;class Ou extends li{constructor(e=null){super(Bw,e),this.camera=fc,this.isQuadMesh=!0}async renderAsync(e){return e.renderAsync(this,fc)}render(e){e.render(this,fc)}}const bl=1/6,qg=a=>pe(bl,pe(a,pe(a,a.negate().add(3)).sub(3)).add(1)),Bh=a=>pe(bl,pe(a,pe(a,pe(3,a).sub(6))).add(4)),Yg=a=>pe(bl,pe(a,pe(a,pe(-3,a).add(3)).add(3)).add(1)),Ih=a=>pe(bl,dl(a,3)),Tp=a=>qg(a).add(Bh(a)),Sp=a=>Yg(a).add(Ih(a)),vp=a=>Ft(-1,Bh(a).div(qg(a).add(Bh(a)))),wp=a=>Ft(1,Ih(a).div(Yg(a).add(Ih(a)))),Ep=(a,e,t)=>{const s=a.uvNode,i=pe(s,e.zw).add(.5),n=cn(i),r=Ii(i),o=Tp(r.x),l=Sp(r.x),c=vp(r.x),h=wp(r.x),u=vp(r.y),d=wp(r.y),p=H(n.x.add(c),n.y.add(u)).sub(.5).mul(e.xy),f=H(n.x.add(h),n.y.add(u)).sub(.5).mul(e.xy),m=H(n.x.add(c),n.y.add(d)).sub(.5).mul(e.xy),y=H(n.x.add(h),n.y.add(d)).sub(.5).mul(e.xy),g=Tp(r.y).mul(Ft(o.mul(a.sample(p).level(t)),l.mul(a.sample(f).level(t)))),_=Sp(r.y).mul(Ft(o.mul(a.sample(m).level(t)),l.mul(a.sample(y).level(t))));return g.add(_)},Iw=L(([a,e=B(3)])=>{const t=H(a.size(Ue(e))),s=H(a.size(Ue(e.add(1)))),i=Us(1,t),n=Us(1,s),r=Ep(a,re(i,t),cn(e)),o=Ep(a,re(n,s),_u(e));return Ii(e).mix(r,o)}),Fr=new hs,mc=new Be;class kt extends ae{static get type(){return"SceneNode"}constructor(e=kt.BACKGROUND_BLURRINESS,t=null){super(),this.scope=e,this.scene=t}setup(e){const t=this.scope,s=this.scene!==null?this.scene:e.scene;let i;return t===kt.BACKGROUND_BLURRINESS?i=Oe("backgroundBlurriness","float",s):t===kt.BACKGROUND_INTENSITY?i=Oe("backgroundIntensity","float",s):t===kt.BACKGROUND_ROTATION?i=J("mat4").label("backgroundRotation").setGroup(K).onRenderUpdate(()=>{const n=s.background;return n!==null&&n.isTexture&&n.mapping!==Xh?(Fr.copy(s.backgroundRotation),Fr.x*=-1,Fr.y*=-1,Fr.z*=-1,mc.makeRotationFromEuler(Fr)):mc.identity(),mc}):console.error("THREE.SceneNode: Unknown scope:",t),i}}kt.BACKGROUND_BLURRINESS="backgroundBlurriness";kt.BACKGROUND_INTENSITY="backgroundIntensity";kt.BACKGROUND_ROTATION="backgroundRotation";const Lw=V(kt,kt.BACKGROUND_BLURRINESS),Mp=V(kt,kt.BACKGROUND_INTENSITY),Uw=V(kt,kt.BACKGROUND_ROTATION),kw=L(({texture:a,uv:e})=>{const s=I().toVar();return Xe(e.x.lessThan(1e-4),()=>{s.assign(I(1,0,0))}).ElseIf(e.y.lessThan(1e-4),()=>{s.assign(I(0,1,0))}).ElseIf(e.z.lessThan(1e-4),()=>{s.assign(I(0,0,1))}).ElseIf(e.x.greaterThan(1-1e-4),()=>{s.assign(I(-1,0,0))}).ElseIf(e.y.greaterThan(1-1e-4),()=>{s.assign(I(0,-1,0))}).ElseIf(e.z.greaterThan(1-1e-4),()=>{s.assign(I(0,0,-1))}).Else(()=>{const n=a.sample(e.add(I(-.01,0,0))).r.sub(a.sample(e.add(I(.01,0,0))).r),r=a.sample(e.add(I(0,-.01,0))).r.sub(a.sample(e.add(I(0,.01,0))).r),o=a.sample(e.add(I(0,0,-.01))).r.sub(a.sample(e.add(I(0,0,.01))).r);s.assign(I(n,r,o))}),s.normalize()});class zw extends mr{static get type(){return"Texture3DNode"}constructor(e,t=null,s=null){super(e,t,s),this.isTexture3DNode=!0}getInputType(){return"texture3D"}getDefaultUV(){return I(.5,.5,.5)}setUpdateMatrix(){}setupUV(e,t){const s=this.value;return e.isFlipY()&&(s.isRenderTargetTexture===!0||s.isFramebufferTexture===!0)&&(this.sampler?t=t.flipY():t=t.setY(Ue(sr(this,this.levelNode).y).sub(t.y).sub(1))),t}generateUV(e,t){return t.build(e,"vec3")}normal(e){return kw({texture:this,uv:e})}}const Gw=U(zw).setParameterLength(1,3),Za=new ce;class Vw extends mr{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.setUpdateMatrix(!1)}setup(e){return e.object.isQuadMesh&&this.passNode.build(e),super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class Cp extends Vw{static get type(){return"PassMultipleTextureNode"}constructor(e,t,s=!1){super(e,null),this.textureName=t,this.previousTexture=s}updateTexture(){this.value=this.previousTexture?this.passNode.getPreviousTexture(this.textureName):this.passNode.getTexture(this.textureName)}setup(e){return this.updateTexture(),super.setup(e)}clone(){return new this.constructor(this.passNode,this.textureName,this.previousTexture)}}class Tl extends st{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 Is;n.isRenderTargetTexture=!0,n.name="depth";const r=new dn(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:ns,...i});r.texture.name="output",r.depthTexture=n,this.renderTarget=r,this._textures={output:r.texture,depth:n},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=J(0),this._cameraFar=J(0),this._mrt=null,this._layers=null,this._resolution=1,this.isPassNode=!0,this.updateBeforeType=he.FRAME,this.global=!0}setResolution(e){return this._resolution=e,this}getResolution(){return this._resolution}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=k(new Cp(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=k(new Cp(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=Lg(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=ca(n,s,i)}return t}setup({renderer:e}){return this.renderTarget.samples=this.options.samples===void 0?e.samples:this.options.samples,e.backend.isWebGLBackend===!0&&(this.renderTarget.samples=0),this.renderTarget.texture.type=e.getColorBufferType(),this.scope===Tl.COLOR?this.getTextureNode():this.getLinearDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:s}=this;let i,n;const r=t.getOutputRenderTarget();r&&r.isXRRenderTarget===!0?(n=1,i=t.xr.getCamera(),t.xr.updateCamera(i),Za.set(r.width,r.height)):(i=this.camera,n=t.getPixelRatio(),t.getSize(Za)),this._pixelRatio=n,this.setSize(Za.width,Za.height);const o=t.getRenderTarget(),l=t.getMRT(),c=i.layers.mask;this._cameraNear.value=i.near,this._cameraFar.value=i.far,this._layers!==null&&(i.layers.mask=this._layers.mask);for(const h in this._previousTextures)this.toggleTexture(h);t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.render(s,i),t.setRenderTarget(o),t.setMRT(l),i.layers.mask=c}setSize(e,t){this._width=e,this._height=t;const s=this._width*this._pixelRatio*this._resolution,i=this._height*this._pixelRatio*this._resolution;this.renderTarget.setSize(s,i)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}Tl.COLOR="color";Tl.DEPTH="depth";const Hw=L(([a,e])=>a.mul(e).clamp()).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),Ww=L(([a,e])=>(a=a.mul(e),a.div(a.add(1)).clamp())).setLayout({name:"reinhardToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),$w=L(([a,e])=>{a=a.mul(e),a=a.sub(.004).max(0);const t=a.mul(a.mul(6.2).add(.5)),s=a.mul(a.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"}]}),jw=L(([a])=>{const e=a.mul(a.add(.0245786)).sub(90537e-9),t=a.mul(a.add(.432951).mul(.983729)).add(.238081);return e.div(t)}),qw=L(([a,e])=>{const t=Pt(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),s=Pt(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return a=a.mul(e).div(.6),a=t.mul(a),a=jw(a),a=s.mul(a),a.clamp()}).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),Yw=Pt(I(1.6605,-.1246,-.0182),I(-.5876,1.1329,-.1006),I(-.0728,-.0083,1.1187)),Xw=Pt(I(.6274,.0691,.0164),I(.3293,.9195,.088),I(.0433,.0113,.8956)),Zw=L(([a])=>{const e=I(a).toVar(),t=I(e.mul(e)).toVar(),s=I(t.mul(t)).toVar();return B(15.5).mul(s.mul(t)).sub(pe(40.14,s.mul(e))).add(pe(31.96,s).sub(pe(6.868,t.mul(e))).add(pe(.4298,t).add(pe(.1191,e).sub(.00232))))}),Qw=L(([a,e])=>{const t=I(a).toVar(),s=Pt(I(.856627153315983,.137318972929847,.11189821299995),I(.0951212405381588,.761241990602591,.0767994186031903),I(.0482516061458583,.101439036467562,.811302368396859)),i=Pt(I(1.1271005818144368,-.1413297634984383,-.14132976349843826),I(-.11060664309660323,1.157823702216272,-.11060664309660294),I(-.016493938717834573,-.016493938717834257,1.2519364065950405)),n=B(-12.47393),r=B(4.026069);return t.mulAssign(e),t.assign(Xw.mul(t)),t.assign(s.mul(t)),t.assign(St(t,1e-10)),t.assign(ii(t)),t.assign(t.sub(n).div(r.sub(n))),t.assign(oi(t,0,1)),t.assign(Zw(t)),t.assign(i.mul(t)),t.assign(dl(St(I(0),t),I(2.2))),t.assign(Yw.mul(t)),t.assign(oi(t,0,1)),t}).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),Kw=L(([a,e])=>{const t=B(.76),s=B(.15);a=a.mul(e);const i=cr(a.r,cr(a.g,a.b)),n=bt(i.lessThan(.08),i.sub(pe(6.25,i.mul(i))),.04);a.subAssign(n);const r=St(a.r,St(a.g,a.b));Xe(r.lessThan(t),()=>a);const o=Ct(1,t),l=Ct(1,o.mul(o).div(r.add(o.sub(t))));a.mulAssign(l.div(r));const c=Ct(1,Us(1,s.mul(r.sub(l)).add(1)));return ze(a,I(l),c)}).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class ot extends ae{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}}class Jw extends ot{static get type(){return"FunctionNode"}constructor(e="",t=[],s=""){super(e,t,s)}getNodeType(e){return this.getNodeFunction(e).type}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,r=e.getCodeFromNode(this,n);i!==""&&(r.name=i);const o=e.getPropertyName(r),l=this.getNodeFunction(e).getCode(o);return r.code=l+`
|
74
|
+
`,t==="property"?o:e.format(`${o}()`,n,t)}}function Xg(a){let e;const t=a.context.getViewZ;return t!==void 0&&(e=t(this)),(e||et.z).negate()}const eE=L(([a,e],t)=>{const s=Xg(t);return Di(a,e,s)}),tE=L(([a],e)=>{const t=Xg(e);return a.mul(a,t,t).negate().exp().oneMinus()}),Ap=L(([a,e])=>re(e.toFloat().mix(oa.rgb,a.toVec3()),oa.a));class sE extends ae{constructor(e){super(),this.scope=e}generate(e){const{scope:t}=this,{renderer:s}=e;s.backend.isWebGLBackend===!0?e.addFlowCode(` // ${t}Barrier
|
75
|
+
`):e.addLineFlowCode(`${t}Barrier()`,this)}}U(sE);class Gs extends ae{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),r=this.getInputType(e),o=this.pointerNode,l=this.valueNode,c=[];c.push(`&${o.build(e,r)}`),l!==null&&c.push(l.build(e,r));const h=`${e.getMethod(i,n)}( ${c.join(", ")} )`;if(s.length===1&&s[0].isStackNode===!0)e.addLineFlowCode(h,this);else return t.constNode===void 0&&(t.constNode=hr(h,n).toConst()),t.constNode.build(e)}}Gs.ATOMIC_LOAD="atomicLoad";Gs.ATOMIC_STORE="atomicStore";Gs.ATOMIC_ADD="atomicAdd";Gs.ATOMIC_SUB="atomicSub";Gs.ATOMIC_MAX="atomicMax";Gs.ATOMIC_MIN="atomicMin";Gs.ATOMIC_AND="atomicAnd";Gs.ATOMIC_OR="atomicOr";Gs.ATOMIC_XOR="atomicXor";U(Gs);let Qa;function Sl(a){Qa=Qa||new WeakMap;let e=Qa.get(a);return e===void 0&&Qa.set(a,e={}),e}function Zg(a){const e=Sl(a);return e.shadowMatrix||(e.shadowMatrix=J("mat4").setGroup(K).onRenderUpdate(t=>((a.castShadow!==!0||t.renderer.shadowMap.enabled===!1)&&a.shadow.updateMatrices(a),a.shadow.matrix)))}function iE(a,e=_a){const t=Zg(a).mul(e);return t.xyz.div(t.w)}function Qg(a){const e=Sl(a);return e.position||(e.position=J(new N).setGroup(K).onRenderUpdate((t,s)=>s.value.setFromMatrixPosition(a.matrixWorld)))}function nE(a){const e=Sl(a);return e.targetPosition||(e.targetPosition=J(new N).setGroup(K).onRenderUpdate((t,s)=>s.value.setFromMatrixPosition(a.target.matrixWorld)))}function Kg(a){const e=Sl(a);return e.viewPosition||(e.viewPosition=J(new N).setGroup(K).onRenderUpdate(({camera:t},s)=>{s.value=s.value||new N,s.value.setFromMatrixPosition(a.matrixWorld),s.value.applyMatrix4(t.matrixWorldInverse)}))}const Jg=a=>hi.transformDirection(Qg(a).sub(nE(a))),rE=a=>a.sort((e,t)=>e.id-t.id),aE=(a,e)=>{for(const t of e)if(t.isAnalyticLightNode&&t.light.id===a)return t;return null},gc=new WeakMap,Dr=[];class ey extends ae{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=I().toVar(),this.totalSpecularNode=I().toVar(),this.outgoingLightNode=I().toVar(),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(Dr.push(i.id),Dr.push(i.castShadow?1:0),i.isSpotLight===!0){const n=i.map!==null?i.map.id:-1,r=i.colorNode?i.colorNode.getCacheKey():-1;Dr.push(n,r)}}const t=nu(Dr);return Dr.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.getSelf().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=rE(this._lights),n=e.renderer.library;for(const r of i)if(r.isNode)t.push(k(r));else{let o=null;if(s!==null&&(o=aE(r.id,s)),o===null){const l=n.getLightNodeClass(r.constructor);if(l===null){console.warn(`LightsNode.setupNodeLights: Light node not found for ${r.constructor.name}`);continue}let c=null;gc.has(r)?c=gc.get(r):(c=k(new l(r)),gc.set(r,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,r=e.getNodeProperties(this);if(n){const{totalDiffuseNode:o,totalSpecularNode:l}=this;i.outgoingLight=s;const c=e.addStack();r.nodes=c.nodes,n.start(e);const{backdrop:h,backdropAlpha:u}=i,{directDiffuse:d,directSpecular:p,indirectDiffuse:f,indirectSpecular:m}=i.reflectedLight;let y=d.add(f);h!==null&&(u!==null?y=I(u.mix(y,h)):y=I(h),i.material.transparent=!0),o.assign(y),l.assign(p.add(m)),s.assign(o.add(l)),n.finish(e),s=s.bypass(e.removeStack())}else r.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}}class oE extends ae{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=he.RENDER,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){ty.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||_a)}}const ty=eg("vec3","shadowPositionWorld");function lE(a,e={}){return e.toneMapping=a.toneMapping,e.toneMappingExposure=a.toneMappingExposure,e.outputColorSpace=a.outputColorSpace,e.renderTarget=a.getRenderTarget(),e.activeCubeFace=a.getActiveCubeFace(),e.activeMipmapLevel=a.getActiveMipmapLevel(),e.renderObjectFunction=a.getRenderObjectFunction(),e.pixelRatio=a.getPixelRatio(),e.mrt=a.getMRT(),e.clearColor=a.getClearColor(e.clearColor||new Se),e.clearAlpha=a.getClearAlpha(),e.autoClear=a.autoClear,e.scissorTest=a.getScissorTest(),e}function cE(a,e){return e=lE(a,e),a.setMRT(null),a.setRenderObjectFunction(null),a.setClearColor(0,1),a.autoClear=!0,e}function hE(a,e){a.toneMapping=e.toneMapping,a.toneMappingExposure=e.toneMappingExposure,a.outputColorSpace=e.outputColorSpace,a.setRenderTarget(e.renderTarget,e.activeCubeFace,e.activeMipmapLevel),a.setRenderObjectFunction(e.renderObjectFunction),a.setPixelRatio(e.pixelRatio),a.setMRT(e.mrt),a.setClearColor(e.clearColor,e.clearAlpha),a.autoClear=e.autoClear,a.setScissorTest(e.scissorTest)}function uE(a,e={}){return e.background=a.background,e.backgroundNode=a.backgroundNode,e.overrideMaterial=a.overrideMaterial,e}function dE(a,e){return e=uE(a,e),a.background=null,a.backgroundNode=null,a.overrideMaterial=null,e}function pE(a,e){a.background=e.background,a.backgroundNode=e.backgroundNode,a.overrideMaterial=e.overrideMaterial}function fE(a,e,t){return t=cE(a,t),t=dE(e,t),t}function mE(a,e,t){hE(a,t),pE(e,t)}const Rp=new WeakMap,gE=L(({depthTexture:a,shadowCoord:e,depthLayer:t})=>{let s=xe(a,e.xy).label("t_basic");return a.isArrayTexture&&(s=s.depth(t)),s.compare(e.z)}),yE=L(({depthTexture:a,shadowCoord:e,shadow:t,depthLayer:s})=>{const i=(y,g)=>{let _=xe(a,y);return a.isArrayTexture&&(_=_.depth(s)),_.compare(g)},n=Oe("mapSize","vec2",t).setGroup(K),r=Oe("radius","float",t).setGroup(K),o=H(1).div(n),l=o.x.negate().mul(r),c=o.y.negate().mul(r),h=o.x.mul(r),u=o.y.mul(r),d=l.div(2),p=c.div(2),f=h.div(2),m=u.div(2);return Ft(i(e.xy.add(H(l,c)),e.z),i(e.xy.add(H(0,c)),e.z),i(e.xy.add(H(h,c)),e.z),i(e.xy.add(H(d,p)),e.z),i(e.xy.add(H(0,p)),e.z),i(e.xy.add(H(f,p)),e.z),i(e.xy.add(H(l,0)),e.z),i(e.xy.add(H(d,0)),e.z),i(e.xy,e.z),i(e.xy.add(H(f,0)),e.z),i(e.xy.add(H(h,0)),e.z),i(e.xy.add(H(d,m)),e.z),i(e.xy.add(H(0,m)),e.z),i(e.xy.add(H(f,m)),e.z),i(e.xy.add(H(l,u)),e.z),i(e.xy.add(H(0,u)),e.z),i(e.xy.add(H(h,u)),e.z)).mul(1/17)}),xE=L(({depthTexture:a,shadowCoord:e,shadow:t,depthLayer:s})=>{const i=(u,d)=>{let p=xe(a,u);return a.isArrayTexture&&(p=p.depth(s)),p.compare(d)},n=Oe("mapSize","vec2",t).setGroup(K),r=H(1).div(n),o=r.x,l=r.y,c=e.xy,h=Ii(c.mul(n).add(.5));return c.subAssign(h.mul(r)),Ft(i(c,e.z),i(c.add(H(o,0)),e.z),i(c.add(H(0,l)),e.z),i(c.add(r),e.z),ze(i(c.add(H(o.negate(),0)),e.z),i(c.add(H(o.mul(2),0)),e.z),h.x),ze(i(c.add(H(o.negate(),l)),e.z),i(c.add(H(o.mul(2),l)),e.z),h.x),ze(i(c.add(H(0,l.negate())),e.z),i(c.add(H(0,l.mul(2))),e.z),h.y),ze(i(c.add(H(o,l.negate())),e.z),i(c.add(H(o,l.mul(2))),e.z),h.y),ze(ze(i(c.add(H(o.negate(),l.negate())),e.z),i(c.add(H(o.mul(2),l.negate())),e.z),h.x),ze(i(c.add(H(o.negate(),l.mul(2))),e.z),i(c.add(H(o.mul(2),l.mul(2))),e.z),h.x),h.y)).mul(1/9)}),_E=L(({depthTexture:a,shadowCoord:e,depthLayer:t})=>{const s=B(1).toVar();let i=xe(a).sample(e.xy);a.isArrayTexture&&(i=i.depth(t)),i=i.rg;const n=fg(e.z,i.x);return Xe(n.notEqual(B(1)),()=>{const r=e.z.sub(i.x),o=St(0,i.y.mul(i.y));let l=o.div(o.add(r.mul(r)));l=oi(Ct(l,.3).div(.95-.3)),s.assign(oi(St(n,l)))}),s}),bE=L(([a,e,t])=>{let s=_a.sub(a).length();return s=s.sub(e).div(t.sub(e)),s=s.saturate(),s}),TE=a=>{const e=a.shadow.camera,t=Oe("near","float",e).setGroup(K),s=Oe("far","float",e).setGroup(K),i=OS(a);return bE(i,t,s)},SE=a=>{let e=Rp.get(a);if(e===void 0){const t=a.isPointLight?TE(a):null;e=new tt,e.colorNode=re(0,0,0,1),e.depthNode=t,e.isShadowPassMaterial=!0,e.name="ShadowMaterial",e.fog=!1,Rp.set(a,e)}return e},Np=new vs,Nn=[],vE=(a,e,t,s)=>{Nn[0]=a,Nn[1]=e;let i=Np.get(Nn);return(i===void 0||i.shadowType!==t||i.useVelocity!==s)&&(i=(n,r,o,l,c,h,...u)=>{(n.castShadow===!0||n.receiveShadow&&t===wo)&&(s&&(km(n).useVelocity=!0),n.onBeforeShadow(a,n,o,e.camera,l,r.overrideMaterial,h),a.renderObject(n,r,o,l,c,h,...u),n.onAfterShadow(a,n,o,e.camera,l,r.overrideMaterial,h))},i.shadowType=t,i.useVelocity=s,Np.set(Nn,i)),Nn[0]=null,Nn[1]=null,i},wE=L(({samples:a,radius:e,size:t,shadowPass:s,depthLayer:i})=>{const n=B(0).toVar("meanVertical"),r=B(0).toVar("squareMeanVertical"),o=a.lessThanEqual(B(1)).select(B(0),B(2).div(a.sub(1))),l=a.lessThanEqual(B(1)).select(B(0),B(-1));Ts({start:Ue(0),end:Ue(a),type:"int",condition:"<"},({i:h})=>{const u=l.add(B(h).mul(o));let d=s.sample(Ft(xl.xy,H(0,u).mul(e)).div(t));s.value.isArrayTexture&&(d=d.depth(i)),d=d.x,n.addAssign(d),r.addAssign(d.mul(d))}),n.divAssign(a),r.divAssign(a);const c=xu(r.sub(n.mul(n)));return H(n,c)}),EE=L(({samples:a,radius:e,size:t,shadowPass:s,depthLayer:i})=>{const n=B(0).toVar("meanHorizontal"),r=B(0).toVar("squareMeanHorizontal"),o=a.lessThanEqual(B(1)).select(B(0),B(2).div(a.sub(1))),l=a.lessThanEqual(B(1)).select(B(0),B(-1));Ts({start:Ue(0),end:Ue(a),type:"int",condition:"<"},({i:h})=>{const u=l.add(B(h).mul(o));let d=s.sample(Ft(xl.xy,H(u,0).mul(e)).div(t));s.value.isArrayTexture&&(d=d.depth(i)),n.addAssign(d.x),r.addAssign(Ft(d.y.mul(d.y),d.x.mul(d.x)))}),n.divAssign(a),r.divAssign(a);const c=xu(r.sub(n.mul(n)));return H(n,c)}),ME=[gE,yE,xE,_E];let yc;const Ka=new Ou;class sy extends oE{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._cameraFrameId=new WeakMap,this.isShadowNode=!0,this.depthLayer=0}setupShadowFilter(e,{filterFn:t,depthTexture:s,shadowCoord:i,shadow:n,depthLayer:r}){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:r});return o.select(l,B(1))}setupShadowCoord(e,t){const{shadow:s}=this,{renderer:i}=e,n=Oe("bias","float",s).setGroup(K);let r=t,o;if(s.camera.isOrthographicCamera||i.logarithmicDepthBuffer!==!0)r=r.xyz.div(r.w),o=r.z,i.coordinateSystem===Fi&&(o=o.mul(2).sub(1));else{const l=r.w;r=r.xy.div(l);const c=Oe("near","float",s.camera).setGroup(K),h=Oe("far","float",s.camera).setGroup(K);o=Ug(l.negate(),c,h)}return r=I(r.x,r.y.oneMinus(),o.add(n)),r}getShadowFilterFn(e){return ME[e]}setupRenderTarget(e,t){const s=new Is(e.mapSize.width,e.mapSize.height);s.name="ShadowDepthTexture",s.compareFunction=iu;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}=e,{light:s,shadow:i}=this,n=t.shadowMap.type,{depthTexture:r,shadowMap:o}=this.setupRenderTarget(i,e);if(i.camera.updateProjectionMatrix(),n===wo&&i.isPointLightShadow!==!0){r.compareFunction=null,o.depth>1?(o._vsmShadowMapVertical||(o._vsmShadowMapVertical=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:on,type:ns,depth:o.depth,depthBuffer:!1}),o._vsmShadowMapVertical.texture.name="VSMVertical"),this.vsmShadowMapVertical=o._vsmShadowMapVertical,o._vsmShadowMapHorizontal||(o._vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:on,type:ns,depth:o.depth,depthBuffer:!1}),o._vsmShadowMapHorizontal.texture.name="VSMHorizontal"),this.vsmShadowMapHorizontal=o._vsmShadowMapHorizontal):(this.vsmShadowMapVertical=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:on,type:ns,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:on,type:ns,depthBuffer:!1}));let g=xe(r);r.isArrayTexture&&(g=g.depth(this.depthLayer));let _=xe(this.vsmShadowMapVertical.texture);r.isArrayTexture&&(_=_.depth(this.depthLayer));const b=Oe("blurSamples","float",i).setGroup(K),S=Oe("radius","float",i).setGroup(K),T=Oe("mapSize","vec2",i).setGroup(K);let M=this.vsmMaterialVertical||(this.vsmMaterialVertical=new tt);M.fragmentNode=wE({samples:b,radius:S,size:T,shadowPass:g,depthLayer:this.depthLayer}).context(e.getSharedContext()),M.name="VSMVertical",M=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new tt),M.fragmentNode=EE({samples:b,radius:S,size:T,shadowPass:_,depthLayer:this.depthLayer}).context(e.getSharedContext()),M.name="VSMHorizontal"}const l=Oe("intensity","float",i).setGroup(K),c=Oe("normalBias","float",i).setGroup(K),h=Zg(s).mul(ty.add(Nu.mul(c))),u=this.setupShadowCoord(e,h),d=i.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(d===null)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const p=n===wo&&i.isPointLightShadow!==!0?this.vsmShadowMapHorizontal.texture:r,f=this.setupShadowFilter(e,{filterFn:d,shadowTexture:o.texture,depthTexture:p,shadowCoord:u,shadow:i,depthLayer:this.depthLayer});let m=xe(o.texture,u);r.isArrayTexture&&(m=m.depth(this.depthLayer));const y=ze(1,f.rgb.mix(m,1),l.mul(m.a)).toVar();return this.shadowMap=o,this.shadow.map=o,y}setup(e){if(e.renderer.shadowMap.enabled!==!1)return L(()=>{let t=this._node;return this.setupShadowPosition(e),t===null&&(this._node=t=this.setupShadow(e)),e.material.shadowNode&&console.warn('THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.'),e.material.receivedShadowNode&&(t=e.material.receivedShadowNode(t)),t})()}renderShadow(e){const{shadow:t,shadowMap:s,light:i}=this,{renderer:n,scene:r}=e;t.updateMatrices(i),s.setSize(t.mapSize.width,t.mapSize.height,s.depth),n.render(r,t.camera)}updateShadow(e){const{shadowMap:t,light:s,shadow:i}=this,{renderer:n,scene:r,camera:o}=e,l=n.shadowMap.type,c=t.depthTexture.version;this._depthVersionCached=c;const h=i.camera.layers.mask;(i.camera.layers.mask&4294967294)===0&&(i.camera.layers.mask=o.layers.mask);const u=n.getRenderObjectFunction(),d=n.getMRT(),p=d?d.has("velocity"):!1;yc=fE(n,r,yc),r.overrideMaterial=SE(s),n.setRenderObjectFunction(vE(n,i,l,p)),n.setClearColor(0,0),n.setRenderTarget(t),this.renderShadow(e),n.setRenderObjectFunction(u),l===wo&&i.isPointLightShadow!==!0&&this.vsmPass(n),i.camera.layers.mask=h,mE(n,r,yc)}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),Ka.material=this.vsmMaterialVertical,Ka.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),Ka.material=this.vsmMaterialHorizontal,Ka.render(e)}dispose(){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),super.dispose()}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 CE=(a,e)=>k(new sy(a,e)),AE=new Se,Ps=L(([a,e])=>{const t=a.toVar(),s=is(t),i=Us(1,St(s.x,St(s.y,s.z)));s.mulAssign(i),t.mulAssign(i.mul(e.mul(2).oneMinus()));const n=H(t.xy).toVar(),o=e.mul(1.5).oneMinus();return Xe(s.z.greaterThanEqual(o),()=>{Xe(t.z.greaterThan(0),()=>{n.x.assign(Ct(4,t.x))})}).ElseIf(s.x.greaterThanEqual(o),()=>{const l=tl(t.x);n.x.assign(t.z.mul(l).add(l.mul(2)))}).ElseIf(s.y.greaterThanEqual(o),()=>{const l=tl(t.y);n.x.assign(t.x.add(l.mul(2)).add(2)),n.y.assign(t.z.mul(l).sub(2))}),H(.125,.25).mul(n).add(H(.375,.75)).flipY()}).setLayout({name:"cubeToUV",type:"vec2",inputs:[{name:"pos",type:"vec3"},{name:"texelSizeY",type:"float"}]}),RE=L(({depthTexture:a,bd3D:e,dp:t,texelSize:s})=>xe(a,Ps(e,s.y)).compare(t)),NE=L(({depthTexture:a,bd3D:e,dp:t,texelSize:s,shadow:i})=>{const n=Oe("radius","float",i).setGroup(K),r=H(-1,1).mul(n).mul(s.y);return xe(a,Ps(e.add(r.xyy),s.y)).compare(t).add(xe(a,Ps(e.add(r.yyy),s.y)).compare(t)).add(xe(a,Ps(e.add(r.xyx),s.y)).compare(t)).add(xe(a,Ps(e.add(r.yyx),s.y)).compare(t)).add(xe(a,Ps(e,s.y)).compare(t)).add(xe(a,Ps(e.add(r.xxy),s.y)).compare(t)).add(xe(a,Ps(e.add(r.yxy),s.y)).compare(t)).add(xe(a,Ps(e.add(r.xxx),s.y)).compare(t)).add(xe(a,Ps(e.add(r.yxx),s.y)).compare(t)).mul(1/9)}),PE=L(({filterFn:a,depthTexture:e,shadowCoord:t,shadow:s})=>{const i=t.xyz.toVar(),n=i.length(),r=J("float").setGroup(K).onRenderUpdate(()=>s.camera.near),o=J("float").setGroup(K).onRenderUpdate(()=>s.camera.far),l=Oe("bias","float",s).setGroup(K),c=J(s.mapSize).setGroup(K),h=B(1).toVar();return Xe(n.sub(o).lessThanEqual(0).and(n.sub(r).greaterThanEqual(0)),()=>{const u=n.sub(r).div(o.sub(r)).toVar();u.addAssign(l);const d=i.normalize(),p=H(1).div(c.mul(H(4,2)));h.assign(a({depthTexture:e,bd3D:d,dp:u,texelSize:p,shadow:s}))}),h}),Pp=new me,Pn=new ce,Or=new ce;class FE extends sy{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return e===Hx?RE:NE}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,shadowTexture:s,depthTexture:i,shadowCoord:n,shadow:r}){return PE({filterFn:t,shadowTexture:s,depthTexture:i,shadowCoord:n,shadow:r})}renderShadow(e){const{shadow:t,shadowMap:s,light:i}=this,{renderer:n,scene:r}=e,o=t.getFrameExtents();Or.copy(t.mapSize),Or.multiply(o),s.setSize(Or.width,Or.height),Pn.copy(t.mapSize);const l=n.autoClear,c=n.getClearColor(AE),h=n.getClearAlpha();n.autoClear=!1,n.setClearColor(t.clearColor,t.clearAlpha),n.clear();const u=t.getViewportCount();for(let d=0;d<u;d++){const p=t.getViewport(d),f=Pn.x*p.x,m=Or.y-Pn.y-Pn.y*p.y;Pp.set(f,m,Pn.x*p.z,Pn.y*p.w),s.viewport.copy(Pp),t.updateMatrices(i,d),n.render(r,t.camera)}n.autoClear=l,n.setClearColor(c,h)}}const DE=(a,e)=>k(new FE(a,e));class pn extends gr{static get type(){return"AnalyticLightNode"}constructor(e=null){super(),this.light=e,this.color=new Se,this.colorNode=e&&e.colorNode||J(this.color).setGroup(K),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=he.FRAME}getHash(){return this.light.uuid}getLightVector(e){return Kg(this.light).sub(e.context.positionView||et)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return CE(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=k(i):n=this.setupShadowNode(),this.shadowNode=n,this.shadowColorNode=s=this.colorNode.mul(n),this.baseColorNode=this.colorNode}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 iy=L(({lightDistance:a,cutoffDistance:e,decayExponent:t})=>{const s=a.pow(t).max(.01).reciprocal();return e.greaterThan(0).select(s.mul(a.div(e).pow4().oneMinus().clamp().pow2()),s)}),OE=({color:a,lightVector:e,cutoffDistance:t,decayExponent:s})=>{const i=e.normalize(),n=e.length(),r=iy({lightDistance:n,cutoffDistance:t,decayExponent:s}),o=a.mul(r);return{lightDirection:i,lightColor:o}};class BE extends pn{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=J(0).setGroup(K),this.decayExponentNode=J(2).setGroup(K)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return DE(this.light)}setupDirect(e){return OE({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}const Fp=B(1),Lh=B(-2),Ja=B(.8),xc=B(-1),eo=B(.4),_c=B(2),to=B(.305),bc=B(3),Dp=B(.21),IE=B(4),Op=B(4),LE=B(16),UE=L(([a])=>{const e=I(is(a)).toVar(),t=B(-1).toVar();return Xe(e.x.greaterThan(e.z),()=>{Xe(e.x.greaterThan(e.y),()=>{t.assign(bt(a.x.greaterThan(0),0,3))}).Else(()=>{t.assign(bt(a.y.greaterThan(0),1,4))})}).Else(()=>{Xe(e.z.greaterThan(e.y),()=>{t.assign(bt(a.z.greaterThan(0),2,5))}).Else(()=>{t.assign(bt(a.y.greaterThan(0),1,4))})}),t}).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),kE=L(([a,e])=>{const t=H().toVar();return Xe(e.equal(0),()=>{t.assign(H(a.z,a.y).div(is(a.x)))}).ElseIf(e.equal(1),()=>{t.assign(H(a.x.negate(),a.z.negate()).div(is(a.y)))}).ElseIf(e.equal(2),()=>{t.assign(H(a.x.negate(),a.y).div(is(a.z)))}).ElseIf(e.equal(3),()=>{t.assign(H(a.z.negate(),a.y).div(is(a.x)))}).ElseIf(e.equal(4),()=>{t.assign(H(a.x.negate(),a.z).div(is(a.y)))}).Else(()=>{t.assign(H(a.x,a.y).div(is(a.z)))}),pe(.5,t.add(1))}).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),zE=L(([a])=>{const e=B(0).toVar();return Xe(a.greaterThanEqual(Ja),()=>{e.assign(Fp.sub(a).mul(xc.sub(Lh)).div(Fp.sub(Ja)).add(Lh))}).ElseIf(a.greaterThanEqual(eo),()=>{e.assign(Ja.sub(a).mul(_c.sub(xc)).div(Ja.sub(eo)).add(xc))}).ElseIf(a.greaterThanEqual(to),()=>{e.assign(eo.sub(a).mul(bc.sub(_c)).div(eo.sub(to)).add(_c))}).ElseIf(a.greaterThanEqual(Dp),()=>{e.assign(to.sub(a).mul(IE.sub(bc)).div(to.sub(Dp)).add(bc))}).Else(()=>{e.assign(B(-2).mul(ii(pe(1.16,a))))}),e}).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),GE=L(([a,e])=>{const t=a.toVar();t.assign(pe(2,t).sub(1));const s=I(t,1).toVar();return Xe(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"}]}),VE=L(([a,e,t,s,i,n])=>{const r=B(t),o=I(e),l=oi(zE(r),Lh,n),c=Ii(l),h=cn(l),u=I(Uh(a,o,h,s,i,n)).toVar();return Xe(c.notEqual(0),()=>{const d=I(Uh(a,o,h.add(1),s,i,n)).toVar();u.assign(ze(u,d,c))}),u}),Uh=L(([a,e,t,s,i,n])=>{const r=B(t).toVar(),o=I(e),l=B(UE(o)).toVar(),c=B(St(Op.sub(r),0)).toVar();r.assign(St(r,Op));const h=B(ya(r)).toVar(),u=H(kE(o,l).mul(h.sub(2)).add(1)).toVar();return Xe(l.greaterThan(2),()=>{u.y.addAssign(h),l.subAssign(3)}),u.x.addAssign(l.mul(h)),u.x.addAssign(c.mul(pe(3,LE))),u.y.addAssign(pe(4,ya(n).sub(h))),u.x.mulAssign(s),u.y.mulAssign(i),a.sample(u).grad(H(),H())}),Tc=L(({envMap:a,mipInt:e,outputDirection:t,theta:s,axis:i,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:r,CUBEUV_MAX_MIP:o})=>{const l=wi(s),c=t.mul(l).add(i.cross(t).mul(_s(s))).add(i.mul(i.dot(t).mul(l.oneMinus())));return Uh(a,c,e,n,r,o)}),HE=L(({n:a,latitudinal:e,poleAxis:t,outputDirection:s,weights:i,samples:n,dTheta:r,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:h,CUBEUV_MAX_MIP:u})=>{const d=I(bt(e,t,mg(t,s))).toVar();Xe(d.equal(I(0)),()=>{d.assign(I(s.z,0,s.x.negate()))}),d.assign(xa(d));const p=I().toVar();return p.addAssign(i.element(0).mul(Tc({theta:0,axis:d,outputDirection:s,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:h,CUBEUV_MAX_MIP:u}))),Ts({start:Ue(1),end:a},({i:f})=>{Xe(f.greaterThanEqual(n),()=>{FS()});const m=B(r.mul(B(f))).toVar();p.addAssign(i.element(f).mul(Tc({theta:m.mul(-1),axis:d,outputDirection:s,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:h,CUBEUV_MAX_MIP:u}))),p.addAssign(i.element(f).mul(Tc({theta:m,axis:d,outputDirection:s,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:h,CUBEUV_MAX_MIP:u})))}),re(p,1)}),yi=new N,Bp=new ce,Ip=new ce;class Xt extends au{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=nr*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(ia*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return nr*2*Math.atan(Math.tan(ia*.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){yi.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(yi.x,yi.y).multiplyScalar(-e/yi.z),yi.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),s.set(yi.x,yi.y).multiplyScalar(-e/yi.z)}getViewSize(e,t){return this.getViewBounds(e,Bp,Ip),t.subVectors(Ip,Bp)}setViewOffset(e,t,s,i,n,r){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=r,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(ia*.5*this.fov)/this.zoom,s=2*t,i=this.aspect*s,n=-.5*i;const r=this.view;if(this.view!==null&&this.view.enabled){const l=r.fullWidth,c=r.fullHeight;n+=r.offsetX*i/l,t-=r.offsetY*s/c,i*=r.width/l,s*=r.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.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 Ma extends ui{constructor(e=1,t=1,s=1,i=1,n=1,r=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:s,widthSegments:i,heightSegments:n,depthSegments:r};const o=this;i=Math.floor(i),n=Math.floor(n),r=Math.floor(r);const l=[],c=[],h=[],u=[];let d=0,p=0;f("z","y","x",-1,-1,s,t,e,r,n,0),f("z","y","x",1,-1,s,t,-e,r,n,1),f("x","z","y",1,1,e,s,t,i,r,2),f("x","z","y",1,-1,e,s,-t,i,r,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 Nt(c,3)),this.setAttribute("normal",new Nt(h,3)),this.setAttribute("uv",new Nt(u,2));function f(m,y,g,_,b,S,T,M,w,R,P){const z=S/w,$=T/R,q=S/2,j=T/2,X=M/2,Z=w+1,ve=R+1;let ue=0,ge=0;const ie=new N;for(let we=0;we<ve;we++){const ke=we*$-j;for(let nt=0;nt<Z;nt++){const _e=nt*z-q;ie[m]=_e*_,ie[y]=ke*b,ie[g]=X,c.push(ie.x,ie.y,ie.z),ie[m]=0,ie[y]=0,ie[g]=M>0?1:-1,h.push(ie.x,ie.y,ie.z),u.push(nt/w),u.push(1-we/R),ue+=1}}for(let we=0;we<R;we++)for(let ke=0;ke<w;ke++){const nt=d+ke+Z*we,_e=d+ke+Z*(we+1),rt=d+(ke+1)+Z*(we+1),Dt=d+(ke+1)+Z*we;l.push(nt,_e,Dt),l.push(_e,rt,Dt),ge+=6}o.addGroup(p,ge,P),p+=ge,d+=ue}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Ma(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}const jn=4,Lp=[.125,.215,.35,.446,.526,.582],rn=20,Sc=new Du(-1,1,1,-1,0,1),WE=new Xt(90,1),Up=new Se;let vc=null,wc=0,Ec=0;const en=(1+Math.sqrt(5))/2,Fn=1/en,kp=[new N(-en,Fn,0),new N(en,Fn,0),new N(-Fn,0,en),new N(Fn,0,en),new N(0,en,-Fn),new N(0,en,Fn),new N(-1,1,-1),new N(1,1,-1),new N(-1,1,1),new N(1,1,1)],$E=new N,ny=new WeakMap,jE=[3,1,5,0,4,2],Mc=GE(Ea(),Oi("faceIndex")).normalize(),Bu=I(Mc.x,Mc.y,Mc.z);class qE{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._blurMaterial=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:r=256,position:o=$E,renderTarget:l=null}=n;if(this._setSize(r),this._hasInitialized===!1){console.warn("THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.");const h=l||this._allocateTarget();return n.renderTarget=h,this.fromSceneAsync(e,t,s,i,n),h}vc=this._renderer.getRenderTarget(),wc=this._renderer.getActiveCubeFace(),Ec=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 this._hasInitialized===!1&&await this._renderer.init(),this.fromScene(e,t,s,i,n)}fromEquirectangular(e,t=null){if(this._hasInitialized===!1){console.warn("THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() 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 this._hasInitialized===!1&&await this._renderer.init(),this._fromTexture(e,t)}fromCubemap(e,t=null){if(this._hasInitialized===!1){console.warn("THREE.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 this._hasInitialized===!1&&await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=Gp(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=Vp(),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===fa||e.mapping===Wo?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._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodPlanes.length;e++)this._lodPlanes[e].dispose()}_cleanup(e){this._renderer.setRenderTarget(vc,wc,Ec),e.scissorTest=!1,so(e,0,0,e.width,e.height)}_fromTexture(e,t){this._setSizeFromTexture(e),vc=this._renderer.getRenderTarget(),wc=this._renderer.getActiveCubeFace(),Ec=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 zp(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=zp(e.width,e.height);const{_lodMax:t}=this;({sizeLods:this._sizeLods,lodPlanes:this._lodPlanes,sigmas:this._sigmas,lodMeshes:this._lodMeshes}=YE(t)),this._blurMaterial=XE(t,e.width,e.height)}}async _compileMaterial(e){const t=new li(this._lodPlanes[0],e);await this._renderer.compile(t,Sc)}_sceneToCubeUV(e,t,s,i,n){const r=WE;r.near=t,r.far=s;const o=[1,1,1,1,-1,1],l=[1,-1,1,-1,1,-1],c=this._renderer,h=c.autoClear;c.getClearColor(Up),c.autoClear=!1;let u=this._backgroundBox;if(u===null){const f=new Ai({name:"PMREM.Background",side:zt,depthWrite:!1,depthTest:!1});u=new li(new Ma,f)}let d=!1;const p=e.background;p?p.isColor&&(u.material.color.copy(p),e.background=null,d=!0):(u.material.color.copy(Up),d=!0),c.setRenderTarget(i),c.clear(),d&&c.render(u,r);for(let f=0;f<6;f++){const m=f%3;m===0?(r.up.set(0,o[f],0),r.position.set(n.x,n.y,n.z),r.lookAt(n.x+l[f],n.y,n.z)):m===1?(r.up.set(0,0,o[f]),r.position.set(n.x,n.y,n.z),r.lookAt(n.x,n.y+l[f],n.z)):(r.up.set(0,o[f],0),r.position.set(n.x,n.y,n.z),r.lookAt(n.x,n.y,n.z+l[f]));const y=this._cubeSize;so(i,m*y,f>2?y:0,y,y),c.render(e,r)}c.autoClear=h,e.background=p}_textureToCubeUV(e,t){const s=this._renderer,i=e.mapping===fa||e.mapping===Wo;i?this._cubemapMaterial===null&&(this._cubemapMaterial=Gp(e)):this._equirectMaterial===null&&(this._equirectMaterial=Vp(e));const n=i?this._cubemapMaterial:this._equirectMaterial;n.fragmentNode.value=e;const r=this._lodMeshes[0];r.material=n;const o=this._cubeSize;so(t,0,0,3*o,2*o),s.setRenderTarget(t),s.render(r,Sc)}_applyPMREM(e){const t=this._renderer,s=t.autoClear;t.autoClear=!1;const i=this._lodPlanes.length;for(let n=1;n<i;n++){const r=Math.sqrt(this._sigmas[n]*this._sigmas[n]-this._sigmas[n-1]*this._sigmas[n-1]),o=kp[(i-n-1)%kp.length];this._blur(e,n-1,n,r,o)}t.autoClear=s}_blur(e,t,s,i,n){const r=this._pingPongRenderTarget;this._halfBlur(e,r,t,s,i,"latitudinal",n),this._halfBlur(r,e,s,s,i,"longitudinal",n)}_halfBlur(e,t,s,i,n,r,o){const l=this._renderer,c=this._blurMaterial;r!=="latitudinal"&&r!=="longitudinal"&&console.error("blur direction must be either latitudinal or longitudinal!");const h=3,u=this._lodMeshes[i];u.material=c;const d=ny.get(c),p=this._sizeLods[s]-1,f=isFinite(n)?Math.PI/(2*p):2*Math.PI/(2*rn-1),m=n/f,y=isFinite(n)?1+Math.floor(h*m):rn;y>rn&&console.warn(`sigmaRadians, ${n}, is too large and will clip, as it requested ${y} samples when the maximum is set to ${rn}`);const g=[];let _=0;for(let w=0;w<rn;++w){const R=w/m,P=Math.exp(-R*R/2);g.push(P),w===0?_+=P:w<y&&(_+=2*P)}for(let w=0;w<g.length;w++)g[w]=g[w]/_;e.texture.frame=(e.texture.frame||0)+1,d.envMap.value=e.texture,d.samples.value=y,d.weights.array=g,d.latitudinal.value=r==="latitudinal"?1:0,o&&(d.poleAxis.value=o);const{_lodMax:b}=this;d.dTheta.value=f,d.mipInt.value=b-s;const S=this._sizeLods[i],T=3*S*(i>b-jn?i-b+jn:0),M=4*(this._cubeSize-S);so(t,T,M,3*S,2*S),l.setRenderTarget(t),l.render(u,Sc)}}function YE(a){const e=[],t=[],s=[],i=[];let n=a;const r=a-jn+1+Lp.length;for(let o=0;o<r;o++){const l=Math.pow(2,n);t.push(l);let c=1/l;o>a-jn?c=Lp[o-a+jn-1]:o===0&&(c=0),s.push(c);const h=1/(l-2),u=-h,d=1+h,p=[u,u,d,u,d,d,u,u,d,d,u,d],f=6,m=6,y=3,g=2,_=1,b=new Float32Array(y*m*f),S=new Float32Array(g*m*f),T=new Float32Array(_*m*f);for(let w=0;w<f;w++){const R=w%3*2/3-1,P=w>2?0:-1,z=[R,P,0,R+2/3,P,0,R+2/3,P+1,0,R,P,0,R+2/3,P+1,0,R,P+1,0],$=jE[w];b.set(z,y*m*$),S.set(p,g*m*$);const q=[$,$,$,$,$,$];T.set(q,_*m*$)}const M=new ui;M.setAttribute("position",new os(b,y)),M.setAttribute("uv",new os(S,g)),M.setAttribute("faceIndex",new os(T,_)),e.push(M),i.push(new li(M,null)),n>jn&&n--}return{lodPlanes:e,sizeLods:t,sigmas:s,lodMeshes:i}}function zp(a,e){const t={magFilter:Qt,minFilter:Qt,generateMipmaps:!1,type:ns,format:rs,colorSpace:Zn},s=new dn(a,e,t);return s.texture.mapping=ch,s.texture.name="PMREM.cubeUv",s.texture.isPMREMTexture=!0,s.scissorTest=!0,s}function so(a,e,t,s,i){a.viewport.set(e,t,s,i),a.scissor.set(e,t,s,i)}function Iu(a){const e=new tt;return e.depthTest=!1,e.depthWrite=!1,e.blending=rr,e.name=`PMREM_${a}`,e}function XE(a,e,t){const s=Os(new Array(rn).fill(0)),i=J(new N(0,1,0)),n=J(0),r=B(rn),o=J(0),l=J(1),c=xe(null),h=J(0),u=B(1/e),d=B(1/t),p=B(a),f={n:r,latitudinal:o,weights:s,poleAxis:i,outputDirection:Bu,dTheta:n,samples:l,envMap:c,mipInt:h,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:p},m=Iu("blur");return m.fragmentNode=HE({...f,latitudinal:o.equal(1)}),ny.set(m,f),m}function Gp(a){const e=Iu("cubemap");return e.fragmentNode=ba(a,Bu),e}function Vp(a){const e=Iu("equirect");return e.fragmentNode=xe(a,Ng(Bu),0),e}const Hp=new WeakMap;function ZE(a){const e=Math.log2(a)-2,t=1/a;return{texelWidth:1/(3*Math.max(Math.pow(2,e),7*16)),texelHeight:t,maxMip:e}}function QE(a,e,t){const s=KE(e);let i=s.get(a);if((i!==void 0?i.pmremVersion:-1)!==a.pmremVersion){const r=a.image;if(a.isCubeTexture)if(eM(r))i=t.fromCubemap(a,i);else return null;else if(tM(r))i=t.fromEquirectangular(a,i);else return null;i.pmremVersion=a.pmremVersion,s.set(a,i)}return i.texture}function KE(a){let e=Hp.get(a);return e===void 0&&(e=new WeakMap,Hp.set(a,e)),e}class JE extends st{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 Tt;i.isRenderTargetTexture=!0,this._texture=xe(i),this._width=J(0),this._height=J(0),this._maxMip=J(0),this.updateBeforeType=he.RENDER}set value(e){this._value=e,this._pmrem=null}get value(){return this._value}updateFromTexture(e){const t=ZE(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=QE(i,e.renderer,this._generator),t!==null&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){this._generator===null&&(this._generator=new qE(e.renderer)),this.updateBefore(e);let t=this.uvNode;t===null&&e.context.getUV&&(t=e.context.getUV(this)),t=Gg.mul(I(t.x,t.y.negate(),t.z));let s=this.levelNode;return s===null&&e.context.getTextureLevel&&(s=e.context.getTextureLevel(this)),VE(this._texture,t,s,this._width,this._height,this._maxMip)}dispose(){super.dispose(),this._generator!==null&&this._generator.dispose()}}function eM(a){if(a==null)return!1;let e=0;const t=6;for(let s=0;s<t;s++)a[s]!==void 0&&e++;return e===t}function tM(a){return a==null?!1:a.height>0}const ry=U(JE).setParameterLength(1,3);L(([a=Ea()],{renderer:e,material:t})=>{const s=yg(a.mul(2).sub(1));let i;if(t.alphaToCoverage&&e.samples>1){const n=B(s.fwidth()).toVar();i=Di(n.oneMinus(),n.add(1),s).oneMinus()}else i=bt(s.greaterThan(1),0,1);return i});const Ta=L(({f0:a,f90:e,dotVH:t})=>{const s=t.mul(-5.55473).sub(6.98316).mul(t).exp2();return a.mul(s.oneMinus()).add(e.mul(s))}),sM=L(({alpha:a,dotNL:e,dotNV:t})=>{const s=a.pow2(),i=e.mul(s.add(s.oneMinus().mul(t.pow2())).sqrt()),n=t.mul(s.add(s.oneMinus().mul(e.pow2())).sqrt());return Us(.5,i.add(n).max(xT))}).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),iM=L(({alphaT:a,alphaB:e,dotTV:t,dotBV:s,dotTL:i,dotBL:n,dotNV:r,dotNL:o})=>{const l=o.mul(I(a.mul(t),e.mul(s),r).length()),c=r.mul(I(a.mul(i),e.mul(n),o).length());return Us(.5,l.add(c)).saturate()}).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"}]}),nM=L(({alpha:a,dotNH:e})=>{const t=a.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"}]}),rM=B(1/Math.PI),aM=L(({alphaT:a,alphaB:e,dotNH:t,dotTH:s,dotBH:i})=>{const n=a.mul(e),r=I(e.mul(s),a.mul(i),n.mul(t)),o=r.dot(r),l=n.div(o);return rM.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"}]}),Wp=L(a=>{const{lightDirection:e,f0:t,f90:s,roughness:i,f:n,USE_IRIDESCENCE:r,USE_ANISOTROPY:o}=a,l=a.normalView||Je,c=i.pow2(),h=e.add($e).normalize(),u=l.dot(e).clamp(),d=l.dot($e).clamp(),p=l.dot(h).clamp(),f=$e.dot(h).clamp();let m=Ta({f0:t,f90:s,dotVH:f}),y,g;if(Kd(r)&&(m=yu.mix(m,n)),Kd(o)){const _=Ao.dot(e),b=Ao.dot($e),S=Ao.dot(h),T=er.dot(e),M=er.dot($e),w=er.dot(h);y=iM({alphaT:Ph,alphaB:c,dotTV:b,dotBV:M,dotTL:_,dotBL:T,dotNV:d,dotNL:u}),g=aM({alphaT:Ph,alphaB:c,dotNH:p,dotTH:S,dotBH:w})}else y=sM({alpha:c,dotNL:u,dotNV:d}),g=nM({alpha:c,dotNH:p});return m.mul(y).mul(g)}),ur=L(a=>a.diffuseColor.mul(1/Math.PI)),ay=L(({roughness:a,dotNV:e})=>{const t=re(-1,-.0275,-.572,.022),s=re(1,.0425,1.04,-.04),i=a.mul(t).add(s),n=i.x.mul(i.x).min(e.mul(-9.28).exp2()).mul(i.x).add(i.y);return H(-1.04,1.04).mul(n).add(i.zw)}).setLayout({name:"DFGApprox",type:"vec2",inputs:[{name:"roughness",type:"float"},{name:"dotNV",type:"vec3"}]}),oM=L(({f:a,f90:e,dotVH:t})=>{const s=t.oneMinus().saturate(),i=s.mul(s),n=s.mul(i,i).clamp(0,.9999);return a.sub(I(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"}]}),lM=L(a=>{if(a.geometry.hasAttribute("normal")===!1)return B(0);const e=zs.dFdx().abs().max(zs.dFdy().abs());return e.x.max(e.y).max(e.z)}),oy=L(a=>{const{roughness:e}=a,t=lM();let s=e.max(.0525);return s=s.add(t),s=s.min(1),s}),cM=L(([a,e])=>{const t=a.x,s=a.y,i=a.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(pe(t,t).sub(pe(s,s)))),n});class Lu extends ui{constructor(e=1,t=32,s=16,i=0,n=Math.PI*2,r=0,o=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:e,widthSegments:t,heightSegments:s,phiStart:i,phiLength:n,thetaStart:r,thetaLength:o},t=Math.max(3,Math.floor(t)),s=Math.max(2,Math.floor(s));const l=Math.min(r+o,Math.PI);let c=0;const h=[],u=new N,d=new N,p=[],f=[],m=[],y=[];for(let g=0;g<=s;g++){const _=[],b=g/s;let S=0;g===0&&r===0?S=.5/t:g===s&&l===Math.PI&&(S=-.5/t);for(let T=0;T<=t;T++){const M=T/t;u.x=-e*Math.cos(i+M*n)*Math.sin(r+b*o),u.y=e*Math.cos(r+b*o),u.z=e*Math.sin(i+M*n)*Math.sin(r+b*o),f.push(u.x,u.y,u.z),d.copy(u).normalize(),m.push(d.x,d.y,d.z),y.push(M+S,1-b),_.push(c++)}h.push(_)}for(let g=0;g<s;g++)for(let _=0;_<t;_++){const b=h[g][_+1],S=h[g][_],T=h[g+1][_],M=h[g+1][_+1];(g!==0||r>0)&&p.push(b,S,M),(g!==s-1||l<Math.PI)&&p.push(S,T,M)}this.setIndex(p),this.setAttribute("position",new Nt(f,3)),this.setAttribute("normal",new Nt(m,3)),this.setAttribute("uv",new Nt(y,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Lu(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}const ms=new lu;class hM extends Bi{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 r=!1;if(n===null)i._clearColor.getRGB(ms),ms.a=i._clearColor.a;else if(n.isColor===!0)n.getRGB(ms),ms.a=1,r=!0;else if(n.isNode===!0){const l=this.get(e),c=n;ms.copy(i._clearColor);let h=l.backgroundMesh;if(h===void 0){let m=function(){n.removeEventListener("dispose",m),h.material.dispose(),h.geometry.dispose()};const d=Tu(re(c).mul(Mp),{getUV:()=>Uw.mul(Ru),getTextureLevel:()=>Lw});let p=jg;p=p.setZ(p.w);const f=new tt;f.name="Background.material",f.side=zt,f.depthTest=!1,f.depthWrite=!1,f.allowOverride=!1,f.fog=!1,f.lights=!1,f.vertexNode=p,f.colorNode=d,l.backgroundMeshNode=d,l.backgroundMesh=h=new li(new Lu(1,32,32),f),h.frustumCulled=!1,h.name="Background.mesh",h.onBeforeRender=function(y,g,_){this.matrixWorld.copyPosition(_.matrixWorld)},n.addEventListener("dispose",m)}const u=c.getCacheKey();l.backgroundCacheKey!==u&&(l.backgroundMeshNode.node=re(c).mul(Mp),l.backgroundMeshNode.needsUpdate=!0,h.material.needsUpdate=!0,l.backgroundCacheKey=u),t.unshift(h,h.geometry,h.material,0,0,null,null)}else console.error("THREE.Renderer: Unsupported background configuration.",n);const o=i.xr.getEnvironmentBlendMode();if(o==="additive"?ms.set(0,0,0,1):o==="alpha-blend"&&ms.set(0,0,0,0),i.autoClear===!0||r===!0){const l=s.clearColorValue;l.r=ms.r,l.g=ms.g,l.b=ms.b,l.a=ms.a,(i.backend.isWebGLBackend===!0||i.alpha===!0)&&(l.r*=l.a,l.g*=l.a,l.b*=l.a),s.depthClearValue=i._clearDepth,s.stencilClearValue=i._clearStencil,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 uM=0;class kh{constructor(e="",t=[],s=0,i=[]){this.name=e,this.bindings=t,this.index=s,this.bindingsReference=i,this.id=uM++}}class dM{constructor(e,t,s,i,n,r,o,l,c,h=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=s,this.transforms=h,this.nodeAttributes=i,this.bindings=n,this.updateNodes=r,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 kh(t.name,[],t.index,t);e.push(i);for(const n of t.bindings)i.bindings.push(n.clone())}else e.push(t);return e}}function ly(a){const e={};for(const t in a){e[t]={};for(const s in a[t]){const i=a[t][s];i&&(i.isColor||i.isMatrix3||i.isMatrix4||i.isVector2||i.isVector3||i.isVector4||i.isTexture||i.isQuaternion)?i.isRenderTargetTexture?(console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[t][s]=null):e[t][s]=i.clone():Array.isArray(i)?e[t][s]=i.slice():e[t][s]=i}}return e}function pM(a){const e=[];for(let t=0;t<a.length;t++)e.push(a[t].clone());return e}const fM=`
|
76
|
+
void main() {
|
77
|
+
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
78
|
+
}
|
79
|
+
`,mM=`
|
80
|
+
void main() {
|
81
|
+
gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
|
82
|
+
}
|
83
|
+
`;class gM extends Gt{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=fM,this.fragmentShader=mM,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=ly(e.uniforms),this.uniformsGroups=pM(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this}toJSON(e){const t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(const i in this.uniforms){const r=this.uniforms[i].value;r&&r.isTexture?t.uniforms[i]={type:"t",value:r.toJSON(e).uuid}:r&&r.isColor?t.uniforms[i]={type:"c",value:r.getHex()}:r&&r.isVector2?t.uniforms[i]={type:"v2",value:r.toArray()}:r&&r.isVector3?t.uniforms[i]={type:"v3",value:r.toArray()}:r&&r.isVector4?t.uniforms[i]={type:"v4",value:r.toArray()}:r&&r.isMatrix3?t.uniforms[i]={type:"m3",value:r.toArray()}:r&&r.isMatrix4?t.uniforms[i]={type:"m4",value:r.toArray()}:t.uniforms[i]={value:r}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const s={};for(const i in this.extensions)this.extensions[i]===!0&&(s[i]=!0);return Object.keys(s).length>0&&(t.extensions=s),t}}class yM extends dn{constructor(e=1,t=1,s={}){super(e,t,s),this.isWebGLRenderTarget=!0}}const Dn=-90,On=1;class cy extends ct{constructor(e,t,s){super(),this.type="CubeCamera",this.renderTarget=s,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new Xt(Dn,On,e,t);i.layers=this.layers,this.add(i);const n=new Xt(Dn,On,e,t);n.layers=this.layers,this.add(n);const r=new Xt(Dn,On,e,t);r.layers=this.layers,this.add(r);const o=new Xt(Dn,On,e,t);o.layers=this.layers,this.add(o);const l=new Xt(Dn,On,e,t);l.layers=this.layers,this.add(l);const c=new Xt(Dn,On,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[s,i,n,r,o,l]=t;for(const c of t)this.remove(c);if(e===Lt)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),r.up.set(0,0,1),r.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===Fi)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),r.up.set(0,0,-1),r.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,r,o,l,c,h]=this.children,u=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,e.setRenderTarget(s,0,i),e.render(t,n),e.setRenderTarget(s,1,i),e.render(t,r),e.setRenderTarget(s,2,i),e.render(t,o),e.setRenderTarget(s,3,i),e.render(t,l),e.setRenderTarget(s,4,i),e.render(t,c),s.texture.generateMipmaps=m,e.setRenderTarget(s,5,i),e.render(t,h),e.setRenderTarget(u,d,p),e.xr.enabled=f,s.texture.needsPMREMUpdate=!0}}class xM extends yM{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const s={width:e,height:e,depth:1},i=[s,s,s,s,s,s];this.texture=new _l(i),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const s={uniforms:{tEquirect:{value:null}},vertexShader:`
|
84
|
+
|
85
|
+
varying vec3 vWorldDirection;
|
86
|
+
|
87
|
+
vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
|
88
|
+
|
89
|
+
return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
|
90
|
+
|
91
|
+
}
|
92
|
+
|
93
|
+
void main() {
|
94
|
+
|
95
|
+
vWorldDirection = transformDirection( position, modelMatrix );
|
96
|
+
|
97
|
+
#include <begin_vertex>
|
98
|
+
#include <project_vertex>
|
99
|
+
|
100
|
+
}
|
101
|
+
`,fragmentShader:`
|
102
|
+
|
103
|
+
uniform sampler2D tEquirect;
|
104
|
+
|
105
|
+
varying vec3 vWorldDirection;
|
106
|
+
|
107
|
+
#include <common>
|
108
|
+
|
109
|
+
void main() {
|
110
|
+
|
111
|
+
vec3 direction = normalize( vWorldDirection );
|
112
|
+
|
113
|
+
vec2 sampleUV = equirectUv( direction );
|
114
|
+
|
115
|
+
gl_FragColor = texture2D( tEquirect, sampleUV );
|
116
|
+
|
117
|
+
}
|
118
|
+
`},i=new Ma(5,5,5),n=new gM({name:"CubemapFromEquirect",uniforms:ly(s.uniforms),vertexShader:s.vertexShader,fragmentShader:s.fragmentShader,side:zt,blending:rr});n.uniforms.tEquirect.value=t;const r=new li(i,n),o=t.minFilter;return t.minFilter===ei&&(t.minFilter=Qt),new cy(1,10,this).update(e,r),t.minFilter=o,r.geometry.dispose(),r.material.dispose(),this}clear(e,t=!0,s=!0,i=!0){const n=e.getRenderTarget();for(let r=0;r<6;r++)e.setRenderTarget(this,r),e.clear(t,s,i);e.setRenderTarget(n)}}class hy extends xM{constructor(e=1,t={}){super(e,t),this.isCubeRenderTarget=!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 Ma(5,5,5),r=Ng(Rg),o=new tt;o.colorNode=xe(t,r,0),o.side=zt,o.blending=rr;const l=new li(n,o),c=new ru;c.add(l),t.minFilter===ei&&(t.minFilter=Qt);const h=new cy(1,10,this),u=e.getMRT();return e.setMRT(null),h.update(e,c),e.setMRT(u),t.minFilter=s,t.currentGenerateMipmaps=i,l.geometry.dispose(),l.material.dispose(),this}}const ha=new WeakMap;class _M extends st{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=ba(null);const t=new _l;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=he.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 r=n.mapping;if(r===Zh||r===Qh){if(ha.has(n)){const o=ha.get(n);$p(o,n.mapping),this._cubeTexture=o}else{const o=n.image;if(bM(o)){const l=new hy(o.height);l.fromEquirectangularTexture(t,n),$p(l.texture,n.mapping),this._cubeTexture=l.texture,ha.set(n,l.texture),n.addEventListener("dispose",uy)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function bM(a){return a==null?!1:a.height>0}function uy(a){const e=a.target;e.removeEventListener("dispose",uy);const t=ha.get(e);t!==void 0&&(ha.delete(e),t.dispose())}function $p(a,e){e===Zh?a.mapping=fa:e===Qh&&(a.mapping=Wo)}const dy=U(_M).setParameterLength(1);class vl{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class jp{constructor(e,t,s=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=s}}class TM{constructor(e,t,s){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=s.getSelf()}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 py{constructor(e,t,s=!1,i=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=s,this.count=i}}class SM extends py{constructor(e,t,s=null,i=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=s,this.interpolationSampling=i}}class vM{constructor(e,t,s=""){this.name=e,this.type=t,this.code=s,Object.defineProperty(this,"isNodeCode",{value:!0})}}let wM=0;class Cc{constructor(e=null){this.id=wM++,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 EM{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class Li{constructor(e,t){this.name=e,this.value=t,this.boundary=0,this.itemSize=0,this.offset=0}setValue(e){this.value=e}getValue(){return this.value}}class MM extends Li{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class CM extends Li{constructor(e,t=new ce){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class AM extends Li{constructor(e,t=new N){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class RM extends Li{constructor(e,t=new me){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class NM extends Li{constructor(e,t=new Se){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class PM extends Li{constructor(e,t=new ol){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class FM extends Li{constructor(e,t=new Vt){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class DM extends Li{constructor(e,t=new Be){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class OM extends MM{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class BM extends CM{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class IM extends AM{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class LM extends RM{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class UM extends NM{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class kM extends PM{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class zM extends FM{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class GM extends DM{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}const qp=new WeakMap,VM=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),io=a=>/e/g.test(a)?String(a).replace(/\+/g,""):(a=Number(a),a+(a%1?"":".0"));class fy{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.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=ql(),this.stacks=[],this.tab=" ",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new Cc,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null}getBindGroupsCache(){let e=qp.get(this.renderer);return e===void 0&&(e=new vs,qp.set(this.renderer,e)),e}createRenderTarget(e,t,s){return new dn(e,t,s)}createCubeRenderTarget(e,t){return new hy(e,t)}includes(e){return this.nodes.includes(e)}getOutputStructName(){}_getBindGroup(e,t){const s=this.getBindGroupsCache(),i=[];let n=!0;for(const o of t)i.push(o),n=n&&o.groupNode.shared!==!0;let r;return n?(r=s.get(i),r===void 0&&(r=new kh(e,i,this.bindingsIndexes[e].group,i),s.set(i,r))):r=new kh(e,i,this.bindingsIndexes[e].group,i),r}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 jd)for(const n in s[i]){const r=s[i][n];(t[n]||(t[n]=[])).push(...r)}e=[];for(const i in t){const n=t[i],r=this._getBindGroup(i,n);e.push(r)}this.bindGroups=e}return e}sortBindingGroups(){const e=this.getBindings();e.sort((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){this.sequentialNodes.includes(e)===!1&&this.sequentialNodes.push(e)}buildUpdateNodes(){for(const e of this.nodes)e.getUpdateType()!==he.NONE&&this.updateNodes.push(e.getSelf());for(const e of this.sequentialNodes){const t=e.getUpdateBeforeType(),s=e.getUpdateAfterType();t!==he.NONE&&this.updateBeforeNodes.push(e.getSelf()),s!==he.NONE&&this.updateAfterNodes.push(e.getSelf())}}get currentNode(){return this.chaining[this.chaining.length-1]}isFilteredTexture(e){return e.magFilter===Qt||e.magFilter===hh||e.magFilter===ma||e.magFilter===ei||e.minFilter===Qt||e.minFilter===hh||e.minFilter===ma||e.minFilter===ei}addChain(e){this.chaining.push(e)}removeChain(e){if(this.chaining.pop()!==e)throw new Error("NodeBuilder: Invalid node chaining!")}getMethod(e){return e}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}getSharedContext(){return{...this.context},this.context}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 Cc(t?this.getCache():null)),s.cache}isAvailable(){return!1}getVertexIndex(){console.warn("Abstract function.")}getInstanceIndex(){console.warn("Abstract function.")}getDrawIndex(){console.warn("Abstract function.")}getFrontFacing(){console.warn("Abstract function.")}getFragCoord(){console.warn("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(){console.warn("Abstract function.")}generateTextureLod(){console.warn("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 r=s?s[n]:null;r!==null?i+=r.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:r,type:o}=n;s&&s[r]&&s[r].isNode?i.push(s[r].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 Se:e==="vec2"?t=new ce:e==="vec3"?t=new N:e==="vec4"&&(t=new me)),e==="float")return io(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")}( ${io(t.r)}, ${io(t.g)}, ${io(t.b)} )`;const s=this.getTypeLength(e),i=this.getComponentType(e),n=r=>this.generateConst(i,r);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 jp(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===Mt)return"int";if(t===Ye)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=C_(e);const i=t==="float"?"":t[0];return/mat2/.test(t)===!0&&(s=s.replace("vec","mat")),i+s}getTypeFromArray(e){return VM.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 r;return!(e instanceof Vm)&&n!==!0&&(r=this.getTypeFromArray(s)),this.getTypeFromLength(i,r)}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")}addStack(){return this.stack=ql(this.stack),this.stacks.push(Zm()||this.stack),Zo(this.stack),this.stack}removeStack(){const e=this.stack;return this.stack=e.parent,Zo(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);return i===void 0&&(i={},s.setData(e,i)),i[t]===void 0&&(i[t]={}),i[t]}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);let i=s.bufferAttribute;if(i===void 0){const n=this.uniforms.index++;i=new jp("nodeAttribute"+n,t,e),this.bufferAttributes.push(i),s.bufferAttribute=i}return i}getStructTypeFromNode(e,t,s=null,i=this.shaderStage){const n=this.getDataFromNode(e,i,this.globalCache);let r=n.structType;if(r===void 0){const o=this.structs.index++;s===null&&(s="StructType"+o),r=new EM(s,t),this.structs[i].push(r),n.structType=r}return r}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 r=n.uniform;if(r===void 0){const o=this.uniforms.index++;r=new TM(i||"nodeUniform"+o,t,e),this.uniforms[s].push(r),this.registerDeclaration(r),n.uniform=r}return r}getArrayCount(e){let t=null;return e.isArrayNode?t=e.count:e.isVarNode&&e.node.isArrayNode&&(t=e.node.count),t}getVarFromNode(e,t=null,s=e.getNodeType(this),i=this.shaderStage,n=!1){const r=this.getDataFromNode(e,i);let o=r.variable;if(o===void 0){const l=n?"_const":"_var",c=this.vars[i]||(this.vars[i]=[]),h=this.vars[l]||(this.vars[l]=0);t===null&&(t=(n?"nodeConst":"nodeVar")+h,this.vars[l]++);const u=this.getArrayCount(e);o=new py(t,s,n,u),n||c.push(o),this.registerDeclaration(o),r.variable=o}return o}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 r=this.getDataFromNode(e,"any");let o=r.varying;if(o===void 0){const l=this.varyings,c=l.length;t===null&&(t="nodeVarying"+c),o=new SM(t,s,i,n),l.push(o),this.registerDeclaration(o),r.varying=o}return o}get namespace(){return this.context.namespace}getOutputNamespace(){return this.getNamespace("outputNode")}getNamespace(e=""){const t=this.namespace;let s;return t?s=e?t+"_"+e:t:s=e,s}registerDeclaration(e){const t=this.shaderStage,s=this.declarations[t]||(this.declarations[t]={}),i=this.getPropertyName(e);let n=1,r=i;for(;s[r]!==void 0;)r=i+"_"+n++;n>1&&(e.name=r,console.warn(`THREE.TSL: Declaration name '${i}' of '${e.type}' already in use. Renamed to '${r}'.`)),s[r]=e}getCodeFromNode(e,t,s=this.shaderStage){const i=this.getDataFromNode(e);let n=i.code;if(n===void 0){const r=this.codes[s]||(this.codes[s]=[]),o=r.length;n=new vM("nodeCode"+o,t),r.push(n),i.code=n}return n}addFlowCodeHierarchy(e,t){const{flowCodes:s,flowCodeBlock:i}=this.getDataFromNode(e);let n=!0,r=t;for(;r;){if(i.get(r)===!0){n=!1;break}r=this.getDataFromNode(r).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=[]),r=i.flowCodeBlock||(i.flowCodeBlock=new WeakMap);n.push(t),r.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+`;
|
119
|
+
`),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 Jw,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 r=0;const o=Object.values(this);return{next:()=>({value:o[r],done:r++>=o.length})}}};for(const r of t.inputs)s[r.name]=new RS(r.type,r.name);e.layout=null;const i=e.call(s),n=this.flowStagesNode(i,t.type);return e.layout=t,n}flowStagesNode(e,t=null){const s=this.flow,i=this.vars,n=this.declarations,r=this.cache,o=this.buildStage,l=this.stack,c={code:""};this.flow=c,this.vars={},this.declarations={},this.cache=new Cc,this.stack=ql();for(const h of $d)this.setBuildStage(h),c.result=e.build(this,t);return c.vars=this.getVars(this.shaderStage),this.flow=s,this.vars=i,this.declarations=n,this.cache=r,this.stack=l,this.setBuildStage(o),c}getFunctionOperator(){return null}buildFunctionCode(){console.warn("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,r=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 h=null;if(this.buildStage==="generate"){const u=this.flowChildNode(t,s);i!==null&&(u.code+=`${this.tab+i} = ${u.result};
|
120
|
+
`),this.flowCode[e]=this.flowCode[e]+u.code,h=u}else h=t.build(this);return this.setShaderStage(o),this.cache=r,this.tab=n,this.context=l,h}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){console.warn("Abstract function.")}getVaryings(){console.warn("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(){console.warn("Abstract function.")}getCodes(e){const t=this.codes[e];let s="";if(t!==void 0)for(const i of t)s+=i.code+`
|
121
|
+
`;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(){console.warn("Abstract function.")}build(){const{object:e,material:t,renderer:s}=this;if(t!==null){let i=s.library.fromMaterial(t);i===null&&(console.error(`NodeMaterial: Material "${t.type}" is not compatible.`),i=new tt),i.build(this)}else this.addFlow("compute",e);for(const i of $d){this.setBuildStage(i),this.context.vertex&&this.context.vertex.isNode&&this.flowNodeFromShaderStage("vertex",this.context.vertex);for(const n of jd){this.setShaderStage(n);const r=this.flowNodes[n];for(const o of r)i==="generate"?this.flowNode(o):o.build(this)}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getNodeUniform(e,t){if(t==="float"||t==="int"||t==="uint")return new OM(e);if(t==="vec2"||t==="ivec2"||t==="uvec2")return new BM(e);if(t==="vec3"||t==="ivec3"||t==="uvec3")return new IM(e);if(t==="vec4"||t==="ivec4"||t==="uvec4")return new LM(e);if(t==="color")return new UM(e);if(t==="mat2")return new kM(e);if(t==="mat3")return new zM(e);if(t==="mat4")return new GM(e);throw new Error(`Uniform "${t}" not declared.`)}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${lm} - Node System
|
122
|
+
`}*[Symbol.iterator](){}createNodeMaterial(e="NodeMaterial"){throw new Error(`THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${e}() instead.`)}}class Yp{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={renderMap:new WeakMap,frameMap:new WeakMap},e.set(t,s)),s}updateBeforeNode(e){const t=e.getUpdateBeforeType(),s=e.updateReference(this);if(t===he.FRAME){const{frameMap:i}=this._getMaps(this.updateBeforeMap,s);i.get(s)!==this.frameId&&e.updateBefore(this)!==!1&&i.set(s,this.frameId)}else if(t===he.RENDER){const{renderMap:i}=this._getMaps(this.updateBeforeMap,s);i.get(s)!==this.renderId&&e.updateBefore(this)!==!1&&i.set(s,this.renderId)}else t===he.OBJECT&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),s=e.updateReference(this);if(t===he.FRAME){const{frameMap:i}=this._getMaps(this.updateAfterMap,s);i.get(s)!==this.frameId&&e.updateAfter(this)!==!1&&i.set(s,this.frameId)}else if(t===he.RENDER){const{renderMap:i}=this._getMaps(this.updateAfterMap,s);i.get(s)!==this.renderId&&e.updateAfter(this)!==!1&&i.set(s,this.renderId)}else t===he.OBJECT&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),s=e.updateReference(this);if(t===he.FRAME){const{frameMap:i}=this._getMaps(this.updateMap,s);i.get(s)!==this.frameId&&e.update(this)!==!1&&i.set(s,this.frameId)}else if(t===he.RENDER){const{renderMap:i}=this._getMaps(this.updateMap,s);i.get(s)!==this.renderId&&e.update(this)!==!1&&i.set(s,this.renderId)}else t===he.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 Uu{constructor(e,t,s=null,i="",n=!1){this.type=e,this.name=t,this.count=s,this.qualifier=i,this.isConst=n}}Uu.isNodeFunctionInput=!0;class HM extends pn{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:Jg(this.light),lightColor:e}}}const Ac=new Be,no=new Be;let Br=null;class WM extends pn{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=J(new N).setGroup(K),this.halfWidth=J(new N).setGroup(K),this.updateType=he.RENDER}update(e){super.update(e);const{light:t}=this,s=e.camera.matrixWorldInverse;no.identity(),Ac.copy(t.matrixWorld),Ac.premultiply(s),no.extractRotation(Ac),this.halfWidth.value.set(t.width*.5,0,0),this.halfHeight.value.set(0,t.height*.5,0),this.halfWidth.value.applyMatrix4(no),this.halfHeight.value.applyMatrix4(no)}setupDirectRectArea(e){let t,s;e.isAvailable("float32Filterable")?(t=xe(Br.LTC_FLOAT_1),s=xe(Br.LTC_FLOAT_2)):(t=xe(Br.LTC_HALF_1),s=xe(Br.LTC_HALF_2));const{colorNode:i,light:n}=this,r=Kg(n);return{lightColor:i,lightPosition:r,halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:s}}static setLTC(e){Br=e}}class ku extends pn{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=J(0).setGroup(K),this.penumbraCosNode=J(0).setGroup(K),this.cutoffDistanceNode=J(0).setGroup(K),this.decayExponentNode=J(0).setGroup(K),this.colorNode=J(this.color).setGroup(K)}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 Di(s,i,t)}getLightCoord(e){const t=e.getNodeProperties(this);let s=t.projectionUV;return s===void 0&&(s=iE(this.light,e.context.positionWorld),t.projectionUV=s),s}setupDirect(e){const{colorNode:t,cutoffDistanceNode:s,decayExponentNode:i,light:n}=this,r=this.getLightVector(e),o=r.normalize(),l=o.dot(Jg(n)),c=this.getSpotAttenuation(e,l),h=r.length(),u=iy({lightDistance:h,cutoffDistance:s,decayExponent:i});let d=t.mul(c).mul(u),p,f;return n.colorNode?(f=this.getLightCoord(e),p=n.colorNode(f)):n.map&&(f=this.getLightCoord(e),p=xe(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 $M extends ku{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=xe(s,H(n,0),0).r}else i=super.getSpotAttenuation(t);return i}}const jM=L(([a,e])=>{const t=a.abs().sub(e);return ni(St(t,0)).add(cr(St(t.x,t.y),0))});class qM extends ku{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=this.penumbraCosNode,s=this.getLightCoord(e),i=s.xyz.div(s.w),n=jM(i.xy.sub(H(.5)),H(.5)),r=Us(-1,Ct(1,hg(t)).sub(1));return xg(n.mul(-2).mul(r))}}class YM extends pn{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class XM extends pn{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=Qg(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=J(new Se).setGroup(K)}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,r=Ru.dot(i).mul(.5).add(.5),o=ze(s,t,r);e.context.irradiance.addAssign(o)}}class ZM extends pn{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let s=0;s<9;s++)t.push(new N);this.lightProbe=Os(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=cM(Ru,this.lightProbe);e.context.irradiance.addAssign(t)}}const Xp=new WeakMap;class QM extends gr{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 u=s.isTextureNode?s.value:t[s.property];let d=Xp.get(u);d===void 0&&(d=ry(u),Xp.set(u,d)),s=d}const n=t.useAnisotropy===!0||t.anisotropy>0?Tv:Je,r=s.context(Zp(Xs,n)).mul(Jl),o=s.context(KM(Nu)).mul(Math.PI).mul(Jl),l=Po(r),c=Po(o);e.context.radiance.addAssign(l),e.context.iblIrradiance.addAssign(c);const h=e.context.lightingModel.clearcoatRadiance;if(h){const u=s.context(Zp(Jo,Zr)).mul(Jl),d=Po(u);h.addAssign(d)}}}const Zp=(a,e)=>{let t=null;return{getUV:()=>(t===null&&(t=$e.negate().reflect(e),t=a.mul(a).mix(t,e).normalize(),t=t.transformDirection(hi)),t),getTextureLevel:()=>a}},KM=a=>({getUV:()=>a,getTextureLevel:()=>B(1)});class zu extends gr{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=dy(this.envNode)}}class my{parseFunction(){console.warn("Abstract function.")}}class Gu{constructor(e,t,s="",i=""){this.type=e,this.inputs=t,this.name=s,this.precision=i}getCode(){console.warn("Abstract function.")}}Gu.isNodeFunction=!0;const JM=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,eC=/[a-z_0-9]+/ig,Qp="#pragma main",tC=a=>{a=a.trim();const e=a.indexOf(Qp),t=e!==-1?a.slice(e+Qp.length):a,s=t.match(JM);if(s!==null&&s.length===5){const i=s[4],n=[];let r=null;for(;(r=eC.exec(i))!==null;)n.push(r);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 y=n[l++][0];let g=Number.parseInt(n[l][0]);Number.isNaN(g)===!1?l++:g=null;const _=n[l++][0];o.push(new Uu(y,_,g,m,f))}const c=t.substring(s[0].length),h=s[3]!==void 0?s[3]:"",u=s[2],d=s[1]!==void 0?s[1]:"",p=e!==-1?a.slice(0,e):"";return{type:u,inputs:o,name:h,precision:d,inputsCode:i,blockCode:c,headerCode:p}}else throw new Error("FunctionNode: Function is not a GLSL code.")};class sC extends Gu{constructor(e){const{type:t,inputs:s,name:i,precision:n,inputsCode:r,blockCode:o,headerCode:l}=tC(e);super(t,s,i,n),this.inputsCode=r,this.blockCode=o,this.headerCode=l}getCode(e=this.name){let t;const s=this.blockCode;if(s!==""){const{type:i,inputsCode:n,headerCode:r,precision:o}=this;let l=`${i} ${e} ( ${n.trim()} )`;o!==""&&(l=`${o} ${l}`),t=r+l+s}else t="";return t}}class iC extends my{parseFunction(e){return new sC(e)}}class gy extends vl{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,s=e.reflectedLight,i=e.irradianceLightMap;s.indirectDiffuse.assign(re(0)),i?s.indirectDiffuse.addAssign(i):s.indirectDiffuse.addAssign(re(1,1,1,0)),s.indirectDiffuse.mulAssign(t),s.indirectDiffuse.mulAssign(Te.rgb)}finish(e){const{material:t,context:s}=e,i=s.outgoingLight,n=e.context.environment;if(n)switch(t.combine){case al:i.rgb.assign(ze(i.rgb,i.rgb.mul(n.rgb),Do.mul(ec)));break;case qx:i.rgb.assign(ze(i.rgb,n.rgb,Do.mul(ec)));break;case Yx:i.rgb.addAssign(n.rgb.mul(Do.mul(ec)));break;default:console.warn("THREE.BasicLightingModel: Unsupported .combine value:",t.combine);break}}}const nC=()=>B(.25),rC=L(({dotNH:a})=>Fh.mul(B(.5)).add(1).mul(B(1/Math.PI)).mul(a.pow(Fh))),aC=L(({lightDirection:a})=>{const e=a.add($e).normalize(),t=Je.dot(e).clamp(),s=$e.dot(e).clamp(),i=Ta({f0:qt,f90:1,dotVH:s}),n=nC(),r=rC({dotNH:t});return i.mul(n).mul(r)});class yy extends gy{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const n=Je.dot(e).clamp().mul(t);s.directDiffuse.addAssign(n.mul(ur({diffuseColor:Te.rgb}))),this.specular===!0&&s.directSpecular.addAssign(n.mul(aC({lightDirection:e})).mul(Do))}indirect(e){const{ambientOcclusion:t,irradiance:s,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(s.mul(ur({diffuseColor:Te}))),i.indirectDiffuse.mulAssign(t)}}const xy=L(a=>{const{dotNV:e,specularColor:t,specularF90:s,roughness:i}=a,n=ay({dotNV:e,roughness:i});return t.mul(n.x).add(s.mul(n.y))}),oC=L(({roughness:a,dotNH:e})=>{const t=a.pow2(),s=B(1).div(t),n=e.pow2().oneMinus().max(.0078125);return B(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"}]}),lC=L(({dotNV:a,dotNL:e})=>B(1).div(B(4).mul(e.add(a).sub(e.mul(a))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),cC=L(({lightDirection:a})=>{const e=a.add($e).normalize(),t=Je.dot(a).clamp(),s=Je.dot($e).clamp(),i=Je.dot(e).clamp(),n=oC({roughness:gu,dotNH:i}),r=lC({dotNV:s,dotNL:t});return $n.mul(n).mul(r)}),hC=L(({N:a,V:e,roughness:t})=>{const n=.0078125,r=a.dot(e).saturate(),o=H(t,r.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"}]}),uC=L(({f:a})=>{const e=a.length();return St(e.mul(e).add(a.z).div(e.add(1)),0)}).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),ro=L(({v1:a,v2:e})=>{const t=a.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(),r=i.div(n),o=t.greaterThan(0).select(r,St(t.mul(t).oneMinus(),1e-7).inverseSqrt().mul(.5).sub(r));return a.cross(e).mul(o)}).setLayout({name:"LTC_EdgeVectorFormFactor",type:"vec3",inputs:[{name:"v1",type:"vec3"},{name:"v2",type:"vec3"}]}),Kp=L(({N:a,V:e,P:t,mInv:s,p0:i,p1:n,p2:r,p3:o})=>{const l=n.sub(i).toVar(),c=o.sub(i).toVar(),h=l.cross(c),u=I().toVar();return Xe(h.dot(t.sub(i)).greaterThanEqual(0),()=>{const d=e.sub(a.mul(e.dot(a))).normalize(),p=a.cross(d).negate(),f=s.mul(Pt(d,p,a).transpose()).toVar(),m=f.mul(i.sub(t)).normalize().toVar(),y=f.mul(n.sub(t)).normalize().toVar(),g=f.mul(r.sub(t)).normalize().toVar(),_=f.mul(o.sub(t)).normalize().toVar(),b=I(0).toVar();b.addAssign(ro({v1:m,v2:y})),b.addAssign(ro({v1:y,v2:g})),b.addAssign(ro({v1:g,v2:_})),b.addAssign(ro({v1:_,v2:m})),u.assign(I(uC({f:b})))}),u}).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"}]}),Jp=L(([a,e,t,s,i])=>{const n=I(_g(e.negate(),xa(a),Us(1,s))),r=I(ni(i[0].xyz),ni(i[1].xyz),ni(i[2].xyz));return xa(n).mul(t.mul(r))}).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"}]}),dC=L(([a,e])=>a.mul(oi(e.mul(2).sub(2),0,1))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),pC=Ig(),fC=Ig(),ef=L(([a,e,t],{material:s})=>{const n=(s.side===zt?pC:fC).sample(a),r=ii(Oh.x).mul(dC(e,t));return Iw(n,r)}),tf=L(([a,e,t])=>(Xe(t.notEqual(0),()=>{const s=cg(e).negate().div(t);return lg(s.negate().mul(a))}),I(1))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),mC=L(([a,e,t,s,i,n,r,o,l,c,h,u,d,p,f])=>{let m,y;if(f){m=re().toVar(),y=I().toVar();const T=h.sub(1).mul(f.mul(.025)),M=I(h.sub(T),h,h.add(T));Ts({start:0,end:3},({i:w})=>{const R=M.element(w),P=Jp(a,e,u,R,o),z=r.add(P),$=c.mul(l.mul(re(z,1))),q=H($.xy.div($.w)).toVar();q.addAssign(1),q.divAssign(2),q.assign(H(q.x,q.y.oneMinus()));const j=ef(q,t,R);m.element(w).assign(j.element(w)),m.a.addAssign(j.a),y.element(w).assign(s.element(w).mul(tf(ni(P),d,p).element(w)))}),m.a.divAssign(3)}else{const T=Jp(a,e,u,h,o),M=r.add(T),w=c.mul(l.mul(re(M,1))),R=H(w.xy.div(w.w)).toVar();R.addAssign(1),R.divAssign(2),R.assign(H(R.x,R.y.oneMinus())),m=ef(R,t,h),y=s.mul(tf(ni(T),d,p))}const g=y.rgb.mul(m.rgb),_=a.dot(e).clamp(),b=I(xy({dotNV:_,specularColor:i,specularF90:n,roughness:t})),S=y.r.add(y.g,y.b).div(3);return re(b.oneMinus().mul(g),m.a.oneMinus().mul(S).oneMinus())}),gC=Pt(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),yC=a=>{const e=a.sqrt();return I(1).add(e).div(I(1).sub(e))},sf=(a,e)=>a.sub(e).div(a.add(e)).pow2(),xC=(a,e)=>{const t=a.mul(2*Math.PI*1e-9),s=I(54856e-17,44201e-17,52481e-17),i=I(1681e3,1795300,2208400),n=I(43278e5,93046e5,66121e5),r=B(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=I(o.x.add(r),o.y,o.z).div(10685e-11),gC.mul(o)},_C=L(({outsideIOR:a,eta2:e,cosTheta1:t,thinFilmThickness:s,baseF0:i})=>{const n=ze(a,e,Di(0,.03,s)),o=a.div(n).pow2().mul(t.pow2().oneMinus()).oneMinus();Xe(o.lessThan(0),()=>I(1));const l=o.sqrt(),c=sf(n,a),h=Ta({f0:c,f90:1,dotVH:t}),u=h.oneMinus(),d=n.lessThan(a).select(Math.PI,0),p=B(Math.PI).sub(d),f=yC(i.clamp(0,.9999)),m=sf(f,n.toVec3()),y=Ta({f0:m,f90:1,dotVH:l}),g=I(f.x.lessThan(n).select(Math.PI,0),f.y.lessThan(n).select(Math.PI,0),f.z.lessThan(n).select(Math.PI,0)),_=n.mul(s,l,2),b=I(p).add(g),S=h.mul(y).clamp(1e-5,.9999),T=S.sqrt(),M=u.pow2().mul(y).div(I(1).sub(S)),R=h.add(M).toVar(),P=M.sub(u).toVar();return Ts({start:1,end:2,condition:"<=",name:"m"},({m:z})=>{P.mulAssign(T);const $=xC(B(z).mul(_),B(z).mul(b)).mul(2);R.addAssign(P.mul($))}),R.max(I(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"}]}),bC=L(({normal:a,viewDir:e,roughness:t})=>{const s=a.dot(e).saturate(),i=t.pow2(),n=bt(t.lessThan(.25),B(-339.2).mul(i).add(B(161.4).mul(t)).sub(25.9),B(-8.48).mul(i).add(B(14.3).mul(t)).sub(9.95)),r=bt(t.lessThan(.25),B(44).mul(i).sub(B(23.7).mul(t)).add(3.26),B(1.97).mul(i).sub(B(3.27).mul(t)).add(.72));return bt(t.lessThan(.25),0,B(.1).mul(t).sub(.025)).add(n.mul(s).add(r).exp()).mul(1/Math.PI).saturate()}),Rc=I(.04),Nc=B(1);class _y extends vl{constructor(e=!1,t=!1,s=!1,i=!1,n=!1,r=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=s,this.anisotropy=i,this.transmission=n,this.dispersion=r,this.clearcoatRadiance=null,this.clearcoatSpecularDirect=null,this.clearcoatSpecularIndirect=null,this.sheenSpecularDirect=null,this.sheenSpecularIndirect=null,this.iridescenceFresnel=null,this.iridescenceF0=null}start(e){if(this.clearcoat===!0&&(this.clearcoatRadiance=I().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=I().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=I().toVar("clearcoatSpecularIndirect")),this.sheen===!0&&(this.sheenSpecularDirect=I().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=I().toVar("sheenSpecularIndirect")),this.iridescence===!0){const t=Je.dot($e).clamp();this.iridescenceFresnel=_C({outsideIOR:B(1),eta2:tg,cosTheta1:t,thinFilmThickness:sg,baseF0:qt}),this.iridescenceF0=oM({f:this.iridescenceFresnel,f90:1,dotVH:t})}if(this.transmission===!0){const t=_a,s=US.sub(_a).normalize(),i=Nu,n=e.context;n.backdrop=mC(i,s,Xs,Te,qt,el,t,hn,hi,Au,Ro,ig,rg,ng,this.dispersion?ag:null),n.backdropAlpha=Dh,Te.a.mulAssign(ze(1,n.backdrop.a,Dh))}super.start(e)}computeMultiscattering(e,t,s){const i=Je.dot($e).clamp(),n=ay({roughness:Xs,dotNV:i}),o=(this.iridescenceF0?yu.mix(qt,this.iridescenceF0):qt).mul(n.x).add(s.mul(n.y)),c=n.x.add(n.y).oneMinus(),h=qt.add(qt.oneMinus().mul(.047619)),u=o.mul(h).div(c.mul(h).oneMinus());e.addAssign(o),t.addAssign(u.mul(c))}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const n=Je.dot(e).clamp().mul(t);if(this.sheen===!0&&this.sheenSpecularDirect.addAssign(n.mul(cC({lightDirection:e}))),this.clearcoat===!0){const o=Zr.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(o.mul(Wp({lightDirection:e,f0:Rc,f90:Nc,roughness:Jo,normalView:Zr})))}s.directDiffuse.addAssign(n.mul(ur({diffuseColor:Te.rgb}))),s.directSpecular.addAssign(n.mul(Wp({lightDirection:e,f0:qt,f90:1,roughness:Xs,iridescence:this.iridescence,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy})))}directRectArea({lightColor:e,lightPosition:t,halfWidth:s,halfHeight:i,reflectedLight:n,ltc_1:r,ltc_2:o}){const l=t.add(s).sub(i),c=t.sub(s).sub(i),h=t.sub(s).add(i),u=t.add(s).add(i),d=Je,p=$e,f=et.toVar(),m=hC({N:d,V:p,roughness:Xs}),y=r.sample(m).toVar(),g=o.sample(m).toVar(),_=Pt(I(y.x,0,y.y),I(0,1,0),I(y.z,0,y.w)).toVar(),b=qt.mul(g.x).add(qt.oneMinus().mul(g.y)).toVar();n.directSpecular.addAssign(e.mul(b).mul(Kp({N:d,V:p,P:f,mInv:_,p0:l,p1:c,p2:h,p3:u}))),n.directDiffuse.addAssign(e.mul(Te).mul(Kp({N:d,V:p,P:f,mInv:Pt(1,0,0,0,1,0,0,0,1),p0:l,p1:c,p2:h,p3:u})))}indirect(e){this.indirectDiffuse(e),this.indirectSpecular(e),this.ambientOcclusion(e)}indirectDiffuse(e){const{irradiance:t,reflectedLight:s}=e.context;s.indirectDiffuse.addAssign(t.mul(ur({diffuseColor:Te})))}indirectSpecular(e){const{radiance:t,iblIrradiance:s,reflectedLight:i}=e.context;if(this.sheen===!0&&this.sheenSpecularIndirect.addAssign(s.mul($n,bC({normal:Je,viewDir:$e,roughness:gu}))),this.clearcoat===!0){const h=Zr.dot($e).clamp(),u=xy({dotNV:h,specularColor:Rc,specularF90:Nc,roughness:Jo});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(u))}const n=I().toVar("singleScattering"),r=I().toVar("multiScattering"),o=s.mul(1/Math.PI);this.computeMultiscattering(n,r,el);const l=n.add(r),c=Te.mul(l.r.max(l.g).max(l.b).oneMinus());i.indirectSpecular.addAssign(t.mul(n)),i.indirectSpecular.addAssign(r.mul(o)),i.indirectDiffuse.addAssign(c.mul(o))}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:s}=e.context,n=Je.dot($e).clamp().add(t),r=Xs.mul(-16).oneMinus().negate().exp2(),o=t.sub(n.pow(r).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=Zr.dot($e).clamp(),i=Ta({dotVH:s,f0:Rc,f90:Nc}),n=t.mul(Nh.mul(i).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(Nh));t.assign(n)}if(this.sheen===!0){const s=$n.r.max($n.g).max($n.b).mul(.157).oneMinus(),i=t.mul(s).add(this.sheenSpecularDirect,this.sheenSpecularIndirect);t.assign(i)}}}const nf=new WeakMap,Es=[],Hi=[];class TC extends Bi{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new Yp,this.nodeBuilderCache=new Map,this.callHashCache=new vs,this.groupsData=new vs,this.cacheLib={}}updateGroup(e){const t=e.groupNode,s=t.name;if(s===Jm.name)return!0;if(s===K.name){const n=this.get(e),r=this.nodeFrame.renderId;return n.renderId!==r?(n.renderId=r,!0):!1}if(s===qb.name){const n=this.get(e),r=this.nodeFrame.frameId;return n.frameId!==r?(n.frameId=r,!0):!1}Es[0]=t,Es[1]=e;let i=this.groupsData.get(Es);return i===void 0&&this.groupsData.set(Es,i={}),Es.length=0,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 r=this.backend.createNodeBuilder(e.object,this.renderer);r.scene=e.scene,r.material=e.material,r.camera=e.camera,r.context.material=e.material,r.lightsNode=e.lightsNode,r.environmentNode=this.getEnvironmentNode(e.scene),r.fogNode=this.getFogNode(e.scene),r.clippingContext=e.clippingContext,this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview&&r.enableMultiview(),r.build(),s=this._createNodeBuilderState(r),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 dM(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){Es[0]=e,Es[1]=t;const s=this.renderer.info.calls,i=this.callHashCache.get(Es)||{};if(i.callId!==s){const n=this.getEnvironmentNode(e),r=this.getFogNode(e);t&&Hi.push(t.getCacheKey(!0)),n&&Hi.push(n.getCacheKey()),r&&Hi.push(r.getCacheKey()),Hi.push(this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview?1:0),Hi.push(this.renderer.shadowMap.enabled?1:0),i.callId=s,i.cacheKey=nu(Hi),this.callHashCache.set(Es,i),Hi.length=0}return Es.length=0,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===Zh||s.mapping===Qh||s.mapping===ch){if(e.backgroundBlurriness>0||s.mapping===ch)return ry(s);{let r;return s.isCubeTexture===!0?r=ba(s):r=xe(s),dy(r)}}else{if(s.isTexture===!0)return xe(s,tr.flipY()).setUpdateMatrix(!0);s.isColor!==!0&&console.error("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 r=n.get(t);return(r===void 0||i)&&(r=s(),n.set(t,r)),r}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=Oe("color","color",s).setGroup(K),r=Oe("density","float",s).setGroup(K);return Ap(n,tE(r))}else if(s.isFog){const n=Oe("color","color",s).setGroup(K),r=Oe("near","float",s).setGroup(K),o=Oe("far","float",s).setGroup(K);return Ap(n,eE(r,o))}else console.error("THREE.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 ba(s);if(s.isTexture===!0)return xe(s);console.error("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 r=this.nodeFrame;return r.renderer=e,r.scene=t,r.object=s,r.camera=i,r.material=n,r}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 nf.get(e)!==this.getOutputCacheKey()}getOutputNode(e){const t=this.renderer,s=this.getOutputCacheKey(),i=e.isArrayTexture?Gw(e,I(tr,fl("gl_ViewID_OVR"))).renderOutput(t.toneMapping,t.currentColorSpace):xe(e,tr).renderOutput(t.toneMapping,t.currentColorSpace);return nf.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 Yp,this.nodeBuilderCache=new Map,this.cacheLib={}}}const Pc=new Ei;class sl{constructor(e=null){this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewNormalMatrix=new Vt,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++){Pc.copy(e[n]).applyMatrix4(this.viewMatrix,this.viewNormalMatrix);const r=t[s+n],o=Pc.normal;r.x=-o.x,r.y=-o.y,r.z=-o.z,r.w=Pc.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 r,o;if(this.clipIntersection?(r=this.intersectionPlanes,o=e.intersectionPlanes.length):(r=this.unionPlanes,o=e.unionPlanes.length),r.length!==o+n){r.length=o+n;for(let l=0;l<n;l++)r[o+l]=new me;s=!0}this.projectPlanes(i,r,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 sl(this),this.clippingGroupContexts.set(e,t)),t.update(this,e),t}get unionClippingCount(){return this.unionPlanes.length}}class SC{constructor(e,t){this.bundleGroup=e,this.camera=t}}const Ir=[];class vC{constructor(){this.bundles=new vs}get(e,t){const s=this.bundles;Ir[0]=e,Ir[1]=t;let i=s.get(Ir);return i===void 0&&(i=new SC(e,t),s.set(Ir,i)),Ir.length=0,i}dispose(){this.bundles=new vs}}class by{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)){console.warn(`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)){console.warn(`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 wC=new ey,Lr=[];class EC extends vs{constructor(){super()}createNode(e=[]){return new ey().setLights(e)}getNode(e,t){if(e.isQuadMesh)return wC;Lr[0]=e,Lr[1]=t;let s=this.get(Lr);return s===void 0&&(s=this.createNode(),this.set(Lr,s)),Lr.length=0,s}}class MC extends Xt{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class ao extends ct{constructor(){super(),this.isGroup=!0,this.type="Group"}}const CC={type:"move"};class AC{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new ao,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 ao,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new N,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new N),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new ao,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new N,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new N),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,r=null;const o=this._targetRay,l=this._grip,c=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(c&&e.hand){r=!0;for(const m of e.hand.values()){const y=t.getJointPose(m,s),g=this._getHandJoint(c,m);y!==null&&(g.matrix.fromArray(y.transform.matrix),g.matrix.decompose(g.position,g.rotation,g.scale),g.matrixWorldNeedsUpdate=!0,g.jointRadius=y.radius),g.visible=y!==null}const h=c.joints["index-finger-tip"],u=c.joints["thumb-tip"],d=h.position.distanceTo(u.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(CC)))}return o!==null&&(o.visible=i!==null),l!==null&&(l.visible=n!==null),c!==null&&(c.visible=r!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const s=new ao;s.matrixAutoUpdate=!1,s.visible=!1,e.joints[t.jointName]=s,e.add(s)}return e.joints[t.jointName]}}class Kr extends dn{constructor(e=1,t=1,s={}){super(e,t,s),this.isXRRenderTarget=!0,this.hasExternalTextures=!1,this.autoAllocateDepthBuffer=!0}copy(e){return super.copy(e),this.hasExternalTextures=e.hasExternalTextures,this.autoAllocateDepthBuffer=e.autoAllocateDepthBuffer,this}}class Vu extends ui{constructor(e=1,t=1,s=1,i=32,n=1,r=!1,o=0,l=Math.PI*2){super(),this.type="CylinderGeometry",this.parameters={radiusTop:e,radiusBottom:t,height:s,radialSegments:i,heightSegments:n,openEnded:r,thetaStart:o,thetaLength:l};const c=this;i=Math.floor(i),n=Math.floor(n);const h=[],u=[],d=[],p=[];let f=0;const m=[],y=s/2;let g=0;_(),r===!1&&(e>0&&b(!0),t>0&&b(!1)),this.setIndex(h),this.setAttribute("position",new Nt(u,3)),this.setAttribute("normal",new Nt(d,3)),this.setAttribute("uv",new Nt(p,2));function _(){const S=new N,T=new N;let M=0;const w=(t-e)/s;for(let R=0;R<=n;R++){const P=[],z=R/n,$=z*(t-e)+e;for(let q=0;q<=i;q++){const j=q/i,X=j*l+o,Z=Math.sin(X),ve=Math.cos(X);T.x=$*Z,T.y=-z*s+y,T.z=$*ve,u.push(T.x,T.y,T.z),S.set(Z,w,ve).normalize(),d.push(S.x,S.y,S.z),p.push(j,1-z),P.push(f++)}m.push(P)}for(let R=0;R<i;R++)for(let P=0;P<n;P++){const z=m[P][R],$=m[P+1][R],q=m[P+1][R+1],j=m[P][R+1];(e>0||P!==0)&&(h.push(z,$,j),M+=3),(t>0||P!==n-1)&&(h.push($,q,j),M+=3)}c.addGroup(g,M,0),g+=M}function b(S){const T=f,M=new ce,w=new N;let R=0;const P=S===!0?e:t,z=S===!0?1:-1;for(let q=1;q<=i;q++)u.push(0,y*z,0),d.push(0,z,0),p.push(.5,.5),f++;const $=f;for(let q=0;q<=i;q++){const X=q/i*l+o,Z=Math.cos(X),ve=Math.sin(X);w.x=P*ve,w.y=y*z,w.z=P*Z,u.push(w.x,w.y,w.z),d.push(0,z,0),M.x=Z*.5+.5,M.y=ve*.5*z+.5,p.push(M.x,M.y),f++}for(let q=0;q<i;q++){const j=T+q,X=$+q;S===!0?h.push(X,X+1,j):h.push(X+1,X,j),R+=3}c.addGroup(g,R,S===!0?1:2),g+=R}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Vu(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class Hu extends ui{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,r=t/2,o=Math.floor(s),l=Math.floor(i),c=o+1,h=l+1,u=e/o,d=t/l,p=[],f=[],m=[],y=[];for(let g=0;g<h;g++){const _=g*d-r;for(let b=0;b<c;b++){const S=b*u-n;f.push(S,-_,0),m.push(0,0,1),y.push(b/o),y.push(1-g/l)}}for(let g=0;g<l;g++)for(let _=0;_<o;_++){const b=_+c*g,S=_+c*(g+1),T=_+1+c*(g+1),M=_+1+c*g;p.push(b,S,M),p.push(S,T,M)}this.setIndex(p),this.setAttribute("position",new Nt(f,3)),this.setAttribute("normal",new Nt(m,3)),this.setAttribute("uv",new Nt(y,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Hu(e.width,e.height,e.widthSegments,e.heightSegments)}}const rf=new N,af=new N;class RC extends un{constructor(e,t=!1){super(),this.enabled=!1,this.isPresenting=!1,this.cameraAutoUpdate=!0,this._renderer=e,this._cameraL=new Xt,this._cameraL.viewport=new me,this._cameraR=new Xt,this._cameraR.viewport=new me,this._cameras=[this._cameraL,this._cameraR],this._cameraXR=new MC,this._currentDepthNear=null,this._currentDepthFar=null,this._controllers=[],this._controllerInputSources=[],this._xrRenderTarget=null,this._layers=[],this._supportsLayers=!1,this._frameBufferTargets=null,this._createXRLayer=BC.bind(this),this._gl=null,this._currentAnimationContext=null,this._currentAnimationLoop=null,this._currentPixelRatio=null,this._currentSize=new ce,this._onSessionEvent=FC.bind(this),this._onSessionEnd=DC.bind(this),this._onInputSourcesChange=OC.bind(this),this._onAnimationFrame=IC.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._useLayers=typeof XRWebGLBinding<"u"&&"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&&console.warn("THREE.XRManager: Cannot change framebuffer scale while presenting.")}getReferenceSpaceType(){return this._referenceSpaceType}setReferenceSpaceType(e){this._referenceSpaceType=e,this.isPresenting===!0&&console.warn("THREE.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}getFrame(){return this._xrFrame}useMultiview(){return this._useMultiview}createQuadLayer(e,t,s,i,n,r,o,l={}){const c=new Hu(e,t),h=new Kr(n,r,{format:rs,type:Rt,depthTexture:new Is(n,r,l.stencil?Ni:Ye,void 0,void 0,void 0,void 0,void 0,void 0,l.stencil?ti:Bs),stencilBuffer:l.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});h.autoAllocateDepthBuffer=!0;const u=new Ai({color:16777215,side:Ks});u.map=h.texture,u.map.offset.y=1,u.map.repeat.y=-1;const d=new li(c,u);d.position.copy(s),d.quaternion.copy(i);const p={type:"quad",width:e,height:t,translation:s,quaternion:i,pixelwidth:n,pixelheight:r,plane:d,material:u,rendercall:o,renderTarget:h};if(this._layers.push(p),this._session!==null){p.plane.material=new Ai({color:16777215,side:Ks}),p.plane.material.blending=na,p.plane.material.blendEquation=bs,p.plane.material.blendSrc=vi,p.plane.material.blendDst=vi,p.xrlayer=this._createXRLayer(p);const f=this._session.renderState.layers;f.unshift(p.xrlayer),this._session.updateRenderState({layers:f})}else h.isXRRenderTarget=!1;return d}createCylinderLayer(e,t,s,i,n,r,o,l,c={}){const h=new Vu(e,e,e*t/s,64,64,!0,Math.PI-t/2,t),u=new Kr(r,o,{format:rs,type:Rt,depthTexture:new Is(r,o,c.stencil?Ni:Ye,void 0,void 0,void 0,void 0,void 0,void 0,c.stencil?ti:Bs),stencilBuffer:c.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});u.autoAllocateDepthBuffer=!0;const d=new Ai({color:16777215,side:zt});d.map=u.texture,d.map.offset.y=1,d.map.repeat.y=-1;const p=new li(h,d);p.position.copy(i),p.quaternion.copy(n);const f={type:"cylinder",radius:e,centralAngle:t,aspectratio:s,translation:i,quaternion:n,pixelwidth:r,pixelheight:o,plane:p,material:d,rendercall:l,renderTarget:u};if(this._layers.push(f),this._session!==null){f.plane.material=new Ai({color:16777215,side:zt}),f.plane.material.blending=na,f.plane.material.blendEquation=bs,f.plane.material.blendSrc=vi,f.plane.material.blendDst=vi,f.xrlayer=this._createXRLayer(f);const m=this._session.renderState.layers;m.unshift(f.xrlayer),this._session.updateRenderState({layers:m})}else u.isXRRenderTarget=!1;return p}renderLayers(){const e=new N,t=new pr,s=this._renderer,i=this.isPresenting,n=s.getOutputRenderTarget(),r=s._frameBufferTarget;this.isPresenting=!1;const o=new ce;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._supportsLayers){c.xrlayer.transform=new XRRigidTransform(c.plane.getWorldPosition(e),c.plane.getWorldQuaternion(t));const h=this._glBinding.getSubImage(c.xrlayer,this._xrFrame);s.backend.setXRRenderTargetTextures(c.renderTarget,h.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:u,quad:d}=this._frameBufferTargets.get(c.renderTarget)||{frameBufferTarget:null,quad:null};u?(s._frameBufferTarget=u,s._quad=d):(s._quad=new Ou(new tt),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=r,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._useLayers===!0){let r=null,o=null,l=null;t.depth&&(l=t.stencil?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT24,r=t.stencil?ti:Bs,o=t.stencil?Ni:Ye);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);const h=new XRWebGLBinding(e,i),u=h.createProjectionLayer(c),d=[u];this._glBinding=h,this._glProjLayer=u,t.setPixelRatio(1),t._setXRLayerSize(u.textureWidth,u.textureHeight);const p=this._useMultiview?2:1,f=new Is(u.textureWidth,u.textureHeight,o,void 0,void 0,void 0,void 0,void 0,void 0,r,p);if(this._xrRenderTarget=new Kr(u.textureWidth,u.textureHeight,{format:rs,type:Rt,colorSpace:t.outputColorSpace,depthTexture:f,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._supportsLayers=e.enabledFeatures.includes("layers"),this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType()),this._supportsLayers)for(const m of this._layers)m.plane.material=new Ai({color:16777215,side:m.type==="cylinder"?zt:Ks}),m.plane.material.blending=na,m.plane.material.blendEquation=bs,m.plane.material.blendSrc=vi,m.plane.material.blendDst=vi,m.xrlayer=this._createXRLayer(m),d.unshift(m.xrlayer);e.updateRenderState({layers:d})}else{const r={antialias:t.samples>0,alpha:!0,depth:t.depth,stencil:t.stencil,framebufferScaleFactor:this.getFramebufferScaleFactor()},o=new XRWebGLLayer(e,i,r);this._glBaseLayer=o,e.updateRenderState({baseLayer:o}),t.setPixelRatio(1),t._setXRLayerSize(o.framebufferWidth,o.framebufferHeight),this._xrRenderTarget=new Kr(o.framebufferWidth,o.framebufferHeight,{format:rs,type:Rt,colorSpace:t.outputColorSpace,stencilBuffer:t.stencil,resolveDepthBuffer:o.ignoreDepthValues===!1,resolveStencilBuffer:o.ignoreDepthValues===!1}),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,r=this._cameraL,o=this._cameraR;n.near=o.near=r.near=s,n.far=o.far=r.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),r.layers.mask=e.layers.mask|2,o.layers.mask=e.layers.mask|4,n.layers.mask=r.layers.mask|o.layers.mask;const l=e.parent,c=n.cameras;of(n,l);for(let h=0;h<c.length;h++)of(c[h],l);c.length===2?NC(n,r,o):n.projectionMatrix.copy(r.projectionMatrix),PC(e,n,l)}_getController(e){let t=this._controllers[e];return t===void 0&&(t=new AC,this._controllers[e]=t),t}}function NC(a,e,t){rf.setFromMatrixPosition(e.matrixWorld),af.setFromMatrixPosition(t.matrixWorld);const s=rf.distanceTo(af),i=e.projectionMatrix.elements,n=t.projectionMatrix.elements,r=i[14]/(i[10]-1),o=i[14]/(i[10]+1),l=(i[9]+1)/i[5],c=(i[9]-1)/i[5],h=(i[8]-1)/i[0],u=(n[8]+1)/n[0],d=r*h,p=r*u,f=s/(-h+u),m=f*-h;if(e.matrixWorld.decompose(a.position,a.quaternion,a.scale),a.translateX(m),a.translateZ(f),a.matrixWorld.compose(a.position,a.quaternion,a.scale),a.matrixWorldInverse.copy(a.matrixWorld).invert(),i[10]===-1)a.projectionMatrix.copy(e.projectionMatrix),a.projectionMatrixInverse.copy(e.projectionMatrixInverse);else{const y=r+f,g=o+f,_=d-m,b=p+(s-m),S=l*o/g*y,T=c*o/g*y;a.projectionMatrix.makePerspective(_,b,S,T,y,g),a.projectionMatrixInverse.copy(a.projectionMatrix).invert()}}function of(a,e){e===null?a.matrixWorld.copy(a.matrix):a.matrixWorld.multiplyMatrices(e.matrixWorld,a.matrix),a.matrixWorldInverse.copy(a.matrixWorld).invert()}function PC(a,e,t){t===null?a.matrix.copy(e.matrixWorld):(a.matrix.copy(t.matrixWorld),a.matrix.invert(),a.matrix.multiply(e.matrixWorld)),a.matrix.decompose(a.position,a.quaternion,a.scale),a.updateMatrixWorld(!0),a.projectionMatrix.copy(e.projectionMatrix),a.projectionMatrixInverse.copy(e.projectionMatrixInverse),a.isPerspectiveCamera&&(a.fov=nr*2*Math.atan(1/a.projectionMatrix.elements[5]),a.zoom=1)}function FC(a){const e=this._controllerInputSources.indexOf(a.inputSource);if(e===-1)return;const t=this._controllers[e];if(t!==void 0){const s=this.getReferenceSpace();t.update(a.inputSource,a.frame,s),t.dispatchEvent({type:a.type,data:a.inputSource})}}function DC(){const a=this._session,e=this._renderer;a.removeEventListener("select",this._onSessionEvent),a.removeEventListener("selectstart",this._onSessionEvent),a.removeEventListener("selectend",this._onSessionEvent),a.removeEventListener("squeeze",this._onSessionEvent),a.removeEventListener("squeezestart",this._onSessionEvent),a.removeEventListener("squeezeend",this._onSessionEvent),a.removeEventListener("end",this._onSessionEnd),a.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._supportsLayers===!0)for(const t of this._layers)t.renderTarget=new Kr(t.pixelwidth,t.pixelheight,{format:rs,type:Rt,depthTexture:new Is(t.pixelwidth,t.pixelheight,t.stencilBuffer?Ni:Ye,void 0,void 0,void 0,void 0,void 0,void 0,t.stencilBuffer?ti:Bs),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 OC(a){const e=this._controllers,t=this._controllerInputSources;for(let s=0;s<a.removed.length;s++){const i=a.removed[s],n=t.indexOf(i);n>=0&&(t[n]=null,e[n].disconnect(i))}for(let s=0;s<a.added.length;s++){const i=a.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 r=e[n];r&&r.connect(i)}}function BC(a){return a.type==="quad"?this._glBinding.createQuadLayer({transform:new XRRigidTransform(a.translation,a.quaternion),width:a.width/2,height:a.height/2,space:this._referenceSpace,viewPixelWidth:a.pixelwidth,viewPixelHeight:a.pixelheight,clearOnAccess:!1}):this._glBinding.createCylinderLayer({transform:new XRRigidTransform(a.translation,a.quaternion),radius:a.radius,centralAngle:a.centralAngle,aspectRatio:a.aspectRatio,space:this._referenceSpace,viewPixelWidth:a.pixelwidth,viewPixelHeight:a.pixelheight,clearOnAccess:!1})}function IC(a,e){if(e===void 0)return;const t=this._cameraXR,s=this._renderer,i=s.backend,n=this._glBaseLayer,r=this.getReferenceSpace(),o=e.getViewerPose(r);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 h=0;h<l.length;h++){const u=l[h];let d;if(this._useLayers===!0){const f=this._glBinding.getViewSubImage(this._glProjLayer,u);d=f.viewport,h===0&&i.setXRRenderTargetTextures(this._xrRenderTarget,f.colorTexture,this._glProjLayer.ignoreDepthValues&&!this._useMultiview?void 0:f.depthStencilTexture)}else d=n.getViewport(u);let p=this._cameras[h];p===void 0&&(p=new Xt,p.layers.enable(h),p.viewport=new me,this._cameras[h]=p),p.matrix.fromArray(u.transform.matrix),p.matrix.decompose(p.position,p.quaternion,p.scale),p.projectionMatrix.fromArray(u.projectionMatrix),p.projectionMatrixInverse.copy(p.projectionMatrix).invert(),p.viewport.set(d.x,d.y,d.width,d.height),h===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],h=this._controllers[l];c!==null&&h!==void 0&&h.update(c,e,r)}this._currentAnimationLoop&&this._currentAnimationLoop(a,e),e.detectedPlanes&&this.dispatchEvent({type:"planesdetected",data:e}),this._xrFrame=null}const Wi=new pl,oo=new N;class Wu{constructor(e=new Ei,t=new Ei,s=new Ei,i=new Ei,n=new Ei,r=new Ei){this.planes=[e,t,s,i,n,r]}set(e,t,s,i,n,r){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(r),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=Lt){const s=this.planes,i=e.elements,n=i[0],r=i[1],o=i[2],l=i[3],c=i[4],h=i[5],u=i[6],d=i[7],p=i[8],f=i[9],m=i[10],y=i[11],g=i[12],_=i[13],b=i[14],S=i[15];if(s[0].setComponents(l-n,d-c,y-p,S-g).normalize(),s[1].setComponents(l+n,d+c,y+p,S+g).normalize(),s[2].setComponents(l+r,d+h,y+f,S+_).normalize(),s[3].setComponents(l-r,d-h,y-f,S-_).normalize(),s[4].setComponents(l-o,d-u,y-m,S-b).normalize(),t===Lt)s[5].setComponents(l+o,d+u,y+m,S+b).normalize();else if(t===Fi)s[5].setComponents(o,u,m,b).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(),Wi.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),Wi.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Wi)}intersectsSprite(e){return Wi.center.set(0,0,0),Wi.radius=.7071067811865476,Wi.applyMatrix4(e.matrixWorld),this.intersectsSphere(Wi)}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(oo.x=i.normal.x>0?e.max.x:e.min.x,oo.y=i.normal.y>0?e.max.y:e.min.y,oo.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(oo)<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 Ms=new Be,Cs=new Wu;class $u{constructor(){this.coordinateSystem=Lt}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(Ms.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Cs.setFromProjectionMatrix(Ms,this.coordinateSystem),Cs.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(Ms.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Cs.setFromProjectionMatrix(Ms,this.coordinateSystem),Cs.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(Ms.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Cs.setFromProjectionMatrix(Ms,this.coordinateSystem),Cs.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(Ms.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Cs.setFromProjectionMatrix(Ms,this.coordinateSystem),Cs.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(Ms.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Cs.setFromProjectionMatrix(Ms,this.coordinateSystem),Cs.containsPoint(e))return!0}return!1}clone(){return new $u}}const lf=new ru,lo=new ce,Fc=new me,Dc=new Wu,Oc=new $u,co=new Be,xi=new me;class LC{constructor(e,t={}){this.isRenderer=!0;const{logarithmicDepthBuffer:s=!1,alpha:i=!0,depth:n=!0,stencil:r=!1,antialias:o=!1,samples:l=0,getFallback:c=null,colorBufferType:h=ns,multiview:u=!1}=t;this.domElement=e.getDomElement(),this.backend=e,this.samples=l||o===!0?4:0,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.alpha=i,this.logarithmicDepthBuffer=s,this.outputColorSpace=Yt,this.toneMapping=Xn,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=n,this.stencil=r,this.info=new z_,this.overrideNodes={modelViewMatrix:null,modelNormalViewMatrix:null},this.library=new by,this.lighting=new EC,this._getFallback=c,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new me(0,0,this._width,this._height),this._scissor=new me(0,0,this._width,this._height),this._scissorTest=!1,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 Ou(new tt),this._quad.material.name="Renderer_output",this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null,this._frameBufferTarget=null;const d=this.alpha===!0?0:1;this._clearColor=new lu(0,0,0,d),this._clearDepth=1,this._clearStencil=0,this._renderTarget=null,this._activeCubeFace=0,this._activeMipmapLevel=0,this._outputRenderTarget=null,this._mrt=null,this._renderObjectFunction=null,this._currentRenderObjectFunction=null,this._currentRenderBundle=null,this._handleObjectFunction=this._renderObjectDirect,this._isDeviceLost=!1,this.onDeviceLost=this._onDeviceLost,this._colorBufferType=h,this._initialized=!1,this._initPromise=null,this._compilationPromises=null,this.transparent=!0,this.opaque=!0,this.shadowMap={enabled:!1,type:Wx},this.xr=new RC(this,u),this.debug={checkShaderErrors:!0,onShaderError:null,getShaderAsync:async(p,f,m)=>{await this.compileAsync(p,f);const y=this._renderLists.get(p,f),g=this._renderContexts.get(p,f,this._renderTarget),_=p.overrideMaterial||m.material,b=this._objects.get(m,_,p,f,y.lightsNode,g,g.clippingContext),{fragmentShader:S,vertexShader:T}=b.getNodeBuilderState();return{fragmentShader:S,vertexShader:T}}}}async init(){if(this._initialized)throw new Error("Renderer: Backend has already been initialized.");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 TC(this,s),this._animation=new kx(this._nodes,this.info),this._attributes=new I_(s),this._background=new hM(this,this._nodes),this._geometries=new k_(this._attributes,this.info),this._textures=new cb(this,s,this.info),this._pipelines=new W_(s,this._nodes),this._bindings=new $_(s,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new D_(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new Y_(this.lighting),this._bundles=new vC,this._renderContexts=new nb,this._animation.start(),this._initialized=!0,e(this)}),this._initPromise)}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,r=this._currentRenderContext,o=this._currentRenderObjectFunction,l=this._compilationPromises,c=e.isScene===!0?e:lf;s===null&&(s=e);const h=this._renderTarget,u=this._renderContexts.get(s,t,h),d=this._activeMipmapLevel,p=[];this._currentRenderContext=u,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=p,i.renderId++,i.update(),u.depth=this.depth,u.stencil=this.stencil,u.clippingContext||(u.clippingContext=new sl),u.clippingContext.updateGlobal(c,t),c.onBeforeRender(this,e,t,h);const f=this._renderLists.get(e,t);if(f.begin(),this._projectObject(e,t,0,f,u.clippingContext),s!==e&&s.traverseVisible(function(b){b.isLight&&b.layers.test(t.layers)&&f.pushLight(b)}),f.finish(),h!==null){this._textures.updateRenderTarget(h,d);const b=this._textures.get(h);u.textures=b.textures,u.depthTexture=b.depthTexture}else u.textures=null,u.depthTexture=null;this._background.update(c,f,u);const m=f.opaque,y=f.transparent,g=f.transparentDoublePass,_=f.lightsNode;this.opaque===!0&&m.length>0&&this._renderObjects(m,t,c,_),this.transparent===!0&&y.length>0&&this._renderTransparents(y,g,t,c,_),i.renderId=n,this._currentRenderContext=r,this._currentRenderObjectFunction=o,this._compilationPromises=l,this._handleObjectFunction=this._renderObjectDirect,await Promise.all(p)}async renderAsync(e,t){this._initialized===!1&&await this.init(),this._renderScene(e,t)}async waitForGPU(){await this.backend.waitForGPU()}set highPrecision(e){e===!0?(this.overrideNodes.modelViewMatrix=rp,this.overrideNodes.modelNormalViewMatrix=ap):this.highPrecision&&(this.overrideNodes.modelViewMatrix=null,this.overrideNodes.modelNormalViewMatrix=null)}get highPrecision(){return this.overrideNodes.modelViewMatrix===rp&&this.overrideNodes.modelNormalViewMatrix===ap}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getColorBufferType(){return this._colorBufferType}_onDeviceLost(e){let t=`THREE.WebGPURenderer: ${e.api} Device Lost:
|
123
|
+
|
124
|
+
Message: ${e.message}`;e.reason&&(t+=`
|
125
|
+
Reason: ${e.reason}`),console.error(t),this._isDeviceLost=!0}_renderBundle(e,t,s){const{bundleGroup:i,camera:n,renderList:r}=e,o=this._currentRenderContext,l=this._bundles.get(i,n),c=this.backend.get(l);c.renderContexts===void 0&&(c.renderContexts=new Set);const h=i.version!==c.version,u=c.renderContexts.has(o)===!1||h;if(c.renderContexts.add(o),u){this.backend.beginBundle(o),(c.renderObjects===void 0||h)&&(c.renderObjects=[]),this._currentRenderBundle=l;const{transparentDoublePass:d,transparent:p,opaque:f}=r;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)return console.warn("THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead."),this.renderAsync(e,t);this._renderScene(e,t)}_getFrameBufferTarget(){const{currentToneMapping:e,currentColorSpace:t}=this;if(e!==Xn===!1&&t!==Zn===!1)return null;const{width:n,height:r}=this.getDrawingBufferSize(lo),{depth:o,stencil:l}=this;let c=this._frameBufferTarget;c===null&&(c=new dn(n,r,{depthBuffer:o,stencilBuffer:l,type:this._colorBufferType,format:rs,colorSpace:Zn,generateMipmaps:!1,minFilter:Qt,magFilter:Qt,samples:this.samples}),c.isPostProcessingRenderTarget=!0,this._frameBufferTarget=c);const h=this.getOutputRenderTarget();return c.depthBuffer=o,c.stencilBuffer=l,h!==null?c.setSize(h.width,h.height,h.depth):c.setSize(n,r,1),c.viewport.copy(this._viewport),c.scissor.copy(this._scissor),c.viewport.multiplyScalar(this._pixelRatio),c.scissor.multiplyScalar(this._pixelRatio),c.scissorTest=this._scissorTest,c.multiview=h!==null?h.multiview:!1,c.resolveDepthBuffer=h!==null?h.resolveDepthBuffer:!0,c.autoAllocateDepthBuffer=h!==null?h.autoAllocateDepthBuffer:!1,c}_renderScene(e,t,s=!0){if(this._isDeviceLost===!0)return;const i=s?this._getFrameBufferTarget():null,n=this._nodes.nodeFrame,r=n.renderId,o=this._currentRenderContext,l=this._currentRenderObjectFunction,c=e.isScene===!0?e:lf,h=this._renderTarget||this._outputRenderTarget,u=this._activeCubeFace,d=this._activeMipmapLevel;let p;i!==null?(p=i,this.setRenderTarget(p)):p=h;const f=this._renderContexts.get(e,t,p);this._currentRenderContext=f,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this.info.calls++,this.info.render.calls++,this.info.render.frameCalls++,n.renderId=this.info.calls;const m=this.coordinateSystem,y=this.xr;if(t.coordinateSystem!==m&&y.isPresenting===!1&&(t.coordinateSystem=m,t.updateProjectionMatrix(),t.isArrayCamera))for(const j of t.cameras)j.coordinateSystem=m,j.updateProjectionMatrix();e.matrixWorldAutoUpdate===!0&&e.updateMatrixWorld(),t.parent===null&&t.matrixWorldAutoUpdate===!0&&t.updateMatrixWorld(),y.enabled===!0&&y.isPresenting===!0&&(y.cameraAutoUpdate===!0&&y.updateCamera(t),t=y.getCamera());let g=this._viewport,_=this._scissor,b=this._pixelRatio;p!==null&&(g=p.viewport,_=p.scissor,b=1),this.getDrawingBufferSize(lo),Fc.set(0,0,lo.width,lo.height);const S=g.minDepth===void 0?0:g.minDepth,T=g.maxDepth===void 0?1:g.maxDepth;f.viewportValue.copy(g).multiplyScalar(b).floor(),f.viewportValue.width>>=d,f.viewportValue.height>>=d,f.viewportValue.minDepth=S,f.viewportValue.maxDepth=T,f.viewport=f.viewportValue.equals(Fc)===!1,f.scissorValue.copy(_).multiplyScalar(b).floor(),f.scissor=this._scissorTest&&f.scissorValue.equals(Fc)===!1,f.scissorValue.width>>=d,f.scissorValue.height>>=d,f.clippingContext||(f.clippingContext=new sl),f.clippingContext.updateGlobal(c,t),c.onBeforeRender(this,e,t,p);const M=t.isArrayCamera?Oc:Dc;t.isArrayCamera||(co.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),M.setFromProjectionMatrix(co,m));const w=this._renderLists.get(e,t);if(w.begin(),this._projectObject(e,t,0,w,f.clippingContext),w.finish(),this.sortObjects===!0&&w.sort(this._opaqueSort,this._transparentSort),p!==null){this._textures.updateRenderTarget(p,d);const j=this._textures.get(p);f.textures=j.textures,f.depthTexture=j.depthTexture,f.width=j.width,f.height=j.height,f.renderTarget=p,f.depth=p.depthBuffer,f.stencil=p.stencilBuffer}else f.textures=null,f.depthTexture=null,f.width=this.domElement.width,f.height=this.domElement.height,f.depth=this.depth,f.stencil=this.stencil;f.width>>=d,f.height>>=d,f.activeCubeFace=u,f.activeMipmapLevel=d,f.occlusionQueryCount=w.occlusionQueryCount,this._background.update(c,w,f),f.camera=t,this.backend.beginRender(f);const{bundles:R,lightsNode:P,transparentDoublePass:z,transparent:$,opaque:q}=w;return R.length>0&&this._renderBundles(R,c,P),this.opaque===!0&&q.length>0&&this._renderObjects(q,t,c,P),this.transparent===!0&&$.length>0&&this._renderTransparents($,z,t,c,P),this.backend.finishRender(f),n.renderId=r,this._currentRenderContext=o,this._currentRenderObjectFunction=l,i!==null&&(this.setRenderTarget(h,u,d),this._renderOutput(p)),c.onAfterRender(this,e,t,p),f}_setXRLayerSize(e,t){this._width=e,this._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)}async getArrayBufferAsync(e){return await this.backend.getArrayBufferAsync(e)}getContext(){return this.backend.getContext()}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._initialized&&this.backend.updateSize())}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._initialized&&this.backend.updateSize())}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}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,this.backend.setScissorTest(e)}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,s,i,n=0,r=1){const o=this._viewport;e.isVector4?o.copy(e):o.set(e,t,s,i),o.minDepth=n,o.maxDepth=r}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._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)return console.warn("THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead."),this.clearAsync(e,t,s);const i=this._renderTarget||this._getFrameBufferTarget();let n=null;if(i!==null){this._textures.updateRenderTarget(i);const r=this._textures.get(i);n=this._renderContexts.getForClear(i),n.textures=r.textures,n.depthTexture=r.depthTexture,n.width=r.width,n.height=r.height,n.renderTarget=i,n.depth=i.depthBuffer,n.stencil=i.stencilBuffer,n.clearColorValue=this.backend.getClearColor(),n.activeCubeFace=this.getActiveCubeFace(),n.activeMipmapLevel=this.getActiveMipmapLevel()}this.backend.clear(e,t,s,n),i!==null&&this._renderTarget===null&&this._renderOutput(i)}clearColor(){return this.clear(!0,!1,!1)}clearDepth(){return this.clear(!1,!0,!1)}clearStencil(){return this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,s=!0){this._initialized===!1&&await this.init(),this.clear(e,t,s)}async clearColorAsync(){this.clearAsync(!0,!1,!1)}async clearDepthAsync(){this.clearAsync(!1,!0,!1)}async clearStencilAsync(){this.clearAsync(!1,!1,!0)}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:Xn}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:Zn}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||this._renderTarget===null}dispose(){this.info.dispose(),this.backend.dispose(),this._animation.dispose(),this._objects.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}_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){if(this._isDeviceLost===!0)return;if(this._initialized===!1)return console.warn("THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e);const t=this._nodes.nodeFrame,s=t.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,t.renderId=this.info.calls;const i=this.backend,n=this._pipelines,r=this._bindings,o=this._nodes,l=Array.isArray(e)?e:[e];if(l[0]===void 0||l[0].isComputeNode!==!0)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");i.beginCompute(e);for(const c of l){if(n.has(c)===!1){const d=()=>{c.removeEventListener("dispose",d),n.delete(c),r.delete(c),o.delete(c)};c.addEventListener("dispose",d);const p=c.onInitFunction;p!==null&&p.call(c,{renderer:this})}o.updateForCompute(c),r.updateForCompute(c);const h=r.getForCompute(c),u=n.getForCompute(c,h);i.compute(e,c,h,u)}i.finishCompute(e),t.renderId=s}async computeAsync(e){this._initialized===!1&&await this.init(),this.compute(e)}async hasFeatureAsync(e){return this._initialized===!1&&await this.init(),this.backend.hasFeature(e)}async resolveTimestampsAsync(e="render"){return this._initialized===!1&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){return this._initialized===!1?(console.warn("THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead."),!1):this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){this._initialized===!1&&await this.init(),this._textures.updateTexture(e)}initTexture(e){this._initialized===!1&&console.warn("THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead."),this._textures.updateTexture(e)}copyFramebufferToTexture(e,t=null){if(t!==null)if(t.isVector2)t=xi.set(t.x,t.y,e.image.width,e.image.height).floor();else if(t.isVector4)t=xi.copy(t).floor();else{console.error("THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.");return}else t=xi.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)}copyTextureToTexture(e,t,s=null,i=null,n=0,r=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,s,i,n,r)}async readRenderTargetPixelsAsync(e,t,s,i,n,r=0,o=0){return this.backend.copyTextureToBuffer(e.textures[r],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?Oc:Dc;if(!e.frustumCulled||l.intersectsSprite(e,t)){this.sortObjects===!0&&xi.setFromMatrixPosition(e.matrixWorld).applyMatrix4(co);const{geometry:c,material:h}=e;h.visible&&i.push(e,c,h,s,xi.z,null,n)}}else if(e.isLineLoop)console.error("THREE.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?Oc:Dc;if(!e.frustumCulled||l.intersectsObject(e,t)){const{geometry:c,material:h}=e;if(this.sortObjects===!0&&(c.boundingSphere===null&&c.computeBoundingSphere(),xi.copy(c.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(co)),Array.isArray(h)){const u=c.groups;for(let d=0,p=u.length;d<p;d++){const f=u[d],m=h[f.materialIndex];m&&m.visible&&i.push(e,c,m,s,xi.z,f,n)}}else h.visible&&i.push(e,c,h,s,xi.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:r}of t)r.side=zt;this._renderObjects(t,s,i,n,"backSide");for(const{material:r}of t)r.side=Ks;this._renderObjects(e,s,i,n);for(const{material:r}of t)r.side=Yn}else this._renderObjects(e,s,i,n)}_renderObjects(e,t,s,i,n=null){for(let r=0,o=e.length;r<o;r++){const{object:l,geometry:c,material:h,group:u,clippingContext:d}=e[r];this._currentRenderObjectFunction(l,s,t,c,h,u,i,d,n)}}renderObject(e,t,s,i,n,r,o,l=null,c=null){let h,u,d;if(e.onBeforeRender(this,t,s,i,n,r),n.allowOverride===!0&&t.overrideMaterial!==null){const p=t.overrideMaterial;n.positionNode&&n.positionNode.isNode&&(h=p.positionNode,p.positionNode=n.positionNode),p.alphaTest=n.alphaTest,p.alphaMap=n.alphaMap,p.transparent=n.transparent||n.transmission>0,p.isShadowPassMaterial&&(p.side=n.shadowSide===null?n.side:n.shadowSide,n.depthNode&&n.depthNode.isNode&&(d=p.depthNode,p.depthNode=n.depthNode),n.castShadowNode&&n.castShadowNode.isNode&&(u=p.colorNode,p.colorNode=n.castShadowNode),n.castShadowPositionNode&&n.castShadowPositionNode.isNode&&(h=p.positionNode,p.positionNode=n.castShadowPositionNode)),n=p}n.transparent===!0&&n.side===Yn&&n.forceSinglePass===!1?(n.side=zt,this._handleObjectFunction(e,n,t,s,o,r,l,"backSide"),n.side=Ks,this._handleObjectFunction(e,n,t,s,o,r,l,c),n.side=Yn):this._handleObjectFunction(e,n,t,s,o,r,l,c),h!==void 0&&(t.overrideMaterial.positionNode=h),d!==void 0&&(t.overrideMaterial.depthNode=d),u!==void 0&&(t.overrideMaterial.colorNode=u),e.onAfterRender(this,t,s,i,n,r)}_renderObjectDirect(e,t,s,i,n,r,o,l){const c=this._objects.get(e,t,s,i,n,this._currentRenderContext,o,l);c.drawRange=e.geometry.drawRange,c.group=r;const h=this._nodes.needsRefresh(c);h&&(this._nodes.updateBefore(c),this._geometries.updateForRender(c),this._nodes.updateForRender(c),this._bindings.updateForRender(c)),this._pipelines.updateForRender(c),this._currentRenderBundle!==null&&(this.backend.get(this._currentRenderBundle).renderObjects.push(c),c.bundle=this._currentRenderBundle.bundleGroup),this.backend.draw(c,this.info),h&&this._nodes.updateAfter(c)}_createObjectPipeline(e,t,s,i,n,r,o,l){const c=this._objects.get(e,t,s,i,n,this._currentRenderContext,o,l);c.drawRange=e.geometry.drawRange,c.group=r,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)}get compile(){return this.compileAsync}}class ju{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}clone(){return Object.assign(new this.constructor,this)}}function UC(a){return a+(Mi-a%Mi)%Mi}class Ty extends ju{constructor(e,t=null){super(e),this.isBuffer=!0,this.bytesPerElement=Float32Array.BYTES_PER_ELEMENT,this._buffer=t}get byteLength(){return UC(this._buffer.byteLength)}get buffer(){return this._buffer}update(){return!0}}class Sy extends Ty{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let kC=0;class vy extends Sy{constructor(e,t){super("UniformBuffer_"+kC++,e?e.value:null),this.nodeUniform=e,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class zC extends Sy{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[]}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],r=n.boundary,o=n.itemSize*e,l=t%Mi,c=l%r,h=l+c;t+=c,h!==0&&Mi-h<o&&(t+=Mi-h),n.offset=t/e,t+=o}return Math.ceil(t/Mi)*Mi}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);console.error("THREE.WebGPUUniformsGroup: Unsupported uniform type.",e)}updateNumber(e){let t=!1;const s=this.values,i=e.getValue(),n=e.offset,r=e.getType();if(s[n]!==i){const o=this._getBufferForType(r);o[n]=s[n]=i,t=!0}return t}updateVector2(e){let t=!1;const s=this.values,i=e.getValue(),n=e.offset,r=e.getType();if(s[n+0]!==i.x||s[n+1]!==i.y){const o=this._getBufferForType(r);o[n+0]=s[n+0]=i.x,o[n+1]=s[n+1]=i.y,t=!0}return t}updateVector3(e){let t=!1;const s=this.values,i=e.getValue(),n=e.offset,r=e.getType();if(s[n+0]!==i.x||s[n+1]!==i.y||s[n+2]!==i.z){const o=this._getBufferForType(r);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}return t}updateVector4(e){let t=!1;const s=this.values,i=e.getValue(),n=e.offset,r=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(r);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}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 r=this.buffer;r[n+0]=s[n+0]=i.r,r[n+1]=s[n+1]=i.g,r[n+2]=s[n+2]=i.b,t=!0}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 r=this.buffer;r[n+0]=s[n+0]=i[0],r[n+1]=s[n+1]=i[1],r[n+2]=s[n+2]=i[2],r[n+4]=s[n+4]=i[3],r[n+5]=s[n+5]=i[4],r[n+6]=s[n+6]=i[5],r[n+8]=s[n+8]=i[6],r[n+9]=s[n+9]=i[7],r[n+10]=s[n+10]=i[8],t=!0}return t}updateMatrix4(e){let t=!1;const s=this.values,i=e.getValue().elements,n=e.offset;return VC(s,i,n)===!1&&(this.buffer.set(i,n),GC(s,i,n),t=!0),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 GC(a,e,t){for(let s=0,i=e.length;s<i;s++)a[t+s]=e[s]}function VC(a,e,t){for(let s=0,i=e.length;s<i;s++)if(a[t+s]!==e[s])return!1;return!0}let HC=0;class wy extends zC{constructor(e,t){super(e),this.id=HC++,this.groupNode=t,this.isNodeUniformsGroup=!0}}let WC=0;class $C extends ju{constructor(e,t){super(e),this.id=WC++,this.texture=t,this.version=t?t.version:0,this.store=!1,this.generation=null,this.isSampledTexture=!0}needsBindingsUpdate(e){const{texture:t}=this;return e!==this.generation?(this.generation=e,!0):t.isVideoTexture}update(){const{texture:e,version:t}=this;return t!==e.version?(this.version=e.version,!0):!1}}class wl extends $C{constructor(e,t,s,i=null){super(e,t?t.value:null),this.textureNode=t,this.groupNode=s,this.access=i}needsBindingsUpdate(e){return this.textureNode.value!==this.texture||super.needsBindingsUpdate(e)}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class Ey extends wl{constructor(e,t,s,i=null){super(e,t,s,i),this.isSampledCubeTexture=!0}}class My extends wl{constructor(e,t,s,i=null){super(e,t,s,i),this.isSampledTexture3D=!0}}class jC extends Tt{constructor(e=null,t=1,s=1,i,n,r,o,l,c=lt,h=lt,u,d){super(null,r,o,l,c,h,i,n,u,d),this.isDataTexture=!0,this.image={data:e,width:t,height:s},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}const qC={textureDimensions:"textureSize",equals:"equal"},YC={low:"lowp",medium:"mediump",high:"highp"},cf={swizzleAssign:!0,storageBuffer:!1},hf={perspective:"smooth",linear:"noperspective"},uf={centroid:"centroid","flat first":"flat","flat either":"flat"},df=`
|
126
|
+
precision highp float;
|
127
|
+
precision highp int;
|
128
|
+
precision highp sampler2D;
|
129
|
+
precision highp sampler3D;
|
130
|
+
precision highp samplerCube;
|
131
|
+
precision highp sampler2DArray;
|
132
|
+
|
133
|
+
precision highp usampler2D;
|
134
|
+
precision highp usampler3D;
|
135
|
+
precision highp usamplerCube;
|
136
|
+
precision highp usampler2DArray;
|
137
|
+
|
138
|
+
precision highp isampler2D;
|
139
|
+
precision highp isampler3D;
|
140
|
+
precision highp isamplerCube;
|
141
|
+
precision highp isampler2DArray;
|
142
|
+
|
143
|
+
precision lowp sampler2DShadow;
|
144
|
+
precision lowp sampler2DArrayShadow;
|
145
|
+
precision lowp samplerCubeShadow;
|
146
|
+
`;class XC extends fy{constructor(e,t){super(e,t,new iC),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return e.isVideoTexture===!0&&e.colorSpace!==ri}getMethod(e){return qC[e]||e}getOutputStructName(){return""}buildFunctionCode(e){const t=e.layout,s=this.flowShaderNode(e),i=[];for(const r of t.inputs)i.push(this.getType(r.type)+" "+r.name);return`${this.getType(t.type)} ${t.name}( ${i.join(", ")} ) {
|
147
|
+
|
148
|
+
${s.vars}
|
149
|
+
|
150
|
+
${s.code}
|
151
|
+
return ${s.result};
|
152
|
+
|
153
|
+
}`}setupPBO(e){const t=e.value;if(t.pbo===void 0){const s=t.array,i=t.count*t.itemSize,{itemSize:n}=t,r=t.array.constructor.name.toLowerCase().includes("int");let o=r?eu:Jh;n===2?o=r?tu:on:n===3?o=r?n_:Kh:n===4&&(o=r?su:rs);const l={Float32Array:Zt,Uint8Array:Rt,Uint16Array:Vn,Uint32Array:Ye,Int8Array:ra,Int16Array:aa,Int32Array:Mt,Uint8ClampedArray:Rt},c=Math.pow(2,Math.ceil(Math.log2(Math.sqrt(i/n))));let h=Math.ceil(i/n/c);c*h*n<i&&h++;const u=c*h*n,d=new s.constructor(u);d.set(s,0),t.array=d;const p=new jC(t.array,c,h,o,l[t.array.constructor.name]||Zt);p.needsUpdate=!0,p.isPBOTexture=!0;const f=new mr(p,null,null);f.setPrecision("high"),t.pboNode=f,t.pbo=f.value,this.getUniformFromNode(t.pboNode,"texture",this.shaderStage,this.context.label)}}getPropertyName(e,t=this.shaderStage){return e.isNodeUniform&&e.node.isTextureNode!==!0&&e.node.isBufferNode!==!0?t.charAt(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 h=this.renderer.backend.get(i);h.pbo=i.pbo}const n=this.getUniformFromNode(i.pboNode,"texture",this.shaderStage,this.context.label),r=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 h=this.getVarFromNode(e);c=this.getPropertyName(h);const u=this.getDataFromNode(t);let d=u.propertySizeName;d===void 0&&(d=c+"Size",this.getVarFromNode(t,d,"uint"),this.addLineFlowCode(`${d} = uint( textureSize( ${r}, 0 ).x )`,e),u.propertySizeName=d);const{itemSize:p}=i,f="."+fr.join("").slice(0,p),m=`ivec2(${o} % ${d}, ${o} / ${d})`,y=this.generateTextureLoad(null,r,m,null,"0");let g="vec4";i.pbo.type===Ye?g="uvec4":i.pbo.type===Mt&&(g="ivec4"),this.addLineFlowCode(`${c} = ${g}(${y})${f}`,e),l.propertyName=c}return c}generateTextureLoad(e,t,s,i,n="0"){return i?`texelFetch( ${t}, ivec3( ${s}, ${i} ), ${n} )`:`texelFetch( ${t}, ${s}, ${n} )`}generateTexture(e,t,s,i){return e.isDepthTexture?(i&&(s=`vec4( ${s}, ${i} )`),`texture( ${t}, ${s} ).x`):(i&&(s=`vec3( ${s}, ${i} )`),`texture( ${t}, ${s} )`)}generateTextureLevel(e,t,s,i){return`textureLod( ${t}, ${s}, ${i} )`}generateTextureBias(e,t,s,i){return`texture( ${t}, ${s}, ${i} )`}generateTextureGrad(e,t,s,i){return`textureGrad( ${t}, ${s}, ${i[0]}, ${i[1]} )`}generateTextureCompare(e,t,s,i,n,r=this.shaderStage){if(r==="fragment")return n?`texture( ${t}, vec4( ${s}, ${n}, ${i} ) )`:`texture( ${t}, vec3( ${s}, ${i} ) )`;console.error(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${r} 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(`
|
154
|
+
`)}getUniforms(e){const t=this.uniforms[e],s=[],i={};for(const r of t){let o=null,l=!1;if(r.type==="texture"||r.type==="texture3D"){const h=r.node.value;let u="";(h.isDataTexture===!0||h.isData3DTexture===!0)&&(h.type===Ye?u="u":h.type===Mt&&(u="i")),r.type==="texture3D"&&h.isArrayTexture===!1?o=`${u}sampler3D ${r.name};`:h.compareFunction?h.isArrayTexture===!0?o=`sampler2DArrayShadow ${r.name};`:o=`sampler2DShadow ${r.name};`:h.isArrayTexture===!0||h.isDataArrayTexture===!0||h.isCompressedArrayTexture===!0?o=`${u}sampler2DArray ${r.name};`:o=`${u}sampler2D ${r.name};`}else if(r.type==="cubeTexture")o=`samplerCube ${r.name};`;else if(r.type==="buffer"){const h=r.node,u=this.getType(h.bufferType),d=h.bufferCount,p=d>0?d:"";o=`${h.name} {
|
155
|
+
${u} ${r.name}[${p}];
|
156
|
+
};
|
157
|
+
`}else o=`${this.getVectorType(r.type)} ${this.getPropertyName(r,e)};`,l=!0;const c=r.node.precision;if(c!==null&&(o=YC[c]+" "+o),l){o=" "+o;const h=r.groupNode.name;(i[h]||(i[h]=[])).push(o)}else o="uniform "+o,s.push(o)}let n="";for(const r in i){const o=i[r];n+=this._getGLSLUniformStruct(e+"_"+r,o.join(`
|
158
|
+
`))+`
|
159
|
+
`}return n+=s.join(`
|
160
|
+
`),n}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==Mt){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};
|
161
|
+
`}return t}getStructMembers(e){const t=[];for(const s of e.members)t.push(` ${s.type} ${s.name};`);return t.join(`
|
162
|
+
`)}getStructs(e){const t=[],s=this.structs[e],i=[];for(const n of s)if(n.output)for(const r of n.members)i.push(`layout( location = ${r.index} ) out ${r.type} ${r.name};`);else{let r="struct "+n.name+` {
|
163
|
+
`;r+=this.getStructMembers(n),r+=`
|
164
|
+
};
|
165
|
+
`,t.push(r)}return i.length===0&&i.push("layout( location = 0 ) out vec4 fragColor;"),`
|
166
|
+
`+i.join(`
|
167
|
+
`)+`
|
168
|
+
|
169
|
+
`+t.join(`
|
170
|
+
`)}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 r=hf[i.interpolationType]||i.interpolationType,o=uf[i.interpolationSampling]||"";t+=`${r} ${o} out ${n} ${i.name};
|
171
|
+
`}else{const r=n.includes("int")||n.includes("uv")||n.includes("iv")?"flat ":"";t+=`${r}out ${n} ${i.name};
|
172
|
+
`}else t+=`${n} ${i.name};
|
173
|
+
`}else if(e==="fragment"){for(const i of s)if(i.needsInterpolation){const n=this.getType(i.type);if(i.interpolationType){const r=hf[i.interpolationType]||i.interpolationType,o=uf[i.interpolationSampling]||"";t+=`${r} ${o} in ${n} ${i.name};
|
174
|
+
`}else{const r=n.includes("int")||n.includes("uv")||n.includes("iv")?"flat ":"";t+=`${r}in ${n} ${i.name};
|
175
|
+
`}}}for(const i of this.builtins[e])t+=`${i};
|
176
|
+
`;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`}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(`
|
177
|
+
`)}getClipDistance(){return"gl_ClipDistance"}isAvailable(e){let t=cf[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)}cf[e]=t}return t}isFlipY(){return!0}enableHardwareClipping(e){this.enableExtension("GL_ANGLE_clip_cull_distance","require"),this.builtins.vertex.push(`out float gl_ClipDistance[ ${e} ]`)}enableMultiview(){this.enableExtension("GL_OVR_multiview2","require","fragment"),this.enableExtension("GL_OVR_multiview2","require","vertex"),this.builtins.vertex.push("layout(num_views = 2) in")}registerTransform(e,t){this.transforms.push({varyingName:e,attributeNode:t})}getTransforms(){const e=this.transforms;let t="";for(let s=0;s<e.length;s++){const i=e[s],n=this.getPropertyName(i.attributeNode);n&&(t+=`${i.varyingName} = ${n};
|
178
|
+
`)}return t}_getGLSLUniformStruct(e,t){return`
|
179
|
+
layout( std140 ) uniform ${e} {
|
180
|
+
${t}
|
181
|
+
};`}_getGLSLVertexCode(e){return`#version 300 es
|
182
|
+
|
183
|
+
${this.getSignature()}
|
184
|
+
|
185
|
+
// extensions
|
186
|
+
${e.extensions}
|
187
|
+
|
188
|
+
// precision
|
189
|
+
${df}
|
190
|
+
|
191
|
+
// uniforms
|
192
|
+
${e.uniforms}
|
193
|
+
|
194
|
+
// varyings
|
195
|
+
${e.varyings}
|
196
|
+
|
197
|
+
// attributes
|
198
|
+
${e.attributes}
|
199
|
+
|
200
|
+
// codes
|
201
|
+
${e.codes}
|
202
|
+
|
203
|
+
void main() {
|
204
|
+
|
205
|
+
// vars
|
206
|
+
${e.vars}
|
207
|
+
|
208
|
+
// transforms
|
209
|
+
${e.transforms}
|
210
|
+
|
211
|
+
// flow
|
212
|
+
${e.flow}
|
213
|
+
|
214
|
+
gl_PointSize = 1.0;
|
215
|
+
|
216
|
+
}
|
217
|
+
`}_getGLSLFragmentCode(e){return`#version 300 es
|
218
|
+
|
219
|
+
${this.getSignature()}
|
220
|
+
|
221
|
+
// extensions
|
222
|
+
${e.extensions}
|
223
|
+
|
224
|
+
// precision
|
225
|
+
${df}
|
226
|
+
|
227
|
+
// uniforms
|
228
|
+
${e.uniforms}
|
229
|
+
|
230
|
+
// varyings
|
231
|
+
${e.varyings}
|
232
|
+
|
233
|
+
// codes
|
234
|
+
${e.codes}
|
235
|
+
|
236
|
+
// structs
|
237
|
+
${e.structs}
|
238
|
+
|
239
|
+
void main() {
|
240
|
+
|
241
|
+
// vars
|
242
|
+
${e.vars}
|
243
|
+
|
244
|
+
// flow
|
245
|
+
${e.flow}
|
246
|
+
|
247
|
+
}
|
248
|
+
`}buildCode(){const e=this.material!==null?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){let s=`// code
|
249
|
+
|
250
|
+
`;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+=`
|
251
|
+
`),s+=` // flow -> ${c}
|
252
|
+
`),s+=`${l.code}
|
253
|
+
`,o===n&&t!=="compute"&&(s+=`// result
|
254
|
+
`,t==="vertex"?(s+="gl_Position = ",s+=`${l.result};`):t==="fragment"&&(o.outputNode.isOutputStructNode||(s+="fragColor = ",s+=`${l.result};`)))}const r=e[t];r.extensions=this.getExtensions(t),r.uniforms=this.getUniforms(t),r.attributes=this.getAttributes(t),r.varyings=this.getVaryings(t),r.vars=this.getVars(t),r.structs=this.getStructs(t),r.codes=this.getCodes(t),r.transforms=this.getTransforms(t),r.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),r=this.getDataFromNode(e,s,this.globalCache);let o=r.uniformGPU;if(o===void 0){const l=e.groupNode,c=l.name,h=this.getBindGroupArray(c,s);if(t==="texture")o=new wl(n.name,n.node,l),h.push(o);else if(t==="cubeTexture")o=new Ey(n.name,n.node,l),h.push(o);else if(t==="texture3D")o=new My(n.name,n.node,l),h.push(o);else if(t==="buffer"){e.name=`NodeBuffer_${e.id}`,n.name=`buffer${e.id}`;const u=new vy(e,l);u.name=e.name,h.push(u),o=u}else{const u=this.uniformGroups[s]||(this.uniformGroups[s]={});let d=u[c];d===void 0&&(d=new wy(s+"_"+c,l),u[c]=d,h.push(d)),o=this.getNodeUniform(n,t),d.addUniform(o)}r.uniformGPU=o}return n}}let Bc=null,Bn=null;class Cy{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={render:null,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(){}createSampler(){}destroySampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}isOccluded(){}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp){ai("WebGPURenderer: Timestamp tracking is disabled.");return}const t=this.timestampQueryPool[e];if(!t){ai(`WebGPURenderer: No timestamp query pool for type '${e}' found.`);return}const s=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=s,s}async waitForGPU(){}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getMaxAnisotropy(){}getDrawingBufferSize(){return Bc=Bc||new ce,this.renderer.getDrawingBufferSize(Bc)}setScissorTest(){}getClearColor(){const e=this.renderer;return Bn=Bn||new lu,e.getClearColor(Bn),Bn.getRGB(Bn),Bn}getDomElement(){let e=this.domElement;return e===null&&(e=this.parameters.canvas!==void 0?this.parameters.canvas:T_(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${lm} webgpu`),this.domElement=e),e}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)}dispose(){}}let ZC=0;class QC{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 KC{constructor(e){this.backend=e}createAttribute(e,t){const s=this.backend,{gl:i}=s,n=e.array,r=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,r),l.bufferGPU=c,l.bufferType=t,l.version=o.version);let h;if(n instanceof Float32Array)h=i.FLOAT;else if(n instanceof Uint16Array)e.isFloat16BufferAttribute?h=i.HALF_FLOAT:h=i.UNSIGNED_SHORT;else if(n instanceof Int16Array)h=i.SHORT;else if(n instanceof Uint32Array)h=i.UNSIGNED_INT;else if(n instanceof Int32Array)h=i.INT;else if(n instanceof Int8Array)h=i.BYTE;else if(n instanceof Uint8Array)h=i.UNSIGNED_BYTE;else if(n instanceof Uint8ClampedArray)h=i.UNSIGNED_BYTE;else throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+n);let u={bufferGPU:c,bufferType:t,type:h,byteLength:n.byteLength,bytesPerElement:n.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:h===i.INT||h===i.UNSIGNED_INT||e.gpuType===Mt,id:ZC++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const d=this._createBuffer(i,t,n,r);u=new QC(u,d)}s.set(e,u)}updateAttribute(e){const t=this.backend,{gl:s}=t,i=e.array,n=e.isInterleavedBufferAttribute?e.data:e,r=t.get(n),o=r.bufferType,l=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(s.bindBuffer(o,r.bufferGPU),l.length===0)s.bufferSubData(o,0,i);else{for(let c=0,h=l.length;c<h;c++){const u=l[c];s.bufferSubData(o,u.start*i.BYTES_PER_ELEMENT,i,u.start,u.count)}n.clearUpdateRanges()}s.bindBuffer(o,null),r.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),r=e.array,o=r.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(r.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 Ic,Ur;class JC{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.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;Ic={[bs]:e.FUNC_ADD,[cm]:e.FUNC_SUBTRACT,[hm]:e.FUNC_REVERSE_SUBTRACT},Ur={[vi]:e.ZERO,[um]:e.ONE,[dm]:e.SRC_COLOR,[Go]:e.SRC_ALPHA,[xm]:e.SRC_ALPHA_SATURATE,[gm]:e.DST_COLOR,[fm]:e.DST_ALPHA,[pm]:e.ONE_MINUS_SRC_COLOR,[Vo]:e.ONE_MINUS_SRC_ALPHA,[ym]:e.ONE_MINUS_DST_COLOR,[mm]:e.ONE_MINUS_DST_ALPHA};const t=e.getParameter(e.SCISSOR_BOX),s=e.getParameter(e.VIEWPORT);this.currentScissor=new me().fromArray(t),this.currentViewport=new me().fromArray(s),this._tempVec4=new me}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!==zx?(this.enable(t.CULL_FACE),e!==this.currentCullFace&&(e===Gx?t.cullFace(t.BACK):e===Vx?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)}setBlending(e,t,s,i,n,r,o,l){const{gl:c}=this;if(e===rr){this.currentBlendingEnabled===!0&&(this.disable(c.BLEND),this.currentBlendingEnabled=!1);return}if(this.currentBlendingEnabled===!1&&(this.enable(c.BLEND),this.currentBlendingEnabled=!0),e!==na){if(e!==this.currentBlending||l!==this.currentPremultipledAlpha){if((this.currentBlendEquation!==bs||this.currentBlendEquationAlpha!==bs)&&(c.blendEquation(c.FUNC_ADD),this.currentBlendEquation=bs,this.currentBlendEquationAlpha=bs),l)switch(e){case Js:c.blendFuncSeparate(c.ONE,c.ONE_MINUS_SRC_ALPHA,c.ONE,c.ONE_MINUS_SRC_ALPHA);break;case Uo:c.blendFunc(c.ONE,c.ONE);break;case ko:c.blendFuncSeparate(c.ZERO,c.ONE_MINUS_SRC_COLOR,c.ZERO,c.ONE);break;case zo:c.blendFuncSeparate(c.ZERO,c.SRC_COLOR,c.ZERO,c.SRC_ALPHA);break;default:console.error("THREE.WebGLState: Invalid blending: ",e);break}else switch(e){case Js:c.blendFuncSeparate(c.SRC_ALPHA,c.ONE_MINUS_SRC_ALPHA,c.ONE,c.ONE_MINUS_SRC_ALPHA);break;case Uo:c.blendFunc(c.SRC_ALPHA,c.ONE);break;case ko:c.blendFuncSeparate(c.ZERO,c.ONE_MINUS_SRC_COLOR,c.ZERO,c.ONE);break;case zo:c.blendFunc(c.ZERO,c.SRC_COLOR);break;default:console.error("THREE.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,r=r||s,o=o||i,(t!==this.currentBlendEquation||n!==this.currentBlendEquationAlpha)&&(c.blendEquationSeparate(Ic[t],Ic[n]),this.currentBlendEquation=t,this.currentBlendEquationAlpha=n),(s!==this.currentBlendSrc||i!==this.currentBlendDst||r!==this.currentBlendSrcAlpha||o!==this.currentBlendDstAlpha)&&(c.blendFuncSeparate(Ur[s],Ur[i],Ur[r],Ur[o]),this.currentBlendSrc=s,this.currentBlendDst=i,this.currentBlendSrcAlpha=r,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)}setDepthMask(e){this.currentDepthMask!==e&&(this.gl.depthMask(e),this.currentDepthMask=e)}setDepthFunc(e){if(this.currentDepthFunc!==e){const{gl:t}=this;switch(e){case _m:t.depthFunc(t.NEVER);break;case bm:t.depthFunc(t.ALWAYS);break;case Tm:t.depthFunc(t.LESS);break;case Ho:t.depthFunc(t.LEQUAL);break;case Sm:t.depthFunc(t.EQUAL);break;case vm:t.depthFunc(t.GEQUAL);break;case wm:t.depthFunc(t.GREATER);break;case Em: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:r}=this;r.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:r}=this;r.viewport(n.x,n.y,n.z,n.w),this.currentViewport.copy(n)}}setScissorTest(e){const t=this.gl;e?t.enable(t.SCISSOR_TEST):t.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===Yn?this.disable(i.CULL_FACE):this.enable(i.CULL_FACE);let n=e.side===zt;t&&(n=!n),this.setFlipSided(n),e.blending===Js&&e.transparent===!1?this.setBlending(rr):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 r=e.stencilWrite;if(this.setStencilTest(r),r&&(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.samples>1?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 r=e.textures;if(i.length!==r.length||i[0]!==s.COLOR_ATTACHMENT0){for(let o=0,l=r.length;o<l;o++)i[o]=s.COLOR_ATTACHMENT0+o;i.length=r.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:r,maxTextures:o}=this;s===void 0&&(n===null?s=i.TEXTURE0+o-1:s=n);let l=r[s];l===void 0&&(l={type:void 0,texture:void 0},r[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 eA{constructor(e){this.backend=e,this.gl=this.backend.gl,this.extensions=e.extensions}convert(e,t=ri){const{gl:s,extensions:i}=this;let n;const r=Le.getTransfer(t);if(e===Rt)return s.UNSIGNED_BYTE;if(e===t_)return s.UNSIGNED_SHORT_4_4_4_4;if(e===s_)return s.UNSIGNED_SHORT_5_5_5_1;if(e===Cm)return s.UNSIGNED_INT_5_9_9_9_REV;if(e===ra)return s.BYTE;if(e===aa)return s.SHORT;if(e===Vn)return s.UNSIGNED_SHORT;if(e===Mt)return s.INT;if(e===Ye)return s.UNSIGNED_INT;if(e===Zt)return s.FLOAT;if(e===ns)return s.HALF_FLOAT;if(e===i_)return s.ALPHA;if(e===Kh)return s.RGB;if(e===rs)return s.RGBA;if(e===Bs)return s.DEPTH_COMPONENT;if(e===ti)return s.DEPTH_STENCIL;if(e===Jh)return s.RED;if(e===eu)return s.RED_INTEGER;if(e===on)return s.RG;if(e===tu)return s.RG_INTEGER;if(e===su)return s.RGBA_INTEGER;if(e===Il||e===Eo||e===Mo||e===Co)if(r===se)if(n=i.get("WEBGL_compressed_texture_s3tc_srgb"),n!==null){if(e===Il)return n.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(e===Eo)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(e===Mo)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(e===Co)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(n=i.get("WEBGL_compressed_texture_s3tc"),n!==null){if(e===Il)return n.COMPRESSED_RGB_S3TC_DXT1_EXT;if(e===Eo)return n.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(e===Mo)return n.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(e===Co)return n.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(e===Sd||e===vd||e===wd||e===Ed)if(n=i.get("WEBGL_compressed_texture_pvrtc"),n!==null){if(e===Sd)return n.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(e===vd)return n.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(e===wd)return n.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(e===Ed)return n.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(e===Md||e===uh||e===dh)if(n=i.get("WEBGL_compressed_texture_etc"),n!==null){if(e===Md||e===uh)return r===se?n.COMPRESSED_SRGB8_ETC2:n.COMPRESSED_RGB8_ETC2;if(e===dh)return r===se?n.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:n.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(e===ph||e===fh||e===mh||e===gh||e===yh||e===xh||e===_h||e===bh||e===Th||e===Sh||e===vh||e===wh||e===Eh||e===Mh)if(n=i.get("WEBGL_compressed_texture_astc"),n!==null){if(e===ph)return r===se?n.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:n.COMPRESSED_RGBA_ASTC_4x4_KHR;if(e===fh)return r===se?n.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:n.COMPRESSED_RGBA_ASTC_5x4_KHR;if(e===mh)return r===se?n.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:n.COMPRESSED_RGBA_ASTC_5x5_KHR;if(e===gh)return r===se?n.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:n.COMPRESSED_RGBA_ASTC_6x5_KHR;if(e===yh)return r===se?n.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:n.COMPRESSED_RGBA_ASTC_6x6_KHR;if(e===xh)return r===se?n.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:n.COMPRESSED_RGBA_ASTC_8x5_KHR;if(e===_h)return r===se?n.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:n.COMPRESSED_RGBA_ASTC_8x6_KHR;if(e===bh)return r===se?n.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:n.COMPRESSED_RGBA_ASTC_8x8_KHR;if(e===Th)return r===se?n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:n.COMPRESSED_RGBA_ASTC_10x5_KHR;if(e===Sh)return r===se?n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:n.COMPRESSED_RGBA_ASTC_10x6_KHR;if(e===vh)return r===se?n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:n.COMPRESSED_RGBA_ASTC_10x8_KHR;if(e===wh)return r===se?n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:n.COMPRESSED_RGBA_ASTC_10x10_KHR;if(e===Eh)return r===se?n.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:n.COMPRESSED_RGBA_ASTC_12x10_KHR;if(e===Mh)return r===se?n.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:n.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(e===Ll)if(n=i.get("EXT_texture_compression_bptc"),n!==null){if(e===Ll)return r===se?n.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:n.COMPRESSED_RGBA_BPTC_UNORM_EXT}else return null;if(e===r_||e===Cd||e===Ad||e===Rd)if(n=i.get("EXT_texture_compression_rgtc"),n!==null){if(e===Ll)return n.COMPRESSED_RED_RGTC1_EXT;if(e===Cd)return n.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(e===Ad)return n.COMPRESSED_RED_GREEN_RGTC2_EXT;if(e===Rd)return n.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return e===Ni?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 r=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(r===e.WAIT_FAILED){e.deleteSync(t),i();return}if(r===e.TIMEOUT_EXPIRED){requestAnimationFrame(n);return}e.deleteSync(t),s()}n()})}}let pf=!1,ho,Lc,ff;class tA{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},pf===!1&&(this._init(),pf=!0)}_init(){const e=this.gl;ho={[ar]:e.REPEAT,[Ri]:e.CLAMP_TO_EDGE,[or]:e.MIRRORED_REPEAT},Lc={[lt]:e.NEAREST,[Mm]:e.NEAREST_MIPMAP_NEAREST,[ma]:e.NEAREST_MIPMAP_LINEAR,[Qt]:e.LINEAR,[hh]:e.LINEAR_MIPMAP_NEAREST,[ei]:e.LINEAR_MIPMAP_LINEAR},ff={[Am]:e.NEVER,[Om]:e.ALWAYS,[iu]:e.LESS,[Nm]:e.LEQUAL,[Rm]:e.EQUAL,[Dm]:e.GEQUAL,[Pm]:e.GREATER,[Fm]: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:r,extensions:o}=this;if(e!==null){if(r[e]!==void 0)return r[e];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+e+"'")}let l=t;if(t===r.RED&&(s===r.FLOAT&&(l=r.R32F),s===r.HALF_FLOAT&&(l=r.R16F),s===r.UNSIGNED_BYTE&&(l=r.R8),s===r.UNSIGNED_SHORT&&(l=r.R16),s===r.UNSIGNED_INT&&(l=r.R32UI),s===r.BYTE&&(l=r.R8I),s===r.SHORT&&(l=r.R16I),s===r.INT&&(l=r.R32I)),t===r.RED_INTEGER&&(s===r.UNSIGNED_BYTE&&(l=r.R8UI),s===r.UNSIGNED_SHORT&&(l=r.R16UI),s===r.UNSIGNED_INT&&(l=r.R32UI),s===r.BYTE&&(l=r.R8I),s===r.SHORT&&(l=r.R16I),s===r.INT&&(l=r.R32I)),t===r.RG&&(s===r.FLOAT&&(l=r.RG32F),s===r.HALF_FLOAT&&(l=r.RG16F),s===r.UNSIGNED_BYTE&&(l=r.RG8),s===r.UNSIGNED_SHORT&&(l=r.RG16),s===r.UNSIGNED_INT&&(l=r.RG32UI),s===r.BYTE&&(l=r.RG8I),s===r.SHORT&&(l=r.RG16I),s===r.INT&&(l=r.RG32I)),t===r.RG_INTEGER&&(s===r.UNSIGNED_BYTE&&(l=r.RG8UI),s===r.UNSIGNED_SHORT&&(l=r.RG16UI),s===r.UNSIGNED_INT&&(l=r.RG32UI),s===r.BYTE&&(l=r.RG8I),s===r.SHORT&&(l=r.RG16I),s===r.INT&&(l=r.RG32I)),t===r.RGB){const c=n?$o:Le.getTransfer(i);s===r.FLOAT&&(l=r.RGB32F),s===r.HALF_FLOAT&&(l=r.RGB16F),s===r.UNSIGNED_BYTE&&(l=r.RGB8),s===r.UNSIGNED_SHORT&&(l=r.RGB16),s===r.UNSIGNED_INT&&(l=r.RGB32UI),s===r.BYTE&&(l=r.RGB8I),s===r.SHORT&&(l=r.RGB16I),s===r.INT&&(l=r.RGB32I),s===r.UNSIGNED_BYTE&&(l=c===se?r.SRGB8:r.RGB8),s===r.UNSIGNED_SHORT_5_6_5&&(l=r.RGB565),s===r.UNSIGNED_SHORT_5_5_5_1&&(l=r.RGB5_A1),s===r.UNSIGNED_SHORT_4_4_4_4&&(l=r.RGB4),s===r.UNSIGNED_INT_5_9_9_9_REV&&(l=r.RGB9_E5)}if(t===r.RGB_INTEGER&&(s===r.UNSIGNED_BYTE&&(l=r.RGB8UI),s===r.UNSIGNED_SHORT&&(l=r.RGB16UI),s===r.UNSIGNED_INT&&(l=r.RGB32UI),s===r.BYTE&&(l=r.RGB8I),s===r.SHORT&&(l=r.RGB16I),s===r.INT&&(l=r.RGB32I)),t===r.RGBA){const c=n?$o:Le.getTransfer(i);s===r.FLOAT&&(l=r.RGBA32F),s===r.HALF_FLOAT&&(l=r.RGBA16F),s===r.UNSIGNED_BYTE&&(l=r.RGBA8),s===r.UNSIGNED_SHORT&&(l=r.RGBA16),s===r.UNSIGNED_INT&&(l=r.RGBA32UI),s===r.BYTE&&(l=r.RGBA8I),s===r.SHORT&&(l=r.RGBA16I),s===r.INT&&(l=r.RGBA32I),s===r.UNSIGNED_BYTE&&(l=c===se?r.SRGB8_ALPHA8:r.RGBA8),s===r.UNSIGNED_SHORT_4_4_4_4&&(l=r.RGBA4),s===r.UNSIGNED_SHORT_5_5_5_1&&(l=r.RGB5_A1)}return t===r.RGBA_INTEGER&&(s===r.UNSIGNED_BYTE&&(l=r.RGBA8UI),s===r.UNSIGNED_SHORT&&(l=r.RGBA16UI),s===r.UNSIGNED_INT&&(l=r.RGBA32UI),s===r.BYTE&&(l=r.RGBA8I),s===r.SHORT&&(l=r.RGBA16I),s===r.INT&&(l=r.RGBA32I)),t===r.DEPTH_COMPONENT&&(s===r.UNSIGNED_SHORT&&(l=r.DEPTH_COMPONENT16),s===r.UNSIGNED_INT&&(l=r.DEPTH_COMPONENT24),s===r.FLOAT&&(l=r.DEPTH_COMPONENT32F)),t===r.DEPTH_STENCIL&&s===r.UNSIGNED_INT_24_8&&(l=r.DEPTH24_STENCIL8),(l===r.R16F||l===r.R32F||l===r.RG16F||l===r.RG32F||l===r.RGBA16F||l===r.RGBA32F)&&o.get("EXT_color_buffer_float"),l}setTextureParameters(e,t){const{gl:s,extensions:i,backend:n}=this,r=Le.getPrimaries(Le.workingColorSpace),o=t.colorSpace===ri?null:Le.getPrimaries(t.colorSpace),l=t.colorSpace===ri||r===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,ho[t.wrapS]),s.texParameteri(e,s.TEXTURE_WRAP_T,ho[t.wrapT]),(e===s.TEXTURE_3D||e===s.TEXTURE_2D_ARRAY)&&(t.isArrayTexture||s.texParameteri(e,s.TEXTURE_WRAP_R,ho[t.wrapR])),s.texParameteri(e,s.TEXTURE_MAG_FILTER,Lc[t.magFilter]);const c=t.mipmaps!==void 0&&t.mipmaps.length>0,h=t.minFilter===Qt&&c?ei:t.minFilter;if(s.texParameteri(e,s.TEXTURE_MIN_FILTER,Lc[h]),t.compareFunction&&(s.texParameteri(e,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE),s.texParameteri(e,s.TEXTURE_COMPARE_FUNC,ff[t.compareFunction])),i.has("EXT_texture_filter_anisotropic")===!0){if(t.magFilter===lt||t.minFilter!==ma&&t.minFilter!==ei||t.type===Zt&&i.has("OES_texture_float_linear")===!1)return;if(t.anisotropy>1){const u=i.get("EXT_texture_filter_anisotropic");s.texParameterf(e,u.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 r=i[n];r===void 0&&(r=t.createTexture(),s.state.bindTexture(n,r),t.texParameteri(n,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(n,t.TEXTURE_MAG_FILTER,t.NEAREST),i[n]=r),s.set(e,{textureGPU:r,glTextureType:n,isDefault:!0})}createTexture(e,t){const{gl:s,backend:i}=this,{levels:n,width:r,height:o,depth:l}=t,c=i.utils.convert(e.format,e.colorSpace),h=i.utils.convert(e.type),u=this.getInternalFormat(e.internalFormat,c,h,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,u,r,o,l):e.isData3DTexture?s.texStorage3D(s.TEXTURE_3D,n,u,r,o,l):e.isVideoTexture||s.texStorage2D(p,n,u,r,o),i.set(e,{textureGPU:d,glTextureType:p,glFormat:c,glType:h,glInternalFormat:u})}copyBufferToTexture(e,t){const{gl:s,backend:i}=this,{textureGPU:n,glTextureType:r,glFormat:o,glType:l}=i.get(t),{width:c,height:h}=t.source.data;s.bindBuffer(s.PIXEL_UNPACK_BUFFER,e),i.state.bindTexture(r,n),s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,!1),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),s.texSubImage2D(r,0,0,0,c,h,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:r,glTextureType:o,glFormat:l,glType:c,glInternalFormat:h}=this.backend.get(e);if(!(e.isRenderTargetTexture||r===void 0))if(this.backend.state.bindTexture(o,r),this.setTextureParameters(o,e),e.isCompressedTexture){const u=e.mipmaps,d=t.image;for(let p=0;p<u.length;p++){const f=u[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):console.warn("THREE.WebGLRenderer: 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):console.warn("Unsupported compressed texture format")}}else if(e.isCubeTexture){const u=t.images;for(let d=0;d<6;d++){const p=mf(u[d]);s.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+d,0,0,0,i,n,l,c,p)}}else if(e.isDataArrayTexture||e.isArrayTexture){const u=t.image;s.texSubImage3D(s.TEXTURE_2D_ARRAY,0,0,0,0,u.width,u.height,u.depth,l,c,u.data)}else if(e.isData3DTexture){const u=t.image;s.texSubImage3D(s.TEXTURE_3D,0,0,0,0,u.width,u.height,u.depth,l,c,u.data)}else if(e.isVideoTexture)e.update(),s.texImage2D(o,0,h,l,c,t.image);else{const u=mf(t.image);s.texSubImage2D(o,0,0,0,i,n,l,c,u)}}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){const{gl:t,backend:s}=this,{textureGPU:i,renderTarget:n}=s.get(e);this.deallocateRenderBuffers(n),t.deleteTexture(i),s.delete(e)}copyTextureToTexture(e,t,s=null,i=null,n=0,r=0){const{gl:o,backend:l}=this,{state:c}=this.backend,{textureGPU:h,glTextureType:u,glType:d,glFormat:p}=l.get(t);c.bindTexture(u,h);let f,m,y,g,_,b,S,T,M;const w=e.isCompressedTexture?e.mipmaps[r]:e.image;if(s!==null)f=s.max.x-s.min.x,m=s.max.y-s.min.y,y=s.isBox3?s.max.z-s.min.z:1,g=s.min.x,_=s.min.y,b=s.isBox3?s.min.z:0;else{const X=Math.pow(2,-n);f=Math.floor(w.width*X),m=Math.floor(w.height*X),e.isDataArrayTexture||e.isArrayTexture?y=w.depth:e.isData3DTexture?y=Math.floor(w.depth*X):y=1,g=0,_=0,b=0}i!==null?(S=i.x,T=i.y,M=i.z):(S=0,T=0,M=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 R=o.getParameter(o.UNPACK_ROW_LENGTH),P=o.getParameter(o.UNPACK_IMAGE_HEIGHT),z=o.getParameter(o.UNPACK_SKIP_PIXELS),$=o.getParameter(o.UNPACK_SKIP_ROWS),q=o.getParameter(o.UNPACK_SKIP_IMAGES);o.pixelStorei(o.UNPACK_ROW_LENGTH,w.width),o.pixelStorei(o.UNPACK_IMAGE_HEIGHT,w.height),o.pixelStorei(o.UNPACK_SKIP_PIXELS,g),o.pixelStorei(o.UNPACK_SKIP_ROWS,_),o.pixelStorei(o.UNPACK_SKIP_IMAGES,b);const j=t.isDataArrayTexture||t.isData3DTexture||t.isArrayTexture;if(e.isRenderTargetTexture||e.isDepthTexture){const X=l.get(e),Z=l.get(t),ve=l.get(X.renderTarget),ue=l.get(Z.renderTarget),ge=ve.framebuffers[X.cacheKey],ie=ue.framebuffers[Z.cacheKey];c.bindFramebuffer(o.READ_FRAMEBUFFER,ge),c.bindFramebuffer(o.DRAW_FRAMEBUFFER,ie);let we=o.COLOR_BUFFER_BIT;e.isDepthTexture&&(we=o.DEPTH_BUFFER_BIT),o.blitFramebuffer(g,_,f,m,S,T,f,m,we,o.NEAREST),c.bindFramebuffer(o.READ_FRAMEBUFFER,null),c.bindFramebuffer(o.DRAW_FRAMEBUFFER,null)}else j?e.isDataTexture||e.isData3DTexture?o.texSubImage3D(u,r,S,T,M,f,m,y,p,d,w.data):t.isCompressedArrayTexture?o.compressedTexSubImage3D(u,r,S,T,M,f,m,y,p,w.data):o.texSubImage3D(u,r,S,T,M,f,m,y,p,d,w):e.isDataTexture?o.texSubImage2D(u,r,S,T,f,m,p,d,w.data):e.isCompressedTexture?o.compressedTexSubImage2D(u,r,S,T,w.width,w.height,p,w.data):o.texSubImage2D(u,r,S,T,f,m,p,d,w);o.pixelStorei(o.UNPACK_ROW_LENGTH,R),o.pixelStorei(o.UNPACK_IMAGE_HEIGHT,P),o.pixelStorei(o.UNPACK_SKIP_PIXELS,z),o.pixelStorei(o.UNPACK_SKIP_ROWS,$),o.pixelStorei(o.UNPACK_SKIP_IMAGES,q),r===0&&t.generateMipmaps&&o.generateMipmap(u),c.unbindTexture()}copyFramebufferToTexture(e,t,s){const{gl:i}=this,{state:n}=this.backend,{textureGPU:r}=this.backend.get(e),{x:o,y:l,z:c,w:h}=s,u=e.isDepthTexture===!0||t.renderTarget&&t.renderTarget.samples>0,d=t.renderTarget?t.renderTarget.height:this.backend.getDrawingBufferSize().y;if(u){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 y=this.backend.get(t.renderTarget),g=y.framebuffers[t.getCacheKey()],_=y.msaaFrameBuffer;n.bindFramebuffer(i.DRAW_FRAMEBUFFER,g),n.bindFramebuffer(i.READ_FRAMEBUFFER,_);const b=d-l-h;i.blitFramebuffer(o,b,o+c,b+h,o,b,o+c,b+h,f,i.NEAREST),n.bindFramebuffer(i.READ_FRAMEBUFFER,g),n.bindTexture(i.TEXTURE_2D,r),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,o,b,c,h),n.unbindTexture()}else{const y=i.createFramebuffer();n.bindFramebuffer(i.DRAW_FRAMEBUFFER,y),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,m,i.TEXTURE_2D,r,0),i.blitFramebuffer(0,0,c,h,0,0,c,h,f,i.NEAREST),i.deleteFramebuffer(y)}}else n.bindTexture(i.TEXTURE_2D,r),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,o,d-h-l,c,h),n.unbindTexture();e.generateMipmaps&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t,s,i=!1){const{gl:n}=this,r=t.renderTarget,{depthTexture:o,depthBuffer:l,stencilBuffer:c,width:h,height:u}=r;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,r.samples,d,h,u):s>0?(o&&o.isDepthTexture&&o.type===n.FLOAT&&(d=n.DEPTH_COMPONENT32F),n.renderbufferStorageMultisample(n.RENDERBUFFER,s,d,h,u)):n.renderbufferStorage(n.RENDERBUFFER,d,h,u),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.DEPTH_ATTACHMENT,n.RENDERBUFFER,e)}else l&&c&&(s>0?n.renderbufferStorageMultisample(n.RENDERBUFFER,s,n.DEPTH24_STENCIL8,h,u):n.renderbufferStorage(n.RENDERBUFFER,n.DEPTH_STENCIL,h,u),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.DEPTH_STENCIL_ATTACHMENT,n.RENDERBUFFER,e))}async copyTextureToBuffer(e,t,s,i,n,r){const{backend:o,gl:l}=this,{textureGPU:c,glFormat:h,glType:u}=this.backend.get(e),d=l.createFramebuffer();l.bindFramebuffer(l.READ_FRAMEBUFFER,d);const p=e.isCubeTexture?l.TEXTURE_CUBE_MAP_POSITIVE_X+r:l.TEXTURE_2D;l.framebufferTexture2D(l.READ_FRAMEBUFFER,l.COLOR_ATTACHMENT0,p,c,0);const f=this._getTypedArrayType(u),m=this._getBytesPerTexel(u,h),g=i*n*m,_=l.createBuffer();l.bindBuffer(l.PIXEL_PACK_BUFFER,_),l.bufferData(l.PIXEL_PACK_BUFFER,g,l.STREAM_READ),l.readPixels(t,s,i,n,h,u,0),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),await o.utils._clientWaitAsync();const b=new f(g/f.BYTES_PER_ELEMENT);return l.bindBuffer(l.PIXEL_PACK_BUFFER,_),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,b),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),l.deleteFramebuffer(d),b}_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}}function mf(a){return a.isDataTexture?a.image.data:typeof HTMLImageElement<"u"&&a instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&a instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&a instanceof ImageBitmap||typeof OffscreenCanvas<"u"&&a instanceof OffscreenCanvas?a:a.data}class sA{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 iA{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 gf={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",WEBKIT_WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBGL_compressed_texture_s3tc:"texture-compression-bc",EXT_texture_compression_bptc:"texture-compression-bptc",EXT_disjoint_timer_query_webgl2:"timestamp-query",OVR_multiview2:"OVR_multiview2"};class nA{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:r,info:o,index:l}=this;l!==0?s.drawElements(i,t,r,e):s.drawArrays(i,e,t),o.update(n,t,1)}renderInstances(e,t,s){const{gl:i,mode:n,type:r,index:o,object:l,info:c}=this;s!==0&&(o!==0?i.drawElementsInstanced(n,t,r,e,s):i.drawArraysInstanced(n,e,t,s),c.update(l,t,s))}renderMultiDraw(e,t,s){const{extensions:i,mode:n,object:r,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 h=0;h<s;h++)c+=t[h];o.update(r,c,1)}}renderMultiDrawInstances(e,t,s,i){const{extensions:n,mode:r,object:o,info:l}=this;if(s===0)return;const c=n.get("WEBGL_multi_draw");if(c===null)for(let h=0;h<s;h++)this.renderInstances(e[h],t[h],i[h]);else{this.index!==0?c.multiDrawElementsInstancedWEBGL(r,t,0,this.type,e,0,i,0,s):c.multiDrawArraysInstancedWEBGL(r,e,0,t,0,i,0,s);let h=0;for(let u=0;u<s;u++)h+=t[u]*i[u];l.update(o,h,1)}}}class Ay{constructor(e=256){this.trackTimestamp=!0,this.maxQueries=e,this.currentQueryIndex=0,this.queryOffsets=new Map,this.isDisposed=!1,this.lastValue=0,this.pendingResolve=!1}allocateQueriesForContext(){}async resolveQueriesAsync(){}dispose(){}}class rA extends Ay{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){console.warn("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 ai(`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.id,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e.id);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){console.error("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.id);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){console.error("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=[];for(const[i,n]of this.queryStates)if(n==="ended"){const r=this.queries[i];e.push(this.resolveQuery(r))}if(e.length===0)return this.lastValue;const s=(await Promise.all(e)).reduce((i,n)=>i+n,0);return this.lastValue=s,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,s}catch(e){return console.error("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)},r=l=>{i||(i=!0,n(),t(l))},o=()=>{if(this.isDisposed){r(this.lastValue);return}try{if(this.gl.getParameter(this.ext.GPU_DISJOINT_EXT)){r(this.lastValue);return}if(!this.gl.getQueryParameter(e,this.gl.QUERY_RESULT_AVAILABLE)){s=setTimeout(o,1);return}const h=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT);t(Number(h)/1e6)}catch(l){console.error("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}}}const yf=new ce;class xf extends Cy{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.samples>0,alpha:!0,depth:e.depth,stencil:e.stencil},i=t.context!==void 0?t.context:e.domElement.getContext("webgl2",s);function n(r){r.preventDefault();const o={api:"WebGL",message:r.statusMessage||"Unknown reason",reason:null,originalEvent:r};e.onDeviceLost(o)}this._onContextLost=n,e.domElement.addEventListener("webglcontextlost",n,!1),this.gl=i,this.extensions=new sA(this),this.capabilities=new iA(this),this.attributeUtils=new KC(this),this.textureUtils=new tA(this),this.bufferRenderer=new nA(this),this.state=new JC(this),this.utils=new eA(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.disjoint=this.extensions.get("EXT_disjoint_timer_query_webgl2"),this.parallel=this.extensions.get("KHR_parallel_shader_compile")}get coordinateSystem(){return Lt}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}async waitForGPU(){await this.utils._clientWaitAsync()}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&&console.warn("THREE.WebGLBackend: Render-to-texture extension was disabled because an external texture was provided"),e.autoAllocateDepthBuffer=!1}}initTimestampQuery(e){if(!this.disjoint||!this.trackTimestamp)return;const t=e.isComputeNode?"compute":"render";this.timestampQueryPool[t]||(this.timestampQueryPool[t]=new rA(this.gl,t,2048));const s=this.timestampQueryPool[t];s.allocateQueriesForContext(e)!==null&&s.beginQuery(e)}prepareTimestampBuffer(e){if(!this.disjoint||!this.trackTimestamp)return;const t=e.isComputeNode?"compute":"render";this.timestampQueryPool[t].endQuery(e)}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:r}=this.getDrawingBufferSize(yf);t.viewport(0,0,n,r)}if(e.scissor){const{x:n,y:r,width:o,height:l}=e.scissorValue;t.scissor(n,e.height-l-r,o,l)}this.initTimestampQuery(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 r=e.occlusionQueryCount;r>0&&(r>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,e.textures!==null&&e.renderTarget){const l=this.get(e.renderTarget),{resolveDepthBuffer:c,samples:h}=e.renderTarget;if(h>0&&this._useMultisampledExtension(e.renderTarget)===!1){const u=l.framebuffers[e.getCacheKey()],d=t.COLOR_BUFFER_BIT,p=l.msaaFrameBuffer,f=e.textures;s.bindFramebuffer(t.READ_FRAMEBUFFER,p),s.bindFramebuffer(t.DRAW_FRAMEBUFFER,u);for(let m=0;m<f.length;m++)if(e.scissor){const{x:y,y:g,width:_,height:b}=e.scissorValue,S=e.height-b-g;t.blitFramebuffer(y,S,y+_,S+b,y,S,y+_,S+b,d,t.NEAREST),this._supportsInvalidateFramebuffer===!0&&t.invalidateSubFramebuffer(t.READ_FRAMEBUFFER,l.invalidationArray,y,S,_,b)}else t.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,d,t.NEAREST),this._supportsInvalidateFramebuffer===!0&&t.invalidateFramebuffer(t.READ_FRAMEBUFFER,l.invalidationArray)}else if(c===!1&&l.framebuffers){const u=l.framebuffers[e.getCacheKey()];s.bindFramebuffer(t.DRAW_FRAMEBUFFER,u),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,l.depthInvalidationArray)}}if(n!==null)if(this._setFramebuffer(n),n.viewport)this.updateViewport(n);else{const{width:l,height:c}=this.getDrawingBufferSize(yf);s.viewport(0,0,l,c)}this.prepareTimestampBuffer(e)}resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueries:s,currentOcclusionQueryObjects:i}=t;if(s&&i){const n=new WeakSet,{gl:r}=this;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueries=null;const o=()=>{let l=0;for(let c=0;c<s.length;c++){const h=s[c];h!==null&&r.getQueryParameter(h,r.QUERY_RESULT_AVAILABLE)&&(r.getQueryParameter(h,r.QUERY_RESULT)===0&&n.add(i[c]),s[c]=null,r.deleteQuery(h),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:r}=e.viewportValue;t.viewport(s,e.height-r-i,n,r)}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){const{gl:r,renderer:o}=this;i===null&&(i={textures:null,clearColorValue:this.getClearColor()});let l=0;if(e&&(l|=r.COLOR_BUFFER_BIT),t&&(l|=r.DEPTH_BUFFER_BIT),s&&(l|=r.STENCIL_BUFFER_BIT),l!==0){let c;i.clearColorValue?c=i.clearColorValue:c=this.getClearColor();const h=o.getClearDepth(),u=o.getClearStencil();if(t&&this.state.setDepthMask(!0),i.textures===null)r.clearColor(c.r,c.g,c.b,c.a),r.clear(l);else{if(n&&this._setFramebuffer(i),e)for(let d=0;d<i.textures.length;d++)d===0?r.clearBufferfv(r.COLOR,d,[c.r,c.g,c.b,c.a]):r.clearBufferfv(r.COLOR,d,[0,0,0,1]);t&&s?r.clearBufferfi(r.DEPTH_STENCIL,0,h,u):t?r.clearBufferfv(r.DEPTH,0,[h]):s&&r.clearBufferiv(r.STENCIL,0,[u])}}}beginCompute(e){const{state:t,gl:s}=this;t.bindFramebuffer(s.FRAMEBUFFER,null),this.initTimestampQuery(e)}compute(e,t,s,i){const{state:n,gl:r}=this;this.discard===!1&&(r.enable(r.RASTERIZER_DISCARD),this.discard=!0);const{programGPU:o,transformBuffers:l,attributes:c}=this.get(i),h=this._getVaoKey(c),u=this.vaoCache[h];u===void 0?this._createVao(c):n.setVertexState(u),n.useProgram(o),this._bindUniforms(s);const d=this._getTransformFeedback(l);r.bindTransformFeedback(r.TRANSFORM_FEEDBACK,d),r.beginTransformFeedback(r.POINTS),c[0].isStorageInstancedBufferAttribute?r.drawArraysInstanced(r.POINTS,0,1,t.count):r.drawArrays(r.POINTS,0,t.count),r.endTransformFeedback(),r.bindTransformFeedback(r.TRANSFORM_FEEDBACK,null);for(let p=0;p<l.length;p++){const f=l[p];f.pbo&&this.textureUtils.copyBufferToTexture(f.transformBuffer,f.pbo),f.switchBuffers()}}finishCompute(e){const t=this.gl;this.discard=!1,t.disable(t.RASTERIZER_DISCARD),this.prepareTimestampBuffer(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:r}=e,{programGPU:o}=this.get(s),{gl:l,state:c}=this,h=this.get(n),u=e.getDrawParameters();if(u===null)return;this._bindUniforms(e.getBindings());const d=t.isMesh&&t.matrixWorld.determinant()<0;c.setMaterial(i,d,r),c.useProgram(o);const p=this.get(e);let f=p.staticVao;if(f===void 0||p.geometryId!==e.geometry.id){const w=this._getVaoKey(e.getAttributes());if(f=this.vaoCache[w],f===void 0){let R;({vaoGPU:f,staticVao:R}=this._createVao(e.getAttributes())),R&&(p.staticVao=f,p.geometryId=e.geometry.id)}}const m=e.getIndex(),y=m!==null?this.get(m).bufferGPU:null;c.setVertexState(f,y);const g=h.lastOcclusionObject;if(g!==t&&g!==void 0){if(g!==null&&g.occlusionTest===!0&&(l.endQuery(l.ANY_SAMPLES_PASSED),h.occlusionQueryIndex++),t.occlusionTest===!0){const w=l.createQuery();l.beginQuery(l.ANY_SAMPLES_PASSED,w),h.occlusionQueries[h.occlusionQueryIndex]=w,h.occlusionQueryObjects[h.occlusionQueryIndex]=t}h.lastOcclusionObject=t}const _=this.bufferRenderer;t.isPoints?_.mode=l.POINTS:t.isLineSegments?_.mode=l.LINES:t.isLine?_.mode=l.LINE_STRIP:t.isLineLoop?_.mode=l.LINE_LOOP:i.wireframe===!0?(c.setLineWidth(i.wireframeLinewidth*this.renderer.getPixelRatio()),_.mode=l.LINES):_.mode=l.TRIANGLES;const{vertexCount:b,instanceCount:S}=u;let{firstVertex:T}=u;if(_.object=t,m!==null){T*=m.array.BYTES_PER_ELEMENT;const w=this.get(m);_.index=m.count,_.type=w.type}else _.index=0;const M=()=>{t.isBatchedMesh?t._multiDrawInstances!==null?(ai("THREE.WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),_.renderMultiDrawInstances(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount,t._multiDrawInstances)):this.hasFeature("WEBGL_multi_draw")?_.renderMultiDraw(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount):ai("THREE.WebGLRenderer: WEBGL_multi_draw not supported."):S>1?_.renderInstances(T,b,S):_.render(T,b)};if(e.camera.isArrayCamera===!0&&e.camera.cameras.length>0&&e.camera.isMultiViewCamera===!1){const w=this.get(e.camera),R=e.camera.cameras,P=e.getBindingGroup("cameraIndex").bindings[0];if(w.indexesGPU===void 0||w.indexesGPU.length!==R.length){const Z=new Uint32Array([0,0,0,0]),ve=[];for(let ue=0,ge=R.length;ue<ge;ue++){const ie=l.createBuffer();Z[0]=ue,l.bindBuffer(l.UNIFORM_BUFFER,ie),l.bufferData(l.UNIFORM_BUFFER,Z,l.STATIC_DRAW),ve.push(ie)}w.indexesGPU=ve}const z=this.get(P),$=this.renderer.getPixelRatio(),q=this._currentContext.renderTarget,j=this._isRenderCameraDepthArray(this._currentContext),X=this._currentContext.activeCubeFace;if(j){const Z=this.get(q.depthTexture);if(Z.clearedRenderId!==this.renderer._nodes.nodeFrame.renderId){Z.clearedRenderId=this.renderer._nodes.nodeFrame.renderId;const{stencilBuffer:ve}=q;for(let ue=0,ge=R.length;ue<ge;ue++)this.renderer._activeCubeFace=ue,this._currentContext.activeCubeFace=ue,this._setFramebuffer(this._currentContext),this.clear(!1,!0,ve,this._currentContext,!1);this.renderer._activeCubeFace=X,this._currentContext.activeCubeFace=X}}for(let Z=0,ve=R.length;Z<ve;Z++){const ue=R[Z];if(t.layers.test(ue.layers)){j&&(this.renderer._activeCubeFace=Z,this._currentContext.activeCubeFace=Z,this._setFramebuffer(this._currentContext));const ge=ue.viewport;if(ge!==void 0){const ie=ge.x*$,we=ge.y*$,ke=ge.width*$,nt=ge.height*$;c.viewport(Math.floor(ie),Math.floor(e.context.height-nt-we),Math.floor(ke),Math.floor(nt))}c.bindBufferBase(l.UNIFORM_BUFFER,z.index,w.indexesGPU[Z]),M()}this._currentContext.activeCubeFace=X,this.renderer._activeCubeFace=X}}else M()}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){this.textureUtils.destroyTexture(e)}async copyTextureToBuffer(e,t,s,i,n,r){return this.textureUtils.copyTextureToBuffer(e,t,s,i,n,r)}createSampler(){}destroySampler(){}createNodeBuilder(e,t){return new XC(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:r}=i,o=s.createProgram(),l=this.get(n).shaderGPU,c=this.get(r).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 h=new Promise(u=>{const d=this.parallel,p=()=>{s.getProgramParameter(o,d.COMPLETION_STATUS_KHR)?(this._completeCompile(e,i),u()):requestAnimationFrame(p)};p()});t.push(h);return}this._completeCompile(e,i)}_handleSource(e,t){const s=e.split(`
|
255
|
+
`),i=[],n=Math.max(t-6,0),r=Math.min(t+6,s.length);for(let o=n;o<r;o++){const l=o+1;i.push(`${l===t?">":" "} ${l}: ${s[o]}`)}return i.join(`
|
256
|
+
`)}_getShaderErrors(e,t,s){const i=e.getShaderParameter(t,e.COMPILE_STATUS),n=e.getShaderInfoLog(t).trim();if(i&&n==="")return"";const r=/ERROR: 0:(\d+)/.exec(n);if(r){const o=parseInt(r[1]);return s.toUpperCase()+`
|
257
|
+
|
258
|
+
`+n+`
|
259
|
+
|
260
|
+
`+this._handleSource(e.getShaderSource(t),o)}else return n}_logProgramError(e,t,s){if(this.renderer.debug.checkShaderErrors){const i=this.gl,n=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 r=this._getShaderErrors(i,s,"vertex"),o=this._getShaderErrors(i,t,"fragment");console.error("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(e,i.VALIDATE_STATUS)+`
|
261
|
+
|
262
|
+
Program Info Log: `+n+`
|
263
|
+
`+r+`
|
264
|
+
`+o)}else n!==""&&console.warn("THREE.WebGLProgram: Program Info Log:",n)}}_completeCompile(e,t){const{state:s,gl:i}=this,n=this.get(t),{programGPU:r,fragmentShader:o,vertexShader:l}=n;i.getProgramParameter(r,i.LINK_STATUS)===!1&&this._logProgramError(r,o,l),s.useProgram(r);const c=e.getBindings();this._setupBindings(c,r),this.set(t,{programGPU:r})}createComputePipeline(e,t){const{state:s,gl:i}=this,n={stage:"fragment",code:`#version 300 es
|
265
|
+
precision highp float;
|
266
|
+
void main() {}`};this.createProgram(n);const{computeProgram:r}=e,o=i.createProgram(),l=this.get(n).shaderGPU,c=this.get(r).shaderGPU,h=r.transforms,u=[],d=[];for(let y=0;y<h.length;y++){const g=h[y];u.push(g.varyingName),d.push(g.attributeNode)}i.attachShader(o,l),i.attachShader(o,c),i.transformFeedbackVaryings(o,u,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=r.attributes,f=[],m=[];for(let y=0;y<p.length;y++){const g=p[y].node.attribute;f.push(g),this.has(g)||this.attributeUtils.createAttribute(g,i.ARRAY_BUFFER)}for(let y=0;y<d.length;y++){const g=d[y].attribute;this.has(g)||this.attributeUtils.createAttribute(g,i.ARRAY_BUFFER);const _=this.get(g);m.push(_)}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 r of n.bindings)r.isUniformBuffer&&s++,r.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 r of e.bindings)if(r.isUniformsGroup||r.isUniformBuffer){const o=r.buffer,l=t.createBuffer();t.bindBuffer(t.UNIFORM_BUFFER,l),t.bufferData(t.UNIFORM_BUFFER,o,t.DYNAMIC_DRAW),this.set(r,{index:i++,bufferGPU:l})}else if(r.isSampledTexture){const{textureGPU:o,glTextureType:l}=this.get(r.texture);this.set(r,{index:n++,textureGPU:o,glTextureType:l})}}updateBinding(e){const t=this.gl;if(e.isUniformsGroup||e.isUniformBuffer){const i=this.get(e).bufferGPU,n=e.buffer;t.bindBuffer(t.UNIFORM_BUFFER,i),t.bufferData(t.UNIFORM_BUFFER,n,t.DYNAMIC_DRAW)}}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(gf).filter(i=>gf[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,r=0){this.textureUtils.copyTextureToTexture(e,t,s,i,n,r)}copyFramebufferToTexture(e,t,s){this.textureUtils.copyFramebufferToTexture(e,t,s)}_setFramebuffer(e){const{gl:t,state:s}=this;let i=null;if(e.textures!==null){const n=e.renderTarget,r=this.get(n),{samples:o,depthBuffer:l,stencilBuffer:c}=n,h=n.isWebGLCubeRenderTarget===!0,u=n.isRenderTarget3D===!0,d=n.depth>1,p=n.isXRRenderTarget===!0,f=p===!0&&n.hasExternalTextures===!0;let m=r.msaaFrameBuffer,y=r.depthRenderbuffer;const g=this.extensions.get("WEBGL_multisampled_render_to_texture"),_=this.extensions.get("OVR_multiview2"),b=this._useMultisampledExtension(n),S=$m(e);let T;if(h?(r.cubeFramebuffers||(r.cubeFramebuffers={}),T=r.cubeFramebuffers[S]):p&&f===!1?T=this._xrFramebuffer:(r.framebuffers||(r.framebuffers={}),T=r.framebuffers[S]),T===void 0){T=t.createFramebuffer(),s.bindFramebuffer(t.FRAMEBUFFER,T);const M=e.textures,w=[];if(h){r.cubeFramebuffers[S]=T;const{textureGPU:P}=this.get(M[0]),z=this.renderer._activeCubeFace;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+z,P,0)}else{r.framebuffers[S]=T;for(let P=0;P<M.length;P++){const z=M[P],$=this.get(z);$.renderTarget=e.renderTarget,$.cacheKey=S;const q=t.COLOR_ATTACHMENT0+P;if(n.multiview)_.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,q,$.textureGPU,0,o,0,2);else if(u||d){const j=this.renderer._activeCubeFace;t.framebufferTextureLayer(t.FRAMEBUFFER,q,$.textureGPU,0,j)}else b?g.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,q,t.TEXTURE_2D,$.textureGPU,0,o):t.framebufferTexture2D(t.FRAMEBUFFER,q,t.TEXTURE_2D,$.textureGPU,0)}s.drawBuffers(e,T)}const R=c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(n.autoAllocateDepthBuffer===!0){const P=t.createRenderbuffer();this.textureUtils.setupRenderBufferStorage(P,e,0,b),r.xrDepthRenderbuffer=P,w.push(c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT),t.bindRenderbuffer(t.RENDERBUFFER,P),t.framebufferRenderbuffer(t.FRAMEBUFFER,R,t.RENDERBUFFER,P)}else if(e.depthTexture!==null){w.push(c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT);const P=this.get(e.depthTexture);if(P.renderTarget=e.renderTarget,P.cacheKey=S,n.multiview)_.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,R,P.textureGPU,0,o,0,2);else if(f&&b)g.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,R,t.TEXTURE_2D,P.textureGPU,0,o);else if(e.depthTexture.isArrayTexture){const z=this.renderer._activeCubeFace;t.framebufferTextureLayer(t.FRAMEBUFFER,R,P.textureGPU,0,z)}else t.framebufferTexture2D(t.FRAMEBUFFER,R,t.TEXTURE_2D,P.textureGPU,0)}r.depthInvalidationArray=w}else{if(this._isRenderCameraDepthArray(e)){s.bindFramebuffer(t.FRAMEBUFFER,T);const w=this.renderer._activeCubeFace,R=this.get(e.depthTexture),P=c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;t.framebufferTextureLayer(t.FRAMEBUFFER,P,R.textureGPU,0,w)}if(p||b||n.multiview){s.bindFramebuffer(t.FRAMEBUFFER,T);const w=this.get(e.textures[0]);n.multiview?_.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,w.textureGPU,0,o,0,2):b?g.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,w.textureGPU,0,o):t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,w.textureGPU,0);const R=c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(n.autoAllocateDepthBuffer===!0){const P=r.xrDepthRenderbuffer;t.bindRenderbuffer(t.RENDERBUFFER,P),t.framebufferRenderbuffer(t.FRAMEBUFFER,R,t.RENDERBUFFER,P)}else{const P=this.get(e.depthTexture);n.multiview?_.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,R,P.textureGPU,0,o,0,2):b?g.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,R,t.TEXTURE_2D,P.textureGPU,0,o):t.framebufferTexture2D(t.FRAMEBUFFER,R,t.TEXTURE_2D,P.textureGPU,0)}}}if(o>0&&b===!1&&!n.multiview){if(m===void 0){const M=[];m=t.createFramebuffer(),s.bindFramebuffer(t.FRAMEBUFFER,m);const w=[],R=e.textures;for(let P=0;P<R.length;P++){if(w[P]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,w[P]),M.push(t.COLOR_ATTACHMENT0+P),l){const q=c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;M.push(q)}const z=e.textures[P],$=this.get(z);t.renderbufferStorageMultisample(t.RENDERBUFFER,o,$.glInternalFormat,e.width,e.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+P,t.RENDERBUFFER,w[P])}if(r.msaaFrameBuffer=m,r.msaaRenderbuffers=w,y===void 0){y=t.createRenderbuffer(),this.textureUtils.setupRenderBufferStorage(y,e,o),r.depthRenderbuffer=y;const P=c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;M.push(P)}r.invalidationArray=M}i=r.msaaFrameBuffer}else i=T}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();let i="",n=!0;t.bindVertexArray(s);for(let r=0;r<e.length;r++){const o=e[r],l=this.get(o);i+=":"+l.id,t.bindBuffer(t.ARRAY_BUFFER,l.bufferGPU),t.enableVertexAttribArray(r),(o.isStorageBufferAttribute||o.isStorageInstancedBufferAttribute)&&(n=!1);let c,h;o.isInterleavedBufferAttribute===!0?(c=o.data.stride*l.bytesPerElement,h=o.offset*l.bytesPerElement):(c=0,h=0),l.isInteger?t.vertexAttribIPointer(r,o.itemSize,l.type,c,h):t.vertexAttribPointer(r,o.itemSize,l.type,o.normalized,c,h),o.isInstancedBufferAttribute&&!o.isInterleavedBufferAttribute?t.vertexAttribDivisor(r,o.meshPerAttribute):o.isInterleavedBufferAttribute&&o.data.isInstancedInterleavedBuffer&&t.vertexAttribDivisor(r,o.data.meshPerAttribute)}return t.bindBuffer(t.ARRAY_BUFFER,null),this.vaoCache[i]=s,{vaoGPU:s,staticVao:n}}_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 r=e[n];i.bindBufferBase(i.TRANSFORM_FEEDBACK_BUFFER,n,r.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 r=this.get(n),o=r.index;n.isUniformsGroup||n.isUniformBuffer?s.bindBufferBase(t.UNIFORM_BUFFER,o,r.bufferGPU):n.isSampledTexture&&s.bindTexture(r.glTextureType,r.textureGPU,t.TEXTURE0+o)}}_useMultisampledExtension(e){return e.multiview===!0?!0:e.samples>0&&this.extensions.has("WEBGL_multisampled_render_to_texture")===!0&&e.autoAllocateDepthBuffer!==!1}dispose(){const e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext(),this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const qn={PointList:"point-list",LineList:"line-list",LineStrip:"line-strip",TriangleList:"triangle-list",TriangleStrip:"triangle-strip"},dt={Never:"never",Less:"less",Equal:"equal",LessEqual:"less-equal",Greater:"greater",NotEqual:"not-equal",GreaterEqual:"greater-equal",Always:"always"},Et={Store:"store"},Ee={Load:"load",Clear:"clear"},Uc={CCW:"ccw"},kc={None:"none",Front:"front",Back:"back"},dr={Uint16:"uint16",Uint32:"uint32"},E={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:"rgb10a2unorm",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-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"},zc={ClampToEdge:"clamp-to-edge",Repeat:"repeat",MirrorRepeat:"mirror-repeat"},an={Linear:"linear",Nearest:"nearest"},ne={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"},$i={Add:"add",Subtract:"subtract",ReverseSubtract:"reverse-subtract",Min:"min",Max:"max"},_f={None:0,All:15},_i={Keep:"keep",Zero:"zero",Replace:"replace",Invert:"invert",IncrementClamp:"increment-clamp",DecrementClamp:"decrement-clamp",IncrementWrap:"increment-wrap",DecrementWrap:"decrement-wrap"},Gc={Storage:"storage",ReadOnlyStorage:"read-only-storage"},Vc={WriteOnly:"write-only",ReadOnly:"read-only",ReadWrite:"read-write"},bf={NonFiltering:"non-filtering",Comparison:"comparison"},ji={Float:"float",UnfilterableFloat:"unfilterable-float",Depth:"depth",SInt:"sint",UInt:"uint"},Tf={TwoD:"2d",ThreeD:"3d"},ut={TwoD:"2d",TwoDArray:"2d-array",Cube:"cube",ThreeD:"3d"},aA={All:"all"},uo={Vertex:"vertex",Instance:"instance"},zh={DepthClipControl:"depth-clip-control",Depth32FloatStencil8:"depth32float-stencil8",TextureCompressionBC:"texture-compression-bc",TextureCompressionETC2:"texture-compression-etc2",TextureCompressionASTC:"texture-compression-astc",TimestampQuery:"timestamp-query",IndirectFirstInstance:"indirect-first-instance",ShaderF16:"shader-f16",RG11B10UFloat:"rg11b10ufloat-renderable",BGRA8UNormStorage:"bgra8unorm-storage",Float32Filterable:"float32-filterable",ClipDistances:"clip-distances",DualSourceBlending:"dual-source-blending",Subgroups:"subgroups"};class oA extends ju{constructor(e,t){super(e),this.texture=t,this.version=t?t.version:0,this.isSampler=!0}}class lA extends oA{constructor(e,t,s){super(e,t?t.value:null),this.textureNode=t,this.groupNode=s}update(){this.texture=this.textureNode.value}}class cA extends Ty{constructor(e,t){super(e,t?t.array:null),this.attribute=t,this.isStorageBuffer=!0}}let hA=0;class uA extends cA{constructor(e,t){super("StorageBuffer_"+hA++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:Zs.READ_WRITE,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class dA extends Bi{constructor(e){super(),this.device=e;const t=`
|
267
|
+
struct VarysStruct {
|
268
|
+
@builtin( position ) Position: vec4<f32>,
|
269
|
+
@location( 0 ) vTex : vec2<f32>
|
270
|
+
};
|
271
|
+
|
272
|
+
@vertex
|
273
|
+
fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
|
274
|
+
|
275
|
+
var Varys : VarysStruct;
|
276
|
+
|
277
|
+
var pos = array< vec2<f32>, 4 >(
|
278
|
+
vec2<f32>( -1.0, 1.0 ),
|
279
|
+
vec2<f32>( 1.0, 1.0 ),
|
280
|
+
vec2<f32>( -1.0, -1.0 ),
|
281
|
+
vec2<f32>( 1.0, -1.0 )
|
282
|
+
);
|
283
|
+
|
284
|
+
var tex = array< vec2<f32>, 4 >(
|
285
|
+
vec2<f32>( 0.0, 0.0 ),
|
286
|
+
vec2<f32>( 1.0, 0.0 ),
|
287
|
+
vec2<f32>( 0.0, 1.0 ),
|
288
|
+
vec2<f32>( 1.0, 1.0 )
|
289
|
+
);
|
290
|
+
|
291
|
+
Varys.vTex = tex[ vertexIndex ];
|
292
|
+
Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
|
293
|
+
|
294
|
+
return Varys;
|
295
|
+
|
296
|
+
}
|
297
|
+
`,s=`
|
298
|
+
@group( 0 ) @binding( 0 )
|
299
|
+
var imgSampler : sampler;
|
300
|
+
|
301
|
+
@group( 0 ) @binding( 1 )
|
302
|
+
var img : texture_2d<f32>;
|
303
|
+
|
304
|
+
@fragment
|
305
|
+
fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
|
306
|
+
|
307
|
+
return textureSample( img, imgSampler, vTex );
|
308
|
+
|
309
|
+
}
|
310
|
+
`,i=`
|
311
|
+
@group( 0 ) @binding( 0 )
|
312
|
+
var imgSampler : sampler;
|
313
|
+
|
314
|
+
@group( 0 ) @binding( 1 )
|
315
|
+
var img : texture_2d<f32>;
|
316
|
+
|
317
|
+
@fragment
|
318
|
+
fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
|
319
|
+
|
320
|
+
return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
|
321
|
+
|
322
|
+
}
|
323
|
+
`;this.mipmapSampler=e.createSampler({minFilter:an.Linear}),this.flipYSampler=e.createSampler({minFilter:an.Nearest}),this.transferPipelines={},this.flipYPipelines={},this.mipmapVertexShaderModule=e.createShaderModule({label:"mipmapVertex",code:t}),this.mipmapFragmentShaderModule=e.createShaderModule({label:"mipmapFragment",code:s}),this.flipYFragmentShaderModule=e.createShaderModule({label:"flipYFragment",code:i})}getTransferPipeline(e){let t=this.transferPipelines[e];return t===void 0&&(t=this.device.createRenderPipeline({label:`mipmap-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.mipmapFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:qn.TriangleStrip,stripIndexFormat:dr.Uint32},layout:"auto"}),this.transferPipelines[e]=t),t}getFlipYPipeline(e){let t=this.flipYPipelines[e];return t===void 0&&(t=this.device.createRenderPipeline({label:`flipY-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.flipYFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:qn.TriangleStrip,stripIndexFormat:dr.Uint32},layout:"auto"}),this.flipYPipelines[e]=t),t}flipY(e,t,s=0){const i=t.format,{width:n,height:r}=t.size,o=this.getTransferPipeline(i),l=this.getFlipYPipeline(i),c=this.device.createTexture({size:{width:n,height:r,depthOrArrayLayers:1},format:i,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),h=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:ut.TwoD,baseArrayLayer:s}),u=c.createView({baseMipLevel:0,mipLevelCount:1,dimension:ut.TwoD,baseArrayLayer:0}),d=this.device.createCommandEncoder({}),p=(f,m,y)=>{const g=f.getBindGroupLayout(0),_=this.device.createBindGroup({layout:g,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:m}]}),b=d.beginRenderPass({colorAttachments:[{view:y,loadOp:Ee.Clear,storeOp:Et.Store,clearValue:[0,0,0,0]}]});b.setPipeline(f),b.setBindGroup(0,_),b.draw(4,1,0,0),b.end()};p(o,h,u),p(l,u,h),this.device.queue.submit([d.finish()]),c.destroy()}generateMipmaps(e,t,s=0){const i=this.get(e);i.useCount===void 0&&(i.useCount=0,i.layers=[]);const n=i.layers[s]||this._mipmapCreateBundles(e,t,s),r=this.device.createCommandEncoder({});this._mipmapRunBundles(r,n),this.device.queue.submit([r.finish()]),i.useCount!==0&&(i.layers[s]=n),i.useCount++}_mipmapCreateBundles(e,t,s){const i=this.getTransferPipeline(t.format),n=i.getBindGroupLayout(0);let r=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:ut.TwoD,baseArrayLayer:s});const o=[];for(let l=1;l<t.mipLevelCount;l++){const c=this.device.createBindGroup({layout:n,entries:[{binding:0,resource:this.mipmapSampler},{binding:1,resource:r}]}),h=e.createView({baseMipLevel:l,mipLevelCount:1,dimension:ut.TwoD,baseArrayLayer:s}),u={colorAttachments:[{view:h,loadOp:Ee.Clear,storeOp:Et.Store,clearValue:[0,0,0,0]}]},d=this.device.createRenderBundleEncoder({colorFormats:[t.format]});d.setPipeline(i),d.setBindGroup(0,c),d.draw(4,1,0,0),o.push({renderBundles:[d.finish()],passDescriptor:u}),r=h}return o}_mipmapRunBundles(e,t){const s=t.length;for(let i=0;i<s;i++){const n=t[i],r=e.beginRenderPass(n.passDescriptor);r.executeBundles(n.renderBundles),r.end()}}}const pA={[Am]:"never",[iu]:"less",[Rm]:"equal",[Nm]:"less-equal",[Pm]:"greater",[Dm]:"greater-equal",[Om]:"always",[Fm]:"not-equal"},fA=[0,1,3,2,4,5];class mA{constructor(e){this.backend=e,this._passUtils=null,this.defaultTexture={},this.defaultCubeTexture={},this.defaultVideoFrame=null,this.colorBuffer=null,this.depthTexture=new Is,this.depthTexture.name="depthBuffer"}createSampler(e){const t=this.backend,s=t.device,i=t.get(e),n={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};n.magFilter===an.Linear&&n.minFilter===an.Linear&&n.mipmapFilter===an.Linear&&(n.maxAnisotropy=e.anisotropy),e.isDepthTexture&&e.compareFunction!==null&&(n.compare=pA[e.compareFunction]),i.sampler=s.createSampler(n)}createDefaultTexture(e){let t;const s=Gh(e);e.isCubeTexture?t=this._getDefaultCubeTextureGPU(s):e.isVideoTexture?this.backend.get(e).externalTexture=this._getDefaultVideoFrame():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.");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:r,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),h=e.internalFormat||t.format||Gh(e,s.device);i.format=h;const{samples:u,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&&(f|=GPUTextureUsage.RENDER_ATTACHMENT);const m={label:e.name,size:{width:n,height:r,depthOrArrayLayers:o},mipLevelCount:l,sampleCount:d,dimension:c,format:h,usage:f};if(e.isVideoTexture){const y=e.source.data,g=new VideoFrame(y);m.size.width=g.displayWidth,m.size.height=g.displayHeight,g.close(),i.externalTexture=y}else{if(h===void 0){console.warn("WebGPURenderer: Texture format not supported."),this.createDefaultTexture(e);return}e.isCubeTexture&&(m.textureBindingViewDimension=ut.Cube),i.texture=s.device.createTexture(m)}if(p){const y=Object.assign({},m);y.label=y.label+"-msaa",y.sampleCount=u,i.msaaTexture=s.device.createTexture(y)}i.initialized=!0,i.textureDescriptorGPU=m}destroyTexture(e){const t=this.backend,s=t.get(e);s.texture!==void 0&&s.texture.destroy(),s.msaaTexture!==void 0&&s.msaaTexture.destroy(),t.delete(e)}destroySampler(e){const s=this.backend.get(e);delete s.sampler}generateMipmaps(e){const t=this.backend.get(e);if(e.isCubeTexture)for(let s=0;s<6;s++)this._generateMipmaps(t.texture,t.textureDescriptorGPU,s);else{const s=e.image.depth||1;for(let i=0;i<s;i++)this._generateMipmaps(t.texture,t.textureDescriptorGPU,i)}}getColorBuffer(){this.colorBuffer&&this.colorBuffer.destroy();const e=this.backend,{width:t,height:s}=e.getDrawingBufferSize();return this.colorBuffer=e.device.createTexture({label:"colorBuffer",size:{width:t,height:s,depthOrArrayLayers:1},sampleCount:e.utils.getSampleCount(e.renderer.samples),format:e.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC}),this.colorBuffer}getDepthBuffer(e=!0,t=!1){const s=this.backend,{width:i,height:n}=s.getDrawingBufferSize(),r=this.depthTexture,o=s.get(r).texture;let l,c;if(t?(l=ti,c=Ni):e&&(l=Bs,c=Ye),o!==void 0){if(r.image.width===i&&r.image.height===n&&r.format===l&&r.type===c)return o;this.destroyTexture(r)}return r.name="depthBuffer",r.format=l,r.type=c,r.image.width=i,r.image.height=n,this.createTexture(r,{width:i,height:n}),s.get(r).texture}updateTexture(e,t){const s=this.backend.get(e),{textureDescriptorGPU:i}=s;if(!(e.isRenderTargetTexture||i===void 0)){if(e.isDataTexture)this._copyBufferToTexture(t.image,s.texture,i,0,e.flipY);else if(e.isArrayTexture||e.isDataArrayTexture||e.isData3DTexture)for(let n=0;n<t.image.depth;n++)this._copyBufferToTexture(t.image,s.texture,i,n,e.flipY,n);else if(e.isCompressedTexture||e.isCompressedArrayTexture)this._copyCompressedBufferToTexture(e.mipmaps,s.texture,i);else if(e.isCubeTexture)this._copyCubeMapToTexture(t.images,s.texture,i,e.flipY,e.premultiplyAlpha);else if(e.isVideoTexture){const n=e.source.data;s.externalTexture=n}else this._copyImageToTexture(t.image,s.texture,i,0,e.flipY,e.premultiplyAlpha);s.version=e.version,e.onUpdate&&e.onUpdate(e)}}async copyTextureToBuffer(e,t,s,i,n,r){const o=this.backend.device,l=this.backend.get(e),c=l.texture,h=l.textureDescriptorGPU.format,u=this._getBytesPerTexel(h);let d=i*u;d=Math.ceil(d/256)*256;const p=o.createBuffer({size:i*n*u,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),f=o.createCommandEncoder();f.copyTextureToBuffer({texture:c,origin:{x:t,y:s,z:r}},{buffer:p,bytesPerRow:d},{width:i,height:n});const m=this._getTypedArrayType(h);o.queue.submit([f.finish()]),await p.mapAsync(GPUMapMode.READ);const y=p.getMappedRange();return new m(y)}_getDefaultTextureGPU(e){let t=this.defaultTexture[e];if(t===void 0){const s=new Tt;s.minFilter=lt,s.magFilter=lt,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.defaultTexture[e];if(t===void 0){const s=new _l;s.minFilter=lt,s.magFilter=lt,this.createTexture(s,{width:1,height:1,depth:6}),this.defaultCubeTexture[e]=t=s}return this.backend.get(t).texture}_getDefaultVideoFrame(){let e=this.defaultVideoFrame;if(e===null){const t={timestamp:0,codedWidth:1,codedHeight:1,format:"RGBA"};this.defaultVideoFrame=e=new VideoFrame(new Uint8Array([0,0,0,255]),t)}return e}_copyCubeMapToTexture(e,t,s,i,n){for(let r=0;r<6;r++){const o=e[r],l=i===!0?fA[r]:r;o.isDataTexture?this._copyBufferToTexture(o.image,t,s,l,i):this._copyImageToTexture(o,t,s,l,i,n)}}_copyImageToTexture(e,t,s,i,n,r){this.backend.device.queue.copyExternalImageToTexture({source:e,flipY:n},{texture:t,mipLevel:0,origin:{x:0,y:0,z:i},premultipliedAlpha:r},{width:e.width,height:e.height,depthOrArrayLayers:1})}_getPassUtils(){let e=this._passUtils;return e===null&&(this._passUtils=e=new dA(this.backend.device)),e}_generateMipmaps(e,t,s=0){this._getPassUtils().generateMipmaps(e,t,s)}_flipY(e,t,s=0){this._getPassUtils().flipY(e,t,s)}_copyBufferToTexture(e,t,s,i,n,r=0){const o=this.backend.device,l=e.data,c=this._getBytesPerTexel(s.format),h=e.width*c;o.queue.writeTexture({texture:t,mipLevel:0,origin:{x:0,y:0,z:i}},l,{offset:e.width*e.height*c*r,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),r=s.size.depthOrArrayLayers>1;for(let o=0;o<e.length;o++){const l=e[o],c=l.width,h=l.height,u=r?s.size.depthOrArrayLayers:1,d=Math.ceil(c/n.width)*n.byteLength,p=d*Math.ceil(h/n.height);for(let f=0;f<u;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(h/n.height)},{width:Math.ceil(c/n.width)*n.width,height:Math.ceil(h/n.height)*n.height,depthOrArrayLayers:1})}}_getBlockData(e){if(e===E.BC1RGBAUnorm||e===E.BC1RGBAUnormSRGB)return{byteLength:8,width:4,height:4};if(e===E.BC2RGBAUnorm||e===E.BC2RGBAUnormSRGB)return{byteLength:16,width:4,height:4};if(e===E.BC3RGBAUnorm||e===E.BC3RGBAUnormSRGB)return{byteLength:16,width:4,height:4};if(e===E.BC4RUnorm||e===E.BC4RSnorm)return{byteLength:8,width:4,height:4};if(e===E.BC5RGUnorm||e===E.BC5RGSnorm)return{byteLength:16,width:4,height:4};if(e===E.BC6HRGBUFloat||e===E.BC6HRGBFloat)return{byteLength:16,width:4,height:4};if(e===E.BC7RGBAUnorm||e===E.BC7RGBAUnormSRGB)return{byteLength:16,width:4,height:4};if(e===E.ETC2RGB8Unorm||e===E.ETC2RGB8UnormSRGB)return{byteLength:8,width:4,height:4};if(e===E.ETC2RGB8A1Unorm||e===E.ETC2RGB8A1UnormSRGB)return{byteLength:8,width:4,height:4};if(e===E.ETC2RGBA8Unorm||e===E.ETC2RGBA8UnormSRGB)return{byteLength:16,width:4,height:4};if(e===E.EACR11Unorm)return{byteLength:8,width:4,height:4};if(e===E.EACR11Snorm)return{byteLength:8,width:4,height:4};if(e===E.EACRG11Unorm)return{byteLength:16,width:4,height:4};if(e===E.EACRG11Snorm)return{byteLength:16,width:4,height:4};if(e===E.ASTC4x4Unorm||e===E.ASTC4x4UnormSRGB)return{byteLength:16,width:4,height:4};if(e===E.ASTC5x4Unorm||e===E.ASTC5x4UnormSRGB)return{byteLength:16,width:5,height:4};if(e===E.ASTC5x5Unorm||e===E.ASTC5x5UnormSRGB)return{byteLength:16,width:5,height:5};if(e===E.ASTC6x5Unorm||e===E.ASTC6x5UnormSRGB)return{byteLength:16,width:6,height:5};if(e===E.ASTC6x6Unorm||e===E.ASTC6x6UnormSRGB)return{byteLength:16,width:6,height:6};if(e===E.ASTC8x5Unorm||e===E.ASTC8x5UnormSRGB)return{byteLength:16,width:8,height:5};if(e===E.ASTC8x6Unorm||e===E.ASTC8x6UnormSRGB)return{byteLength:16,width:8,height:6};if(e===E.ASTC8x8Unorm||e===E.ASTC8x8UnormSRGB)return{byteLength:16,width:8,height:8};if(e===E.ASTC10x5Unorm||e===E.ASTC10x5UnormSRGB)return{byteLength:16,width:10,height:5};if(e===E.ASTC10x6Unorm||e===E.ASTC10x6UnormSRGB)return{byteLength:16,width:10,height:6};if(e===E.ASTC10x8Unorm||e===E.ASTC10x8UnormSRGB)return{byteLength:16,width:10,height:8};if(e===E.ASTC10x10Unorm||e===E.ASTC10x10UnormSRGB)return{byteLength:16,width:10,height:10};if(e===E.ASTC12x10Unorm||e===E.ASTC12x10UnormSRGB)return{byteLength:16,width:12,height:10};if(e===E.ASTC12x12Unorm||e===E.ASTC12x12UnormSRGB)return{byteLength:16,width:12,height:12}}_convertAddressMode(e){let t=zc.ClampToEdge;return e===ar?t=zc.Repeat:e===or&&(t=zc.MirrorRepeat),t}_convertFilterMode(e){let t=an.Linear;return(e===lt||e===Mm||e===ma)&&(t=an.Nearest),t}_getBytesPerTexel(e){if(e===E.R8Unorm||e===E.R8Snorm||e===E.R8Uint||e===E.R8Sint)return 1;if(e===E.R16Uint||e===E.R16Sint||e===E.R16Float||e===E.RG8Unorm||e===E.RG8Snorm||e===E.RG8Uint||e===E.RG8Sint)return 2;if(e===E.R32Uint||e===E.R32Sint||e===E.R32Float||e===E.RG16Uint||e===E.RG16Sint||e===E.RG16Float||e===E.RGBA8Unorm||e===E.RGBA8UnormSRGB||e===E.RGBA8Snorm||e===E.RGBA8Uint||e===E.RGBA8Sint||e===E.BGRA8Unorm||e===E.BGRA8UnormSRGB||e===E.RGB9E5UFloat||e===E.RGB10A2Unorm||e===E.RG11B10UFloat||e===E.Depth32Float||e===E.Depth24Plus||e===E.Depth24PlusStencil8||e===E.Depth32FloatStencil8)return 4;if(e===E.RG32Uint||e===E.RG32Sint||e===E.RG32Float||e===E.RGBA16Uint||e===E.RGBA16Sint||e===E.RGBA16Float)return 8;if(e===E.RGBA32Uint||e===E.RGBA32Sint||e===E.RGBA32Float)return 16}_getTypedArrayType(e){if(e===E.R8Uint)return Uint8Array;if(e===E.R8Sint)return Int8Array;if(e===E.R8Unorm)return Uint8Array;if(e===E.R8Snorm)return Int8Array;if(e===E.RG8Uint)return Uint8Array;if(e===E.RG8Sint)return Int8Array;if(e===E.RG8Unorm)return Uint8Array;if(e===E.RG8Snorm)return Int8Array;if(e===E.RGBA8Uint)return Uint8Array;if(e===E.RGBA8Sint)return Int8Array;if(e===E.RGBA8Unorm)return Uint8Array;if(e===E.RGBA8Snorm)return Int8Array;if(e===E.R16Uint)return Uint16Array;if(e===E.R16Sint)return Int16Array;if(e===E.RG16Uint)return Uint16Array;if(e===E.RG16Sint)return Int16Array;if(e===E.RGBA16Uint)return Uint16Array;if(e===E.RGBA16Sint)return Int16Array;if(e===E.R16Float||e===E.RG16Float||e===E.RGBA16Float)return Uint16Array;if(e===E.R32Uint)return Uint32Array;if(e===E.R32Sint)return Int32Array;if(e===E.R32Float)return Float32Array;if(e===E.RG32Uint)return Uint32Array;if(e===E.RG32Sint)return Int32Array;if(e===E.RG32Float)return Float32Array;if(e===E.RGBA32Uint)return Uint32Array;if(e===E.RGBA32Sint)return Int32Array;if(e===E.RGBA32Float)return Float32Array;if(e===E.BGRA8Unorm||e===E.BGRA8UnormSRGB)return Uint8Array;if(e===E.RGB10A2Unorm||e===E.RGB9E5UFloat||e===E.RG11B10UFloat)return Uint32Array;if(e===E.Depth32Float)return Float32Array;if(e===E.Depth24Plus||e===E.Depth24PlusStencil8)return Uint32Array;if(e===E.Depth32FloatStencil8)return Float32Array}_getDimension(e){let t;return e.isData3DTexture?t=Tf.ThreeD:t=Tf.TwoD,t}}function Gh(a,e=null){const t=a.format,s=a.type,i=a.colorSpace,n=Le.getTransfer(i);let r;if(a.isCompressedTexture===!0||a.isCompressedArrayTexture===!0)switch(t){case Eo:r=n===se?E.BC1RGBAUnormSRGB:E.BC1RGBAUnorm;break;case Mo:r=n===se?E.BC2RGBAUnormSRGB:E.BC2RGBAUnorm;break;case Co:r=n===se?E.BC3RGBAUnormSRGB:E.BC3RGBAUnorm;break;case uh:r=n===se?E.ETC2RGB8UnormSRGB:E.ETC2RGB8Unorm;break;case dh:r=n===se?E.ETC2RGBA8UnormSRGB:E.ETC2RGBA8Unorm;break;case ph:r=n===se?E.ASTC4x4UnormSRGB:E.ASTC4x4Unorm;break;case fh:r=n===se?E.ASTC5x4UnormSRGB:E.ASTC5x4Unorm;break;case mh:r=n===se?E.ASTC5x5UnormSRGB:E.ASTC5x5Unorm;break;case gh:r=n===se?E.ASTC6x5UnormSRGB:E.ASTC6x5Unorm;break;case yh:r=n===se?E.ASTC6x6UnormSRGB:E.ASTC6x6Unorm;break;case xh:r=n===se?E.ASTC8x5UnormSRGB:E.ASTC8x5Unorm;break;case _h:r=n===se?E.ASTC8x6UnormSRGB:E.ASTC8x6Unorm;break;case bh:r=n===se?E.ASTC8x8UnormSRGB:E.ASTC8x8Unorm;break;case Th:r=n===se?E.ASTC10x5UnormSRGB:E.ASTC10x5Unorm;break;case Sh:r=n===se?E.ASTC10x6UnormSRGB:E.ASTC10x6Unorm;break;case vh:r=n===se?E.ASTC10x8UnormSRGB:E.ASTC10x8Unorm;break;case wh:r=n===se?E.ASTC10x10UnormSRGB:E.ASTC10x10Unorm;break;case Eh:r=n===se?E.ASTC12x10UnormSRGB:E.ASTC12x10Unorm;break;case Mh:r=n===se?E.ASTC12x12UnormSRGB:E.ASTC12x12Unorm;break;case rs:r=n===se?E.RGBA8UnormSRGB:E.RGBA8Unorm;break;default:console.error("WebGPURenderer: Unsupported texture format.",t)}else switch(t){case rs:switch(s){case ra:r=E.RGBA8Snorm;break;case aa:r=E.RGBA16Sint;break;case Vn:r=E.RGBA16Uint;break;case Ye:r=E.RGBA32Uint;break;case Mt:r=E.RGBA32Sint;break;case Rt:r=n===se?E.RGBA8UnormSRGB:E.RGBA8Unorm;break;case ns:r=E.RGBA16Float;break;case Zt:r=E.RGBA32Float;break;default:console.error("WebGPURenderer: Unsupported texture type with RGBAFormat.",s)}break;case Kh:switch(s){case Cm:r=E.RGB9E5UFloat;break;default:console.error("WebGPURenderer: Unsupported texture type with RGBFormat.",s)}break;case Jh:switch(s){case ra:r=E.R8Snorm;break;case aa:r=E.R16Sint;break;case Vn:r=E.R16Uint;break;case Ye:r=E.R32Uint;break;case Mt:r=E.R32Sint;break;case Rt:r=E.R8Unorm;break;case ns:r=E.R16Float;break;case Zt:r=E.R32Float;break;default:console.error("WebGPURenderer: Unsupported texture type with RedFormat.",s)}break;case on:switch(s){case ra:r=E.RG8Snorm;break;case aa:r=E.RG16Sint;break;case Vn:r=E.RG16Uint;break;case Ye:r=E.RG32Uint;break;case Mt:r=E.RG32Sint;break;case Rt:r=E.RG8Unorm;break;case ns:r=E.RG16Float;break;case Zt:r=E.RG32Float;break;default:console.error("WebGPURenderer: Unsupported texture type with RGFormat.",s)}break;case Bs:switch(s){case Vn:r=E.Depth16Unorm;break;case Ye:r=E.Depth24Plus;break;case Zt:r=E.Depth32Float;break;default:console.error("WebGPURenderer: Unsupported texture type with DepthFormat.",s)}break;case ti:switch(s){case Ni:r=E.Depth24PlusStencil8;break;case Zt:e&&e.features.has(zh.Depth32FloatStencil8)===!1&&console.error('WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.'),r=E.Depth32FloatStencil8;break;default:console.error("WebGPURenderer: Unsupported texture type with DepthStencilFormat.",s)}break;case eu:switch(s){case Mt:r=E.R32Sint;break;case Ye:r=E.R32Uint;break;default:console.error("WebGPURenderer: Unsupported texture type with RedIntegerFormat.",s)}break;case tu:switch(s){case Mt:r=E.RG32Sint;break;case Ye:r=E.RG32Uint;break;default:console.error("WebGPURenderer: Unsupported texture type with RGIntegerFormat.",s)}break;case su:switch(s){case Mt:r=E.RGBA32Sint;break;case Ye:r=E.RGBA32Uint;break;default:console.error("WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.",s)}break;default:console.error("WebGPURenderer: Unsupported texture format.",t)}return r}const gA=/^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,yA=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig,Sf={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"},xA=a=>{a=a.trim();const e=a.match(gA);if(e!==null&&e.length===4){const t=e[2],s=[];let i=null;for(;(i=yA.exec(t))!==null;)s.push({name:i[1],type:i[2]});const n=[];for(let h=0;h<s.length;h++){const{name:u,type:d}=s[h];let p=d;p.startsWith("ptr")?p="pointer":(p.startsWith("texture")&&(p=d.split("<")[0]),p=Sf[p]),n.push(new Uu(p,u))}const r=a.substring(e[0].length),o=e[3]||"void",l=e[1]!==void 0?e[1]:"";return{type:Sf[o]||o,inputs:n,name:l,inputsCode:t,blockCode:r,outputType:o}}else throw new Error("FunctionNode: Function is not a WGSL code.")};class _A extends Gu{constructor(e){const{type:t,inputs:s,name:i,inputsCode:n,blockCode:r,outputType:o}=xA(e);super(t,s,i),this.inputsCode=n,this.blockCode=r,this.outputType=o}getCode(e=this.name){const t=this.outputType!=="void"?"-> "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class bA extends my{parseFunction(e){return new _A(e)}}const In=typeof self<"u"?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},TA={[Zs.READ_ONLY]:"read",[Zs.WRITE_ONLY]:"write",[Zs.READ_WRITE]:"read_write"},vf={[ar]:"repeat",[Ri]:"clamp",[or]:"mirror"},po={vertex:In?In.VERTEX:1,fragment:In?In.FRAGMENT:2,compute:In?In.COMPUTE:4},wf={instance:!0,swizzleAssign:!1,storageBuffer:!0},SA={"^^":"tsl_xor"},vA={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>"},Ef={},ts={tsl_xor:new ot("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new ot("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new ot("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new ot("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new ot("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new ot("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new ot("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new ot("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 ot("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 ot("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new ot("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 ot("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new ot(`
|
324
|
+
fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
|
325
|
+
|
326
|
+
let res = vec2f( iRes );
|
327
|
+
|
328
|
+
let uvScaled = coord * res;
|
329
|
+
let uvWrapping = ( ( uvScaled % res ) + res ) % res;
|
330
|
+
|
331
|
+
// https://www.shadertoy.com/view/WtyXRy
|
332
|
+
|
333
|
+
let uv = uvWrapping - 0.5;
|
334
|
+
let iuv = floor( uv );
|
335
|
+
let f = fract( uv );
|
336
|
+
|
337
|
+
let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
|
338
|
+
let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
|
339
|
+
let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
|
340
|
+
let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
|
341
|
+
|
342
|
+
return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
|
343
|
+
|
344
|
+
}
|
345
|
+
`)},Jr={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>"};typeof navigator<"u"&&/Windows/g.test(navigator.userAgent)&&(ts.pow_float=new ot("fn tsl_pow_float( a : f32, b : f32 ) -> f32 { return select( -pow( -a, b ), pow( a, b ), a > 0.0 ); }"),ts.pow_vec2=new ot("fn tsl_pow_vec2( a : vec2f, b : vec2f ) -> vec2f { return vec2f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ) ); }",[ts.pow_float]),ts.pow_vec3=new ot("fn tsl_pow_vec3( a : vec3f, b : vec3f ) -> vec3f { return vec3f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ) ); }",[ts.pow_float]),ts.pow_vec4=new ot("fn tsl_pow_vec4( a : vec4f, b : vec4f ) -> vec4f { return vec4f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ), tsl_pow_float( a.w, b.w ) ); }",[ts.pow_float]),Jr.pow_float="tsl_pow_float",Jr.pow_vec2="tsl_pow_vec2",Jr.pow_vec3="tsl_pow_vec3",Jr.pow_vec4="tsl_pow_vec4");let Ry="";(typeof navigator<"u"&&/Firefox|Deno/g.test(navigator.userAgent))!==!0&&(Ry+=`diagnostic( off, derivative_uniformity );
|
346
|
+
`);class wA extends fy{constructor(e,t){super(e,t,new bA),this.uniformGroups={},this.builtins={},this.directives={},this.scopedArrays=new Map}needsToWorkingColorSpace(e){return e.isVideoTexture===!0&&e.colorSpace!==ri}_generateTextureSample(e,t,s,i,n=this.shaderStage){return n==="fragment"?i?`textureSample( ${t}, ${t}_sampler, ${s}, ${i} )`:`textureSample( ${t}, ${t}_sampler, ${s} )`:this._generateTextureSampleLevel(e,t,s,"0",i)}_generateVideoSample(e,t,s=this.shaderStage){if(s==="fragment")return`textureSampleBaseClampToEdge( ${e}, ${e}_sampler, vec2<f32>( ${t}.x, 1.0 - ${t}.y ) )`;console.error(`WebGPURenderer: THREE.VideoTexture does not support ${s} shader.`)}_generateTextureSampleLevel(e,t,s,i,n){return this.isUnfilterable(e)===!1?`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,s,i):this.generateTextureLod(e,t,s,n,i)}generateWrapFunction(e){const t=`tsl_coord_${vf[e.wrapS]}S_${vf[e.wrapT]}_${e.isData3DTexture?"3d":"2d"}T`;let s=Ef[t];if(s===void 0){const i=[],n=e.isData3DTexture?"vec3f":"vec2f";let r=`fn ${t}( coord : ${n} ) -> ${n} {
|
347
|
+
|
348
|
+
return ${n}(
|
349
|
+
`;const o=(l,c)=>{l===ar?(i.push(ts.repeatWrapping_float),r+=` tsl_repeatWrapping_float( coord.${c} )`):l===Ri?(i.push(ts.clampWrapping_float),r+=` tsl_clampWrapping_float( coord.${c} )`):l===or?(i.push(ts.mirrorWrapping_float),r+=` tsl_mirrorWrapping_float( coord.${c} )`):(r+=` coord.${c}`,console.warn(`WebGPURenderer: Unsupported texture wrap type "${l}" for vertex shader.`))};o(e.wrapS,"x"),r+=`,
|
350
|
+
`,o(e.wrapT,"y"),e.isData3DTexture&&(r+=`,
|
351
|
+
`,o(e.wrapR,"z")),r+=`
|
352
|
+
);
|
353
|
+
|
354
|
+
}
|
355
|
+
`,Ef[t]=s=new ot(r,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 r,o;const{primarySamples:l}=this.renderer.backend.utils.getTextureSampleData(e),c=l>1;e.isData3DTexture?o="vec3<u32>":o="vec2<u32>",c||e.isVideoTexture||e.isStorageTexture?r=t:r=`${t}${s?`, u32( ${s} )`:""}`,n=new No(new Fo(`textureDimensions( ${r} )`,o)),i.dimensionsSnippet[s]=n,(e.isArrayTexture||e.isDataArrayTexture||e.isData3DTexture)&&(i.arrayLayerCount=new No(new Fo(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(i.cubeFaceCount=new No(new Fo("6u","u32")))}return n.build(this)}generateFilteredTexture(e,t,s,i="0u"){this._include("biquadraticTexture");const n=this.generateWrapFunction(e),r=this.generateTextureDimension(e,t,i);return`tsl_biquadraticTexture( ${t}, ${n}( ${s} ), ${r}, u32( ${i} ) )`}generateTextureLod(e,t,s,i,n="0u"){const r=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,n),l=e.isData3DTexture?"vec3":"vec2",c=`${l}<u32>( ${r}( ${s} ) * ${l}<f32>( ${o} ) )`;return this.generateTextureLoad(e,t,c,i,n)}generateTextureLoad(e,t,s,i,n="0u"){let r;return e.isVideoTexture===!0?r=`textureLoad( ${t}, ${s} )`:i?r=`textureLoad( ${t}, ${s}, ${i}, u32( ${n} ) )`:(r=`textureLoad( ${t}, ${s}, u32( ${n} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(r+=".x")),r}generateTextureStore(e,t,s,i,n){let r;return i?r=`textureStore( ${t}, ${s}, ${i}, ${n} )`:r=`textureStore( ${t}, ${s}, ${n} )`,r}isSampleCompare(e){return e.isDepthTexture===!0&&e.compareFunction!==null}isUnfilterable(e){return this.getComponentTypeFromTexture(e)!=="float"||!this.isAvailable("float32Filterable")&&e.isDataTexture===!0&&e.type===Zt||this.isSampleCompare(e)===!1&&e.minFilter===lt&&e.magFilter===lt||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1}generateTexture(e,t,s,i,n=this.shaderStage){let r=null;return e.isVideoTexture===!0?r=this._generateVideoSample(t,s,n):this.isUnfilterable(e)?r=this.generateTextureLod(e,t,s,i,"0",n):r=this._generateTextureSample(e,t,s,i,n),r}generateTextureGrad(e,t,s,i,n,r=this.shaderStage){if(r==="fragment")return`textureSampleGrad( ${t}, ${t}_sampler, ${s}, ${i[0]}, ${i[1]} )`;console.error(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${r} shader.`)}generateTextureCompare(e,t,s,i,n,r=this.shaderStage){if(r==="fragment")return e.isDepthTexture===!0&&e.isArrayTexture===!0?`textureSampleCompare( ${t}, ${t}_sampler, ${s}, ${n}, ${i} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${s}, ${i} )`;console.error(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${r} shader.`)}generateTextureLevel(e,t,s,i,n,r=this.shaderStage){let o=null;return e.isVideoTexture===!0?o=this._generateVideoSample(t,s,r):o=this._generateTextureSampleLevel(e,t,s,i,n),o}generateTextureBias(e,t,s,i,n,r=this.shaderStage){if(r==="fragment")return`textureSampleBias( ${t}, ${t}_sampler, ${s}, ${i} )`;console.error(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${r} 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==="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=SA[e];return t!==void 0?(this._include(t),t):null}getNodeAccess(e,t){return t!=="compute"?Zs.READ_ONLY:e.access}getStorageAccess(e,t){return TA[this.getNodeAccess(e,t)]}getUniformFromNode(e,t,s,i=null){const n=super.getUniformFromNode(e,t,s,i),r=this.getDataFromNode(e,s,this.globalCache);if(r.uniformGPU===void 0){let o;const l=e.groupNode,c=l.name,h=this.getBindGroupArray(c,s);if(t==="texture"||t==="cubeTexture"||t==="storageTexture"||t==="texture3D"){let u=null;const d=this.getNodeAccess(e,s);if(t==="texture"||t==="storageTexture"?u=new wl(n.name,n.node,l,d):t==="cubeTexture"?u=new Ey(n.name,n.node,l,d):t==="texture3D"&&(u=new My(n.name,n.node,l,d)),u.store=e.isStorageTextureNode===!0,u.setVisibility(po[s]),this.isUnfilterable(e.value)===!1&&u.store===!1){const p=new lA(`${n.name}_sampler`,n.node,l);p.setVisibility(po[s]),h.push(p,u),o=[p,u]}else h.push(u),o=[u]}else if(t==="buffer"||t==="storageBuffer"||t==="indirectStorageBuffer"){const u=t==="buffer"?vy:uA,d=new u(e,l);d.setVisibility(po[s]),h.push(d),o=d,n.name=i||"NodeBuffer_"+n.id}else{const u=this.uniformGroups[s]||(this.uniformGroups[s]={});let d=u[c];d===void 0&&(d=new wy(c,l),d.setVisibility(po[s]),u[c]=d,h.push(d)),o=this.getNodeUniform(n,t),d.addUniform(o)}r.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 r of t.inputs)i.push(r.name+" : "+this.getType(r.type));let n=`fn ${t.name}( ${i.join(", ")} ) -> ${this.getType(t.type)} {
|
356
|
+
${s.vars}
|
357
|
+
${s.code}
|
358
|
+
`;return s.result&&(n+=` return ${s.result};
|
359
|
+
`),n+=`
|
360
|
+
}
|
361
|
+
`,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(`
|
362
|
+
`)}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:r}of s.values())t.push(`@builtin( ${i} ) ${n} : ${r}`);return t.join(`,
|
363
|
+
`)}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:r}of this.scopedArrays.values()){const o=this.getType(n);t.push(`var<${i}> ${s}: array< ${o}, ${r} >;`)}return t.join(`
|
364
|
+
`)}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,r=i.length;n<r;n++){const o=i[n],l=o.name,c=this.getType(o.type);t.push(`@location( ${n} ) ${l} : ${c}`)}}return t.join(`,
|
365
|
+
`)}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(`,
|
366
|
+
`)}getStructs(e){let t="";const s=this.structs[e];if(s.length>0){const i=[];for(const n of s){let r=`struct ${n.name} {
|
367
|
+
`;r+=this.getStructMembers(n),r+=`
|
368
|
+
};`,i.push(r)}t=`
|
369
|
+
`+i.join(`
|
370
|
+
|
371
|
+
`)+`
|
372
|
+
`}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`
|
373
|
+
${t.join(`
|
374
|
+
`)}
|
375
|
+
`}getVaryings(e){const t=[];if(e==="vertex"&&this.getBuiltin("position","Vertex","vec4<f32>","vertex"),e==="vertex"||e==="fragment"){const n=this.varyings,r=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 h=l.interpolationSampling!==null?`, ${l.interpolationSampling} )`:" )";c+=` @interpolate( ${l.interpolationType}${h}`}else/^(int|uint|ivec|uvec)/.test(l.type)&&(c+=` @interpolate( ${this.renderer.backend.compatibilityMode?"flat, either":"flat"} )`);t.push(`${c} ${l.name} : ${this.getType(l.type)}`)}else e==="vertex"&&r.includes(l)===!1&&r.push(l)}}const s=this.getBuiltins(e);s&&t.push(s);const i=t.join(`,
|
376
|
+
`);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=[],r={};for(const l of t){const c=l.groupNode.name,h=this.bindingsIndexes[c];if(l.type==="texture"||l.type==="cubeTexture"||l.type==="storageTexture"||l.type==="texture3D"){const u=l.node.value;this.isUnfilterable(u)===!1&&l.node.isStorageTextureNode!==!0&&(this.isSampleCompare(u)?s.push(`@binding( ${h.binding++} ) @group( ${h.group} ) var ${l.name}_sampler : sampler_comparison;`):s.push(`@binding( ${h.binding++} ) @group( ${h.group} ) var ${l.name}_sampler : sampler;`));let d,p="";const{primarySamples:f}=this.renderer.backend.utils.getTextureSampleData(u);if(f>1&&(p="_multisampled"),u.isCubeTexture===!0)d="texture_cube<f32>";else if(u.isDepthTexture===!0)this.renderer.backend.compatibilityMode&&u.compareFunction===null?d=`texture${p}_2d<f32>`:d=`texture_depth${p}_2d${u.isArrayTexture===!0?"_array":""}`;else if(u.isArrayTexture===!0||u.isDataArrayTexture===!0||u.isCompressedArrayTexture===!0)d="texture_2d_array<f32>";else if(u.isVideoTexture===!0)d="texture_external";else if(u.isData3DTexture===!0)d="texture_3d<f32>";else if(l.node.isStorageTextureNode===!0){const m=Gh(u),y=this.getStorageAccess(l.node,e);d=`texture_storage_2d<${m}, ${y}>`}else{const m=this.getComponentTypeFromTexture(u).charAt(0);d=`texture${p}_2d<${m}32>`}s.push(`@binding( ${h.binding++} ) @group( ${h.group} ) var ${l.name} : ${d};`)}else if(l.type==="buffer"||l.type==="storageBuffer"||l.type==="indirectStorageBuffer"){const u=l.node,d=this.getType(u.getNodeType(this)),p=u.bufferCount,f=p>0&&l.type==="buffer"?", "+p:"",m=u.isStorageBufferNode?`storage, ${this.getStorageAccess(u,e)}`:"uniform";if(this.isCustomStruct(l))i.push(`@binding( ${h.binding++} ) @group( ${h.group} ) var<${m}> ${l.name} : ${d};`);else{const g=` value : array< ${u.isAtomic?`atomic<${d}>`:`${d}`}${f} >`;i.push(this._getWGSLStructBinding(l.name,g,m,h.binding++,h.group))}}else{const u=this.getType(this.getVectorType(l.type)),d=l.groupNode.name;(r[d]||(r[d]={index:h.binding++,id:h.group,snippets:[]})).snippets.push(` ${l.name} : ${u}`)}}for(const l in r){const c=r[l];n.push(this._getWGSLStructBinding(l,c.snippets.join(`,
|
377
|
+
`),"uniform",c.index,c.id))}let o=s.join(`
|
378
|
+
`);return o+=i.join(`
|
379
|
+
`),o+=n.join(`
|
380
|
+
`),o}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
|
381
|
+
|
382
|
+
`;i+=this.flowCode[t];const n=this.flowNodes[t],r=n[n.length-1],o=r.outputNode,l=o!==void 0&&o.isOutputStructNode===!0;for(const c of n){const h=this.getFlowData(c),u=c.name;if(u&&(i.length>0&&(i+=`
|
383
|
+
`),i+=` // flow -> ${u}
|
384
|
+
`),i+=`${h.code}
|
385
|
+
`,c===r&&t!=="compute"){if(i+=`// result
|
386
|
+
|
387
|
+
`,t==="vertex")i+=`varyings.Vertex = ${h.result};`;else if(t==="fragment")if(l)s.returnType=o.getNodeType(this),s.structs+="var<private> output : "+s.returnType+";",i+=`return ${h.result};`;else{let d=" @location(0) color: vec4<f32>";const p=this.getBuiltins("output");p&&(d+=`,
|
388
|
+
`+p),s.returnType="OutputStruct",s.structs+=this._getWGSLStruct("OutputStruct",d),s.structs+=`
|
389
|
+
var<private> output : OutputStruct;`,i+=`output.color = ${h.result};
|
390
|
+
|
391
|
+
return output;`}}}s.flow=i}this.shaderStage=null,this.material!==null?(this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment)):this.computeShader=this._getWGSLComputeCode(e.compute,(this.object.workgroupSize||[64]).join(", "))}getMethod(e,t=null){let s;return t!==null&&(s=this._getWGSLMethod(e+"_"+t)),s===void 0&&(s=this._getWGSLMethod(e)),s||e}getType(e){return vA[e]||e}isAvailable(e){let t=wf[e];return t===void 0&&(e==="float32Filterable"?t=this.renderer.hasFeature("float32-filterable"):e==="clipDistance"&&(t=this.renderer.hasFeature("clip-distances")),wf[e]=t),t}_getWGSLMethod(e){return ts[e]!==void 0&&this._include(e),Jr[e]}_include(e){const t=ts[e];return t.build(this),this.currentFunctionNode!==null&&this.currentFunctionNode.includes.push(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}
|
392
|
+
// directives
|
393
|
+
${e.directives}
|
394
|
+
|
395
|
+
// structs
|
396
|
+
${e.structs}
|
397
|
+
|
398
|
+
// uniforms
|
399
|
+
${e.uniforms}
|
400
|
+
|
401
|
+
// varyings
|
402
|
+
${e.varyings}
|
403
|
+
var<private> varyings : VaryingsStruct;
|
404
|
+
|
405
|
+
// codes
|
406
|
+
${e.codes}
|
407
|
+
|
408
|
+
@vertex
|
409
|
+
fn main( ${e.attributes} ) -> VaryingsStruct {
|
410
|
+
|
411
|
+
// vars
|
412
|
+
${e.vars}
|
413
|
+
|
414
|
+
// flow
|
415
|
+
${e.flow}
|
416
|
+
|
417
|
+
return varyings;
|
418
|
+
|
419
|
+
}
|
420
|
+
`}_getWGSLFragmentCode(e){return`${this.getSignature()}
|
421
|
+
// global
|
422
|
+
${Ry}
|
423
|
+
|
424
|
+
// structs
|
425
|
+
${e.structs}
|
426
|
+
|
427
|
+
// uniforms
|
428
|
+
${e.uniforms}
|
429
|
+
|
430
|
+
// codes
|
431
|
+
${e.codes}
|
432
|
+
|
433
|
+
@fragment
|
434
|
+
fn main( ${e.varyings} ) -> ${e.returnType} {
|
435
|
+
|
436
|
+
// vars
|
437
|
+
${e.vars}
|
438
|
+
|
439
|
+
// flow
|
440
|
+
${e.flow}
|
441
|
+
|
442
|
+
}
|
443
|
+
`}_getWGSLComputeCode(e,t){return`${this.getSignature()}
|
444
|
+
// directives
|
445
|
+
${e.directives}
|
446
|
+
|
447
|
+
// system
|
448
|
+
var<private> instanceIndex : u32;
|
449
|
+
|
450
|
+
// locals
|
451
|
+
${e.scopedArrays}
|
452
|
+
|
453
|
+
// structs
|
454
|
+
${e.structs}
|
455
|
+
|
456
|
+
// uniforms
|
457
|
+
${e.uniforms}
|
458
|
+
|
459
|
+
// codes
|
460
|
+
${e.codes}
|
461
|
+
|
462
|
+
@compute @workgroup_size( ${t} )
|
463
|
+
fn main( ${e.attributes} ) {
|
464
|
+
|
465
|
+
// system
|
466
|
+
instanceIndex = globalId.x + globalId.y * numWorkgroups.x * u32(${t}) + globalId.z * numWorkgroups.x * numWorkgroups.y * u32(${t});
|
467
|
+
|
468
|
+
// vars
|
469
|
+
${e.vars}
|
470
|
+
|
471
|
+
// flow
|
472
|
+
${e.flow}
|
473
|
+
|
474
|
+
}
|
475
|
+
`}_getWGSLStruct(e,t){return`
|
476
|
+
struct ${e} {
|
477
|
+
${t}
|
478
|
+
};`}_getWGSLStructBinding(e,t,s,i=0,n=0){const r=e+"Struct";return`${this._getWGSLStruct(r,t)}
|
479
|
+
@binding( ${i} ) @group( ${n} )
|
480
|
+
var<${s}> ${e} : ${r};`}}class EA{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return e.depthTexture!==null?t=this.getTextureFormatGPU(e.depthTexture):e.depth&&e.stencil?t=E.Depth24PlusStencil8:e.depth&&(t=E.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,r=n.getRenderTarget();t=r?r.samples:n.samples}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}getCurrentColorSpace(e){return e.textures!==null?e.textures[0].colorSpace:this.backend.renderer.outputColorSpace}getPrimitiveTopology(e,t){if(e.isPoints)return qn.PointList;if(e.isLineSegments||e.isMesh&&t.wireframe===!0)return qn.LineList;if(e.isLine)return qn.LineStrip;if(e.isMesh)return qn.TriangleList}getSampleCount(e){let t=1;return e>1&&(t=Math.pow(2,Math.floor(Math.log2(e))),t===2&&(t=4)),t}getSampleCountRenderContext(e){return e.textures!==null?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.samples)}getPreferredCanvasFormat(){const e=this.backend.parameters.outputType;if(e===void 0)return navigator.gpu.getPreferredCanvasFormat();if(e===Rt)return E.BGRA8Unorm;if(e===ns)return E.RGBA16Float;throw new Error("Unsupported outputType")}}const MA=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]),CA=new Map([[Vm,["float16"]]]),AA=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class RA{constructor(e){this.backend=e}createAttribute(e,t){const s=this._getBufferAttribute(e),i=this.backend,n=i.get(s);let r=n.buffer;if(r===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 u=0;u<l.length;u++)l[u]===65535&&(l[u]=4294967295)}if(s.array=l,(s.isStorageBufferAttribute||s.isStorageInstancedBufferAttribute)&&s.itemSize===3){l=new l.constructor(s.count*4);for(let u=0;u<s.count;u++)l.set(s.array.subarray(u*3,u*3+3),u*4);s.itemSize=4,s.array=l,n._force3to4BytesAlignment=!0}const c=l.byteLength,h=c+(4-c%4)%4;r=o.createBuffer({label:s.name,size:h,usage:t,mappedAtCreation:!0}),new l.constructor(r.getMappedRange()).set(l),r.unmap(),n.buffer=r}}updateAttribute(e){const t=this._getBufferAttribute(e),s=this.backend,i=s.device,n=s.get(t),r=s.get(t).buffer;let o=t.array;if(n._force3to4BytesAlignment===!0){o=new o.constructor(t.count*4);for(let h=0;h<t.count;h++)o.set(t.array.subarray(h*3,h*3+3),h*4);t.array=o}const l=this._isTypedArray(o),c=t.updateRanges;if(c.length===0)i.queue.writeBuffer(r,0,o,0);else{const h=l?1:o.BYTES_PER_ELEMENT;for(let u=0,d=c.length;u<d;u++){const p=c[u];let f,m;if(n._force3to4BytesAlignment===!0){const g=Math.floor(p.start/3),_=Math.ceil(p.count/3);f=g*4*h,m=_*4*h}else f=p.start*h,m=p.count*h;const y=f*(l?o.BYTES_PER_ELEMENT:1);i.queue.writeBuffer(r,y,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],r=n.array.BYTES_PER_ELEMENT,o=this._getBufferAttribute(n);let l=s.get(o);if(l===void 0){let u,d;n.isInterleavedBufferAttribute===!0?(u=n.data.stride*r,d=n.data.isInstancedInterleavedBuffer?uo.Instance:uo.Vertex):(u=n.itemSize*r,d=n.isInstancedBufferAttribute?uo.Instance:uo.Vertex),n.normalized===!1&&(n.array.constructor===Int16Array||n.array.constructor===Uint16Array)&&(u=4),l={arrayStride:u,attributes:[],stepMode:d},s.set(o,l)}const c=this._getVertexFormat(n),h=n.isInterleavedBufferAttribute===!0?n.offset*r:0;l.attributes.push({shaderLocation:i,offset:h,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,r=n.size,o=s.createBuffer({label:`${e.name}_readback`,size:r,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),l=s.createCommandEncoder({label:`readback_encoder_${e.name}`});l.copyBufferToBuffer(n,0,o,0,r);const c=l.finish();s.queue.submit([c]),await o.mapAsync(GPUMapMode.READ);const h=o.getMappedRange(),u=new e.array.constructor(h.slice(0));return o.unmap(),u.buffer}_getVertexFormat(e){const{itemSize:t,normalized:s}=e,i=e.array.constructor,n=e.constructor;let r;if(t===1)r=AA.get(i);else{const l=(CA.get(n)||MA.get(i))[s?1:0];if(l){const c=i.BYTES_PER_ELEMENT*t,u=Math.floor((c+3)/4)*4/i.BYTES_PER_ELEMENT;if(u%1)throw new Error("THREE.WebGPUAttributeUtils: Bad vertex format item size.");r=`${l}x${u}`}}return r||console.error("THREE.WebGPUAttributeUtils: Vertex format not supported yet."),r}_isTypedArray(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}class NA{constructor(e){this.backend=e,this.bindGroupLayoutCache=new WeakMap}createBindingsLayout(e){const t=this.backend,s=t.device,i=[];let n=0;for(const r of e.bindings){const o={binding:n++,visibility:r.visibility};if(r.isUniformBuffer||r.isStorageBuffer){const l={};r.isStorageBuffer&&(r.visibility&4&&(r.access===Zs.READ_WRITE||r.access===Zs.WRITE_ONLY)?l.type=Gc.Storage:l.type=Gc.ReadOnlyStorage),o.buffer=l}else if(r.isSampler){const l={};r.texture.isDepthTexture&&(r.texture.compareFunction!==null?l.type=bf.Comparison:t.compatibilityMode&&(l.type=bf.NonFiltering)),o.sampler=l}else if(r.isSampledTexture&&r.texture.isVideoTexture)o.externalTexture={};else if(r.isSampledTexture&&r.store){const l={};l.format=this.backend.get(r.texture).texture.format;const c=r.access;c===Zs.READ_WRITE?l.access=Vc.ReadWrite:c===Zs.WRITE_ONLY?l.access=Vc.WriteOnly:l.access=Vc.ReadOnly,o.storageTexture=l}else if(r.isSampledTexture){const l={},{primarySamples:c}=t.utils.getTextureSampleData(r.texture);if(c>1&&(l.multisampled=!0,r.texture.isDepthTexture||(l.sampleType=ji.UnfilterableFloat)),r.texture.isDepthTexture)t.compatibilityMode&&r.texture.compareFunction===null?l.sampleType=ji.UnfilterableFloat:l.sampleType=ji.Depth;else if(r.texture.isDataTexture||r.texture.isDataArrayTexture||r.texture.isData3DTexture){const h=r.texture.type;h===Mt?l.sampleType=ji.SInt:h===Ye?l.sampleType=ji.UInt:h===Zt&&(this.backend.hasFeature("float32-filterable")?l.sampleType=ji.Float:l.sampleType=ji.UnfilterableFloat)}r.isSampledCubeTexture?l.viewDimension=ut.Cube:r.texture.isArrayTexture||r.texture.isDataArrayTexture||r.texture.isCompressedArrayTexture?l.viewDimension=ut.TwoDArray:r.isSampledTexture3D&&(l.viewDimension=ut.ThreeD),o.texture=l}else console.error(`WebGPUBindingUtils: Unsupported binding "${r}".`);i.push(o)}return s.createBindGroupLayout({entries:i})}createBindings(e,t,s,i=0){const{backend:n,bindGroupLayoutCache:r}=this,o=n.get(e);let l=r.get(e.bindingsReference);l===void 0&&(l=this.createBindingsLayout(e),r.set(e.bindingsReference,l));let c;s>0&&(o.groups===void 0&&(o.groups=[],o.versions=[]),o.versions[s]===i&&(c=o.groups[s])),c===void 0&&(c=this.createBindGroup(e,l),s>0&&(o.groups[s]=c,o.versions[s]=i)),o.group=c,o.layout=l}updateBinding(e){const t=this.backend,s=t.device,i=e.buffer,n=t.get(e).buffer;s.queue.writeBuffer(n,0,i,0)}createBindGroupIndex(e,t){const i=this.backend.device,n=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,r=e[0],o=i.createBuffer({label:"bindingCameraIndex_"+r,size:16,usage:n});i.queue.writeBuffer(o,0,e,0);const l=[{binding:0,resource:{buffer:o}}];return i.createBindGroup({label:"bindGroupCameraIndex_"+r,layout:t,entries:l})}createBindGroup(e,t){const s=this.backend,i=s.device;let n=0;const r=[];for(const o of e.bindings){if(o.isUniformBuffer){const l=s.get(o);if(l.buffer===void 0){const c=o.byteLength,h=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,u=i.createBuffer({label:"bindingBuffer_"+o.name,size:c,usage:h});l.buffer=u}r.push({binding:n,resource:{buffer:l.buffer}})}else if(o.isStorageBuffer){const l=s.get(o);if(l.buffer===void 0){const c=o.attribute;l.buffer=s.get(c).buffer}r.push({binding:n,resource:{buffer:l.buffer}})}else if(o.isSampler){const l=s.get(o.texture);r.push({binding:n,resource:l.sampler})}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 h=o.store?1:l.texture.mipLevelCount,u=`view-${l.texture.width}-${l.texture.height}-${h}`;if(c=l[u],c===void 0){const d=aA.All;let p;o.isSampledCubeTexture?p=ut.Cube:o.isSampledTexture3D?p=ut.ThreeD:o.texture.isArrayTexture||o.texture.isDataArrayTexture||o.texture.isCompressedArrayTexture?p=ut.TwoDArray:p=ut.TwoD,c=l[u]=l.texture.createView({aspect:d,dimension:p,mipLevelCount:h})}}r.push({binding:n,resource:c})}n++}return i.createBindGroup({label:"bindGroup_"+e.name,layout:t,entries:r})}}class PA{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:r}=e,{vertexProgram:o,fragmentProgram:l}=r,c=this.backend,h=c.device,u=c.utils,d=c.get(r),p=[];for(const j of e.getBindings()){const X=c.get(j);p.push(X.layout)}const f=c.attributeUtils.createShaderVertexBuffers(e);let m;i.blending!==rr&&(i.blending!==Js||i.transparent!==!1)&&(m=this._getBlending(i));let y={};i.stencilWrite===!0&&(y={compare:this._getStencilCompare(i),failOp:this._getStencilOperation(i.stencilFail),depthFailOp:this._getStencilOperation(i.stencilZFail),passOp:this._getStencilOperation(i.stencilZPass)});const g=this._getColorWriteMask(i),_=[];if(e.context.textures!==null){const j=e.context.textures;for(let X=0;X<j.length;X++){const Z=u.getTextureFormatGPU(j[X]);_.push({format:Z,blend:m,writeMask:g})}}else{const j=u.getCurrentColorFormat(e.context);_.push({format:j,blend:m,writeMask:g})}const b=c.get(o).module,S=c.get(l).module,T=this._getPrimitiveState(s,n,i),M=this._getDepthCompare(i),w=u.getCurrentDepthStencilFormat(e.context),R=this._getSampleCount(e.context),P={label:`renderPipeline_${i.name||i.type}_${i.id}`,vertex:Object.assign({},b,{buffers:f}),fragment:Object.assign({},S,{targets:_}),primitive:T,multisample:{count:R,alphaToCoverageEnabled:i.alphaToCoverage&&R>1},layout:h.createPipelineLayout({bindGroupLayouts:p})},z={},$=e.context.depth,q=e.context.stencil;if(($===!0||q===!0)&&($===!0&&(z.format=w,z.depthWriteEnabled=i.depthWrite,z.depthCompare=M),q===!0&&(z.stencilFront=y,z.stencilBack={},z.stencilReadMask=i.stencilFuncMask,z.stencilWriteMask=i.stencilWriteMask),i.polygonOffset===!0&&(z.depthBias=i.polygonOffsetUnits,z.depthBiasSlopeScale=i.polygonOffsetFactor,z.depthBiasClamp=0),P.depthStencil=z),t===null)d.pipeline=h.createRenderPipeline(P);else{const j=new Promise(X=>{h.createRenderPipelineAsync(P).then(Z=>{d.pipeline=Z,X()})});t.push(j)}}createBundleEncoder(e,t="renderBundleEncoder"){const s=this.backend,{utils:i,device:n}=s,r=i.getCurrentDepthStencilFormat(e),o=i.getCurrentColorFormat(e),l=this._getSampleCount(e),c={label:t,colorFormats:[o],depthStencilFormat:r,sampleCount:l};return n.createRenderBundleEncoder(c)}createComputePipeline(e,t){const s=this.backend,i=s.device,n=s.get(e.computeProgram).module,r=s.get(e),o=[];for(const l of t){const c=s.get(l);o.push(c.layout)}r.pipeline=i.createComputePipeline({compute:n,layout:i.createPipelineLayout({bindGroupLayouts:o})})}_getBlending(e){let t,s;const i=e.blending,n=e.blendSrc,r=e.blendDst,o=e.blendEquation;if(i===na){const l=e.blendSrcAlpha!==null?e.blendSrcAlpha:n,c=e.blendDstAlpha!==null?e.blendDstAlpha:r,h=e.blendEquationAlpha!==null?e.blendEquationAlpha:o;t={srcFactor:this._getBlendFactor(n),dstFactor:this._getBlendFactor(r),operation:this._getBlendOperation(o)},s={srcFactor:this._getBlendFactor(l),dstFactor:this._getBlendFactor(c),operation:this._getBlendOperation(h)}}else{const l=e.premultipliedAlpha,c=(h,u,d,p)=>{t={srcFactor:h,dstFactor:u,operation:$i.Add},s={srcFactor:d,dstFactor:p,operation:$i.Add}};if(l)switch(i){case Js:c(ne.One,ne.OneMinusSrcAlpha,ne.One,ne.OneMinusSrcAlpha);break;case Uo:c(ne.One,ne.One,ne.One,ne.One);break;case ko:c(ne.Zero,ne.OneMinusSrc,ne.Zero,ne.One);break;case zo:c(ne.Zero,ne.Src,ne.Zero,ne.SrcAlpha);break}else switch(i){case Js:c(ne.SrcAlpha,ne.OneMinusSrcAlpha,ne.One,ne.OneMinusSrcAlpha);break;case Uo:c(ne.SrcAlpha,ne.One,ne.SrcAlpha,ne.One);break;case ko:c(ne.Zero,ne.OneMinusSrc,ne.Zero,ne.One);break;case zo:c(ne.Zero,ne.Src,ne.Zero,ne.Src);break}}if(t!==void 0&&s!==void 0)return{color:t,alpha:s};console.error("THREE.WebGPURenderer: Invalid blending: ",i)}_getBlendFactor(e){let t;switch(e){case vi:t=ne.Zero;break;case um:t=ne.One;break;case dm:t=ne.Src;break;case pm:t=ne.OneMinusSrc;break;case Go:t=ne.SrcAlpha;break;case Vo:t=ne.OneMinusSrcAlpha;break;case gm:t=ne.Dst;break;case ym:t=ne.OneMinusDst;break;case fm:t=ne.DstAlpha;break;case mm:t=ne.OneMinusDstAlpha;break;case xm:t=ne.SrcAlphaSaturated;break;case O_:t=ne.Constant;break;case B_:t=ne.OneMinusConstant;break;default:console.error("THREE.WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const s=e.stencilFunc;switch(s){case f_:t=dt.Never;break;case Ch:t=dt.Always;break;case m_:t=dt.Less;break;case y_:t=dt.LessEqual;break;case g_:t=dt.Equal;break;case b_:t=dt.GreaterEqual;break;case x_:t=dt.Greater;break;case __:t=dt.NotEqual;break;default:console.error("THREE.WebGPURenderer: Invalid stencil function.",s)}return t}_getStencilOperation(e){let t;switch(e){case Ki:t=_i.Keep;break;case o_:t=_i.Zero;break;case l_:t=_i.Replace;break;case p_:t=_i.Invert;break;case c_:t=_i.IncrementClamp;break;case h_:t=_i.DecrementClamp;break;case u_:t=_i.IncrementWrap;break;case d_:t=_i.DecrementWrap;break;default:console.error("THREE.WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case bs:t=$i.Add;break;case cm:t=$i.Subtract;break;case hm:t=$i.ReverseSubtract;break;case $x:t=$i.Min;break;case jx:t=$i.Max;break;default:console.error("THREE.WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,s){const i={},n=this.backend.utils;switch(i.topology=n.getPrimitiveTopology(e,s),t.index!==null&&e.isLine===!0&&e.isLineSegments!==!0&&(i.stripIndexFormat=t.index.array instanceof Uint16Array?dr.Uint16:dr.Uint32),s.side){case Ks:i.frontFace=Uc.CCW,i.cullMode=kc.Back;break;case zt:i.frontFace=Uc.CCW,i.cullMode=kc.Front;break;case Yn:i.frontFace=Uc.CCW,i.cullMode=kc.None;break;default:console.error("THREE.WebGPUPipelineUtils: Unknown material.side value.",s.side);break}return i}_getColorWriteMask(e){return e.colorWrite===!0?_f.All:_f.None}_getDepthCompare(e){let t;if(e.depthTest===!1)t=dt.Always;else{const s=e.depthFunc;switch(s){case _m:t=dt.Never;break;case bm:t=dt.Always;break;case Tm:t=dt.Less;break;case Ho:t=dt.LessEqual;break;case Sm:t=dt.Equal;break;case vm:t=dt.GreaterEqual;break;case wm:t=dt.Greater;break;case Em:t=dt.NotEqual;break;default:console.error("THREE.WebGPUPipelineUtils: Invalid depth function.",s)}}return t}}class FA extends Ay{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 ai(`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.id,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 r=new BigUint64Array(this.resultBuffer.getMappedRange(0,s));let o=0;for(const[,l]of e){const c=r[l],h=r[l+1],u=Number(h-c)/1e6;o+=u}return this.resultBuffer.unmap(),this.lastValue=o,o}catch(e){return console.error("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){console.error("Error waiting for pending resolve:",e)}if(this.resultBuffer&&this.resultBuffer.mapState==="mapped")try{this.resultBuffer.unmap()}catch(e){console.error("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 DA extends Cy{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=e.alpha===void 0?!0:e.alpha,this.parameters.compatibilityMode=e.compatibilityMode===void 0?!1:e.compatibilityMode,this.parameters.requiredLimits=e.requiredLimits===void 0?{}:e.requiredLimits,this.compatibilityMode=this.parameters.compatibilityMode,this.device=null,this.context=null,this.colorBuffer=null,this.defaultRenderPassdescriptor=null,this.utils=new EA(this),this.attributeUtils=new RA(this),this.bindingUtils=new NA(this),this.pipelineUtils=new PA(this),this.textureUtils=new mA(this),this.occludedResolveCache=new Map}async init(e){await super.init(e);const t=this.parameters;let s;if(t.device===void 0){const r={powerPreference:t.powerPreference,featureLevel:t.compatibilityMode?"compatibility":void 0},o=typeof navigator<"u"?await navigator.gpu.requestAdapter(r):null;if(o===null)throw new Error("WebGPUBackend: Unable to create WebGPU adapter.");const l=Object.values(zh),c=[];for(const u of l)o.features.has(u)&&c.push(u);const h={requiredFeatures:c,requiredLimits:t.requiredLimits};s=await o.requestDevice(h)}else s=t.device;s.lost.then(r=>{const o={api:"WebGPU",message:r.message||"Unknown reason",reason:r.reason||null,originalEvent:r};e.onDeviceLost(o)});const i=t.context!==void 0?t.context:e.domElement.getContext("webgpu");this.device=s,this.context=i;const n=t.alpha?"premultiplied":"opaque";this.trackTimestamp=this.trackTimestamp&&this.hasFeature(zh.TimestampQuery),this.context.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:n}),this.updateSize()}get coordinateSystem(){return Fi}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){let e=this.defaultRenderPassdescriptor;if(e===null){const s=this.renderer;e={colorAttachments:[{view:null}]},(this.renderer.depth===!0||this.renderer.stencil===!0)&&(e.depthStencilAttachment={view:this.textureUtils.getDepthBuffer(s.depth,s.stencil).createView()});const i=e.colorAttachments[0];this.renderer.samples>0?i.view=this.colorBuffer.createView():i.resolveTarget=void 0,this.defaultRenderPassdescriptor=e}const t=e.colorAttachments[0];return this.renderer.samples>0?t.resolveTarget=this.context.getCurrentTexture().createView():t.view=this.context.getCurrentTexture().createView(),e}_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;if(n===void 0||i.width!==s.width||i.height!==s.height||i.dimensions!==s.dimensions||i.activeMipmapLevel!==e.activeMipmapLevel||i.activeCubeFace!==e.activeCubeFace||i.samples!==s.samples){n={},i.descriptors=n;const c=()=>{s.removeEventListener("dispose",c),this.delete(s)};s.hasEventListener("dispose",c)===!1&&s.addEventListener("dispose",c)}const r=e.getCacheKey();let o=n[r];if(o===void 0){const c=e.textures,h=[];let u;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:ut.TwoD};if(s.isRenderTarget3D)u=e.activeCubeFace,m.baseArrayLayer=0,m.dimension=ut.ThreeD,m.depthOrArrayLayers=c[p].image.depth;else if(s.isRenderTarget&&c[p].image.depth>1)if(d===!0){const y=e.camera.cameras;for(let g=0;g<y.length;g++){const _={...m,baseArrayLayer:g,arrayLayerCount:1,dimension:ut.TwoD},b=f.texture.createView(_);h.push({view:b,resolveTarget:void 0,depthSlice:void 0})}}else m.dimension=ut.TwoDArray,m.depthOrArrayLayers=c[p].image.depth;if(d!==!0){const y=f.texture.createView(m);let g,_;f.msaaTexture!==void 0?(g=f.msaaTexture.createView(),_=y):(g=y,_=void 0),h.push({view:g,resolveTarget:_,depthSlice:u})}}if(o={textureViews:h},e.depth){const p=this.get(e.depthTexture),f={};e.depthTexture.isArrayTexture&&(f.dimension=ut.TwoD,f.arrayLayerCount=1,f.baseArrayLayer=e.activeCubeFace),o.depthStencilView=p.texture.createView(f)}n[r]=o,i.width=s.width,i.height=s.height,i.samples=s.samples,i.activeMipmapLevel=e.activeMipmapLevel,i.activeCubeFace=e.activeCubeFace,i.dimensions=s.dimensions}const l={colorAttachments:[]};for(let c=0;c<o.textureViews.length;c++){const h=o.textureViews[c];let u={r:0,g:0,b:0,a:1};c===0&&t.clearValue&&(u=t.clearValue),l.colorAttachments.push({view:h.view,depthSlice:h.depthSlice,resolveTarget:h.resolveTarget,loadOp:t.loadOp||Ee.Load,storeOp:t.storeOp||Et.Store,clearValue:u})}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 r;e.textures===null?r=this._getDefaultRenderPassDescriptor():r=this._getRenderPassDescriptor(e,{loadOp:Ee.Load}),this.initTimestampQuery(e,r),r.occlusionQuerySet=n;const o=r.depthStencilAttachment;if(e.textures!==null){const c=r.colorAttachments;for(let h=0;h<c.length;h++){const u=c[h];e.clearColor?(u.clearValue=h===0?e.clearColorValue:{r:0,g:0,b:0,a:1},u.loadOp=Ee.Clear):u.loadOp=Ee.Load,u.storeOp=Et.Store}}else{const c=r.colorAttachments[0];e.clearColor?(c.clearValue=e.clearColorValue,c.loadOp=Ee.Clear):c.loadOp=Ee.Load,c.storeOp=Et.Store}e.depth&&(e.clearDepth?(o.depthClearValue=e.clearDepthValue,o.depthLoadOp=Ee.Clear):o.depthLoadOp=Ee.Load,o.depthStoreOp=Et.Store),e.stencil&&(e.clearStencil?(o.stencilClearValue=e.clearStencilValue,o.stencilLoadOp=Ee.Clear):o.stencilLoadOp=Ee.Load,o.stencilStoreOp=Et.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,r,c):this._updateDepthLayerDescriptors(e,t,c),t.bundleEncoders=[],t.bundleSets=[];for(let h=0;h<c.length;h++){const u=this.pipelineUtils.createBundleEncoder(e,"renderBundleArrayCamera_"+h),d={attributes:{},bindingGroups:[],pipeline:null,index:null};t.bundleEncoders.push(u),t.bundleSets.push(d)}t.currentPass=null}else{const c=l.beginRenderPass(r);if(t.currentPass=c,e.viewport&&this.updateViewport(e),e.scissor){const{x:h,y:u,width:d,height:p}=e.scissorValue;c.setScissorRect(h,u,d,p)}}t.descriptor=r,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 r=this.get(e.depthTexture);r.viewCache||(r.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;r.viewCache[c]||(r.viewCache[c]=r.texture.createView({dimension:ut.TwoD,baseArrayLayer:o,arrayLayerCount:1})),l.depthStencilAttachment={view:r.viewCache[c],depthLoadOp:n.depthLoadOp||Ee.Clear,depthStoreOp:n.depthStoreOp||Et.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 r=n.depthStencilAttachment;e.depth&&(e.clearDepth?(r.depthClearValue=e.clearDepthValue,r.depthLoadOp=Ee.Clear):r.depthLoadOp=Ee.Load),e.stencil&&(e.clearStencil?(r.stencilClearValue=e.clearStencilValue,r.stencilLoadOp=Ee.Clear):r.stencilLoadOp=Ee.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 r=0;r<t.bundleEncoders.length;r++){const o=t.bundleEncoders[r];n.push(o.finish())}for(let r=0;r<t.layerDescriptors.length;r++)if(r<n.length){const o=t.layerDescriptors[r],l=i.beginRenderPass(o);if(e.viewport){const{x:c,y:h,width:u,height:d,minDepth:p,maxDepth:f}=e.viewportValue;l.setViewport(c,h,u,d,p,f)}if(e.scissor){const{x:c,y:h,width:u,height:d}=e.scissorValue;l.setScissorRect(c,h,u,d)}l.executeBundles([n[r]]),l.end()}}else t.currentPass&&t.currentPass.end();if(s>0){const n=s*8;let r=this.occludedResolveCache.get(n);r===void 0&&(r=this.device.createBuffer({size:n,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.occludedResolveCache.set(n,r));const o=this.device.createBuffer({size:n,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});t.encoder.resolveQuerySet(t.occlusionQuerySet,0,s,r,0),t.encoder.copyBufferToBuffer(r,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 r=0;r<n.length;r++){const o=n[r];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 r=s.getMappedRange(),o=new BigUint64Array(r);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:r,minDepth:o,maxDepth:l}=e.viewportValue;t.setViewport(s,i,n,r,o,l)}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,r=this.renderer;let o=[],l,c,h,u;if(e){const f=this.getClearColor();c={r:f.r,g:f.g,b:f.b,a:f.a}}if(i===null){h=r.depth,u=r.stencil;const f=this._getDefaultRenderPassDescriptor();if(e){o=f.colorAttachments;const m=o[0];m.clearValue=c,m.loadOp=Ee.Clear,m.storeOp=Et.Store}(h||u)&&(l=f.depthStencilAttachment)}else{h=i.depth,u=i.stencil;const f={loadOp:e?Ee.Clear:Ee.Load,clearValue:e?c:void 0};h&&(f.depthLoadOp=t?Ee.Clear:Ee.Load,f.depthClearValue=t?r.getClearDepth():void 0,f.depthStoreOp=Et.Store),u&&(f.stencilLoadOp=s?Ee.Clear:Ee.Load,f.stencilClearValue=s?r.getClearStencil():void 0,f.stencilStoreOp=Et.Store);const m=this._getRenderPassDescriptor(i,f);o=m.colorAttachments,l=m.depthStencilAttachment}h&&l&&l.depthLoadOp===void 0&&(t?(l.depthLoadOp=Ee.Clear,l.depthClearValue=r.getClearDepth(),l.depthStoreOp=Et.Store):(l.depthLoadOp=Ee.Load,l.depthStoreOp=Et.Store)),u&&l&&l.stencilLoadOp===void 0&&(s?(l.stencilLoadOp=Ee.Clear,l.stencilClearValue=r.getClearStencil(),l.stencilStoreOp=Et.Store):(l.stencilLoadOp=Ee.Load,l.stencilStoreOp=Et.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(e,s),t.cmdEncoderGPU=this.device.createCommandEncoder({label:"computeGroup_"+e.id}),t.passEncoderGPU=t.cmdEncoderGPU.beginComputePass(s)}compute(e,t,s,i){const{passEncoderGPU:n}=this.get(e),r=this.get(i).pipeline;this.pipelineUtils.setPipeline(n,r);for(let h=0,u=s.length;h<u;h++){const d=s[h],p=this.get(d);n.setBindGroup(h,p.group)}const o=this.device.limits.maxComputeWorkgroupsPerDimension,l=this.get(t);l.dispatchSize===void 0&&(l.dispatchSize={x:0,y:1,z:1});const{dispatchSize:c}=l;t.dispatchCount>o?(c.x=Math.min(t.dispatchCount,o),c.y=Math.ceil(t.dispatchCount/o)):c.x=t.dispatchCount,n.dispatchWorkgroups(c.x,c.y,c.z)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.device.queue.submit([t.cmdEncoderGPU.finish()])}async waitForGPU(){await this.device.queue.onSubmittedWorkDone()}draw(e,t){const{object:s,material:i,context:n,pipeline:r}=e,o=e.getBindings(),l=this.get(n),c=this.get(r).pipeline,h=e.getIndex(),u=h!==null,d=e.getDrawParameters();if(d===null)return;const p=(m,y)=>{this.pipelineUtils.setPipeline(m,c),y.pipeline=c;const g=y.bindingGroups;for(let b=0,S=o.length;b<S;b++){const T=o[b],M=this.get(T);g[T.index]!==T.id&&(m.setBindGroup(T.index,M.group),g[T.index]=T.id)}if(u===!0&&y.index!==h){const b=this.get(h).buffer,S=h.array instanceof Uint16Array?dr.Uint16:dr.Uint32;m.setIndexBuffer(b,S),y.index=h}const _=e.getVertexBuffers();for(let b=0,S=_.length;b<S;b++){const T=_[b];if(y.attributes[b]!==T){const M=this.get(T).buffer;m.setVertexBuffer(b,M),y.attributes[b]=T}}n.stencil===!0&&i.stencilWrite===!0&&l.currentStencilRef!==i.stencilRef&&(m.setStencilReference(i.stencilRef),l.currentStencilRef=i.stencilRef)},f=(m,y)=>{if(p(m,y),s.isBatchedMesh===!0){const g=s._multiDrawStarts,_=s._multiDrawCounts,b=s._multiDrawCount,S=s._multiDrawInstances;S!==null&&ai("THREE.WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.");for(let T=0;T<b;T++){const M=S?S[T]:1,w=M>1?0:T;u===!0?m.drawIndexed(_[T],M,g[T]/h.array.BYTES_PER_ELEMENT,0,w):m.draw(_[T],M,g[T],w),t.update(s,_[T],M)}}else if(u===!0){const{vertexCount:g,instanceCount:_,firstVertex:b}=d,S=e.getIndirect();if(S!==null){const T=this.get(S).buffer;m.drawIndexedIndirect(T,0)}else m.drawIndexed(g,_,b,0,0);t.update(s,g,_)}else{const{vertexCount:g,instanceCount:_,firstVertex:b}=d,S=e.getIndirect();if(S!==null){const T=this.get(S).buffer;m.drawIndirect(T,0)}else m.draw(g,_,b,0);t.update(s,g,_)}};if(e.camera.isArrayCamera&&e.camera.cameras.length>0){const m=this.get(e.camera),y=e.camera.cameras,g=e.getBindingGroup("cameraIndex");if(m.indexesGPU===void 0||m.indexesGPU.length!==y.length){const b=this.get(g),S=[],T=new Uint32Array([0,0,0,0]);for(let M=0,w=y.length;M<w;M++){T[0]=M;const R=this.bindingUtils.createBindGroupIndex(T,b.layout);S.push(R)}m.indexesGPU=S}const _=this.renderer.getPixelRatio();for(let b=0,S=y.length;b<S;b++){const T=y[b];if(s.layers.test(T.layers)){const M=T.viewport;let w=l.currentPass,R=l.currentSets;if(l.bundleEncoders){const P=l.bundleEncoders[b],z=l.bundleSets[b];w=P,R=z}M&&w.setViewport(Math.floor(M.x*_),Math.floor(M.y*_),Math.floor(M.width*_),Math.floor(M.height*_),n.viewportValue.minDepth,n.viewportValue.maxDepth),g&&m.indexesGPU&&(w.setBindGroup(g.index,m.indexesGPU[b]),R.bindingGroups[g.index]=g.id),f(w,R)}}}else if(l.currentPass){if(l.occlusionQuerySet!==void 0){const m=l.lastOcclusionObject;m!==s&&(m!==null&&m.occlusionTest===!0&&(l.currentPass.endOcclusionQuery(),l.occlusionQueryIndex++),s.occlusionTest===!0&&(l.currentPass.beginOcclusionQuery(l.occlusionQueryIndex),l.occlusionQueryObjects[l.occlusionQueryIndex]=s),l.lastOcclusionObject=s)}f(l.currentPass,l.currentSets)}}needsRenderUpdate(e){const t=this.get(e),{object:s,material:i}=e,n=this.utils,r=n.getSampleCountRenderContext(e.context),o=n.getCurrentColorSpace(e.context),l=n.getCurrentColorFormat(e.context),c=n.getCurrentDepthStencilFormat(e.context),h=n.getPrimitiveTopology(s,i);let u=!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!==r||t.colorSpace!==o||t.colorFormat!==l||t.depthStencilFormat!==c||t.primitiveTopology!==h||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=r,t.colorSpace=o,t.colorFormat=l,t.depthStencilFormat=c,t.primitiveTopology=h,t.clippingContextCacheKey=e.clippingContextCacheKey,u=!0),u}getRenderCacheKey(e){const{object:t,material:s}=e,i=this.utils,n=e.context;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,i.getSampleCountRenderContext(n),i.getCurrentColorSpace(n),i.getCurrentColorFormat(n),i.getCurrentDepthStencilFormat(n),i.getPrimitiveTopology(t,s),e.getGeometryCacheKey(),e.clippingContextCacheKey].join()}createSampler(e){this.textureUtils.createSampler(e)}destroySampler(e){this.textureUtils.destroySampler(e)}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){this.textureUtils.destroyTexture(e)}async copyTextureToBuffer(e,t,s,i,n,r){return this.textureUtils.copyTextureToBuffer(e,t,s,i,n,r)}initTimestampQuery(e,t){if(!this.trackTimestamp)return;const s=e.isComputeNode?"compute":"render";this.timestampQueryPool[s]||(this.timestampQueryPool[s]=new FA(this.device,s,2048));const i=this.timestampQueryPool[s],n=i.allocateQueriesForContext(e);t.timestampWrites={querySet:i.querySet,beginningOfPassWriteIndex:n,endOfPassWriteIndex:n+1}}createNodeBuilder(e,t){return new wA(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)}createIndexAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.INDEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}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.colorBuffer=this.textureUtils.getColorBuffer(),this.defaultRenderPassdescriptor=null}getMaxAnisotropy(){return 16}hasFeature(e){return this.device.features.has(e)}copyTextureToTexture(e,t,s=null,i=null,n=0,r=0){let o=0,l=0,c=0,h=0,u=0,d=0,p=e.image.width,f=e.image.height,m=1;s!==null&&(s.isBox3===!0?(h=s.min.x,u=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):(h=s.min.x,u=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 y=this.device.createCommandEncoder({label:"copyTextureToTexture_"+e.id+"_"+t.id}),g=this.get(e).texture,_=this.get(t).texture;y.copyTextureToTexture({texture:g,mipLevel:n,origin:{x:h,y:u,z:d}},{texture:_,mipLevel:r,origin:{x:o,y:l,z:c}},[p,f,m]),this.device.queue.submit([y.finish()]),r===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 r=this.get(e).texture;if(n.format!==r.format){console.error("WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.",n.format,r.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:r},[s.z,s.w]),i.currentPass){const{descriptor:l}=i;for(let c=0;c<l.colorAttachments.length;c++)l.colorAttachments[c].loadOp=Ee.Load;if(t.depth&&(l.depthStencilAttachment.depthLoadOp=Ee.Load),t.stencil&&(l.depthStencilAttachment.stencilLoadOp=Ee.Load),i.currentPass=o.beginRenderPass(l),i.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.viewport&&this.updateViewport(t),t.scissor){const{x:c,y:h,width:u,height:d}=t.scissorValue;i.currentPass.setScissorRect(c,h,u,d)}}else this.device.queue.submit([o.finish()]);e.generateMipmaps&&this.textureUtils.generateMipmaps(e)}}class OA extends Gt{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new Se(16777215),this.specular=new Se(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Se(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Pi,this.normalScale=new ce(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new hs,this.combine=al,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}const BA=new OA;class IA extends tt{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(BA),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new zu(t):null}setupLightingModel(){return new yy}setupVariants(){const e=(this.shininessNode?B(this.shininessNode):Nv).max(1e-4);Fh.assign(e);const t=this.specularNode||Fv;qt.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}class Ny extends Gt{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new Se(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 Se(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Pi,this.normalScale=new ce(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 hs,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}}const LA=new Ny;class Py extends tt{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(LA),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return t===null&&e.environmentNode&&(t=e.environmentNode),t?new QM(t):null}setupLightingModel(){return new _y}setupSpecular(){const e=ze(I(.04),Te.rgb,Ko);qt.assign(e),el.assign(1)}setupVariants(){const e=this.metalnessNode?B(this.metalnessNode):Bv;Ko.assign(e);let t=this.roughnessNode?B(this.roughnessNode):Ov;t=oy({roughness:t}),Xs.assign(t),this.setupSpecular(),Te.assign(re(Te.rgb.mul(e.oneMinus()),Te.a))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}class UA extends Ny{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 ce(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return de(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 Se(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 Se(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new Se(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}}const kA=new UA;class zA extends Py{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(kA),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?B(this.iorNode):Xv;Ro.assign(e),qt.assign(ze(cr(gg(Ro.sub(1).div(Ro.add(1))).mul(Dv),I(1)).mul(dp),Te.rgb,Ko)),el.assign(ze(dp,1,Ko))}setupLightingModel(){return new _y(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const t=this.clearcoatNode?B(this.clearcoatNode):Lv,s=this.clearcoatRoughnessNode?B(this.clearcoatRoughnessNode):Uv;Nh.assign(t),Jo.assign(oy({roughness:s}))}if(this.useSheen){const t=this.sheenNode?I(this.sheenNode):Gv,s=this.sheenRoughnessNode?B(this.sheenRoughnessNode):Vv;$n.assign(t),gu.assign(s)}if(this.useIridescence){const t=this.iridescenceNode?B(this.iridescenceNode):Wv,s=this.iridescenceIORNode?B(this.iridescenceIORNode):$v,i=this.iridescenceThicknessNode?B(this.iridescenceThicknessNode):jv;yu.assign(t),tg.assign(s),sg.assign(i)}if(this.useAnisotropy){const t=(this.anisotropyNode?H(this.anisotropyNode):Hv).toVar();Ji.assign(t.length()),Xe(Ji.equal(0),()=>{t.assign(H(1,0))}).Else(()=>{t.divAssign(H(Ji)),Ji.assign(Ji.saturate())}),Ph.assign(Ji.pow2().mix(Xs.pow2(),1)),Ao.assign(Qr[0].mul(t.x).add(Qr[1].mul(t.y))),er.assign(Qr[1].mul(t.x).sub(Qr[0].mul(t.y)))}if(this.useTransmission){const t=this.transmissionNode?B(this.transmissionNode):qv,s=this.thicknessNode?B(this.thicknessNode):Yv,i=this.attenuationDistanceNode?B(this.attenuationDistanceNode):Zv,n=this.attenuationColorNode?I(this.attenuationColorNode):Qv;if(Dh.assign(t),ig.assign(s),ng.assign(i),rg.assign(n),this.useDispersion){const r=this.dispersionNode?B(this.dispersionNode):iw;ag.assign(r)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?I(this.clearcoatNormalNode):kv}setup(e){e.context.setupClearcoatNormal=()=>this.setupClearcoatNormal(e),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.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 GA=L(({normal:a,lightDirection:e,builder:t})=>{const s=a.dot(e),i=H(s.mul(.5).add(.5),0);if(t.material.gradientMap){const n=Ci("gradientMap","texture").context({getUV:()=>i});return I(n.r)}else{const n=i.fwidth().mul(.5);return ze(I(.7),I(1),Di(B(.7).sub(n.x),B(.7).add(n.x),i.x))}});class VA extends vl{direct({lightDirection:e,lightColor:t,reflectedLight:s},i){const n=GA({normal:Pg,lightDirection:e,builder:i}).mul(t);s.directDiffuse.addAssign(n.mul(ur({diffuseColor:Te.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:s,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(s.mul(ur({diffuseColor:Te}))),i.indirectDiffuse.mulAssign(t)}}class HA extends Gt{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new Se(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Se(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Pi,this.normalScale=new ce(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}}const WA=new HA;class $A extends tt{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(WA),this.setValues(e)}setupLightingModel(){return new VA}}class jA extends gr{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=B(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}const qA=new Ai;class YA extends tt{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(qA),this.setValues(e)}setupNormal(){return zs}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new zu(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new jA($g)),t}setupOutgoingLight(){return Te.rgb}setupLightingModel(){return new gy}}class XA extends Gt{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new Se(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Se(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Pi,this.normalScale=new ce(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new hs,this.combine=al,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}const ZA=new XA;class QA extends tt{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(ZA),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new zu(t):null}setupLightingModel(){return new yy(!1)}}class KA extends Gt{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Pi,this.normalScale=new ce(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}}const JA=new KA;class eR extends tt{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(JA),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?B(this.opacityNode):Wg;Te.assign(wu(re(ZS(Je),e),Yt))}}class tR extends Gt{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new Se(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Pi,this.normalScale=new ce(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:""},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.flatShading=e.flatShading,this.fog=e.fog,this}}const sR=new tR;class iR extends tt{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(sR),this.setValues(e)}setupVariants(e){const t=qS;let s;e.material.matcap?s=Ci("matcap","texture").context({getUV:()=>t}):s=I(ze(.2,.8,t.y)),Te.rgb.mulAssign(s.rgb)}}class Fy extends Gt{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new Se(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}}const nR=new Fy;class rR extends tt{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(nR),this.setValues(e)}}class aR extends Fy{constructor(e){super(),this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}}const oR=new aR;class lR extends tt{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(oR),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?B(this.offsetNode):tw,t=this.dashScaleNode?B(this.dashScaleNode):Kv,s=this.dashSizeNode?B(this.dashSizeNode):Jv,i=this.gapSizeNode?B(this.gapSizeNode):ew;jl.assign(s),tp.assign(i);const n=ws(Oi("lineDistance").mul(t));(e?n.add(e):n).mod(jl.add(tp)).greaterThan(jl).discard()}}class cR extends Gt{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new Se(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 hR=new cR;class Dy extends tt{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(hR),this.setValues(e)}setupPositionView(e){const{object:t,camera:s}=e,i=this.sizeAttenuation,{positionNode:n,rotationNode:r,scaleNode:o}=this,l=ml.mul(I(n||0));let c=H(hn[0].xyz.length(),hn[1].xyz.length());if(o!==null&&(c=c.mul(H(o))),i===!1)if(s.isPerspectiveCamera)c=c.mul(l.z.negate());else{const p=B(2).div(Au.element(1).element(1));c=c.mul(p.mul(2))}let h=gl.xy;if(t.center&&t.center.isVector2===!0){const p=aS("center","vec2",t);h=h.sub(p.sub(.5))}h=h.mul(c);const u=B(r||zv),d=Dg(h,u);return re(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)}}class uR extends Gt{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new Se(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.size=e.size,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}const dR=new uR;class pR extends Dy{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(dR),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return ml.mul(I(e||_t)).xyz}setupVertex(e){const t=super.setupVertex(e);if(e.material.isNodeMaterial!==!0)return t;const{rotationNode:s,scaleNode:i,sizeNode:n}=this,r=gl.xy.toVar(),o=la.z.div(la.w);if(s&&s.isNode){const c=B(s);r.assign(Dg(r,c))}let l=n!==null?H(n):sw;return this.sizeAttenuation===!0&&(l=l.mul(l.div(et.z.negate()))),i&&i.isNode&&(l=l.mul(H(i))),r.mulAssign(l.mul(2)),r.assign(r.div(la.z)),r.y.assign(r.y.mul(o)),r.assign(r.mul(t.w)),t.addAssign(re(r,0,0)),t}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}}class fR extends vl{constructor(){super(),this.shadowNode=B(1).toVar("shadowMask")}direct({lightNode:e}){e.shadowNode!==null&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){Te.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(Te.rgb)}}class mR extends Gt{constructor(e){super(),this.isShadowMaterial=!0,this.type="ShadowMaterial",this.color=new Se(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}}const gR=new mR;class yR extends tt{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(gR),this.setValues(e)}setupLightingModel(){return new fR}}class fn extends ct{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new Se(e),this.intensity=t}dispose(){}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){const t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,this.groundColor!==void 0&&(t.object.groundColor=this.groundColor.getHex()),this.distance!==void 0&&(t.object.distance=this.distance),this.angle!==void 0&&(t.object.angle=this.angle),this.decay!==void 0&&(t.object.decay=this.decay),this.penumbra!==void 0&&(t.object.penumbra=this.penumbra),this.shadow!==void 0&&(t.object.shadow=this.shadow.toJSON()),this.target!==void 0&&(t.object.target=this.target.uuid),t}}const Hc=new Be,Mf=new N,Cf=new N;class qu{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new ce(512,512),this.mapType=Rt,this.map=null,this.mapPass=null,this.matrix=new Be,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new Wu,this._frameExtents=new ce(1,1),this._viewportCount=1,this._viewports=[new me(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const t=this.camera,s=this.matrix;Mf.setFromMatrixPosition(e.matrixWorld),t.position.copy(Mf),Cf.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(Cf),t.updateMatrixWorld(),Hc.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Hc),s.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),s.multiply(Hc)}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}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 Af=new Be,kr=new N,Wc=new N;class xR extends qu{constructor(){super(new Xt(90,1,.5,500)),this.isPointLightShadow=!0,this._frameExtents=new ce(4,2),this._viewportCount=6,this._viewports=[new me(2,1,1,1),new me(0,1,1,1),new me(3,1,1,1),new me(1,1,1,1),new me(3,0,1,1),new me(1,0,1,1)],this._cubeDirections=[new N(1,0,0),new N(-1,0,0),new N(0,0,1),new N(0,0,-1),new N(0,1,0),new N(0,-1,0)],this._cubeUps=[new N(0,1,0),new N(0,1,0),new N(0,1,0),new N(0,1,0),new N(0,0,1),new N(0,0,-1)]}updateMatrices(e,t=0){const s=this.camera,i=this.matrix,n=e.distance||s.far;n!==s.far&&(s.far=n,s.updateProjectionMatrix()),kr.setFromMatrixPosition(e.matrixWorld),s.position.copy(kr),Wc.copy(s.position),Wc.add(this._cubeDirections[t]),s.up.copy(this._cubeUps[t]),s.lookAt(Wc),s.updateMatrixWorld(),i.makeTranslation(-kr.x,-kr.y,-kr.z),Af.multiplyMatrices(s.projectionMatrix,s.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Af)}}class _R extends fn{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 xR}get power(){return this.intensity*4*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}dispose(){this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.decay=e.decay,this.shadow=e.shadow.clone(),this}}class bR extends qu{constructor(){super(new Du(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class TR extends fn{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(ct.DEFAULT_UP),this.updateMatrix(),this.target=new ct,this.shadow=new bR}dispose(){this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}}class SR extends fn{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 vR extends qu{constructor(){super(new Xt(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(e){const t=this.camera,s=nr*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 Yu extends fn{constructor(e,t,s=0,i=Math.PI/3,n=0,r=2){super(e,t),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(ct.DEFAULT_UP),this.updateMatrix(),this.target=new ct,this.distance=s,this.angle=i,this.penumbra=n,this.decay=r,this.map=null,this.shadow=new vR}get power(){return this.intensity*Math.PI}set power(e){this.intensity=e/Math.PI}dispose(){this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.angle=e.angle,this.penumbra=e.penumbra,this.decay=e.decay,this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}}class wR extends fn{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}}class ER extends fn{constructor(e,t,s){super(e,s),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(ct.DEFAULT_UP),this.updateMatrix(),this.groundColor=new Se(t)}copy(e,t){return super.copy(e,t),this.groundColor.copy(e.groundColor),this}}class MR{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let e=0;e<9;e++)this.coefficients.push(new N)}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,r=this.coefficients;return t.copy(r[0]).multiplyScalar(.282095),t.addScaledVector(r[1],.488603*i),t.addScaledVector(r[2],.488603*n),t.addScaledVector(r[3],.488603*s),t.addScaledVector(r[4],1.092548*(s*i)),t.addScaledVector(r[5],1.092548*(i*n)),t.addScaledVector(r[6],.315392*(3*n*n-1)),t.addScaledVector(r[7],1.092548*(s*n)),t.addScaledVector(r[8],.546274*(s*s-i*i)),t}getIrradianceAt(e,t){const s=e.x,i=e.y,n=e.z,r=this.coefficients;return t.copy(r[0]).multiplyScalar(.886227),t.addScaledVector(r[1],2*.511664*i),t.addScaledVector(r[2],2*.511664*n),t.addScaledVector(r[3],2*.511664*s),t.addScaledVector(r[4],2*.429043*s*i),t.addScaledVector(r[5],2*.429043*i*n),t.addScaledVector(r[6],.743125*n*n-.247708),t.addScaledVector(r[7],2*.429043*s*n),t.addScaledVector(r[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 CR extends fn{constructor(e=new MR,t=1){super(void 0,t),this.isLightProbe=!0,this.sh=e}copy(e){return super.copy(e),this.sh.copy(e.sh),this}fromJSON(e){return this.intensity=e.intensity,this.sh.fromArray(e.sh),this}toJSON(e){const t=super.toJSON(e);return t.object.sh=this.sh.toArray(),t}}class AR extends Yu{constructor(e,t,s,i,n,r){super(e,t,s,i,n,r),this.iesMap=null}copy(e,t){return super.copy(e,t),this.iesMap=e.iesMap,this}}class RR extends Yu{constructor(e,t,s,i,n,r){super(e,t,s,i,n,r),this.aspect=null}copy(e,t){return super.copy(e,t),this.aspect=e.aspect,this}}class NR extends by{constructor(){super(),this.addMaterial(IA,"MeshPhongMaterial"),this.addMaterial(Py,"MeshStandardMaterial"),this.addMaterial(zA,"MeshPhysicalMaterial"),this.addMaterial($A,"MeshToonMaterial"),this.addMaterial(YA,"MeshBasicMaterial"),this.addMaterial(QA,"MeshLambertMaterial"),this.addMaterial(eR,"MeshNormalMaterial"),this.addMaterial(iR,"MeshMatcapMaterial"),this.addMaterial(rR,"LineBasicMaterial"),this.addMaterial(lR,"LineDashedMaterial"),this.addMaterial(pR,"PointsMaterial"),this.addMaterial(Dy,"SpriteMaterial"),this.addMaterial(yR,"ShadowMaterial"),this.addLight(BE,_R),this.addLight(HM,TR),this.addLight(WM,SR),this.addLight(ku,Yu),this.addLight(YM,wR),this.addLight(XM,ER),this.addLight(ZM,CR),this.addLight($M,AR),this.addLight(qM,RR),this.addToneMapping(Hw,Xx),this.addToneMapping(Ww,Zx),this.addToneMapping($w,Qx),this.addToneMapping(qw,Kx),this.addToneMapping(Qw,Jx),this.addToneMapping(Kw,e_)}}class $c extends LC{constructor(e={}){let t;e.forceWebGL?t=xf:(t=DA,e.getFallback=()=>(console.warn("THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new xf(e)));const s=new t(e);super(s,e),this.library=new NR,this.isWebGPURenderer=!0,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}class PR extends x.Line{constructor(e,t){const s=[1,1,0,-1,1,0,-1,-1,0,1,-1,0,1,1,0],i=new x.BufferGeometry;i.setAttribute("position",new x.Float32BufferAttribute(s,3)),i.computeBoundingSphere();const n=new x.LineBasicMaterial({fog:!1});super(i,n),this.light=e,this.color=t,this.type="RectAreaLightHelper";const r=[1,1,0,-1,1,0,-1,-1,0,1,1,0,-1,-1,0,1,-1,0],o=new x.BufferGeometry;o.setAttribute("position",new x.Float32BufferAttribute(r,3)),o.computeBoundingSphere(),this.add(new x.Mesh(o,new x.MeshBasicMaterial({side:x.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 Rf={type:"change"},Xu={type:"start"},Oy={type:"end"},fo=new x.Ray,Nf=new x.Plane,FR=Math.cos(70*x.MathUtils.DEG2RAD),at=new x.Vector3,Bt=2*Math.PI,Pe={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},jc=1e-6;class DR extends x.Controls{constructor(e,t=null){super(e,t),this.state=Pe.NONE,this.target=new x.Vector3,this.cursor=new x.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:x.MOUSE.ROTATE,MIDDLE:x.MOUSE.DOLLY,RIGHT:x.MOUSE.PAN},this.touches={ONE:x.TOUCH.ROTATE,TWO:x.TOUCH.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this._lastPosition=new x.Vector3,this._lastQuaternion=new x.Quaternion,this._lastTargetPosition=new x.Vector3,this._quat=new x.Quaternion().setFromUnitVectors(e.up,new x.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new x.Spherical,this._sphericalDelta=new x.Spherical,this._scale=1,this._panOffset=new x.Vector3,this._rotateStart=new x.Vector2,this._rotateEnd=new x.Vector2,this._rotateDelta=new x.Vector2,this._panStart=new x.Vector2,this._panEnd=new x.Vector2,this._panDelta=new x.Vector2,this._dollyStart=new x.Vector2,this._dollyEnd=new x.Vector2,this._dollyDelta=new x.Vector2,this._dollyDirection=new x.Vector3,this._mouse=new x.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=BR.bind(this),this._onPointerDown=OR.bind(this),this._onPointerUp=IR.bind(this),this._onContextMenu=HR.bind(this),this._onMouseWheel=kR.bind(this),this._onKeyDown=zR.bind(this),this._onTouchStart=GR.bind(this),this._onTouchMove=VR.bind(this),this._onMouseDown=LR.bind(this),this._onMouseMove=UR.bind(this),this._interceptControlDown=WR.bind(this),this._interceptControlUp=$R.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}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.removeEventListener("pointermove",this._onPointerMove),this.domElement.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(Rf),this.update(),this.state=Pe.NONE}update(e=null){const t=this.object.position;at.copy(t).sub(this.target),at.applyQuaternion(this._quat),this._spherical.setFromVector3(at),this.autoRotate&&this.state===Pe.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+=Bt:s>Math.PI&&(s-=Bt),i<-Math.PI?i+=Bt:i>Math.PI&&(i-=Bt),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 r=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),n=r!=this._spherical.radius}if(at.setFromSpherical(this._spherical),at.applyQuaternion(this._quatInverse),t.copy(this.target).add(at),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 r=null;if(this.object.isPerspectiveCamera){const o=at.length();r=this._clampDistance(o*this._scale);const l=o-r;this.object.position.addScaledVector(this._dollyDirection,l),this.object.updateMatrixWorld(),n=!!l}else if(this.object.isOrthographicCamera){const o=new x.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 x.Vector3(this._mouse.x,this._mouse.y,0);c.unproject(this.object),this.object.position.sub(c).add(o),this.object.updateMatrixWorld(),r=at.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;r!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(r).add(this.object.position):(fo.origin.copy(this.object.position),fo.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(fo.direction))<FR?this.object.lookAt(this.target):(Nf.setFromNormalAndCoplanarPoint(this.object.up,this.target),fo.intersectPlane(Nf,this.target))))}else if(this.object.isOrthographicCamera){const r=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),r!==this.object.zoom&&(this.object.updateProjectionMatrix(),n=!0)}return this._scale=1,this._performCursorZoom=!1,n||this._lastPosition.distanceToSquared(this.object.position)>jc||8*(1-this._lastQuaternion.dot(this.object.quaternion))>jc||this._lastTargetPosition.distanceToSquared(this.target)>jc?(this.dispatchEvent(Rf),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?Bt/60*this.autoRotateSpeed*e:Bt/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){at.setFromMatrixColumn(t,0),at.multiplyScalar(-e),this._panOffset.add(at)}_panUp(e,t){this.screenSpacePanning===!0?at.setFromMatrixColumn(t,1):(at.setFromMatrixColumn(t,0),at.crossVectors(this.object.up,at)),at.multiplyScalar(e),this._panOffset.add(at)}_pan(e,t){const s=this.domElement;if(this.object.isPerspectiveCamera){const i=this.object.position;at.copy(i).sub(this.target);let n=at.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,r=s.width,o=s.height;this._mouse.x=i/r*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(Bt*this._rotateDelta.x/t.clientHeight),this._rotateUp(Bt*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(Bt*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(-Bt*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(Bt*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(-Bt*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(Bt*this._rotateDelta.x/t.clientHeight),this._rotateUp(Bt*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 r=(e.pageX+t.x)*.5,o=(e.pageY+t.y)*.5;this._updateZoomParameters(r,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 x.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 OR(a){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(a.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(a)&&(this._addPointer(a),a.pointerType==="touch"?this._onTouchStart(a):this._onMouseDown(a)))}function BR(a){this.enabled!==!1&&(a.pointerType==="touch"?this._onTouchMove(a):this._onMouseMove(a))}function IR(a){switch(this._removePointer(a),this._pointers.length){case 0:this.domElement.releasePointerCapture(a.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(Oy),this.state=Pe.NONE;break;case 1:const e=this._pointers[0],t=this._pointerPositions[e];this._onTouchStart({pointerId:e,pageX:t.x,pageY:t.y});break}}function LR(a){let e;switch(a.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 x.MOUSE.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(a),this.state=Pe.DOLLY;break;case x.MOUSE.ROTATE:if(a.ctrlKey||a.metaKey||a.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(a),this.state=Pe.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(a),this.state=Pe.ROTATE}break;case x.MOUSE.PAN:if(a.ctrlKey||a.metaKey||a.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(a),this.state=Pe.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(a),this.state=Pe.PAN}break;default:this.state=Pe.NONE}this.state!==Pe.NONE&&this.dispatchEvent(Xu)}function UR(a){switch(this.state){case Pe.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(a);break;case Pe.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(a);break;case Pe.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(a);break}}function kR(a){this.enabled===!1||this.enableZoom===!1||this.state!==Pe.NONE||(a.preventDefault(),this.dispatchEvent(Xu),this._handleMouseWheel(this._customWheelEvent(a)),this.dispatchEvent(Oy))}function zR(a){this.enabled!==!1&&this._handleKeyDown(a)}function GR(a){switch(this._trackPointer(a),this._pointers.length){case 1:switch(this.touches.ONE){case x.TOUCH.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(a),this.state=Pe.TOUCH_ROTATE;break;case x.TOUCH.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(a),this.state=Pe.TOUCH_PAN;break;default:this.state=Pe.NONE}break;case 2:switch(this.touches.TWO){case x.TOUCH.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(a),this.state=Pe.TOUCH_DOLLY_PAN;break;case x.TOUCH.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(a),this.state=Pe.TOUCH_DOLLY_ROTATE;break;default:this.state=Pe.NONE}break;default:this.state=Pe.NONE}this.state!==Pe.NONE&&this.dispatchEvent(Xu)}function VR(a){switch(this._trackPointer(a),this.state){case Pe.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(a),this.update();break;case Pe.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(a),this.update();break;case Pe.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(a),this.update();break;case Pe.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(a),this.update();break;default:this.state=Pe.NONE}}function HR(a){this.enabled!==!1&&a.preventDefault()}function WR(a){a.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function $R(a){a.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}/*!
|
48
481
|
* camera-controls
|
49
482
|
* https://github.com/yomotsu/camera-controls
|
50
483
|
* (c) 2017 @yomotsu
|
51
484
|
* Released under the MIT License.
|
52
|
-
*/const $={LEFT:1,RIGHT:2,MIDDLE:4},v=Object.freeze({NONE:0,ROTATE:1,TRUCK:2,OFFSET:4,DOLLY:8,ZOOM:16,TOUCH_ROTATE:32,TOUCH_TRUCK:64,TOUCH_OFFSET:128,TOUCH_DOLLY:256,TOUCH_ZOOM:512,TOUCH_DOLLY_TRUCK:1024,TOUCH_DOLLY_OFFSET:2048,TOUCH_DOLLY_ROTATE:4096,TOUCH_ZOOM_TRUCK:8192,TOUCH_ZOOM_OFFSET:16384,TOUCH_ZOOM_ROTATE:32768}),Qe={NONE:0,IN:1,OUT:-1};function je(i){return i.isPerspectiveCamera}function ke(i){return i.isOrthographicCamera}const Ke=Math.PI*2,Ki=Math.PI/2,Ms=1e-5,ot=Math.PI/180;function Ee(i,e,t){return Math.max(e,Math.min(t,i))}function q(i,e=Ms){return Math.abs(i)<e}function H(i,e,t=Ms){return q(i-e,t)}function $i(i,e){return Math.round(i/e)*e}function lt(i){return isFinite(i)?i:i<0?-Number.MAX_VALUE:Number.MAX_VALUE}function ct(i){return Math.abs(i)<Number.MAX_VALUE?i:i*(1/0)}function Mt(i,e,t,s,n=1/0,r){s=Math.max(1e-4,s);const a=2/s,l=a*r,c=1/(1+l+.48*l*l+.235*l*l*l);let h=i-e;const u=e,f=n*s;h=Ee(h,-f,f),e=i-h;const m=(t.value+a*h)*r;t.value=(t.value-a*m)*c;let g=e+(h+m)*c;return u-i>0==g>u&&(g=u,t.value=(g-u)/r),g}function Ji(i,e,t,s,n=1/0,r,a){s=Math.max(1e-4,s);const l=2/s,c=l*r,h=1/(1+c+.48*c*c+.235*c*c*c);let u=e.x,f=e.y,m=e.z,g=i.x-u,E=i.y-f,y=i.z-m;const O=u,_=f,b=m,S=n*s,w=S*S,x=g*g+E*E+y*y;if(x>w){const X=Math.sqrt(x);g=g/X*S,E=E/X*S,y=y/X*S}u=i.x-g,f=i.y-E,m=i.z-y;const M=(t.x+l*g)*r,D=(t.y+l*E)*r,k=(t.z+l*y)*r;t.x=(t.x-l*M)*h,t.y=(t.y-l*D)*h,t.z=(t.z-l*k)*h,a.x=u+(g+M)*h,a.y=f+(E+D)*h,a.z=m+(y+k)*h;const R=O-i.x,V=_-i.y,ge=b-i.z,ue=a.x-O,se=a.y-_,Q=a.z-b;return R*ue+V*se+ge*Q>0&&(a.x=O,a.y=_,a.z=b,t.x=(a.x-O)/r,t.y=(a.y-_)/r,t.z=(a.z-b)/r),a}function ti(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 ii(i,e){return ke(i)?(console.warn(`${e} is not supported in OrthographicCamera`),!0):!1}class La{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 r=n.indexOf(t);r!==-1&&n.splice(r,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 r=0,a=n.length;r<a;r++)n[r].call(this,e)}}}var si;const ka="2.9.0",At=1/8,Ua=/Mac/.test((si=globalThis?.navigator)===null||si===void 0?void 0:si.platform);let I,es,Pt,ni,me,U,F,$e,ht,Se,we,Ne,ts,is,ve,dt,Je,ss,ai,ns,ri,oi,Rt;class Oe extends La{static install(e){I=e.THREE,es=Object.freeze(new I.Vector3(0,0,0)),Pt=Object.freeze(new I.Vector3(0,1,0)),ni=Object.freeze(new I.Vector3(0,0,1)),me=new I.Vector2,U=new I.Vector3,F=new I.Vector3,$e=new I.Vector3,ht=new I.Vector3,Se=new I.Vector3,we=new I.Vector3,Ne=new I.Vector3,ts=new I.Vector3,is=new I.Vector3,ve=new I.Spherical,dt=new I.Spherical,Je=new I.Box3,ss=new I.Box3,ai=new I.Sphere,ns=new I.Quaternion,ri=new I.Quaternion,oi=new I.Matrix4,Rt=new I.Raycaster}static get ACTION(){return v}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.verticalDragToForward=!1,this.boundaryFriction=0,this.restThreshold=.01,this.colliderMeshes=[],this.cancel=()=>{},this._enabled=!0,this._state=v.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=Qe.NONE,this._thetaVelocity={value:0},this._phiVelocity={value:0},this._radiusVelocity={value:0},this._targetVelocity=new I.Vector3,this._focalOffsetVelocity=new I.Vector3,this._zoomVelocity={value:0},this._truckInternal=(_,b,S)=>{let w,x;if(je(this._camera)){const M=U.copy(this._camera.position).sub(this._target),D=this._camera.getEffectiveFOV()*ot,k=M.length()*Math.tan(D*.5);w=this.truckSpeed*_*k/this._elementRect.height,x=this.truckSpeed*b*k/this._elementRect.height}else if(ke(this._camera)){const M=this._camera;w=_*(M.right-M.left)/M.zoom/this._elementRect.width,x=b*(M.top-M.bottom)/M.zoom/this._elementRect.height}else return;this.verticalDragToForward?(S?this.setFocalOffset(this._focalOffsetEnd.x+w,this._focalOffsetEnd.y,this._focalOffsetEnd.z,!0):this.truck(w,0,!0),this.forward(-x,!0)):S?this.setFocalOffset(this._focalOffsetEnd.x+w,this._focalOffsetEnd.y+x,this._focalOffsetEnd.z,!0):this.truck(w,x,!0)},this._rotateInternal=(_,b)=>{const S=Ke*this.azimuthRotateSpeed*_/this._elementRect.height,w=Ke*this.polarRotateSpeed*b/this._elementRect.height;this.rotate(S,w,!0)},this._dollyInternal=(_,b,S)=>{const w=Math.pow(.95,-_*this.dollySpeed),x=this._sphericalEnd.radius,M=this._sphericalEnd.radius*w,D=Ee(M,this.minDistance,this.maxDistance),k=D-M;this.infinityDolly&&this.dollyToCursor?this._dollyToNoClamp(M,!0):this.infinityDolly&&!this.dollyToCursor?(this.dollyInFixed(k,!0),this._dollyToNoClamp(D,!0)):this._dollyToNoClamp(D,!0),this.dollyToCursor&&(this._changedDolly+=(this.infinityDolly?M:D)-x,this._dollyControlCoord.set(b,S)),this._lastDollyDirection=Math.sign(-_)},this._zoomInternal=(_,b,S)=>{const w=Math.pow(.95,_*this.dollySpeed),x=this._zoom,M=this._zoom*w;this.zoomTo(M,!0),this.dollyToCursor&&(this._changedZoom+=M-x,this._dollyControlCoord.set(b,S))},typeof I>"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 I.Quaternion().setFromUnitVectors(this._camera.up,Pt),this._yAxisUpSpaceInverse=this._yAxisUpSpace.clone().invert(),this._state=v.NONE,this._target=new I.Vector3,this._targetEnd=this._target.clone(),this._focalOffset=new I.Vector3,this._focalOffsetEnd=this._focalOffset.clone(),this._spherical=new I.Spherical().setFromVector3(U.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 I.Vector3,new I.Vector3,new I.Vector3,new I.Vector3],this._updateNearPlaneCorners(),this._boundary=new I.Box3(new I.Vector3(-1/0,-1/0,-1/0),new I.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 I.Vector2,this.mouseButtons={left:v.ROTATE,middle:v.DOLLY,right:v.TRUCK,wheel:je(this._camera)?v.DOLLY:ke(this._camera)?v.ZOOM:v.NONE},this.touches={one:v.TOUCH_ROTATE,two:je(this._camera)?v.TOUCH_DOLLY_TRUCK:ke(this._camera)?v.TOUCH_ZOOM_TRUCK:v.NONE,three:v.TOUCH_TRUCK};const s=new I.Vector2,n=new I.Vector2,r=new I.Vector2,a=_=>{if(!this._enabled||!this._domElement)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){const w=this._domElement.getBoundingClientRect(),x=_.clientX/w.width,M=_.clientY/w.height;if(x<this._interactiveArea.left||x>this._interactiveArea.right||M<this._interactiveArea.top||M>this._interactiveArea.bottom)return}const b=_.pointerType!=="mouse"?null:(_.buttons&$.LEFT)===$.LEFT?$.LEFT:(_.buttons&$.MIDDLE)===$.MIDDLE?$.MIDDLE:(_.buttons&$.RIGHT)===$.RIGHT?$.RIGHT:null;if(b!==null){const w=this._findPointerByMouseButton(b);w&&this._disposePointer(w)}if((_.buttons&$.LEFT)===$.LEFT&&this._lockedPointer)return;const S={pointerId:_.pointerId,clientX:_.clientX,clientY:_.clientY,deltaX:0,deltaY:0,mouseButton:b};this._activePointers.push(S),this._domElement.ownerDocument.removeEventListener("pointermove",l,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",c),this._domElement.ownerDocument.addEventListener("pointermove",l,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",c),this._isDragging=!0,m(_)},l=_=>{_.cancelable&&_.preventDefault();const b=_.pointerId,S=this._lockedPointer||this._findPointerById(b);if(S){if(S.clientX=_.clientX,S.clientY=_.clientY,S.deltaX=_.movementX,S.deltaY=_.movementY,this._state=0,_.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&&(_.buttons&$.LEFT)===$.LEFT)&&(this._state=this._state|this.mouseButtons.left),this._isDragging&&(_.buttons&$.MIDDLE)===$.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),this._isDragging&&(_.buttons&$.RIGHT)===$.RIGHT&&(this._state=this._state|this.mouseButtons.right);g()}},c=_=>{const b=this._findPointerById(_.pointerId);if(!(b&&b===this._lockedPointer)){if(b&&this._disposePointer(b),_.pointerType==="touch")switch(this._activePointers.length){case 0:this._state=v.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=v.NONE;E()}};let h=-1;const u=_=>{if(!this._domElement||!this._enabled||this.mouseButtons.wheel===v.NONE)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){const M=this._domElement.getBoundingClientRect(),D=_.clientX/M.width,k=_.clientY/M.height;if(D<this._interactiveArea.left||D>this._interactiveArea.right||k<this._interactiveArea.top||k>this._interactiveArea.bottom)return}if(_.preventDefault(),this.dollyToCursor||this.mouseButtons.wheel===v.ROTATE||this.mouseButtons.wheel===v.TRUCK){const M=performance.now();h-M<1e3&&this._getClientRect(this._elementRect),h=M}const b=Ua?-1:-3,S=_.deltaMode===1?_.deltaY/b:_.deltaY/(b*10),w=this.dollyToCursor?(_.clientX-this._elementRect.x)/this._elementRect.width*2-1:0,x=this.dollyToCursor?(_.clientY-this._elementRect.y)/this._elementRect.height*-2+1:0;switch(this.mouseButtons.wheel){case v.ROTATE:{this._rotateInternal(_.deltaX,_.deltaY),this._isUserControllingRotate=!0;break}case v.TRUCK:{this._truckInternal(_.deltaX,_.deltaY,!1),this._isUserControllingTruck=!0;break}case v.OFFSET:{this._truckInternal(_.deltaX,_.deltaY,!0),this._isUserControllingOffset=!0;break}case v.DOLLY:{this._dollyInternal(-S,w,x),this._isUserControllingDolly=!0;break}case v.ZOOM:{this._zoomInternal(-S,w,x),this._isUserControllingZoom=!0;break}}this.dispatchEvent({type:"control"})},f=_=>{if(!(!this._domElement||!this._enabled)){if(this.mouseButtons.right===Oe.ACTION.NONE){const b=_ instanceof PointerEvent?_.pointerId:0,S=this._findPointerById(b);S&&this._disposePointer(S),this._domElement.ownerDocument.removeEventListener("pointermove",l,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",c);return}_.preventDefault()}},m=_=>{if(!this._enabled)return;if(ti(this._activePointers,me),this._getClientRect(this._elementRect),s.copy(me),n.copy(me),this._activePointers.length>=2){const S=me.x-this._activePointers[1].clientX,w=me.y-this._activePointers[1].clientY,x=Math.sqrt(S*S+w*w);r.set(0,x);const M=(this._activePointers[0].clientX+this._activePointers[1].clientX)*.5,D=(this._activePointers[0].clientY+this._activePointers[1].clientY)*.5;n.set(M,D)}if(this._state=0,!_)this._lockedPointer&&(this._state=this._state|this.mouseButtons.left);else if("pointerType"in _&&_.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&&(_.buttons&$.LEFT)===$.LEFT&&(this._state=this._state|this.mouseButtons.left),(_.buttons&$.MIDDLE)===$.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),(_.buttons&$.RIGHT)===$.RIGHT&&(this._state=this._state|this.mouseButtons.right);((this._state&v.ROTATE)===v.ROTATE||(this._state&v.TOUCH_ROTATE)===v.TOUCH_ROTATE||(this._state&v.TOUCH_DOLLY_ROTATE)===v.TOUCH_DOLLY_ROTATE||(this._state&v.TOUCH_ZOOM_ROTATE)===v.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&v.TRUCK)===v.TRUCK||(this._state&v.TOUCH_TRUCK)===v.TOUCH_TRUCK||(this._state&v.TOUCH_DOLLY_TRUCK)===v.TOUCH_DOLLY_TRUCK||(this._state&v.TOUCH_ZOOM_TRUCK)===v.TOUCH_ZOOM_TRUCK)&&(this._targetEnd.copy(this._target),this._targetVelocity.set(0,0,0)),((this._state&v.DOLLY)===v.DOLLY||(this._state&v.TOUCH_DOLLY)===v.TOUCH_DOLLY||(this._state&v.TOUCH_DOLLY_TRUCK)===v.TOUCH_DOLLY_TRUCK||(this._state&v.TOUCH_DOLLY_OFFSET)===v.TOUCH_DOLLY_OFFSET||(this._state&v.TOUCH_DOLLY_ROTATE)===v.TOUCH_DOLLY_ROTATE)&&(this._sphericalEnd.radius=this._spherical.radius,this._radiusVelocity.value=0),((this._state&v.ZOOM)===v.ZOOM||(this._state&v.TOUCH_ZOOM)===v.TOUCH_ZOOM||(this._state&v.TOUCH_ZOOM_TRUCK)===v.TOUCH_ZOOM_TRUCK||(this._state&v.TOUCH_ZOOM_OFFSET)===v.TOUCH_ZOOM_OFFSET||(this._state&v.TOUCH_ZOOM_ROTATE)===v.TOUCH_ZOOM_ROTATE)&&(this._zoomEnd=this._zoom,this._zoomVelocity.value=0),((this._state&v.OFFSET)===v.OFFSET||(this._state&v.TOUCH_OFFSET)===v.TOUCH_OFFSET||(this._state&v.TOUCH_DOLLY_OFFSET)===v.TOUCH_DOLLY_OFFSET||(this._state&v.TOUCH_ZOOM_OFFSET)===v.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,ti(this._activePointers,me);const b=this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement?this._lockedPointer||this._activePointers[0]:null,S=b?-b.deltaX:n.x-me.x,w=b?-b.deltaY:n.y-me.y;if(n.copy(me),((this._state&v.ROTATE)===v.ROTATE||(this._state&v.TOUCH_ROTATE)===v.TOUCH_ROTATE||(this._state&v.TOUCH_DOLLY_ROTATE)===v.TOUCH_DOLLY_ROTATE||(this._state&v.TOUCH_ZOOM_ROTATE)===v.TOUCH_ZOOM_ROTATE)&&(this._rotateInternal(S,w),this._isUserControllingRotate=!0),(this._state&v.DOLLY)===v.DOLLY||(this._state&v.ZOOM)===v.ZOOM){const x=this.dollyToCursor?(s.x-this._elementRect.x)/this._elementRect.width*2-1:0,M=this.dollyToCursor?(s.y-this._elementRect.y)/this._elementRect.height*-2+1:0,D=this.dollyDragInverted?-1:1;(this._state&v.DOLLY)===v.DOLLY?(this._dollyInternal(D*w*At,x,M),this._isUserControllingDolly=!0):(this._zoomInternal(D*w*At,x,M),this._isUserControllingZoom=!0)}if((this._state&v.TOUCH_DOLLY)===v.TOUCH_DOLLY||(this._state&v.TOUCH_ZOOM)===v.TOUCH_ZOOM||(this._state&v.TOUCH_DOLLY_TRUCK)===v.TOUCH_DOLLY_TRUCK||(this._state&v.TOUCH_ZOOM_TRUCK)===v.TOUCH_ZOOM_TRUCK||(this._state&v.TOUCH_DOLLY_OFFSET)===v.TOUCH_DOLLY_OFFSET||(this._state&v.TOUCH_ZOOM_OFFSET)===v.TOUCH_ZOOM_OFFSET||(this._state&v.TOUCH_DOLLY_ROTATE)===v.TOUCH_DOLLY_ROTATE||(this._state&v.TOUCH_ZOOM_ROTATE)===v.TOUCH_ZOOM_ROTATE){const x=me.x-this._activePointers[1].clientX,M=me.y-this._activePointers[1].clientY,D=Math.sqrt(x*x+M*M),k=r.y-D;r.set(0,D);const R=this.dollyToCursor?(n.x-this._elementRect.x)/this._elementRect.width*2-1:0,V=this.dollyToCursor?(n.y-this._elementRect.y)/this._elementRect.height*-2+1:0;(this._state&v.TOUCH_DOLLY)===v.TOUCH_DOLLY||(this._state&v.TOUCH_DOLLY_ROTATE)===v.TOUCH_DOLLY_ROTATE||(this._state&v.TOUCH_DOLLY_TRUCK)===v.TOUCH_DOLLY_TRUCK||(this._state&v.TOUCH_DOLLY_OFFSET)===v.TOUCH_DOLLY_OFFSET?(this._dollyInternal(k*At,R,V),this._isUserControllingDolly=!0):(this._zoomInternal(k*At,R,V),this._isUserControllingZoom=!0)}((this._state&v.TRUCK)===v.TRUCK||(this._state&v.TOUCH_TRUCK)===v.TOUCH_TRUCK||(this._state&v.TOUCH_DOLLY_TRUCK)===v.TOUCH_DOLLY_TRUCK||(this._state&v.TOUCH_ZOOM_TRUCK)===v.TOUCH_ZOOM_TRUCK)&&(this._truckInternal(S,w,!1),this._isUserControllingTruck=!0),((this._state&v.OFFSET)===v.OFFSET||(this._state&v.TOUCH_OFFSET)===v.TOUCH_OFFSET||(this._state&v.TOUCH_DOLLY_OFFSET)===v.TOUCH_DOLLY_OFFSET||(this._state&v.TOUCH_ZOOM_OFFSET)===v.TOUCH_ZOOM_OFFSET)&&(this._truckInternal(S,w,!0),this._isUserControllingOffset=!0),this.dispatchEvent({type:"control"})},E=()=>{ti(this._activePointers,me),n.copy(me),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",l,{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",l,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",c),this._domElement.requestPointerLock(),this._domElement.ownerDocument.addEventListener("pointerlockchange",y),this._domElement.ownerDocument.addEventListener("pointerlockerror",O),this._domElement.ownerDocument.addEventListener("pointermove",l,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",c),m())},this.unlockPointer=()=>{var _,b,S;this._lockedPointer!==null&&(this._disposePointer(this._lockedPointer),this._lockedPointer=null),(_=this._domElement)===null||_===void 0||_.ownerDocument.exitPointerLock(),(b=this._domElement)===null||b===void 0||b.ownerDocument.removeEventListener("pointerlockchange",y),(S=this._domElement)===null||S===void 0||S.ownerDocument.removeEventListener("pointerlockerror",O),this.cancel()};const y=()=>{this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement||this.unlockPointer()},O=()=>{this.unlockPointer()};this._addAllEventListeners=_=>{this._domElement=_,this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none",this._domElement.addEventListener("pointerdown",a),this._domElement.addEventListener("pointercancel",c),this._domElement.addEventListener("wheel",u,{passive:!1}),this._domElement.addEventListener("contextmenu",f)},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",c),this._domElement.removeEventListener("wheel",u,{passive:!1}),this._domElement.removeEventListener("contextmenu",f),this._domElement.ownerDocument.removeEventListener("pointermove",l,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",c),this._domElement.ownerDocument.removeEventListener("pointerlockchange",y),this._domElement.ownerDocument.removeEventListener("pointerlockerror",O))},this.cancel=()=>{this._state!==v.NONE&&(this._state=v.NONE,this._activePointers.length=0,E())},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=Ee(e.width,0,1),this._interactiveArea.height=Ee(e.height,0,1),this._interactiveArea.x=Ee(e.x,0,1-this._interactiveArea.width),this._interactiveArea.y=Ee(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=Ee(e,this.minAzimuthAngle,this.maxAzimuthAngle),r=Ee(t,this.minPolarAngle,this.maxPolarAngle);this._sphericalEnd.theta=n,this._sphericalEnd.phi=r,this._sphericalEnd.makeSafe(),this._needsUpdate=!0,s||(this._spherical.theta=this._sphericalEnd.theta,this._spherical.phi=this._sphericalEnd.phi);const a=!s||H(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&H(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=Qe.NONE,this._changedDolly=0,this._dollyToNoClamp(Ee(e,this.minDistance,this.maxDistance),t)}_dollyToNoClamp(e,t=!1){const s=this._sphericalEnd.radius;if(this.colliderMeshes.length>=1){const a=this._collisionTest(),l=H(a,this._spherical.radius);if(!(s>e)&&l)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 r=!t||H(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(r)}dollyInFixed(e,t=!1){this._targetEnd.add(this._getCameraDirection(ht).multiplyScalar(e)),t||this._target.copy(this._targetEnd);const s=!t||H(this._target.x,this._targetEnd.x,this.restThreshold)&&H(this._target.y,this._targetEnd.y,this.restThreshold)&&H(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=Ee(e,this.minZoom,this.maxZoom),this._needsUpdate=!0,t||(this._zoom=this._zoomEnd);const s=!t||H(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(),Se.setFromMatrixColumn(this._camera.matrix,0),we.setFromMatrixColumn(this._camera.matrix,1),Se.multiplyScalar(e),we.multiplyScalar(-t);const n=U.copy(Se).add(we),r=F.copy(this._targetEnd).add(n);return this.moveTo(r.x,r.y,r.z,s)}forward(e,t=!1){U.setFromMatrixColumn(this._camera.matrix,0),U.crossVectors(this._camera.up,U),U.multiplyScalar(e);const s=F.copy(this._targetEnd).add(U);return this.moveTo(s.x,s.y,s.z,t)}elevate(e,t=!1){return U.copy(this._camera.up).multiplyScalar(e),this.moveTo(this._targetEnd.x+U.x,this._targetEnd.y+U.y,this._targetEnd.z+U.z,t)}moveTo(e,t,s,n=!1){this._isUserControllingTruck=!1;const r=U.set(e,t,s).sub(this._targetEnd);this._encloseToBoundary(this._targetEnd,r,this.boundaryFriction),this._needsUpdate=!0,n||this._target.copy(this._targetEnd);const a=!n||H(this._target.x,this._targetEnd.x,this.restThreshold)&&H(this._target.y,this._targetEnd.y,this.restThreshold)&&H(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(a)}lookInDirectionOf(e,t,s,n=!1){const l=U.set(e,t,s).sub(this._targetEnd).normalize().multiplyScalar(-this._sphericalEnd.radius).add(this._targetEnd);return this.setPosition(l.x,l.y,l.z,n)}fitToBox(e,t,{cover:s=!1,paddingLeft:n=0,paddingRight:r=0,paddingBottom:a=0,paddingTop:l=0}={}){const c=[],h=e.isBox3?Je.copy(e):Je.setFromObject(e);h.isEmpty()&&(console.warn("camera-controls: fitTo() cannot be used with an empty box. Aborting"),Promise.resolve());const u=$i(this._sphericalEnd.theta,Ki),f=$i(this._sphericalEnd.phi,Ki);c.push(this.rotateTo(u,f,t));const m=U.setFromSpherical(this._sphericalEnd).normalize(),g=ns.setFromUnitVectors(m,ni),E=H(Math.abs(m.y),1);E&&g.multiply(ri.setFromAxisAngle(Pt,u)),g.multiply(this._yAxisUpSpaceInverse);const y=ss.makeEmpty();F.copy(h.min).applyQuaternion(g),y.expandByPoint(F),F.copy(h.min).setX(h.max.x).applyQuaternion(g),y.expandByPoint(F),F.copy(h.min).setY(h.max.y).applyQuaternion(g),y.expandByPoint(F),F.copy(h.max).setZ(h.min.z).applyQuaternion(g),y.expandByPoint(F),F.copy(h.min).setZ(h.max.z).applyQuaternion(g),y.expandByPoint(F),F.copy(h.max).setY(h.min.y).applyQuaternion(g),y.expandByPoint(F),F.copy(h.max).setX(h.min.x).applyQuaternion(g),y.expandByPoint(F),F.copy(h.max).applyQuaternion(g),y.expandByPoint(F),y.min.x-=n,y.min.y-=a,y.max.x+=r,y.max.y+=l,g.setFromUnitVectors(ni,m),E&&g.premultiply(ri.invert()),g.premultiply(this._yAxisUpSpace);const O=y.getSize(U),_=y.getCenter(F).applyQuaternion(g);if(je(this._camera)){const b=this.getDistanceToFitBox(O.x,O.y,O.z,s);c.push(this.moveTo(_.x,_.y,_.z,t)),c.push(this.dollyTo(b,t)),c.push(this.setFocalOffset(0,0,0,t))}else if(ke(this._camera)){const b=this._camera,S=b.right-b.left,w=b.top-b.bottom,x=s?Math.max(S/O.x,w/O.y):Math.min(S/O.x,w/O.y);c.push(this.moveTo(_.x,_.y,_.z,t)),c.push(this.zoomTo(x,t)),c.push(this.setFocalOffset(0,0,0,t))}return Promise.all(c)}fitToSphere(e,t){const s=[],r="isObject3D"in e?Oe.createBoundingSphere(e,ai):ai.copy(e);if(s.push(this.moveTo(r.center.x,r.center.y,r.center.z,t)),je(this._camera)){const a=this.getDistanceToFitSphere(r.radius);s.push(this.dollyTo(a,t))}else if(ke(this._camera)){const a=this._camera.right-this._camera.left,l=this._camera.top-this._camera.bottom,c=2*r.radius,h=Math.min(a/c,l/c);s.push(this.zoomTo(h,t))}return s.push(this.setFocalOffset(0,0,0,t)),Promise.all(s)}setLookAt(e,t,s,n,r,a,l=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=Qe.NONE,this._changedDolly=0;const c=F.set(n,r,a),h=U.set(e,t,s);this._targetEnd.copy(c),this._sphericalEnd.setFromVector3(h.sub(c).applyQuaternion(this._yAxisUpSpace)),this.normalizeRotations(),this._needsUpdate=!0,l||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const u=!l||H(this._target.x,this._targetEnd.x,this.restThreshold)&&H(this._target.y,this._targetEnd.y,this.restThreshold)&&H(this._target.z,this._targetEnd.z,this.restThreshold)&&H(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&H(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&H(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(u)}lerpLookAt(e,t,s,n,r,a,l,c,h,u,f,m,g,E=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=Qe.NONE,this._changedDolly=0;const y=U.set(n,r,a),O=F.set(e,t,s);ve.setFromVector3(O.sub(y).applyQuaternion(this._yAxisUpSpace));const _=$e.set(u,f,m),b=F.set(l,c,h);dt.setFromVector3(b.sub(_).applyQuaternion(this._yAxisUpSpace)),this._targetEnd.copy(y.lerp(_,g));const S=dt.theta-ve.theta,w=dt.phi-ve.phi,x=dt.radius-ve.radius;this._sphericalEnd.set(ve.radius+x*g,ve.phi+w*g,ve.theta+S*g),this.normalizeRotations(),this._needsUpdate=!0,E||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const M=!E||H(this._target.x,this._targetEnd.x,this.restThreshold)&&H(this._target.y,this._targetEnd.y,this.restThreshold)&&H(this._target.z,this._targetEnd.z,this.restThreshold)&&H(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&H(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&H(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(M)}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 r=this.getPosition(U),a=this.setLookAt(r.x,r.y,r.z,e,t,s,n);return this._sphericalEnd.phi=Ee(this._sphericalEnd.phi,this.minPolarAngle,this.maxPolarAngle),a}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 r=!n||H(this._focalOffset.x,this._focalOffsetEnd.x,this.restThreshold)&&H(this._focalOffset.y,this._focalOffsetEnd.y,this.restThreshold)&&H(this._focalOffset.z,this._focalOffsetEnd.z,this.restThreshold);return this._createOnRestPromise(r)}setOrbitPoint(e,t,s){this._camera.updateMatrixWorld(),Se.setFromMatrixColumn(this._camera.matrixWorldInverse,0),we.setFromMatrixColumn(this._camera.matrixWorldInverse,1),Ne.setFromMatrixColumn(this._camera.matrixWorldInverse,2);const n=U.set(e,t,s),r=n.distanceTo(this._camera.position),a=n.sub(this._camera.position);Se.multiplyScalar(a.x),we.multiplyScalar(a.y),Ne.multiplyScalar(a.z),U.copy(Se).add(we).add(Ne),U.z=U.z+r,this.dollyTo(r,!1),this.setFocalOffset(-U.x,U.y,-U.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 I.Vector4,typeof e=="number"?this._viewport.set(e,t,s,n):this._viewport.copy(e)}getDistanceToFitBox(e,t,s,n=!1){if(ii(this._camera,"getDistanceToFitBox"))return this._spherical.radius;const r=e/t,a=this._camera.getEffectiveFOV()*ot,l=this._camera.aspect;return((n?r>l:r<l)?t:e/l)*.5/Math.tan(a*.5)+s*.5}getDistanceToFitSphere(e){if(ii(this._camera,"getDistanceToFitSphere"))return this._spherical.radius;const t=this._camera.getEffectiveFOV()*ot,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 I.Vector3).copy(t?this._targetEnd:this._target)}getPosition(e,t=!0){return(e&&e.isVector3?e:new I.Vector3).setFromSpherical(t?this._sphericalEnd:this._spherical).applyQuaternion(this._yAxisUpSpaceInverse).add(t?this._targetEnd:this._target)}getSpherical(e,t=!0){return(e||new I.Spherical).copy(t?this._sphericalEnd:this._spherical)}getFocalOffset(e,t=!0){return(e&&e.isVector3?e:new I.Vector3).copy(t?this._focalOffsetEnd:this._focalOffset)}normalizeRotations(){this._sphericalEnd.theta=this._sphericalEnd.theta%Ke,this._sphericalEnd.theta<0&&(this._sphericalEnd.theta+=Ke),this._spherical.theta+=Ke*Math.round((this._sphericalEnd.theta-this._spherical.theta)/Ke)}stop(){this._focalOffset.copy(this._focalOffsetEnd),this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd),this._zoom=this._zoomEnd}reset(e=!1){if(!H(this._camera.up.x,this._cameraUp0.x)||!H(this._camera.up.y,this._cameraUp0.y)||!H(this._camera.up.z,this._cameraUp0.z)){this._camera.up.copy(this._cameraUp0);const s=this.getPosition(U);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,Pt),this._yAxisUpSpaceInverse.copy(this._yAxisUpSpace).invert()}applyCameraUp(){const e=U.subVectors(this._target,this._camera.position).normalize(),t=F.crossVectors(e,this._camera.up);this._camera.up.crossVectors(t,e).normalize(),this._camera.updateMatrixWorld();const s=this.getPosition(U);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,r=ts.subVectors(this._targetEnd,this._target),a=is.subVectors(this._focalOffsetEnd,this._focalOffset),l=this._zoomEnd-this._zoom;if(q(t))this._thetaVelocity.value=0,this._spherical.theta=this._sphericalEnd.theta;else{const f=this._isUserControllingRotate?this.draggingSmoothTime:this.smoothTime;this._spherical.theta=Mt(this._spherical.theta,this._sphericalEnd.theta,this._thetaVelocity,f,1/0,e),this._needsUpdate=!0}if(q(s))this._phiVelocity.value=0,this._spherical.phi=this._sphericalEnd.phi;else{const f=this._isUserControllingRotate?this.draggingSmoothTime:this.smoothTime;this._spherical.phi=Mt(this._spherical.phi,this._sphericalEnd.phi,this._phiVelocity,f,1/0,e),this._needsUpdate=!0}if(q(n))this._radiusVelocity.value=0,this._spherical.radius=this._sphericalEnd.radius;else{const f=this._isUserControllingDolly?this.draggingSmoothTime:this.smoothTime;this._spherical.radius=Mt(this._spherical.radius,this._sphericalEnd.radius,this._radiusVelocity,f,this.maxSpeed,e),this._needsUpdate=!0}if(q(r.x)&&q(r.y)&&q(r.z))this._targetVelocity.set(0,0,0),this._target.copy(this._targetEnd);else{const f=this._isUserControllingTruck?this.draggingSmoothTime:this.smoothTime;Ji(this._target,this._targetEnd,this._targetVelocity,f,this.maxSpeed,e,this._target),this._needsUpdate=!0}if(q(a.x)&&q(a.y)&&q(a.z))this._focalOffsetVelocity.set(0,0,0),this._focalOffset.copy(this._focalOffsetEnd);else{const f=this._isUserControllingOffset?this.draggingSmoothTime:this.smoothTime;Ji(this._focalOffset,this._focalOffsetEnd,this._focalOffsetVelocity,f,this.maxSpeed,e,this._focalOffset),this._needsUpdate=!0}if(q(l))this._zoomVelocity.value=0,this._zoom=this._zoomEnd;else{const f=this._isUserControllingZoom?this.draggingSmoothTime:this.smoothTime;this._zoom=Mt(this._zoom,this._zoomEnd,this._zoomVelocity,f,1/0,e)}if(this.dollyToCursor){if(je(this._camera)&&this._changedDolly!==0){const f=this._spherical.radius-this._lastDistance,m=this._camera,g=this._getCameraDirection(ht),E=U.copy(g).cross(m.up).normalize();E.lengthSq()===0&&(E.x=1);const y=F.crossVectors(E,g),O=this._sphericalEnd.radius*Math.tan(m.getEffectiveFOV()*ot*.5),b=(this._sphericalEnd.radius-f-this._sphericalEnd.radius)/this._sphericalEnd.radius,S=$e.copy(this._targetEnd).add(E.multiplyScalar(this._dollyControlCoord.x*O*m.aspect)).add(y.multiplyScalar(this._dollyControlCoord.y*O)),w=U.copy(this._targetEnd).lerp(S,b),x=this._lastDollyDirection===Qe.IN&&this._spherical.radius<=this.minDistance,M=this._lastDollyDirection===Qe.OUT&&this.maxDistance<=this._spherical.radius;if(this.infinityDolly&&(x||M)){this._sphericalEnd.radius-=f,this._spherical.radius-=f;const k=F.copy(g).multiplyScalar(-f);w.add(k)}this._boundary.clampPoint(w,w);const D=F.subVectors(w,this._targetEnd);this._targetEnd.copy(w),this._target.add(D),this._changedDolly-=f,q(this._changedDolly)&&(this._changedDolly=0)}else if(ke(this._camera)&&this._changedZoom!==0){const f=this._zoom-this._lastZoom,m=this._camera,g=U.set(this._dollyControlCoord.x,this._dollyControlCoord.y,(m.near+m.far)/(m.near-m.far)).unproject(m),E=F.set(0,0,-1).applyQuaternion(m.quaternion),y=$e.copy(g).add(E.multiplyScalar(-g.dot(m.up))),_=-(this._zoom-f-this._zoom)/this._zoom,b=this._getCameraDirection(ht),S=this._targetEnd.dot(b),w=U.copy(this._targetEnd).lerp(y,_),x=w.dot(b),M=b.multiplyScalar(x-S);w.sub(M),this._boundary.clampPoint(w,w);const D=F.subVectors(w,this._targetEnd);this._targetEnd.copy(w),this._target.add(D),this._changedZoom-=f,q(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),(!q(this._focalOffset.x)||!q(this._focalOffset.y)||!q(this._focalOffset.z))&&(this._camera.updateMatrixWorld(),Se.setFromMatrixColumn(this._camera.matrix,0),we.setFromMatrixColumn(this._camera.matrix,1),Ne.setFromMatrixColumn(this._camera.matrix,2),Se.multiplyScalar(this._focalOffset.x),we.multiplyScalar(-this._focalOffset.y),Ne.multiplyScalar(this._focalOffset.z),U.copy(Se).add(we).add(Ne),this._camera.position.add(U)),this._boundaryEnclosesCamera&&this._encloseToBoundary(this._camera.position.copy(this._target),U.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"}),q(t,this.restThreshold)&&q(s,this.restThreshold)&&q(n,this.restThreshold)&&q(r.x,this.restThreshold)&&q(r.y,this.restThreshold)&&q(r.z,this.restThreshold)&&q(a.x,this.restThreshold)&&q(a.y,this.restThreshold)&&q(a.z,this.restThreshold)&&q(l,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:lt(this.maxDistance),minZoom:this.minZoom,maxZoom:lt(this.maxZoom),minPolarAngle:this.minPolarAngle,maxPolarAngle:lt(this.maxPolarAngle),minAzimuthAngle:lt(this.minAzimuthAngle),maxAzimuthAngle:lt(this.maxAzimuthAngle),smoothTime:this.smoothTime,draggingSmoothTime:this.draggingSmoothTime,dollySpeed:this.dollySpeed,truckSpeed:this.truckSpeed,dollyToCursor:this.dollyToCursor,verticalDragToForward:this.verticalDragToForward,target:this._targetEnd.toArray(),position:U.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=ct(s.maxDistance),this.minZoom=s.minZoom,this.maxZoom=ct(s.maxZoom),this.minPolarAngle=s.minPolarAngle,this.maxPolarAngle=ct(s.maxPolarAngle),this.minAzimuthAngle=ct(s.minAzimuthAngle),this.maxAzimuthAngle=ct(s.maxAzimuthAngle),this.smoothTime=s.smoothTime,this.draggingSmoothTime=s.draggingSmoothTime,this.dollySpeed=s.dollySpeed,this.truckSpeed=s.truckSpeed,this.dollyToCursor=s.dollyToCursor,this.verticalDragToForward=s.verticalDragToForward,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),ve.setFromVector3(U.fromArray(s.position).sub(this._targetEnd).applyQuaternion(this._yAxisUpSpace)),this.rotateTo(ve.theta,ve.phi,t),this.dollyTo(ve.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",ka),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 r=F.copy(t).add(e),l=this._boundary.clampPoint(r,$e).sub(r),c=l.lengthSq();if(c===0)return e.add(t);if(c===n)return e;if(s===0)return e.add(t).add(l);{const h=1+s*c/t.dot(l);return e.add(F.copy(t).multiplyScalar(h)).add(l.multiplyScalar(1-s))}}_updateNearPlaneCorners(){if(je(this._camera)){const e=this._camera,t=e.near,s=e.getEffectiveFOV()*ot,n=Math.tan(s*.5)*t,r=n*e.aspect;this._nearPlaneCorners[0].set(-r,-n,0),this._nearPlaneCorners[1].set(r,-n,0),this._nearPlaneCorners[2].set(r,n,0),this._nearPlaneCorners[3].set(-r,n,0)}else if(ke(this._camera)){const e=this._camera,t=1/e.zoom,s=e.left*t,n=e.right*t,r=e.top*t,a=e.bottom*t;this._nearPlaneCorners[0].set(s,r,0),this._nearPlaneCorners[1].set(n,r,0),this._nearPlaneCorners[2].set(n,a,0),this._nearPlaneCorners[3].set(s,a,0)}}_collisionTest(){let e=1/0;if(!(this.colliderMeshes.length>=1)||ii(this._camera,"_collisionTest"))return e;const s=this._getTargetDirection(ht);oi.lookAt(es,s,this._camera.up);for(let n=0;n<4;n++){const r=F.copy(this._nearPlaneCorners[n]);r.applyMatrix4(oi);const a=$e.addVectors(this._target,r);Rt.set(a,s),Rt.far=this._spherical.radius+1;const l=Rt.intersectObjects(this.colliderMeshes);l.length!==0&&l[0].distance<e&&(e=l[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 I.Sphere){const s=t,n=s.center;Je.makeEmpty(),e.traverseVisible(a=>{a.isMesh&&Je.expandByObject(a)}),Je.getCenter(n);let r=0;return e.traverseVisible(a=>{if(!a.isMesh)return;const l=a,c=l.geometry.clone();c.applyMatrix4(l.matrixWorld);const u=c.attributes.position;for(let f=0,m=u.count;f<m;f++)U.fromBufferAttribute(u,f),r=Math.max(r,n.distanceToSquared(U))}),s.radius=Math.sqrt(r),s}}const zt=i=>{const[e,t]=T.useState(i.options[i.index]),s=()=>{i.onToggle(!i.open)},n=r=>{r!==e&&(i.onSelect(r),t(r)),i.onToggle(!1)};return p.jsxs("div",{className:`dropdown ${i.up===!0?"up":""}`,children:[p.jsx("div",{className:"dropdown-toggle",onClick:s,children:`${i.title}: ${e}`}),i.open&&p.jsx("ul",{className:"dropdown-menu",children:i.options.map(r=>p.jsx("li",{onClick:()=>n(r),children:r},r))})]})},Fe=T.forwardRef(function(e,t){const s=["Renderer","Depth","Normals","UVs","Wireframe"],[n,r]=T.useState("Renderer"),[a,l]=T.useState(!1),[c,h]=T.useState(!1),[u,f]=T.useState(!1);return p.jsxs("div",{className:`CameraWindow ${e.name}`,children:[p.jsx("div",{ref:t,className:"clickable",onClick:()=>{u&&f(!1)}}),p.jsxs("div",{className:"options",children:[e.camera!==null&&p.jsx(zt,{title:"Camera",index:e.options.indexOf(e.camera.name),open:u,options:e.options,onSelect:e.onSelectCamera,onToggle:m=>{f(m)},up:!0}),p.jsx(zt,{title:"Mode",index:s.indexOf(n),open:c,options:s,onSelect:m=>{if(m===n)return;const g=m;e.onSelectRenderMode(g),r(g)},onToggle:m=>{a&&l(!1),h(m)},up:!0})]})]})}),ja=`out vec3 worldPosition;
|
485
|
+
*/const We={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}),Ln={NONE:0,IN:1,OUT:-1};function qi(a){return a.isPerspectiveCamera}function Ti(a){return a.isOrthographicCamera}const Un=Math.PI*2,Pf=Math.PI/2,By=1e-5,zr=Math.PI/180;function gs(a,e,t){return Math.max(e,Math.min(t,a))}function Ie(a,e=By){return Math.abs(a)<e}function Ce(a,e,t=By){return Ie(a-e,t)}function Ff(a,e){return Math.round(a/e)*e}function Gr(a){return isFinite(a)?a:a<0?-Number.MAX_VALUE:Number.MAX_VALUE}function Vr(a){return Math.abs(a)<Number.MAX_VALUE?a:a*(1/0)}function mo(a,e,t,s,i=1/0,n){s=Math.max(1e-4,s);const r=2/s,o=r*n,l=1/(1+o+.48*o*o+.235*o*o*o);let c=a-e;const h=e,u=i*s;c=gs(c,-u,u),e=a-c;const d=(t.value+r*c)*n;t.value=(t.value-r*d)*l;let p=e+(c+d)*l;return h-a>0==p>h&&(p=h,t.value=(p-h)/n),p}function Df(a,e,t,s,i=1/0,n,r){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 h=e.x,u=e.y,d=e.z,p=a.x-h,f=a.y-u,m=a.z-d;const y=h,g=u,_=d,b=i*s,S=b*b,T=p*p+f*f+m*m;if(T>S){const Z=Math.sqrt(T);p=p/Z*b,f=f/Z*b,m=m/Z*b}h=a.x-p,u=a.y-f,d=a.z-m;const M=(t.x+o*p)*n,w=(t.y+o*f)*n,R=(t.z+o*m)*n;t.x=(t.x-o*M)*c,t.y=(t.y-o*w)*c,t.z=(t.z-o*R)*c,r.x=h+(p+M)*c,r.y=u+(f+w)*c,r.z=d+(m+R)*c;const P=y-a.x,z=g-a.y,$=_-a.z,q=r.x-y,j=r.y-g,X=r.z-_;return P*q+z*j+$*X>0&&(r.x=y,r.y=g,r.z=_,t.x=(r.x-y)/n,t.y=(r.y-g)/n,t.z=(r.z-_)/n),r}function qc(a,e){e.set(0,0),a.forEach(t=>{e.x+=t.clientX,e.y+=t.clientY}),e.x/=a.length,e.y/=a.length}function Yc(a,e){return Ti(a)?(console.warn(`${e} is not supported in OrthographicCamera`),!0):!1}class jR{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,r=i.length;n<r;n++)i[n].call(this,e)}}}var Xc;const qR="2.10.1",go=1/8,YR=/Mac/.test((Xc=globalThis?.navigator)===null||Xc===void 0?void 0:Xc.platform);let ee,Of,yo,Zc,It,le,be,kn,Hr,As,Rs,Yi,Bf,If,es,Wr,zn,Lf,Qc,Uf,Kc,Jc,xo;class Ds extends jR{static install(e){ee=e.THREE,Of=Object.freeze(new ee.Vector3(0,0,0)),yo=Object.freeze(new ee.Vector3(0,1,0)),Zc=Object.freeze(new ee.Vector3(0,0,1)),It=new ee.Vector2,le=new ee.Vector3,be=new ee.Vector3,kn=new ee.Vector3,Hr=new ee.Vector3,As=new ee.Vector3,Rs=new ee.Vector3,Yi=new ee.Vector3,Bf=new ee.Vector3,If=new ee.Vector3,es=new ee.Spherical,Wr=new ee.Spherical,zn=new ee.Box3,Lf=new ee.Box3,Qc=new ee.Sphere,Uf=new ee.Quaternion,Kc=new ee.Quaternion,Jc=new ee.Matrix4,xo=new ee.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=Ln.NONE,this._thetaVelocity={value:0},this._phiVelocity={value:0},this._radiusVelocity={value:0},this._targetVelocity=new ee.Vector3,this._focalOffsetVelocity=new ee.Vector3,this._zoomVelocity={value:0},this._truckInternal=(g,_,b,S)=>{let T,M;if(qi(this._camera)){const w=le.copy(this._camera.position).sub(this._target),R=this._camera.getEffectiveFOV()*zr,P=w.length()*Math.tan(R*.5);T=this.truckSpeed*g*P/this._elementRect.height,M=this.truckSpeed*_*P/this._elementRect.height}else if(Ti(this._camera)){const w=this._camera;T=this.truckSpeed*g*(w.right-w.left)/w.zoom/this._elementRect.width,M=this.truckSpeed*_*(w.top-w.bottom)/w.zoom/this._elementRect.height}else return;S?(b?this.setFocalOffset(this._focalOffsetEnd.x+T,this._focalOffsetEnd.y,this._focalOffsetEnd.z,!0):this.truck(T,0,!0),this.forward(-M,!0)):b?this.setFocalOffset(this._focalOffsetEnd.x+T,this._focalOffsetEnd.y+M,this._focalOffsetEnd.z,!0):this.truck(T,M,!0)},this._rotateInternal=(g,_)=>{const b=Un*this.azimuthRotateSpeed*g/this._elementRect.height,S=Un*this.polarRotateSpeed*_/this._elementRect.height;this.rotate(b,S,!0)},this._dollyInternal=(g,_,b)=>{const S=Math.pow(.95,-g*this.dollySpeed),T=this._sphericalEnd.radius,M=this._sphericalEnd.radius*S,w=gs(M,this.minDistance,this.maxDistance),R=w-M;this.infinityDolly&&this.dollyToCursor?this._dollyToNoClamp(M,!0):this.infinityDolly&&!this.dollyToCursor?(this.dollyInFixed(R,!0),this._dollyToNoClamp(w,!0)):this._dollyToNoClamp(w,!0),this.dollyToCursor&&(this._changedDolly+=(this.infinityDolly?M:w)-T,this._dollyControlCoord.set(_,b)),this._lastDollyDirection=Math.sign(-g)},this._zoomInternal=(g,_,b)=>{const S=Math.pow(.95,g*this.dollySpeed),T=this._zoom,M=this._zoom*S;this.zoomTo(M,!0),this.dollyToCursor&&(this._changedZoom+=M-T,this._dollyControlCoord.set(_,b))},typeof ee>"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 ee.Quaternion().setFromUnitVectors(this._camera.up,yo),this._yAxisUpSpaceInverse=this._yAxisUpSpace.clone().invert(),this._state=F.NONE,this._target=new ee.Vector3,this._targetEnd=this._target.clone(),this._focalOffset=new ee.Vector3,this._focalOffsetEnd=this._focalOffset.clone(),this._spherical=new ee.Spherical().setFromVector3(le.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 ee.Vector3,new ee.Vector3,new ee.Vector3,new ee.Vector3],this._updateNearPlaneCorners(),this._boundary=new ee.Box3(new ee.Vector3(-1/0,-1/0,-1/0),new ee.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 ee.Vector2,this.mouseButtons={left:F.ROTATE,middle:F.DOLLY,right:F.TRUCK,wheel:qi(this._camera)?F.DOLLY:Ti(this._camera)?F.ZOOM:F.NONE},this.touches={one:F.TOUCH_ROTATE,two:qi(this._camera)?F.TOUCH_DOLLY_TRUCK:Ti(this._camera)?F.TOUCH_ZOOM_TRUCK:F.NONE,three:F.TOUCH_TRUCK};const s=new ee.Vector2,i=new ee.Vector2,n=new ee.Vector2,r=g=>{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(),T=g.clientX/S.width,M=g.clientY/S.height;if(T<this._interactiveArea.left||T>this._interactiveArea.right||M<this._interactiveArea.top||M>this._interactiveArea.bottom)return}const _=g.pointerType!=="mouse"?null:(g.buttons&We.LEFT)===We.LEFT?We.LEFT:(g.buttons&We.MIDDLE)===We.MIDDLE?We.MIDDLE:(g.buttons&We.RIGHT)===We.RIGHT?We.RIGHT:null;if(_!==null){const S=this._findPointerByMouseButton(_);S&&this._disposePointer(S)}if((g.buttons&We.LEFT)===We.LEFT&&this._lockedPointer)return;const b={pointerId:g.pointerId,clientX:g.clientX,clientY:g.clientY,deltaX:0,deltaY:0,mouseButton:_};this._activePointers.push(b),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(g)},o=g=>{g.cancelable&&g.preventDefault();const _=g.pointerId,b=this._lockedPointer||this._findPointerById(_);if(b){if(b.clientX=g.clientX,b.clientY=g.clientY,b.deltaX=g.movementX,b.deltaY=g.movementY,this._state=0,g.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&&(g.buttons&We.LEFT)===We.LEFT)&&(this._state=this._state|this.mouseButtons.left),this._isDragging&&(g.buttons&We.MIDDLE)===We.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),this._isDragging&&(g.buttons&We.RIGHT)===We.RIGHT&&(this._state=this._state|this.mouseButtons.right);p()}},l=g=>{const _=this._findPointerById(g.pointerId);if(!(_&&_===this._lockedPointer)){if(_&&this._disposePointer(_),g.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;f()}};let c=-1;const h=g=>{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 M=this._domElement.getBoundingClientRect(),w=g.clientX/M.width,R=g.clientY/M.height;if(w<this._interactiveArea.left||w>this._interactiveArea.right||R<this._interactiveArea.top||R>this._interactiveArea.bottom)return}if(g.preventDefault(),this.dollyToCursor||this.mouseButtons.wheel===F.ROTATE||this.mouseButtons.wheel===F.TRUCK){const M=performance.now();c-M<1e3&&this._getClientRect(this._elementRect),c=M}const _=YR?-1:-3,b=g.deltaMode===1||g.ctrlKey?g.deltaY/_:g.deltaY/(_*10),S=this.dollyToCursor?(g.clientX-this._elementRect.x)/this._elementRect.width*2-1:0,T=this.dollyToCursor?(g.clientY-this._elementRect.y)/this._elementRect.height*-2+1:0;switch(this.mouseButtons.wheel){case F.ROTATE:{this._rotateInternal(g.deltaX,g.deltaY),this._isUserControllingRotate=!0;break}case F.TRUCK:{this._truckInternal(g.deltaX,g.deltaY,!1,!1),this._isUserControllingTruck=!0;break}case F.SCREEN_PAN:{this._truckInternal(g.deltaX,g.deltaY,!1,!0),this._isUserControllingTruck=!0;break}case F.OFFSET:{this._truckInternal(g.deltaX,g.deltaY,!0,!1),this._isUserControllingOffset=!0;break}case F.DOLLY:{this._dollyInternal(-b,S,T),this._isUserControllingDolly=!0;break}case F.ZOOM:{this._zoomInternal(-b,S,T),this._isUserControllingZoom=!0;break}}this.dispatchEvent({type:"control"})},u=g=>{if(!(!this._domElement||!this._enabled)){if(this.mouseButtons.right===Ds.ACTION.NONE){const _=g instanceof PointerEvent?g.pointerId:0,b=this._findPointerById(_);b&&this._disposePointer(b),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l);return}g.preventDefault()}},d=g=>{if(!this._enabled)return;if(qc(this._activePointers,It),this._getClientRect(this._elementRect),s.copy(It),i.copy(It),this._activePointers.length>=2){const b=It.x-this._activePointers[1].clientX,S=It.y-this._activePointers[1].clientY,T=Math.sqrt(b*b+S*S);n.set(0,T);const M=(this._activePointers[0].clientX+this._activePointers[1].clientX)*.5,w=(this._activePointers[0].clientY+this._activePointers[1].clientY)*.5;i.set(M,w)}if(this._state=0,!g)this._lockedPointer&&(this._state=this._state|this.mouseButtons.left);else if("pointerType"in g&&g.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&&(g.buttons&We.LEFT)===We.LEFT&&(this._state=this._state|this.mouseButtons.left),(g.buttons&We.MIDDLE)===We.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),(g.buttons&We.RIGHT)===We.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"})},p=()=>{if(!this._enabled||!this._dragNeedsUpdate)return;this._dragNeedsUpdate=!1,qc(this._activePointers,It);const _=this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement?this._lockedPointer||this._activePointers[0]:null,b=_?-_.deltaX:i.x-It.x,S=_?-_.deltaY:i.y-It.y;if(i.copy(It),((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(b,S),this._isUserControllingRotate=!0),(this._state&F.DOLLY)===F.DOLLY||(this._state&F.ZOOM)===F.ZOOM){const T=this.dollyToCursor?(s.x-this._elementRect.x)/this._elementRect.width*2-1:0,M=this.dollyToCursor?(s.y-this._elementRect.y)/this._elementRect.height*-2+1:0,w=this.dollyDragInverted?-1:1;(this._state&F.DOLLY)===F.DOLLY?(this._dollyInternal(w*S*go,T,M),this._isUserControllingDolly=!0):(this._zoomInternal(w*S*go,T,M),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 T=It.x-this._activePointers[1].clientX,M=It.y-this._activePointers[1].clientY,w=Math.sqrt(T*T+M*M),R=n.y-w;n.set(0,w);const P=this.dollyToCursor?(i.x-this._elementRect.x)/this._elementRect.width*2-1:0,z=this.dollyToCursor?(i.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(R*go,P,z),this._isUserControllingDolly=!0):(this._zoomInternal(R*go,P,z),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(b,S,!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(b,S,!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(b,S,!0,!1),this._isUserControllingOffset=!0),this.dispatchEvent({type:"control"})},f=()=>{qc(this._activePointers,It),i.copy(It),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",y),this._domElement.ownerDocument.addEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",l),d())},this.unlockPointer=()=>{var g,_,b;this._lockedPointer!==null&&(this._disposePointer(this._lockedPointer),this._lockedPointer=null),(g=this._domElement)===null||g===void 0||g.ownerDocument.exitPointerLock(),(_=this._domElement)===null||_===void 0||_.ownerDocument.removeEventListener("pointerlockchange",m),(b=this._domElement)===null||b===void 0||b.ownerDocument.removeEventListener("pointerlockerror",y),this.cancel()};const m=()=>{this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement||this.unlockPointer()},y=()=>{this.unlockPointer()};this._addAllEventListeners=g=>{this._domElement=g,this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none",this._domElement.addEventListener("pointerdown",r),this._domElement.addEventListener("pointercancel",l),this._domElement.addEventListener("wheel",h,{passive:!1}),this._domElement.addEventListener("contextmenu",u)},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",l),this._domElement.removeEventListener("wheel",h,{passive:!1}),this._domElement.removeEventListener("contextmenu",u),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",y))},this.cancel=()=>{this._state!==F.NONE&&(this._state=F.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=gs(e.width,0,1),this._interactiveArea.height=gs(e.height,0,1),this._interactiveArea.x=gs(e.x,0,1-this._interactiveArea.width),this._interactiveArea.y=gs(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=gs(e,this.minAzimuthAngle,this.maxAzimuthAngle),n=gs(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 r=!s||Ce(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Ce(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=Ln.NONE,this._changedDolly=0,this._dollyToNoClamp(gs(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=Ce(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 n=!t||Ce(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(n)}dollyInFixed(e,t=!1){this._targetEnd.add(this._getCameraDirection(Hr).multiplyScalar(e)),t||this._target.copy(this._targetEnd);const s=!t||Ce(this._target.x,this._targetEnd.x,this.restThreshold)&&Ce(this._target.y,this._targetEnd.y,this.restThreshold)&&Ce(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=gs(e,this.minZoom,this.maxZoom),this._needsUpdate=!0,t||(this._zoom=this._zoomEnd);const s=!t||Ce(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(),As.setFromMatrixColumn(this._camera.matrix,0),Rs.setFromMatrixColumn(this._camera.matrix,1),As.multiplyScalar(e),Rs.multiplyScalar(-t);const i=le.copy(As).add(Rs),n=be.copy(this._targetEnd).add(i);return this.moveTo(n.x,n.y,n.z,s)}forward(e,t=!1){le.setFromMatrixColumn(this._camera.matrix,0),le.crossVectors(this._camera.up,le),le.multiplyScalar(e);const s=be.copy(this._targetEnd).add(le);return this.moveTo(s.x,s.y,s.z,t)}elevate(e,t=!1){return le.copy(this._camera.up).multiplyScalar(e),this.moveTo(this._targetEnd.x+le.x,this._targetEnd.y+le.y,this._targetEnd.z+le.z,t)}moveTo(e,t,s,i=!1){this._isUserControllingTruck=!1;const n=le.set(e,t,s).sub(this._targetEnd);this._encloseToBoundary(this._targetEnd,n,this.boundaryFriction),this._needsUpdate=!0,i||this._target.copy(this._targetEnd);const r=!i||Ce(this._target.x,this._targetEnd.x,this.restThreshold)&&Ce(this._target.y,this._targetEnd.y,this.restThreshold)&&Ce(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(r)}lookInDirectionOf(e,t,s,i=!1){const o=le.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:r=0,paddingTop:o=0}={}){const l=[],c=e.isBox3?zn.copy(e):zn.setFromObject(e);c.isEmpty()&&(console.warn("camera-controls: fitTo() cannot be used with an empty box. Aborting"),Promise.resolve());const h=Ff(this._sphericalEnd.theta,Pf),u=Ff(this._sphericalEnd.phi,Pf);l.push(this.rotateTo(h,u,t));const d=le.setFromSpherical(this._sphericalEnd).normalize(),p=Uf.setFromUnitVectors(d,Zc),f=Ce(Math.abs(d.y),1);f&&p.multiply(Kc.setFromAxisAngle(yo,h)),p.multiply(this._yAxisUpSpaceInverse);const m=Lf.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-=r,m.max.x+=n,m.max.y+=o,p.setFromUnitVectors(Zc,d),f&&p.premultiply(Kc.invert()),p.premultiply(this._yAxisUpSpace);const y=m.getSize(le),g=m.getCenter(be).applyQuaternion(p);if(qi(this._camera)){const _=this.getDistanceToFitBox(y.x,y.y,y.z,s);l.push(this.moveTo(g.x,g.y,g.z,t)),l.push(this.dollyTo(_,t)),l.push(this.setFocalOffset(0,0,0,t))}else if(Ti(this._camera)){const _=this._camera,b=_.right-_.left,S=_.top-_.bottom,T=s?Math.max(b/y.x,S/y.y):Math.min(b/y.x,S/y.y);l.push(this.moveTo(g.x,g.y,g.z,t)),l.push(this.zoomTo(T,t)),l.push(this.setFocalOffset(0,0,0,t))}return Promise.all(l)}fitToSphere(e,t){const s=[],n="isObject3D"in e?Ds.createBoundingSphere(e,Qc):Qc.copy(e);if(s.push(this.moveTo(n.center.x,n.center.y,n.center.z,t)),qi(this._camera)){const r=this.getDistanceToFitSphere(n.radius);s.push(this.dollyTo(r,t))}else if(Ti(this._camera)){const r=this._camera.right-this._camera.left,o=this._camera.top-this._camera.bottom,l=2*n.radius,c=Math.min(r/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,r,o=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=Ln.NONE,this._changedDolly=0;const l=be.set(i,n,r),c=le.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 h=!o||Ce(this._target.x,this._targetEnd.x,this.restThreshold)&&Ce(this._target.y,this._targetEnd.y,this.restThreshold)&&Ce(this._target.z,this._targetEnd.z,this.restThreshold)&&Ce(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Ce(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&Ce(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(h)}lerpLookAt(e,t,s,i,n,r,o,l,c,h,u,d,p,f=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=Ln.NONE,this._changedDolly=0;const m=le.set(i,n,r),y=be.set(e,t,s);es.setFromVector3(y.sub(m).applyQuaternion(this._yAxisUpSpace));const g=kn.set(h,u,d),_=be.set(o,l,c);Wr.setFromVector3(_.sub(g).applyQuaternion(this._yAxisUpSpace)),this._targetEnd.copy(m.lerp(g,p));const b=Wr.theta-es.theta,S=Wr.phi-es.phi,T=Wr.radius-es.radius;this._sphericalEnd.set(es.radius+T*p,es.phi+S*p,es.theta+b*p),this.normalizeRotations(),this._needsUpdate=!0,f||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const M=!f||Ce(this._target.x,this._targetEnd.x,this.restThreshold)&&Ce(this._target.y,this._targetEnd.y,this.restThreshold)&&Ce(this._target.z,this._targetEnd.z,this.restThreshold)&&Ce(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Ce(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&Ce(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(M)}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(le),r=this.setLookAt(n.x,n.y,n.z,e,t,s,i);return this._sphericalEnd.phi=gs(this._sphericalEnd.phi,this.minPolarAngle,this.maxPolarAngle),r}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||Ce(this._focalOffset.x,this._focalOffsetEnd.x,this.restThreshold)&&Ce(this._focalOffset.y,this._focalOffsetEnd.y,this.restThreshold)&&Ce(this._focalOffset.z,this._focalOffsetEnd.z,this.restThreshold);return this._createOnRestPromise(n)}setOrbitPoint(e,t,s){this._camera.updateMatrixWorld(),As.setFromMatrixColumn(this._camera.matrixWorldInverse,0),Rs.setFromMatrixColumn(this._camera.matrixWorldInverse,1),Yi.setFromMatrixColumn(this._camera.matrixWorldInverse,2);const i=le.set(e,t,s),n=i.distanceTo(this._camera.position),r=i.sub(this._camera.position);As.multiplyScalar(r.x),Rs.multiplyScalar(r.y),Yi.multiplyScalar(r.z),le.copy(As).add(Rs).add(Yi),le.z=le.z+n,this.dollyTo(n,!1),this.setFocalOffset(-le.x,le.y,-le.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 ee.Vector4,typeof e=="number"?this._viewport.set(e,t,s,i):this._viewport.copy(e)}getDistanceToFitBox(e,t,s,i=!1){if(Yc(this._camera,"getDistanceToFitBox"))return this._spherical.radius;const n=e/t,r=this._camera.getEffectiveFOV()*zr,o=this._camera.aspect;return((i?n>o:n<o)?t:e/o)*.5/Math.tan(r*.5)+s*.5}getDistanceToFitSphere(e){if(Yc(this._camera,"getDistanceToFitSphere"))return this._spherical.radius;const t=this._camera.getEffectiveFOV()*zr,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 ee.Vector3).copy(t?this._targetEnd:this._target)}getPosition(e,t=!0){return(e&&e.isVector3?e:new ee.Vector3).setFromSpherical(t?this._sphericalEnd:this._spherical).applyQuaternion(this._yAxisUpSpaceInverse).add(t?this._targetEnd:this._target)}getSpherical(e,t=!0){return(e||new ee.Spherical).copy(t?this._sphericalEnd:this._spherical)}getFocalOffset(e,t=!0){return(e&&e.isVector3?e:new ee.Vector3).copy(t?this._focalOffsetEnd:this._focalOffset)}normalizeRotations(){this._sphericalEnd.theta=this._sphericalEnd.theta%Un,this._sphericalEnd.theta<0&&(this._sphericalEnd.theta+=Un),this._spherical.theta+=Un*Math.round((this._sphericalEnd.theta-this._spherical.theta)/Un)}stop(){this._focalOffset.copy(this._focalOffsetEnd),this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd),this._zoom=this._zoomEnd}reset(e=!1){if(!Ce(this._camera.up.x,this._cameraUp0.x)||!Ce(this._camera.up.y,this._cameraUp0.y)||!Ce(this._camera.up.z,this._cameraUp0.z)){this._camera.up.copy(this._cameraUp0);const s=this.getPosition(le);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,yo),this._yAxisUpSpaceInverse.copy(this._yAxisUpSpace).invert()}applyCameraUp(){const e=le.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(le);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=Bf.subVectors(this._targetEnd,this._target),r=If.subVectors(this._focalOffsetEnd,this._focalOffset),o=this._zoomEnd-this._zoom;if(Ie(t))this._thetaVelocity.value=0,this._spherical.theta=this._sphericalEnd.theta;else{const u=this._isUserControllingRotate?this.draggingSmoothTime:this.smoothTime;this._spherical.theta=mo(this._spherical.theta,this._sphericalEnd.theta,this._thetaVelocity,u,1/0,e),this._needsUpdate=!0}if(Ie(s))this._phiVelocity.value=0,this._spherical.phi=this._sphericalEnd.phi;else{const u=this._isUserControllingRotate?this.draggingSmoothTime:this.smoothTime;this._spherical.phi=mo(this._spherical.phi,this._sphericalEnd.phi,this._phiVelocity,u,1/0,e),this._needsUpdate=!0}if(Ie(i))this._radiusVelocity.value=0,this._spherical.radius=this._sphericalEnd.radius;else{const u=this._isUserControllingDolly?this.draggingSmoothTime:this.smoothTime;this._spherical.radius=mo(this._spherical.radius,this._sphericalEnd.radius,this._radiusVelocity,u,this.maxSpeed,e),this._needsUpdate=!0}if(Ie(n.x)&&Ie(n.y)&&Ie(n.z))this._targetVelocity.set(0,0,0),this._target.copy(this._targetEnd);else{const u=this._isUserControllingTruck?this.draggingSmoothTime:this.smoothTime;Df(this._target,this._targetEnd,this._targetVelocity,u,this.maxSpeed,e,this._target),this._needsUpdate=!0}if(Ie(r.x)&&Ie(r.y)&&Ie(r.z))this._focalOffsetVelocity.set(0,0,0),this._focalOffset.copy(this._focalOffsetEnd);else{const u=this._isUserControllingOffset?this.draggingSmoothTime:this.smoothTime;Df(this._focalOffset,this._focalOffsetEnd,this._focalOffsetVelocity,u,this.maxSpeed,e,this._focalOffset),this._needsUpdate=!0}if(Ie(o))this._zoomVelocity.value=0,this._zoom=this._zoomEnd;else{const u=this._isUserControllingZoom?this.draggingSmoothTime:this.smoothTime;this._zoom=mo(this._zoom,this._zoomEnd,this._zoomVelocity,u,1/0,e)}if(this.dollyToCursor){if(qi(this._camera)&&this._changedDolly!==0){const u=this._spherical.radius-this._lastDistance,d=this._camera,p=this._getCameraDirection(Hr),f=le.copy(p).cross(d.up).normalize();f.lengthSq()===0&&(f.x=1);const m=be.crossVectors(f,p),y=this._sphericalEnd.radius*Math.tan(d.getEffectiveFOV()*zr*.5),_=(this._sphericalEnd.radius-u-this._sphericalEnd.radius)/this._sphericalEnd.radius,b=kn.copy(this._targetEnd).add(f.multiplyScalar(this._dollyControlCoord.x*y*d.aspect)).add(m.multiplyScalar(this._dollyControlCoord.y*y)),S=le.copy(this._targetEnd).lerp(b,_),T=this._lastDollyDirection===Ln.IN&&this._spherical.radius<=this.minDistance,M=this._lastDollyDirection===Ln.OUT&&this.maxDistance<=this._spherical.radius;if(this.infinityDolly&&(T||M)){this._sphericalEnd.radius-=u,this._spherical.radius-=u;const R=be.copy(p).multiplyScalar(-u);S.add(R)}this._boundary.clampPoint(S,S);const w=be.subVectors(S,this._targetEnd);this._targetEnd.copy(S),this._target.add(w),this._changedDolly-=u,Ie(this._changedDolly)&&(this._changedDolly=0)}else if(Ti(this._camera)&&this._changedZoom!==0){const u=this._zoom-this._lastZoom,d=this._camera,p=le.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=kn.copy(p).add(f.multiplyScalar(-p.dot(d.up))),g=-(this._zoom-u-this._zoom)/this._zoom,_=this._getCameraDirection(Hr),b=this._targetEnd.dot(_),S=le.copy(this._targetEnd).lerp(m,g),T=S.dot(_),M=_.multiplyScalar(T-b);S.sub(M),this._boundary.clampPoint(S,S);const w=be.subVectors(S,this._targetEnd);this._targetEnd.copy(S),this._target.add(w),this._changedZoom-=u,Ie(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),(!Ie(this._focalOffset.x)||!Ie(this._focalOffset.y)||!Ie(this._focalOffset.z))&&(As.setFromMatrixColumn(this._camera.matrix,0),Rs.setFromMatrixColumn(this._camera.matrix,1),Yi.setFromMatrixColumn(this._camera.matrix,2),As.multiplyScalar(this._focalOffset.x),Rs.multiplyScalar(-this._focalOffset.y),Yi.multiplyScalar(this._focalOffset.z),le.copy(As).add(Rs).add(Yi),this._camera.position.add(le),this._camera.updateMatrixWorld()),this._boundaryEnclosesCamera&&this._encloseToBoundary(this._camera.position.copy(this._target),le.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"}),Ie(t,this.restThreshold)&&Ie(s,this.restThreshold)&&Ie(i,this.restThreshold)&&Ie(n.x,this.restThreshold)&&Ie(n.y,this.restThreshold)&&Ie(n.z,this.restThreshold)&&Ie(r.x,this.restThreshold)&&Ie(r.y,this.restThreshold)&&Ie(r.z,this.restThreshold)&&Ie(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:Gr(this.maxDistance),minZoom:this.minZoom,maxZoom:Gr(this.maxZoom),minPolarAngle:this.minPolarAngle,maxPolarAngle:Gr(this.maxPolarAngle),minAzimuthAngle:Gr(this.minAzimuthAngle),maxAzimuthAngle:Gr(this.maxAzimuthAngle),smoothTime:this.smoothTime,draggingSmoothTime:this.draggingSmoothTime,dollySpeed:this.dollySpeed,truckSpeed:this.truckSpeed,dollyToCursor:this.dollyToCursor,target:this._targetEnd.toArray(),position:le.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=Vr(s.maxDistance),this.minZoom=s.minZoom,this.maxZoom=Vr(s.maxZoom),this.minPolarAngle=s.minPolarAngle,this.maxPolarAngle=Vr(s.maxPolarAngle),this.minAzimuthAngle=Vr(s.minAzimuthAngle),this.maxAzimuthAngle=Vr(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),es.setFromVector3(le.fromArray(s.position).sub(this._targetEnd).applyQuaternion(this._yAxisUpSpace)),this.rotateTo(es.theta,es.phi,t),this.dollyTo(es.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",qR),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,kn).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(qi(this._camera)){const e=this._camera,t=e.near,s=e.getEffectiveFOV()*zr,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(Ti(this._camera)){const e=this._camera,t=1/e.zoom,s=e.left*t,i=e.right*t,n=e.top*t,r=e.bottom*t;this._nearPlaneCorners[0].set(s,n,0),this._nearPlaneCorners[1].set(i,n,0),this._nearPlaneCorners[2].set(i,r,0),this._nearPlaneCorners[3].set(s,r,0)}}_collisionTest(){let e=1/0;if(!(this.colliderMeshes.length>=1)||Yc(this._camera,"_collisionTest"))return e;const s=this._getTargetDirection(Hr);Jc.lookAt(Of,s,this._camera.up);for(let i=0;i<4;i++){const n=be.copy(this._nearPlaneCorners[i]);n.applyMatrix4(Jc);const r=kn.addVectors(this._target,n);xo.set(r,s),xo.far=this._spherical.radius+1;const o=xo.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 ee.Sphere){const s=t,i=s.center;zn.makeEmpty(),e.traverseVisible(r=>{r.isMesh&&zn.expandByObject(r)}),zn.getCenter(i);let n=0;return e.traverseVisible(r=>{if(!r.isMesh)return;const o=r;if(!o.geometry)return;const l=o.geometry.clone();l.applyMatrix4(o.matrixWorld);const h=l.attributes.position;for(let u=0,d=h.count;u<d;u++)le.fromBufferAttribute(h,u),n=Math.max(n,i.distanceToSquared(le))}),s.radius=Math.sqrt(n),s}}const il=a=>{const[e,t]=W.useState(a.options[a.index]),s=()=>{a.onToggle(!a.open)},i=n=>{n!==e&&(a.onSelect(n),t(n)),a.onToggle(!1)};return C.jsxs("div",{className:`dropdown ${a.up===!0?"up":""}`,children:[C.jsx("div",{className:"dropdown-toggle",onClick:s,children:`${a.title}: ${e}`}),a.open&&C.jsx("ul",{className:"dropdown-menu",children:a.options.map(n=>C.jsx("li",{onClick:()=>i(n),children:n},n))})]})},Xi=W.forwardRef(function(e,t){const s=["Renderer","Depth","Normals","UVs","Wireframe"],[i,n]=W.useState("Renderer"),[r,o]=W.useState(!1),[l,c]=W.useState(!1),[h,u]=W.useState(!1);return C.jsxs("div",{className:`CameraWindow ${e.name}`,children:[C.jsx("div",{ref:t,className:"clickable",onClick:()=>{h&&u(!1)}}),C.jsxs("div",{className:"options",children:[e.camera!==null&&C.jsx(il,{title:"Camera",index:e.options.indexOf(e.camera.name),open:h,options:e.options,onSelect:e.onSelectCamera,onToggle:d=>{u(d)},up:!0}),C.jsx(il,{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=>{r&&o(!1),c(d)},up:!0})]})]})}),XR=`out vec3 worldPosition;
|
53
486
|
uniform float uDistance;
|
54
487
|
|
55
488
|
void main() {
|
@@ -58,7 +491,7 @@ void main() {
|
|
58
491
|
worldPosition.xz += cameraPosition.xz;
|
59
492
|
|
60
493
|
gl_Position = projectionMatrix * modelViewMatrix * vec4(worldPosition, 1.0);
|
61
|
-
}`,
|
494
|
+
}`,ZR=`out vec4 fragColor;
|
62
495
|
in vec3 worldPosition;
|
63
496
|
uniform float uDivisions;
|
64
497
|
uniform float uScale;
|
@@ -124,7 +557,7 @@ void main() {
|
|
124
557
|
fragColor.a = mix(fragColor.a, baseOpacity * uGridOpacity, nextGrid);
|
125
558
|
|
126
559
|
if (fragColor.a <= 0.0) discard;
|
127
|
-
}`;class
|
560
|
+
}`;class QR extends x.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 x.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:x.GLSL3,side:x.DoubleSide,transparent:!0,name:"InfiniteGrid",vertexShader:XR,fragmentShader:ZR})}}class KR extends x.Mesh{gridMaterial;constructor(e){const t=new QR(e);super(new x.PlaneGeometry,t),this.gridMaterial=t,this.frustumCulled=!1,this.name="InfiniteGridHelper"}update(){this.gridMaterial.needsUpdate=!0}}function eh(a){const[e,t]=W.useState(a.selected),s="toggle"+(e?" selected":"");return C.jsx("button",{className:s,onClick:()=>{const i=!e;t(i),a.onClick(i)},style:{backgroundImage:`url(${a.icon})`,backgroundPositionX:"center",backgroundPositionY:a.top!==void 0?`${a.top}px`:"center",backgroundSize:`${a.width!==void 0?`${a.width}px`:"26px"} ${a.height}px`}},a.name)}const JR=`#include <common>
|
128
561
|
#include <batching_pars_vertex>
|
129
562
|
#include <uv_pars_vertex>
|
130
563
|
#include <color_pars_vertex>
|
@@ -154,7 +587,7 @@ void main() {
|
|
154
587
|
#include <logdepthbuf_vertex>
|
155
588
|
#include <clipping_planes_vertex>
|
156
589
|
#include <worldpos_vertex>
|
157
|
-
}`,
|
590
|
+
}`,eN=`
|
158
591
|
#include <common>
|
159
592
|
#include <uv_pars_fragment>
|
160
593
|
#include <clipping_planes_pars_fragment>
|
@@ -162,4 +595,4 @@ void main() {
|
|
162
595
|
void main() {
|
163
596
|
#include <clipping_planes_fragment>
|
164
597
|
gl_FragColor = vec4(vec3(vUv, 0.0), 1.0);
|
165
|
-
}`;class Ba extends o.ShaderMaterial{constructor(){super({defines:{USE_UV:""},vertexShader:Ha,fragmentShader:Va})}}const ze=new o.Raycaster,ce=new o.Vector3,Le=new o.Vector3,K=new o.Quaternion,as={X:new o.Vector3(1,0,0),Y:new o.Vector3(0,1,0),Z:new o.Vector3(0,0,1)},ci={type:"change"},rs={type:"mouseDown",mode:null},os={type:"mouseUp",mode:null},ls={type:"objectChange"};class Ya extends o.Controls{constructor(e,t=null){super(void 0,t);const s=new Qa(this);this._root=s;const n=new Ka;this._gizmo=n,s.add(n);const r=new $a;this._plane=r,s.add(r);const a=this;function l(S,w){let x=w;Object.defineProperty(a,S,{get:function(){return x!==void 0?x:w},set:function(M){x!==M&&(x=M,r[S]=M,n[S]=M,a.dispatchEvent({type:S+"-changed",value:M}),a.dispatchEvent(ci))}}),a[S]=w,r[S]=w,n[S]=w}l("camera",e),l("object",void 0),l("enabled",!0),l("axis",null),l("mode","translate"),l("translationSnap",null),l("rotationSnap",null),l("scaleSnap",null),l("space","world"),l("size",1),l("dragging",!1),l("showX",!0),l("showY",!0),l("showZ",!0);const c=new o.Vector3,h=new o.Vector3,u=new o.Quaternion,f=new o.Quaternion,m=new o.Vector3,g=new o.Quaternion,E=new o.Vector3,y=new o.Vector3,O=new o.Vector3,_=0,b=new o.Vector3;l("worldPosition",c),l("worldPositionStart",h),l("worldQuaternion",u),l("worldQuaternionStart",f),l("cameraPosition",m),l("cameraQuaternion",g),l("pointStart",E),l("pointEnd",y),l("rotationAxis",O),l("rotationAngle",_),l("eye",b),this._offset=new o.Vector3,this._startNorm=new o.Vector3,this._endNorm=new o.Vector3,this._cameraScale=new o.Vector3,this._parentPosition=new o.Vector3,this._parentQuaternion=new o.Quaternion,this._parentQuaternionInv=new o.Quaternion,this._parentScale=new o.Vector3,this._worldScaleStart=new o.Vector3,this._worldQuaternionInv=new o.Quaternion,this._worldScale=new o.Vector3,this._positionStart=new o.Vector3,this._quaternionStart=new o.Quaternion,this._scaleStart=new o.Vector3,this._getPointer=Ga.bind(this),this._onPointerDown=Za.bind(this),this._onPointerHover=Wa.bind(this),this._onPointerMove=Xa.bind(this),this._onPointerUp=qa.bind(this),t!==null&&this.connect()}connect(){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&&ze.setFromCamera(e,this.camera);const t=hi(this._gizmo.picker[this.mode],ze);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&&ze.setFromCamera(e,this.camera);const t=hi(this._plane,ze,!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,rs.mode=this.mode,this.dispatchEvent(rs)}}pointerMove(e){const t=this.axis,s=this.mode,n=this.object;let r=this.space;if(s==="scale"?r="local":(t==="E"||t==="XYZE"||t==="XYZ")&&(r="world"),n===void 0||t===null||this.dragging===!1||e!==null&&e.button!==-1)return;e!==null&&ze.setFromCamera(e,this.camera);const a=hi(this._plane,ze,!0);if(a){if(this.pointEnd.copy(a.point).sub(this.worldPositionStart),s==="translate")this._offset.copy(this.pointEnd).sub(this.pointStart),r==="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),r==="local"&&t!=="XYZ"?this._offset.applyQuaternion(this._quaternionStart).divide(this._parentScale):this._offset.applyQuaternion(this._parentQuaternionInv).divide(this._parentScale),n.position.copy(this._offset).add(this._positionStart),this.translationSnap&&(r==="local"&&(n.position.applyQuaternion(K.copy(this._quaternionStart).invert()),t.search("X")!==-1&&(n.position.x=Math.round(n.position.x/this.translationSnap)*this.translationSnap),t.search("Y")!==-1&&(n.position.y=Math.round(n.position.y/this.translationSnap)*this.translationSnap),t.search("Z")!==-1&&(n.position.z=Math.round(n.position.z/this.translationSnap)*this.translationSnap),n.position.applyQuaternion(this._quaternionStart)),r==="world"&&(n.parent&&n.position.add(ce.setFromMatrixPosition(n.parent.matrixWorld)),t.search("X")!==-1&&(n.position.x=Math.round(n.position.x/this.translationSnap)*this.translationSnap),t.search("Y")!==-1&&(n.position.y=Math.round(n.position.y/this.translationSnap)*this.translationSnap),t.search("Z")!==-1&&(n.position.z=Math.round(n.position.z/this.translationSnap)*this.translationSnap),n.parent&&n.position.sub(ce.setFromMatrixPosition(n.parent.matrixWorld))));else if(s==="scale"){if(t.search("XYZ")!==-1){let l=this.pointEnd.length()/this.pointStart.length();this.pointEnd.dot(this.pointStart)<0&&(l*=-1),Le.set(l,l,l)}else ce.copy(this.pointStart),Le.copy(this.pointEnd),ce.applyQuaternion(this._worldQuaternionInv),Le.applyQuaternion(this._worldQuaternionInv),Le.divide(ce),t.search("X")===-1&&(Le.x=1),t.search("Y")===-1&&(Le.y=1),t.search("Z")===-1&&(Le.z=1);n.scale.copy(this._scaleStart).multiply(Le),this.scaleSnap&&(t.search("X")!==-1&&(n.scale.x=Math.round(n.scale.x/this.scaleSnap)*this.scaleSnap||this.scaleSnap),t.search("Y")!==-1&&(n.scale.y=Math.round(n.scale.y/this.scaleSnap)*this.scaleSnap||this.scaleSnap),t.search("Z")!==-1&&(n.scale.z=Math.round(n.scale.z/this.scaleSnap)*this.scaleSnap||this.scaleSnap))}else if(s==="rotate"){this._offset.copy(this.pointEnd).sub(this.pointStart);const l=20/this.worldPosition.distanceTo(ce.setFromMatrixPosition(this.camera.matrixWorld));let c=!1;t==="XYZE"?(this.rotationAxis.copy(this._offset).cross(this.eye).normalize(),this.rotationAngle=this._offset.dot(ce.copy(this.rotationAxis).cross(this.eye))*l):(t==="X"||t==="Y"||t==="Z")&&(this.rotationAxis.copy(as[t]),ce.copy(as[t]),r==="local"&&ce.applyQuaternion(this.worldQuaternion),ce.cross(this.eye),ce.length()===0?c=!0:this.rotationAngle=this._offset.dot(ce.normalize())*l),(t==="E"||c)&&(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),r==="local"&&t!=="E"&&t!=="XYZE"?(n.quaternion.copy(this._quaternionStart),n.quaternion.multiply(K.setFromAxisAngle(this.rotationAxis,this.rotationAngle)).normalize()):(this.rotationAxis.applyQuaternion(this._parentQuaternionInv),n.quaternion.copy(K.setFromAxisAngle(this.rotationAxis,this.rotationAngle)),n.quaternion.multiply(this._quaternionStart).normalize())}this.dispatchEvent(ci),this.dispatchEvent(ls)}}pointerUp(e){e!==null&&e.button!==0||(this.dragging&&this.axis!==null&&(os.mode=this.mode,this.dispatchEvent(os)),this.dragging=!1,this.axis=null)}dispose(){this.disconnect(),this.traverse(function(e){e.geometry&&e.geometry.dispose(),e.material&&e.material.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(ci),this.dispatchEvent(ls),this.pointStart.copy(this.pointEnd))}getRaycaster(){return ze}getMode(){return this.mode}setMode(e){this.mode=e}setTranslationSnap(e){this.translationSnap=e}setRotationSnap(e){this.rotationSnap=e}setScaleSnap(e){this.scaleSnap=e}setSize(e){this.size=e}setSpace(e){this.space=e}}function Ga(i){if(this.domElement.ownerDocument.pointerLockElement)return{x:0,y:0,button:i.button};{const e=this.domElement.getBoundingClientRect();return{x:(i.clientX-e.left)/e.width*2-1,y:-(i.clientY-e.top)/e.height*2+1,button:i.button}}}function Wa(i){if(this.enabled)switch(i.pointerType){case"mouse":case"pen":this.pointerHover(this._getPointer(i));break}}function Za(i){this.enabled&&(document.pointerLockElement||this.domElement.setPointerCapture(i.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.pointerHover(this._getPointer(i)),this.pointerDown(this._getPointer(i)))}function Xa(i){this.enabled&&this.pointerMove(this._getPointer(i))}function qa(i){this.enabled&&(this.domElement.releasePointerCapture(i.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.pointerUp(this._getPointer(i)))}function hi(i,e,t){const s=e.intersectObject(i,!0);for(let n=0;n<s.length;n++)if(s[n].object.visible||t)return s[n];return!1}const Dt=new o.Euler,Z=new o.Vector3(0,1,0),cs=new o.Vector3(0,0,0),hs=new o.Matrix4,It=new o.Quaternion,jt=new o.Quaternion,xe=new o.Vector3,ds=new o.Matrix4,gt=new o.Vector3(1,0,0),He=new o.Vector3(0,1,0),_t=new o.Vector3(0,0,1),Lt=new o.Vector3,ut=new o.Vector3,pt=new o.Vector3;class Qa extends o.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)}}class Ka extends o.Object3D{constructor(){super(),this.isTransformControlsGizmo=!0,this.type="TransformControlsGizmo";const e=new o.MeshBasicMaterial({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),t=new o.LineBasicMaterial({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),s=e.clone();s.opacity=.15;const n=t.clone();n.opacity=.5;const r=e.clone();r.color.setHex(16711680);const a=e.clone();a.color.setHex(65280);const l=e.clone();l.color.setHex(255);const c=e.clone();c.color.setHex(16711680),c.opacity=.5;const h=e.clone();h.color.setHex(65280),h.opacity=.5;const u=e.clone();u.color.setHex(255),u.opacity=.5;const f=e.clone();f.opacity=.25;const m=e.clone();m.color.setHex(16776960),m.opacity=.25,e.clone().color.setHex(16776960);const E=e.clone();E.color.setHex(7895160);const y=new o.CylinderGeometry(0,.04,.1,12);y.translate(0,.05,0);const O=new o.BoxGeometry(.08,.08,.08);O.translate(0,.04,0);const _=new o.BufferGeometry;_.setAttribute("position",new o.Float32BufferAttribute([0,0,0,1,0,0],3));const b=new o.CylinderGeometry(.0075,.0075,.5,3);b.translate(0,.25,0);function S(X,Ae){const le=new o.TorusGeometry(X,.0075,3,64,Ae*Math.PI*2);return le.rotateY(Math.PI/2),le.rotateX(Math.PI/2),le}function w(){const X=new o.BufferGeometry;return X.setAttribute("position",new o.Float32BufferAttribute([0,0,0,1,1,1],3)),X}const x={X:[[new o.Mesh(y,r),[.5,0,0],[0,0,-Math.PI/2]],[new o.Mesh(y,r),[-.5,0,0],[0,0,Math.PI/2]],[new o.Mesh(b,r),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new o.Mesh(y,a),[0,.5,0]],[new o.Mesh(y,a),[0,-.5,0],[Math.PI,0,0]],[new o.Mesh(b,a)]],Z:[[new o.Mesh(y,l),[0,0,.5],[Math.PI/2,0,0]],[new o.Mesh(y,l),[0,0,-.5],[-Math.PI/2,0,0]],[new o.Mesh(b,l),null,[Math.PI/2,0,0]]],XYZ:[[new o.Mesh(new o.OctahedronGeometry(.1,0),f.clone()),[0,0,0]]],XY:[[new o.Mesh(new o.BoxGeometry(.15,.15,.01),u.clone()),[.15,.15,0]]],YZ:[[new o.Mesh(new o.BoxGeometry(.15,.15,.01),c.clone()),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new o.Mesh(new o.BoxGeometry(.15,.15,.01),h.clone()),[.15,0,.15],[-Math.PI/2,0,0]]]},M={X:[[new o.Mesh(new o.CylinderGeometry(.2,0,.6,4),s),[.3,0,0],[0,0,-Math.PI/2]],[new o.Mesh(new o.CylinderGeometry(.2,0,.6,4),s),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new o.Mesh(new o.CylinderGeometry(.2,0,.6,4),s),[0,.3,0]],[new o.Mesh(new o.CylinderGeometry(.2,0,.6,4),s),[0,-.3,0],[0,0,Math.PI]]],Z:[[new o.Mesh(new o.CylinderGeometry(.2,0,.6,4),s),[0,0,.3],[Math.PI/2,0,0]],[new o.Mesh(new o.CylinderGeometry(.2,0,.6,4),s),[0,0,-.3],[-Math.PI/2,0,0]]],XYZ:[[new o.Mesh(new o.OctahedronGeometry(.2,0),s)]],XY:[[new o.Mesh(new o.BoxGeometry(.2,.2,.01),s),[.15,.15,0]]],YZ:[[new o.Mesh(new o.BoxGeometry(.2,.2,.01),s),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new o.Mesh(new o.BoxGeometry(.2,.2,.01),s),[.15,0,.15],[-Math.PI/2,0,0]]]},D={START:[[new o.Mesh(new o.OctahedronGeometry(.01,2),n),null,null,null,"helper"]],END:[[new o.Mesh(new o.OctahedronGeometry(.01,2),n),null,null,null,"helper"]],DELTA:[[new o.Line(w(),n),null,null,null,"helper"]],X:[[new o.Line(_,n.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new o.Line(_,n.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new o.Line(_,n.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},k={XYZE:[[new o.Mesh(S(.5,1),E),null,[0,Math.PI/2,0]]],X:[[new o.Mesh(S(.5,.5),r)]],Y:[[new o.Mesh(S(.5,.5),a),null,[0,0,-Math.PI/2]]],Z:[[new o.Mesh(S(.5,.5),l),null,[0,Math.PI/2,0]]],E:[[new o.Mesh(S(.75,1),m),null,[0,Math.PI/2,0]]]},R={AXIS:[[new o.Line(_,n.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]]},V={XYZE:[[new o.Mesh(new o.SphereGeometry(.25,10,8),s)]],X:[[new o.Mesh(new o.TorusGeometry(.5,.1,4,24),s),[0,0,0],[0,-Math.PI/2,-Math.PI/2]]],Y:[[new o.Mesh(new o.TorusGeometry(.5,.1,4,24),s),[0,0,0],[Math.PI/2,0,0]]],Z:[[new o.Mesh(new o.TorusGeometry(.5,.1,4,24),s),[0,0,0],[0,0,-Math.PI/2]]],E:[[new o.Mesh(new o.TorusGeometry(.75,.1,2,24),s)]]},ge={X:[[new o.Mesh(O,r),[.5,0,0],[0,0,-Math.PI/2]],[new o.Mesh(b,r),[0,0,0],[0,0,-Math.PI/2]],[new o.Mesh(O,r),[-.5,0,0],[0,0,Math.PI/2]]],Y:[[new o.Mesh(O,a),[0,.5,0]],[new o.Mesh(b,a)],[new o.Mesh(O,a),[0,-.5,0],[0,0,Math.PI]]],Z:[[new o.Mesh(O,l),[0,0,.5],[Math.PI/2,0,0]],[new o.Mesh(b,l),[0,0,0],[Math.PI/2,0,0]],[new o.Mesh(O,l),[0,0,-.5],[-Math.PI/2,0,0]]],XY:[[new o.Mesh(new o.BoxGeometry(.15,.15,.01),u),[.15,.15,0]]],YZ:[[new o.Mesh(new o.BoxGeometry(.15,.15,.01),c),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new o.Mesh(new o.BoxGeometry(.15,.15,.01),h),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new o.Mesh(new o.BoxGeometry(.1,.1,.1),f.clone())]]},ue={X:[[new o.Mesh(new o.CylinderGeometry(.2,0,.6,4),s),[.3,0,0],[0,0,-Math.PI/2]],[new o.Mesh(new o.CylinderGeometry(.2,0,.6,4),s),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new o.Mesh(new o.CylinderGeometry(.2,0,.6,4),s),[0,.3,0]],[new o.Mesh(new o.CylinderGeometry(.2,0,.6,4),s),[0,-.3,0],[0,0,Math.PI]]],Z:[[new o.Mesh(new o.CylinderGeometry(.2,0,.6,4),s),[0,0,.3],[Math.PI/2,0,0]],[new o.Mesh(new o.CylinderGeometry(.2,0,.6,4),s),[0,0,-.3],[-Math.PI/2,0,0]]],XY:[[new o.Mesh(new o.BoxGeometry(.2,.2,.01),s),[.15,.15,0]]],YZ:[[new o.Mesh(new o.BoxGeometry(.2,.2,.01),s),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new o.Mesh(new o.BoxGeometry(.2,.2,.01),s),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new o.Mesh(new o.BoxGeometry(.2,.2,.2),s),[0,0,0]]]},se={X:[[new o.Line(_,n.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new o.Line(_,n.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new o.Line(_,n.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]};function Q(X){const Ae=new o.Object3D;for(const le in X)for(let fe=X[le].length;fe--;){const te=X[le][fe][0].clone(),Pe=X[le][fe][1],Re=X[le][fe][2],De=X[le][fe][3],G=X[le][fe][4];te.name=le,te.tag=G,Pe&&te.position.set(Pe[0],Pe[1],Pe[2]),Re&&te.rotation.set(Re[0],Re[1],Re[2]),De&&te.scale.set(De[0],De[1],De[2]),te.updateMatrix();const ae=te.geometry.clone();ae.applyMatrix4(te.matrix),te.geometry=ae,te.renderOrder=1/0,te.position.set(0,0,0),te.rotation.set(0,0,0),te.scale.set(1,1,1),Ae.add(te)}return Ae}this.gizmo={},this.picker={},this.helper={},this.add(this.gizmo.translate=Q(x)),this.add(this.gizmo.rotate=Q(k)),this.add(this.gizmo.scale=Q(ge)),this.add(this.picker.translate=Q(M)),this.add(this.picker.rotate=Q(V)),this.add(this.picker.scale=Q(ue)),this.add(this.helper.translate=Q(D)),this.add(this.helper.rotate=Q(R)),this.add(this.helper.scale=Q(se)),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:jt;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 n=[];n=n.concat(this.picker[this.mode].children),n=n.concat(this.gizmo[this.mode].children),n=n.concat(this.helper[this.mode].children);for(let r=0;r<n.length;r++){const a=n[r];a.visible=!0,a.rotation.set(0,0,0),a.position.copy(this.worldPosition);let l;if(this.camera.isOrthographicCamera?l=(this.camera.top-this.camera.bottom)/this.camera.zoom:l=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(l*this.size/4),a.tag==="helper"){a.visible=!1,a.name==="AXIS"?(a.visible=!!this.axis,this.axis==="X"&&(K.setFromEuler(Dt.set(0,0,0)),a.quaternion.copy(s).multiply(K),Math.abs(Z.copy(gt).applyQuaternion(s).dot(this.eye))>.9&&(a.visible=!1)),this.axis==="Y"&&(K.setFromEuler(Dt.set(0,0,Math.PI/2)),a.quaternion.copy(s).multiply(K),Math.abs(Z.copy(He).applyQuaternion(s).dot(this.eye))>.9&&(a.visible=!1)),this.axis==="Z"&&(K.setFromEuler(Dt.set(0,Math.PI/2,0)),a.quaternion.copy(s).multiply(K),Math.abs(Z.copy(_t).applyQuaternion(s).dot(this.eye))>.9&&(a.visible=!1)),this.axis==="XYZE"&&(K.setFromEuler(Dt.set(0,Math.PI/2,0)),Z.copy(this.rotationAxis),a.quaternion.setFromRotationMatrix(hs.lookAt(cs,Z,He)),a.quaternion.multiply(K),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),ce.set(1e-10,1e-10,1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1),ce.applyQuaternion(this.worldQuaternionStart.clone().invert()),a.scale.copy(ce),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(Z.copy(gt).applyQuaternion(s).dot(this.eye))>.99&&(a.scale.set(1e-10,1e-10,1e-10),a.visible=!1),a.name==="Y"&&Math.abs(Z.copy(He).applyQuaternion(s).dot(this.eye))>.99&&(a.scale.set(1e-10,1e-10,1e-10),a.visible=!1),a.name==="Z"&&Math.abs(Z.copy(_t).applyQuaternion(s).dot(this.eye))>.99&&(a.scale.set(1e-10,1e-10,1e-10),a.visible=!1),a.name==="XY"&&Math.abs(Z.copy(_t).applyQuaternion(s).dot(this.eye))<.2&&(a.scale.set(1e-10,1e-10,1e-10),a.visible=!1),a.name==="YZ"&&Math.abs(Z.copy(gt).applyQuaternion(s).dot(this.eye))<.2&&(a.scale.set(1e-10,1e-10,1e-10),a.visible=!1),a.name==="XZ"&&Math.abs(Z.copy(He).applyQuaternion(s).dot(this.eye))<.2&&(a.scale.set(1e-10,1e-10,1e-10),a.visible=!1)):this.mode==="rotate"&&(It.copy(s),Z.copy(this.eye).applyQuaternion(K.copy(s).invert()),a.name.search("E")!==-1&&a.quaternion.setFromRotationMatrix(hs.lookAt(this.eye,cs,He)),a.name==="X"&&(K.setFromAxisAngle(gt,Math.atan2(-Z.y,Z.z)),K.multiplyQuaternions(It,K),a.quaternion.copy(K)),a.name==="Y"&&(K.setFromAxisAngle(He,Math.atan2(Z.x,Z.z)),K.multiplyQuaternions(It,K),a.quaternion.copy(K)),a.name==="Z"&&(K.setFromAxisAngle(_t,Math.atan2(Z.y,Z.x)),K.multiplyQuaternions(It,K),a.quaternion.copy(K))),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||this.axis.split("").some(function(c){return a.name===c}))&&(a.material.color.setHex(16776960),a.material.opacity=1)}super.updateMatrixWorld(e)}}class $a extends o.Mesh{constructor(){super(new o.PlaneGeometry(1e5,1e5,2,2),new o.MeshBasicMaterial({visible:!1,wireframe:!0,side:o.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"),Lt.copy(gt).applyQuaternion(t==="local"?this.worldQuaternion:jt),ut.copy(He).applyQuaternion(t==="local"?this.worldQuaternion:jt),pt.copy(_t).applyQuaternion(t==="local"?this.worldQuaternion:jt),Z.copy(ut),this.mode){case"translate":case"scale":switch(this.axis){case"X":Z.copy(this.eye).cross(Lt),xe.copy(Lt).cross(Z);break;case"Y":Z.copy(this.eye).cross(ut),xe.copy(ut).cross(Z);break;case"Z":Z.copy(this.eye).cross(pt),xe.copy(pt).cross(Z);break;case"XY":xe.copy(pt);break;case"YZ":xe.copy(Lt);break;case"XZ":Z.copy(pt),xe.copy(ut);break;case"XYZ":case"E":xe.set(0,0,0);break}break;case"rotate":default:xe.set(0,0,0)}xe.length()===0?this.quaternion.copy(this.cameraQuaternion):(ds.lookAt(ce.set(0,0,0),xe,Z),this.quaternion.setFromRotationMatrix(ds)),super.updateMatrixWorld(e)}}class he extends o.EventDispatcher{static DRAG_START="Transform::dragStart";static DRAG_END="Transform::dragEnd";static _instance;app;three;activeCamera;controls=new Map;visibility=new Map;setApp(e,t){this.app=e,this.three=t,this.app.addEventListener(P.SET_SCENE,this.setScene)}clear(){for(const e of this.controls.values()){e.detach(),e.disconnect();const t=e.getHelper();Me(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 Ya(this.activeCamera,s),t.getHelper().name=e,t.setSpace("local"),this.controls.set(e,t),this.visibility.set(e,!0),t.addEventListener("mouseDown",()=>{this.dispatchEvent({type:he.DRAG_START})}),t.addEventListener("mouseUp",()=>{this.dispatchEvent({type:he.DRAG_END})}),t.addEventListener("dragging-changed",n=>{oe.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(),Me(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())})}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 he._instance||(he._instance=new he),he._instance}}const Ja=new o.BoxGeometry,di=new o.Vector2;class yi extends o.Object3D{curve=new o.CatmullRomCurve3;line;draggable;curvePos;tension=.5;closed=!1;subdivide=50;curveType;offset=1;lineMaterial;_camera;_curvePercentage=0;_draggableScale=10;_transform;raycaster;draggedMat=new o.MeshBasicMaterial;parentGroup;group;constructor(e,t){const s=new o.Color(qe(.5,1,Math.random()),qe(.5,1,Math.random()),qe(.5,1,Math.random()));super(),this.name=e,this.lineMaterial=new o.LineBasicMaterial({color:s}),this.line=new o.Line(new o.BufferGeometry,this.lineMaterial),this.line.name="line",this.add(this.line),this._camera=t,this.curveType="catmullrom",this.draggedMat.color=s,this.draggable=new o.Object3D,this.draggable.name="draggablePoints",this.add(this.draggable),this.curvePos=new o.Mesh(new o.SphereGeometry(1.5),new o.MeshBasicMaterial({color:s})),this.curvePos.name="curvePos",this.curvePos.scale.setScalar(this._draggableScale),this.curvePos.visible=!1,this.add(this.curvePos),this.raycaster=new o.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),he.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([ye(t.position.x,3),ye(t.position.y,3),ye(t.position.z,3)])}),ms({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])}else this.addPoint(new o.Vector3(-50,0,0),!1),this.addPoint(new o.Vector3(50,0,0))};addPoint=(e,t=!0)=>{const s=this.draggable.children.length,n=new o.Mesh(Ja,this.draggedMat);return n.name=`point_${s}`,n.position.copy(e),n.scale.setScalar(this._draggableScale),this.draggable.add(n),t&&this.updateSpline(),n};addNextPt=()=>{const e=this.draggable.children.length,t=new o.Vector3(qe(-this.offset,this.offset,Math.random()),qe(-this.offset,this.offset,Math.random()),qe(-this.offset,this.offset,Math.random()));e>0&&t.add(this.draggable.children[e-1].position);const s=this.addPoint(t);this._transform?.attach(s),this.group.current?.setField("Current Point",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.group.current?.setField("Current Point",t.position)}Me(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)};updateSpline=()=>{this.curve=new o.CatmullRomCurve3(this.points,this.closed,this.curveType,this.tension),this.line.geometry.setFromPoints(this.getPoints()),this.curvePos.position.copy(this.getPointAt(this._curvePercentage))};onMouseClick=e=>{if(!oe.instance||this._transform&&!this._transform.getHelper().visible)return;const s=oe.instance.currentWindow.current.getBoundingClientRect();di.x=(e.clientX-s.x)/s.width*2-1,di.y=-((e.clientY-s.y)/s.height)*2+1,this.raycaster.setFromCamera(di,this.camera);const n=this.raycaster.intersectObjects(this.draggable.children,!1);if(n.length>0){const r=n[0].object;r!==this._transform?.object&&(this._transform?.attach(r),this.group.current?.setField("Current Point",r.position))}};getPointAt(e){return this.curve.getPointAt(e)}getPoints(){return this.curve.getPoints(this.subdivide)}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))}onUpdateTransform=()=>{if(this._transform?.object&&this.group){const e=this._transform?.object;e.name.search("point")>-1&&this.group.current?.setField("Current Point",e.position)}this.updateSpline()};initDebug(e){const t=this.draggable.children;this.parentGroup=e,this._transform=he.instance.add(this.name),this._transform.camera=this._camera,this._transform.addEventListener("objectChange",this.onUpdateTransform),this._transform.attach(t.length>0?t[t.length-1]:this),oe.instance?.scene.add(this._transform.getHelper());const s=t.length>0?t[t.length-1].position:{x:0,y:0,z:0};this.group=e.addGroup({title:this.name,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:100,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:s}],onUpdate:(n,r)=>{switch(n){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":Me(this);break;case"Current Point":if(this.group.current&&this._transform?.object){const a=this._transform?.object;a.name.search("point")>-1&&(a.position.copy(r),this.updateSpline())}break}}}),this.draggable.children.forEach(n=>{this.debugPoint(n)})}debugPoint=e=>{e.name,e.visible=this.draggable.visible}}let kt=0;class As extends o.Object3D{defaultScale=10;_camera;group=null;app;constructor(e,t){super(),this.name="Spline Editor",this._camera=e,this.app=t,this.app.addEventListener(P.ADD_SPLINE,this.onAddSpline)}initDebug(){this.group=B.addEditorGroup({title:this.name,items:[{type:"button",prop:"New Spline"},{type:"boolean",prop:"Show Points",value:!0},{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"Show Points":this.showPoints(t);break;case"Visible":this.visible=t;break;case"Default Scale":this.defaultScale=t;break}}})}dispose(){this.app.removeEventListener(P.ADD_SPLINE,this.onAddSpline),B.removeEditorGroup(this.name)}addSpline(e){e.draggableScale=this.defaultScale,e.hideTransform(),this.group?.current!==null&&e.initDebug(this.group.current),this.add(e)}createSpline=(e=[])=>{const t=`Spline ${kt+1}`,s=new yi(t,this._camera);return s.addPoints(e),this.addSpline(s),kt++,s};createSplineFromArray=e=>{const t=[];return e.forEach(s=>{t.push(new o.Vector3(s[0],s[1],s[2]))}),this.createSpline(t)};createSplineFromCatmullRom=e=>this.createSpline(e.points);createSplineFromJSON=e=>{const t=this.createSplineFromArray(e.points);return t.name=e.name,t.closed=e.closed,t.subdivide=e.subdivide,t.tension=e.tension,t.type=e.type,t.updateSpline(),t};showPoints=(e=!0)=>{this.children.forEach(t=>{t.showPoints(e)})};onAddSpline=e=>{const t=JSON.parse(e.value),s=`Spline ${kt+1}`,n=[];t.points.forEach(a=>{n.push(new o.Vector3(a[0],a[1],a[2]))});const r=new yi(s,this.camera);r.addPoints(n),this.addSpline(r),kt++};get camera(){return this._camera}set camera(e){this._camera=e,this.children.forEach(t=>{const s=t;s.camera=e})}}const us=["Single","Side by Side","Stacked","Quad"],er="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",tr="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==",ir="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAYAAACpF6WWAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAQ0lEQVQ4jWP8////fwYqAxYozUhFM/8zkaKYWIWkGEq0b0ZdSjQY5i79TyWagRGaTUdzFEEw6lLqGzqwLoVVJ1StpwA9sBwbUqAh5gAAAABJRU5ErkJggg==";class oe extends T.Component{static instance=null;app;scene=new o.Scene;renderer;currentScene;cameras=new Map;controls=new Map;currentCamera;currentWindow;cameraHelpers=new Map;lightHelpers=new Map;helpersContainer=new o.Group;grid=new za;interactionHelper=new o.AxesHelper(25);currentTransform;splineEditor;depthMaterial=new o.MeshDepthMaterial;normalsMaterial=new o.MeshNormalMaterial;uvMaterial=new Ba;wireframeMaterial=new o.MeshBasicMaterial({opacity:.33,transparent:!0,wireframe:!0});playing=!1;rafID=-1;cameraControlsRafID=-1;width=0;height=0;sceneSet=!1;tlCam=null;trCam=null;blCam=null;brCam=null;tlRender="Renderer";trRender="Renderer";blRender="Renderer";brRender="Renderer";cameraVisibility=!0;lightVisibility=!0;gridVisibility=!0;selectedItem=void 0;debugCamera;raycaster=new o.Raycaster;pointer=new o.Vector2;cameraControls=void 0;canvasRef;containerRef;tlWindow;trWindow;blWindow;brWindow;constructor(e){super(e),this.app=e.app,this.canvasRef=T.createRef(),this.containerRef=T.createRef(),this.tlWindow=T.createRef(),this.trWindow=T.createRef(),this.blWindow=T.createRef(),this.brWindow=T.createRef();const t=e.three.app.appID,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 r={Vector2:o.Vector2,Vector3:o.Vector3,Vector4:o.Vector4,Quaternion:o.Quaternion,Matrix4:o.Matrix4,Spherical:o.Spherical,Box3:o.Box3,Sphere:o.Sphere,Raycaster:o.Raycaster};Oe.install({THREE:r}),this.setupScene(),this.setupTools();const a=localStorage.getItem(this.expandedCameraVisibility);a!==null&&(this.cameraVisibility=a==="open"),this.saveExpandedCameraVisibility();const l=localStorage.getItem(this.expandedLightVisibility);l!==null&&(this.lightVisibility=l==="open"),this.saveExpandedLightVisibility();const c=localStorage.getItem(this.expandedGridVisibility);c!==null&&(this.gridVisibility=c==="open"),this.grid.visible=this.gridVisibility,this.saveExpandedGridVisibility(),oe.instance=this}componentDidMount(){this.setupRenderer(),this.enable(),this.assignControls(),this.resize(),this.play(),he.instance.setApp(this.props.app,this.props.three),he.instance.activeCamera=this.debugCamera}componentDidUpdate(e,t,s){t.mode!==this.state.mode&&(this.assignControls(),this.resize())}componentWillUnmount(){this.disable(),B.removeEditorGroup("View Settings")}render(){const e=[];return this.cameras.forEach((t,s)=>{e.push(s)}),p.jsxs("div",{className:"multiview",children:[p.jsx("canvas",{ref:this.canvasRef}),p.jsxs("div",{className:`cameras ${this.state.mode==="Single"||this.state.mode==="Stacked"?"single":""}`,ref:this.containerRef,children:[this.state.mode==="Single"&&p.jsx(p.Fragment,{children:p.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")&&p.jsxs(p.Fragment,{children:[p.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)}}),p.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"&&p.jsxs(p.Fragment,{children:[p.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)}}),p.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)}}),p.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)}}),p.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)}})]})]}),p.jsxs("div",{className:"settings",children:[p.jsx(zt,{title:"View",index:us.indexOf(this.state.mode),options:us,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})}}),p.jsx(zt,{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})}}),p.jsx(li,{name:"cameraHelper",icon:er,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)}}}),p.jsx(li,{name:"lightHelper",icon:tr,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)}}}),p.jsx(li,{name:"gridHelper",icon:ir,selected:this.gridVisibility,height:21,width:21,onClick:t=>{this.gridVisibility=t,this.saveExpandedGridVisibility(),this.grid.visible=t}})]},this.state.lastUpdate)]})}setupRenderer(){this.renderer=new o.WebGLRenderer({canvas:this.canvasRef.current,stencil:!1}),this.renderer.autoClear=!1,this.renderer.shadowMap.enabled=!0,this.renderer.setPixelRatio(devicePixelRatio),this.renderer.setClearColor(0),this.props.three.renderer=this.renderer}setupScene(){this.scene.name="Debug Scene",this.scene.uuid="",this.helpersContainer.name="helpers",this.scene.add(this.helpersContainer),this.grid.position.y=-1,this.helpersContainer.add(this.grid),this.interactionHelper.name="interactionHelper",this.interactionHelper.visible=!1,this.helpersContainer.add(this.interactionHelper);const e=(r,a)=>{const l=new o.OrthographicCamera(-100,100,100,-100,0,3e3);return l.name=r,l.position.copy(a),l.lookAt(0,0,0),this.cameras.set(r,l),l},t=1e3;e("Top",new o.Vector3(0,t,0)),e("Bottom",new o.Vector3(0,-t,0)),e("Left",new o.Vector3(-t,0,0)),e("Right",new o.Vector3(t,0,0)),e("Front",new o.Vector3(0,0,t)),e("Back",new o.Vector3(0,0,-t)),e("Orthographic",new o.Vector3(t,t,t)),e("UI",new o.Vector3),this.debugCamera=new o.PerspectiveCamera(60,1,50,5e3),this.debugCamera.name="Debug",this.debugCamera.position.set(500,500,500),this.debugCamera.lookAt(0,0,0),this.cameras.set("Debug",this.debugCamera),this.currentCamera=this.debugCamera;const s=localStorage,n=this.props.three.app.appID;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"))}setupTools(){this.splineEditor=new As(this.currentCamera,this.app),this.splineEditor.initDebug(),this.scene.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})}update(){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.sceneSet&&this.props.onSceneUpdate(this.currentScene)}draw(){switch(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.app.addEventListener(P.SET_SCENE,this.sceneUpdate),this.app.addEventListener(P.ADD_CAMERA,this.addCamera),this.app.addEventListener(P.REMOVE_CAMERA,this.removeCamera),this.app.addEventListener(P.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.app.removeEventListener(P.SET_SCENE,this.sceneUpdate),this.app.removeEventListener(P.ADD_CAMERA,this.addCamera),this.app.removeEventListener(P.REMOVE_CAMERA,this.removeCamera),this.app.removeEventListener(P.SET_OBJECT,this.onSetSelectedItem)}resize=()=>{this.width=window.innerWidth-300,this.height=window.innerHeight;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.sceneSet&&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 r=s/n;this.cameras.forEach(a=>{a instanceof o.OrthographicCamera?(a.left=s/-2,a.right=s/2,a.top=n/2,a.bottom=n/-2,a.name==="UI"&&(a.position.x=this.width/2,a.position.y=this.height/-2,a.position.z=100),a.updateProjectionMatrix()):a instanceof o.PerspectiveCamera&&(a.aspect=r,a.updateProjectionMatrix()),this.cameraHelpers.get(a.name)?.update()})};sceneUpdate=e=>{this.clearLightHelpers(),this.scene.remove(this.currentScene),Me(this.currentScene);const t=this.props.scenes.get(e.value.name);if(t!==void 0){const s=new t;this.props.onSceneSet!==void 0&&this.props.onSceneSet(s),this.currentScene=s,this.props.three.scene=this.currentScene,this.scene.add(this.currentScene),this.sceneSet=!0,this.addLightHelpers()}};addCamera=e=>{const t=e.value,s=this.props.three.scene?.getObjectByProperty("uuid",t.uuid);if(s!==void 0){const n=s;this.cameras.set(t.name,n);const r=new o.CameraHelper(n);r.visible=this.cameraVisibility,this.cameraHelpers.set(n.name,r),this.scene.add(r),this.setState({lastUpdate:Date.now()})}};removeCamera=e=>{const t=this.cameraHelpers.get(e.value.name);t!==void 0&&(this.scene.remove(t),t.dispose()),this.cameras.delete(e.value.name),this.setState({lastUpdate:Date.now()})};onMouseMove=e=>{const t=new o.Vector2;this.renderer.getSize(t);const s=Math.min(e.clientX,t.x),n=Math.min(e.clientY,t.y);this.pointer.x=Xe(s,0,t.x,-1,1),this.pointer.y=Xe(n,0,t.y,1,-1);const r=t.x/2,a=t.y/2,l=()=>{s<r?this.pointer.x=Xe(s,0,r,-1,1):this.pointer.x=Xe(s,r,t.x,-1,1)},c=()=>{n<a?this.pointer.y=Xe(n,0,a,1,-1):this.pointer.y=Xe(n,a,t.y,1,-1)};switch(this.state.mode){case"Quad":l(),c();break;case"Side by Side":l();break;case"Stacked":c(),c();break}if(this.updateCamera(s,n,r,a),this.state.interactionMode==="Orbit")return;const h=this.raycaster.intersectObjects(this.currentScene.children);h.length>0&&this.interactionHelper.position.copy(h[0].point)};onClick=e=>{if(this.state.interactionMode==="Orbit")return;const t=new o.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 Oe(this.currentCamera,this.currentWindow.current),this.selectedItem instanceof o.Mesh||this.selectedItem instanceof o.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 Oe(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 Oe(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 Oe(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 Oe(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 Oe(this.currentCamera,this.currentWindow.current),this.cameraControls.rotateTo(_i(45),_i(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=this.currentScene.getObjectByProperty("uuid",e.value.uuid),this.selectedItem!==void 0&&(this.currentTransform!==void 0&&(this.currentTransform.removeEventListener("objectChange",this.onUpdateTransform),he.instance.remove(this.currentTransform.getHelper().name)),this.currentTransform=he.instance.add(e.value.name),this.currentTransform.attach(this.selectedItem),this.scene.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),Bt.instance.update())};clearLightHelpers=()=>{this.lightHelpers.forEach(e=>{this.helpersContainer.remove(e),e.dispose()}),this.lightHelpers.clear()};addLightHelpers=()=>{this.currentScene!==void 0&&this.currentScene.traverse(e=>{if(e.type.search("Light")>-1){let t;switch(e.type){case"DirectionalLight":t=new o.DirectionalLightHelper(e,100),t.name=`${e.name}Helper`,t.visible=this.lightVisibility,this.lightHelpers.set(e.name,t),this.helpersContainer.add(t);break;case"HemisphereLight":t=new o.HemisphereLightHelper(e,250),t.name=`${e.name}Helper`,t.visible=this.lightVisibility,this.lightHelpers.set(e.name,t),this.helpersContainer.add(t);break;case"RectAreaLight":t=new ya(e),t.name=`${e.name}Helper`,t.visible=this.lightVisibility,this.lightHelpers.set(e.name,t),this.helpersContainer.add(t);break;case"PointLight":t=new o.PointLightHelper(e,100),t.name=`${e.name}Helper`,t.visible=this.lightVisibility,this.lightHelpers.set(e.name,t),this.helpersContainer.add(t);break;case"SpotLight":t=new o.SpotLightHelper(e),t.name=`${e.name}Helper`,t.visible=this.lightVisibility,this.lightHelpers.set(e.name,t),this.helpersContainer.add(t);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 Ca(e,t);switch(n.enableDamping=!0,n.dampingFactor=.05,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.scene.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.scene.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),he.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 o.Clock;n.start(),this.selectedItem.getWorldPosition(e.target0);const r=()=>{const a=n.getDelta();this.cameraControls&&this.cameraControls.update(a),t&&(e.target.lerp(e.target0,s),e.object.position.lerp(e.position0,s),e.object.zoom=tt(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(r)};r()};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,r,a){switch(r.name){case"Left":case"Right":this.grid.rotation.z=Math.PI/2;break;case"Front":case"Back":this.grid.rotation.x=Math.PI/2;break}this.scene.overrideMaterial=a,this.renderer?.setViewport(e,t,s,n),this.renderer?.setScissor(e,t,s,n),this.renderer?.render(this.scene,r),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);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;this.drawTo(0,r,this.width,n,this.tlCam,e),this.drawTo(0,0,this.width,n,this.trCam,t)}};drawQuad=()=>{const e=this.getSceneOverride(this.tlRender),t=this.getSceneOverride(this.trRender),s=this.getSceneOverride(this.blRender),n=this.getSceneOverride(this.brRender),r=Math.floor(this.width/2),a=Math.floor(this.height/2);let l=0,c=0;c=this.height-a,l=0,this.drawTo(l,c,r,a,this.tlCam,e),l=r,this.drawTo(l,c,r,a,this.trCam,t),c=0,l=0,this.scene.overrideMaterial=s,this.drawTo(l,c,r,a,this.blCam,s),l=r,this.drawTo(l,c,r,a,this.brCam,n)};get appID(){return this.props.three.app.appID}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 Bt extends T.Component{static instance;app;matrix=new o.Matrix4;position=new o.Vector3;rotation=new o.Euler;scale=new o.Vector3;open=!1;constructor(e){super(e),this.app=e.app;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)),Bt.instance=this}update(){if(oe.instance){const e=oe.instance.selectedItem;if(e===void 0)return;this.position.x=ye(e.position.x,3),this.position.y=ye(e.position.y,3),this.position.z=ye(e.position.z,3),this.rotation.copy(e.rotation),this.scale.x=ye(e.scale.x,3),this.scale.y=ye(e.scale.y,3),this.scale.z=ye(e.scale.z,3),this.setState({lastUpdated:Date.now()})}}render(){return p.jsx(be,{app:this.app,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 r=n.getObjectByProperty("uuid",this.props.object.uuid);ee(r,e,s)}};saveExpanded(){localStorage.setItem(this.expandedName,this.open?"open":"closed")}get expandedName(){return`${this.props.three.app.appID}_transform`}}function ps(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 sr(i,e,t){function s(){return`${t.app.appID}_light`}const n=localStorage.getItem(s()),r=n!==null?n==="open":!1;function a(c){localStorage.setItem(s(),c?"open":"closed")}const l=[];if(i.lightInfo!==void 0)for(const c in i.lightInfo){const h=i.lightInfo[c];h!==void 0&&(h.isColor!==void 0?l.push({title:ps(c),prop:c,type:"color",value:h,onChange:(u,f)=>{const m=new o.Color(f);t.updateObject(i.uuid,u,m);const g=t.getScene(i.uuid);if(g!==null){const E=g.getObjectByProperty("uuid",i.uuid);ee(E,u,m)}}}):l.push({title:ps(c),prop:c,type:typeof h,value:h,step:typeof h=="number"?.01:void 0,onChange:(u,f)=>{t.updateObject(i.uuid,u,f);const m=t.getScene(i.uuid);if(m!==null){const g=m.getObjectByProperty("uuid",i.uuid);ee(g,u,f)}}}))}return p.jsx(be,{app:e,title:"Light",items:l,expanded:r,onToggle:c=>{a(c)}})}function nr(i){const e=i.object,t=i.three;function s(){return`${t.app.appID}_animation`}const n=localStorage.getItem(s()),r=n!==null?n==="open":!1;function a(m){localStorage.setItem(s(),m?"open":"closed")}const l=[],c=[];let h=0;e.animations.forEach(m=>{h=Math.max(h,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}]}]})}),l.push({title:"Animations",items:c});let u;const f=t.getScene(e.uuid);if(f!==null){const m=f.getObjectByProperty("uuid",e.uuid);if(m!==void 0){const g=m.mixer;if(g!==void 0){const y=[{title:"Time Scale",type:"range",value:g.timeScale,step:.01,min:-1,max:2,onChange:(O,_)=>{g.timeScale=_,t.updateObject(e.uuid,"mixer.timeScale",_)}}];y.push({title:"Stop All",type:"button",onChange:()=>{g.stopAllAction(),t.requestMethod(e.uuid,"stopAllAction",void 0,"mixer")}}),l.push({title:"Mixer",items:y}),u=new o.SkeletonHelper(m),oe.instance?.scene.add(u)}}}return T.useEffect(()=>()=>{u!==void 0&&Me(u)},[]),p.jsx(be,{app:i.app,title:"Animation",items:l,expanded:r,onToggle:m=>{a(m)}})}const bi={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:[]};let re={...bi};function Ps(i){const[e,t]=T.useState(-1);T.useEffect(()=>{function a(c){re={...c.value},t(Date.now())}function l(){re={...bi},t(Date.now())}return i.app.addEventListener(P.SET_SCENE,l),i.app.addEventListener(P.SET_OBJECT,a),()=>{i.app.removeEventListener(P.SET_SCENE,l),i.app.removeEventListener(P.SET_OBJECT,a)}},[]);const s=re.type.toLowerCase(),n=re.animations.length>0||re.mixer!==void 0,r=s.search("mesh")>-1||s.search("line")>-1||s.search("points")>-1;return p.jsx(Ct,{app:i.app,label:"Inspector",button:re.uuid.length>0?p.jsx("button",{className:"remove",onClick:()=>{he.instance.remove(re.name),re={...bi},t(Date.now())}}):void 0,children:p.jsx("div",{id:"Inspector",className:i.class,children:re.uuid.length>0&&p.jsxs(p.Fragment,{children:[p.jsxs(p.Fragment,{children:[p.jsx(Ut,{type:"string",title:"Name",prop:"name",value:re.name,disabled:!0}),p.jsx(Ut,{type:"string",title:"Type",prop:"type",value:re.type,disabled:!0}),p.jsx(Ut,{type:"string",title:"UUID",prop:"uuid",value:re.uuid,disabled:!0})]}),p.jsxs(p.Fragment,{children:[p.jsx(Bt,{object:re,app:i.app,three:i.three}),n?p.jsx(nr,{app:i.app,object:re,three:i.three}):null,s.search("camera")>-1?va(re,i.app,i.three):null,s.search("light")>-1?sr(re,i.app,i.three):null,r?fa(re,i.app,i.three):null]})]})},e)},"Inspector")}class ar extends T.Component{app;autoClear=!0;autoClearColor=!0;autoClearDepth=!0;autoClearStencil=!0;outputColorSpace=o.SRGBColorSpace;localClippingEnabled=!1;clearColor=new o.Color(0);clearAlpha=1;toneMapping=o.NoToneMapping;toneMappingExposure=1;constructor(e){super(e),this.app=e.app;const t=localStorage.getItem(this.expandedName),s=t!==null?t==="open":!1;if(this.state={expanded:s,lastUpdated:Date.now()},this.saveExpanded(s),oe.instance){const n=oe.instance.renderer;n&&(this.autoClear=n.autoClear,this.autoClearColor=n.autoClearColor,this.autoClearDepth=n.autoClearDepth,this.autoClearStencil=n.autoClearStencil,this.outputColorSpace=n.outputColorSpace,this.localClippingEnabled=n.localClippingEnabled,this.clearAlpha=n.getClearAlpha(),this.toneMapping=n.toneMapping,this.toneMappingExposure=n.toneMappingExposure,n.getClearColor(this.clearColor))}this.app.addEventListener(P.ADD_RENDERER,this.onAddRenderer)}componentwillunmount(){this.app.removeEventListener(P.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.toneMapping=t.toneMapping,this.toneMappingExposure=t.toneMappingExposure,this.clearColor.setStyle(t.clearColor,o.LinearSRGBColorSpace),o.ColorManagement.enabled=t.colorManagement,oe.instance){const s=oe.instance.renderer;s&&(s.autoClear=this.autoClear,s.autoClearColor=this.autoClearColor,s.autoClearDepth=this.autoClearDepth,s.autoClearStencil=this.autoClearStencil,s.outputColorSpace=this.outputColorSpace,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(oe.instance){const t=oe.instance.renderer;t&&(t.autoClear=this.autoClear,t.autoClearColor=this.autoClearColor,t.autoClearDepth=this.autoClearDepth,t.autoClearStencil=this.autoClearStencil,t.outputColorSpace=this.outputColorSpace,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:o.ColorManagement.enabled,toneMapping:this.toneMapping,toneMappingExposure:this.toneMappingExposure}))}};return p.jsx(be,{app:this.app,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:"Clear Management",value:o.ColorManagement.enabled,onChange:(t,s)=>{o.ColorManagement.enabled=s,e()}},{type:"option",title:"Color Space",value:this.outputColorSpace,options:[{title:"No Color Space",value:o.NoColorSpace},{title:"SRB Color Space",value:o.SRGBColorSpace},{title:"Linear SRB Color Space",value:o.LinearSRGBColorSpace}],onChange:(t,s)=>{this.outputColorSpace=s,e()}},{type:"option",title:"Tone Mapping",value:this.toneMapping,options:[{title:"None ",value:o.NoToneMapping},{title:"Linear ",value:o.LinearToneMapping},{title:"Reinhard",value:o.ReinhardToneMapping},{title:"Cineon ",value:o.CineonToneMapping},{title:"ACES Filmic",value:o.ACESFilmicToneMapping},{title:"AgX",value:o.AgXToneMapping},{title:"Neutral",value:o.NeutralToneMapping},{title:"Custom",value:o.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()}}],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.app.appID}_renderer`}}function Rs(i){const[e]=T.useState([]),[t]=T.useState([]),[s,n]=T.useState(0),r=c=>{const h=c.value;e.push(h),t.push(p.jsx(Ct,{app:i.app,label:`Scene: ${h.name}`,scene:h,open:!0,onRefresh:()=>{i.three.refreshScene(h.name)},children:p.jsx(gi,{app:i.app,child:h,scene:h,three:i.three})},Math.random())),n(Date.now())},a=c=>{const h=c.value;for(let u=0;u<e.length;u++)if(h.uuid===e[u].uuid){e[u]=h,t[u]=p.jsx(Ct,{app:i.app,label:`Scene: ${h.name}`,scene:h,open:!0,onRefresh:()=>{i.three.refreshScene(h.name)},children:p.jsx(gi,{app:i.app,child:h,scene:h,three:i.three})},Math.random()),n(Date.now());return}},l=c=>{const h=c.value;for(let u=0;u<e.length;u++)if(h.uuid===e[u].uuid){e.splice(u,1),t.splice(u,1),n(Date.now());return}};return T.useEffect(()=>(i.app.addEventListener(P.ADD_SCENE,r),i.app.addEventListener(P.REFRESH_SCENE,a),i.app.addEventListener(P.REMOVE_SCENE,l),()=>{i.app.removeEventListener(P.ADD_SCENE,r),i.app.removeEventListener(P.REFRESH_SCENE,a),i.app.removeEventListener(P.REMOVE_SCENE,l)}),[]),p.jsxs("div",{id:"SidePanel",children:[p.jsx("div",{className:"scenes",children:t},s),p.jsx(Ps,{app:i.app,three:i.three}),p.jsx(ar,{app:i.app,three:i.three}),p.jsx(B,{app:i.app,three:i.three})]})}function rr(i){return T.useEffect(()=>{function e(l){let c=null;return i.three.scenes.forEach(h=>{l.search(h.uuid)>-1&&(c=h)}),c}const t=l=>{const c=l.value,u=e(c)?.getObjectByProperty("uuid",c);u!==void 0&&i.three.setObject(u)},s=(l,c,h)=>{const f=e(l)?.getObjectByProperty("uuid",l);f!==void 0&&ee(f,c,h)},n=l=>{const c=l.value,{key:h,value:u,uuid:f}=c;s(f,h,u)},r=l=>{const c=l.value,u=e(c.uuid)?.getObjectByProperty("uuid",c.uuid);if(u!==void 0){const f=m=>{const g=c.key.split(".");switch(g.length){case 1:u[g[0]]=m;break;case 2:u[g[0]][g[1]]=m;break;case 3:u[g[0]][g[1]][g[2]]=m;break;case 4:u[g[0]][g[1]][g[2]][g[3]]=m;break;case 5:u[g[0]][g[1]][g[2]][g[3]][g[4]]=m;break}u.material.needsUpdate=!0};c.value.src.length>0?Cs(c.value.src).then(m=>{m.offset.set(c.value.offset[0],c.value.offset[1]),m.repeat.set(c.value.repeat[0],c.value.repeat[1]),f(m)}):f(null)}},a=l=>{const{key:c,uuid:h,value:u,subitem:f}=l.value,g=e(h)?.getObjectByProperty("uuid",h);if(g!==void 0)try{f!==void 0?Bn(g,f)[c](u):g[c](u)}catch(E){console.log("Error requesting method:"),console.log(E),console.log(c),console.log(u)}};return i.app.addEventListener(P.GET_OBJECT,t),i.app.addEventListener(P.UPDATE_OBJECT,n),i.app.addEventListener(P.CREATE_TEXTURE,r),i.app.addEventListener(P.REQUEST_METHOD,a),()=>{i.app.removeEventListener(P.GET_OBJECT,t),i.app.removeEventListener(P.UPDATE_OBJECT,n),i.app.removeEventListener(P.CREATE_TEXTURE,r),i.app.removeEventListener(P.REQUEST_METHOD,a)}},[]),null}function Ds(i){return p.jsxs("div",{className:"editor",ref:i.ref,style:i.style,children:[p.jsx("div",{className:"header",children:i.header}),i.children,p.jsx("div",{className:"footer",children:i.footer})]})}function or(i){return p.jsx(Ds,{children:p.jsxs(p.Fragment,{children:[p.jsx(oe,{app:i.app,three:i.three,scenes:i.scenes,onSceneResize:i.onSceneResize,onSceneSet:i.onSceneSet,onSceneUpdate:i.onSceneUpdate}),p.jsx(Rs,{app:i.app,three:i.three})]})})}exports.Accordion=Ct;exports.AppRunner=Dn;exports.Application=Rn;exports.BaseRemote=Ht;exports.BaseScene=In;exports.ChildObject=wi;exports.ContainerObject=gi;exports.Draggable=Ss;exports.DraggableItem=Es;exports.Dropdown=ws;exports.DropdownItem=xs;exports.Editor=Ds;exports.ElementProxy=An;exports.ElementProxyReceiver=bs;exports.ExportTexture=vt;exports.Inspector=Ps;exports.MultiView=oe;exports.NavButton=Si;exports.ProxyManager=Pn;exports.QualityType=vs;exports.RemoteComponents=Ln;exports.RemoteTheatre=Fn;exports.RemoteThree=Gn;exports.SceneInspector=rr;exports.SidePanel=Rs;exports.Spline=yi;exports.SplineEditor=As;exports.ThreeEditor=or;exports.ToolEvents=P;exports.Transform=he;exports.WebworkerEventHandlers=On;exports.capitalize=bt;exports.clamp=Ue;exports.colorToHex=ui;exports.copyToClipboard=ms;exports.cubicBezier=vn;exports.customizeTheatreElements=Un;exports.damp=un;exports.defaultTheatreCallback=sn;exports.detectMaxFrameRate=ys;exports.detectSettings=cn;exports.dispose=Me;exports.disposeMaterial=Ci;exports.disposeTexture=pi;exports.distance=dn;exports.hierarchyUUID=Ft;exports.isColor=gs;exports.map=hn;exports.mix=tt;exports.noop=yt;exports.normalize=Nt;exports.parseModelLite=yn;exports.randomID=fs;exports.resetThreeObjects=mi;exports.round=ye;exports.roundTo=pn;exports.theatreEditorApp=kn;
|
598
|
+
}`;class tN extends x.ShaderMaterial{constructor(){super({defines:{USE_UV:""},vertexShader:JR,fragmentShader:eN})}}const Zi=new x.Raycaster,yt=new x.Vector3,bi=new x.Vector3,Ve=new x.Quaternion,kf={X:new x.Vector3(1,0,0),Y:new x.Vector3(0,1,0),Z:new x.Vector3(0,0,1)},th={type:"change"},zf={type:"mouseDown",mode:null},Gf={type:"mouseUp",mode:null},Vf={type:"objectChange"};class sN extends x.Controls{constructor(e,t=null){super(void 0,t);const s=new lN(this);this._root=s;const i=new cN;this._gizmo=i,s.add(i);const n=new hN;this._plane=n,s.add(n);const r=this;function o(b,S){let T=S;Object.defineProperty(r,b,{get:function(){return T!==void 0?T:S},set:function(M){T!==M&&(T=M,n[b]=M,i[b]=M,r.dispatchEvent({type:b+"-changed",value:M}),r.dispatchEvent(th))}}),r[b]=S,n[b]=S,i[b]=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 x.Vector3,c=new x.Vector3,h=new x.Quaternion,u=new x.Quaternion,d=new x.Vector3,p=new x.Quaternion,f=new x.Vector3,m=new x.Vector3,y=new x.Vector3,g=0,_=new x.Vector3;o("worldPosition",l),o("worldPositionStart",c),o("worldQuaternion",h),o("worldQuaternionStart",u),o("cameraPosition",d),o("cameraQuaternion",p),o("pointStart",f),o("pointEnd",m),o("rotationAxis",y),o("rotationAngle",g),o("eye",_),this._offset=new x.Vector3,this._startNorm=new x.Vector3,this._endNorm=new x.Vector3,this._cameraScale=new x.Vector3,this._parentPosition=new x.Vector3,this._parentQuaternion=new x.Quaternion,this._parentQuaternionInv=new x.Quaternion,this._parentScale=new x.Vector3,this._worldScaleStart=new x.Vector3,this._worldQuaternionInv=new x.Quaternion,this._worldScale=new x.Vector3,this._positionStart=new x.Vector3,this._quaternionStart=new x.Quaternion,this._scaleStart=new x.Vector3,this._getPointer=iN.bind(this),this._onPointerDown=rN.bind(this),this._onPointerHover=nN.bind(this),this._onPointerMove=aN.bind(this),this._onPointerUp=oN.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&&Zi.setFromCamera(e,this.camera);const t=sh(this._gizmo.picker[this.mode],Zi);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&&Zi.setFromCamera(e,this.camera);const t=sh(this._plane,Zi,!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,zf.mode=this.mode,this.dispatchEvent(zf)}}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&&Zi.setFromCamera(e,this.camera);const r=sh(this._plane,Zi,!0);if(r){if(this.pointEnd.copy(r.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(Ve.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(yt.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(yt.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),bi.set(o,o,o)}else yt.copy(this.pointStart),bi.copy(this.pointEnd),yt.applyQuaternion(this._worldQuaternionInv),bi.applyQuaternion(this._worldQuaternionInv),bi.divide(yt),t.search("X")===-1&&(bi.x=1),t.search("Y")===-1&&(bi.y=1),t.search("Z")===-1&&(bi.z=1);i.scale.copy(this._scaleStart).multiply(bi),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(yt.setFromMatrixPosition(this.camera.matrixWorld));let l=!1;t==="XYZE"?(this.rotationAxis.copy(this._offset).cross(this.eye).normalize(),this.rotationAngle=this._offset.dot(yt.copy(this.rotationAxis).cross(this.eye))*o):(t==="X"||t==="Y"||t==="Z")&&(this.rotationAxis.copy(kf[t]),yt.copy(kf[t]),n==="local"&&yt.applyQuaternion(this.worldQuaternion),yt.cross(this.eye),yt.length()===0?l=!0:this.rotationAngle=this._offset.dot(yt.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(Ve.setFromAxisAngle(this.rotationAxis,this.rotationAngle)).normalize()):(this.rotationAxis.applyQuaternion(this._parentQuaternionInv),i.quaternion.copy(Ve.setFromAxisAngle(this.rotationAxis,this.rotationAngle)),i.quaternion.multiply(this._quaternionStart).normalize())}this.dispatchEvent(th),this.dispatchEvent(Vf)}}pointerUp(e){e!==null&&e.button!==0||(this.dragging&&this.axis!==null&&(Gf.mode=this.mode,this.dispatchEvent(Gf)),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(th),this.dispatchEvent(Vf),this.pointStart.copy(this.pointEnd))}getRaycaster(){return Zi}getMode(){return this.mode}setMode(e){this.mode=e}setTranslationSnap(e){this.translationSnap=e}setRotationSnap(e){this.rotationSnap=e}setScaleSnap(e){this.scaleSnap=e}setSize(e){this.size=e}setSpace(e){this.space=e}}function iN(a){if(this.domElement.ownerDocument.pointerLockElement)return{x:0,y:0,button:a.button};{const e=this.domElement.getBoundingClientRect();return{x:(a.clientX-e.left)/e.width*2-1,y:-(a.clientY-e.top)/e.height*2+1,button:a.button}}}function nN(a){if(this.enabled)switch(a.pointerType){case"mouse":case"pen":this.pointerHover(this._getPointer(a));break}}function rN(a){this.enabled&&(document.pointerLockElement||this.domElement.setPointerCapture(a.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.pointerHover(this._getPointer(a)),this.pointerDown(this._getPointer(a)))}function aN(a){this.enabled&&this.pointerMove(this._getPointer(a))}function oN(a){this.enabled&&(this.domElement.releasePointerCapture(a.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.pointerUp(this._getPointer(a)))}function sh(a,e,t){const s=e.intersectObject(a,!0);for(let i=0;i<s.length;i++)if(s[i].object.visible||t)return s[i];return!1}const _o=new x.Euler,De=new x.Vector3(0,1,0),Hf=new x.Vector3(0,0,0),Wf=new x.Matrix4,bo=new x.Quaternion,Oo=new x.Quaternion,Ns=new x.Vector3,$f=new x.Matrix4,ea=new x.Vector3(1,0,0),tn=new x.Vector3(0,1,0),ta=new x.Vector3(0,0,1),To=new x.Vector3,$r=new x.Vector3,jr=new x.Vector3;class lN extends x.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 cN extends x.Object3D{constructor(){super(),this.isTransformControlsGizmo=!0,this.type="TransformControlsGizmo";const e=new x.MeshBasicMaterial({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),t=new x.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 r=e.clone();r.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 h=e.clone();h.color.setHex(255),h.opacity=.5;const u=e.clone();u.opacity=.25;const d=e.clone();d.color.setHex(16776960),d.opacity=.25,e.clone().color.setHex(16776960);const f=e.clone();f.color.setHex(7895160);const m=new x.CylinderGeometry(0,.04,.1,12);m.translate(0,.05,0);const y=new x.BoxGeometry(.08,.08,.08);y.translate(0,.04,0);const g=new x.BufferGeometry;g.setAttribute("position",new x.Float32BufferAttribute([0,0,0,1,0,0],3));const _=new x.CylinderGeometry(.0075,.0075,.5,3);_.translate(0,.25,0);function b(Z,ve){const ue=new x.TorusGeometry(Z,.0075,3,64,ve*Math.PI*2);return ue.rotateY(Math.PI/2),ue.rotateX(Math.PI/2),ue}function S(){const Z=new x.BufferGeometry;return Z.setAttribute("position",new x.Float32BufferAttribute([0,0,0,1,1,1],3)),Z}const T={X:[[new x.Mesh(m,n),[.5,0,0],[0,0,-Math.PI/2]],[new x.Mesh(m,n),[-.5,0,0],[0,0,Math.PI/2]],[new x.Mesh(_,n),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new x.Mesh(m,r),[0,.5,0]],[new x.Mesh(m,r),[0,-.5,0],[Math.PI,0,0]],[new x.Mesh(_,r)]],Z:[[new x.Mesh(m,o),[0,0,.5],[Math.PI/2,0,0]],[new x.Mesh(m,o),[0,0,-.5],[-Math.PI/2,0,0]],[new x.Mesh(_,o),null,[Math.PI/2,0,0]]],XYZ:[[new x.Mesh(new x.OctahedronGeometry(.1,0),u.clone()),[0,0,0]]],XY:[[new x.Mesh(new x.BoxGeometry(.15,.15,.01),h.clone()),[.15,.15,0]]],YZ:[[new x.Mesh(new x.BoxGeometry(.15,.15,.01),l.clone()),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new x.Mesh(new x.BoxGeometry(.15,.15,.01),c.clone()),[.15,0,.15],[-Math.PI/2,0,0]]]},M={X:[[new x.Mesh(new x.CylinderGeometry(.2,0,.6,4),s),[.3,0,0],[0,0,-Math.PI/2]],[new x.Mesh(new x.CylinderGeometry(.2,0,.6,4),s),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new x.Mesh(new x.CylinderGeometry(.2,0,.6,4),s),[0,.3,0]],[new x.Mesh(new x.CylinderGeometry(.2,0,.6,4),s),[0,-.3,0],[0,0,Math.PI]]],Z:[[new x.Mesh(new x.CylinderGeometry(.2,0,.6,4),s),[0,0,.3],[Math.PI/2,0,0]],[new x.Mesh(new x.CylinderGeometry(.2,0,.6,4),s),[0,0,-.3],[-Math.PI/2,0,0]]],XYZ:[[new x.Mesh(new x.OctahedronGeometry(.2,0),s)]],XY:[[new x.Mesh(new x.BoxGeometry(.2,.2,.01),s),[.15,.15,0]]],YZ:[[new x.Mesh(new x.BoxGeometry(.2,.2,.01),s),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new x.Mesh(new x.BoxGeometry(.2,.2,.01),s),[.15,0,.15],[-Math.PI/2,0,0]]]},w={START:[[new x.Mesh(new x.OctahedronGeometry(.01,2),i),null,null,null,"helper"]],END:[[new x.Mesh(new x.OctahedronGeometry(.01,2),i),null,null,null,"helper"]],DELTA:[[new x.Line(S(),i),null,null,null,"helper"]],X:[[new x.Line(g,i.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new x.Line(g,i.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new x.Line(g,i.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},R={XYZE:[[new x.Mesh(b(.5,1),f),null,[0,Math.PI/2,0]]],X:[[new x.Mesh(b(.5,.5),n)]],Y:[[new x.Mesh(b(.5,.5),r),null,[0,0,-Math.PI/2]]],Z:[[new x.Mesh(b(.5,.5),o),null,[0,Math.PI/2,0]]],E:[[new x.Mesh(b(.75,1),d),null,[0,Math.PI/2,0]]]},P={AXIS:[[new x.Line(g,i.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]]},z={XYZE:[[new x.Mesh(new x.SphereGeometry(.25,10,8),s)]],X:[[new x.Mesh(new x.TorusGeometry(.5,.1,4,24),s),[0,0,0],[0,-Math.PI/2,-Math.PI/2]]],Y:[[new x.Mesh(new x.TorusGeometry(.5,.1,4,24),s),[0,0,0],[Math.PI/2,0,0]]],Z:[[new x.Mesh(new x.TorusGeometry(.5,.1,4,24),s),[0,0,0],[0,0,-Math.PI/2]]],E:[[new x.Mesh(new x.TorusGeometry(.75,.1,2,24),s)]]},$={X:[[new x.Mesh(y,n),[.5,0,0],[0,0,-Math.PI/2]],[new x.Mesh(_,n),[0,0,0],[0,0,-Math.PI/2]],[new x.Mesh(y,n),[-.5,0,0],[0,0,Math.PI/2]]],Y:[[new x.Mesh(y,r),[0,.5,0]],[new x.Mesh(_,r)],[new x.Mesh(y,r),[0,-.5,0],[0,0,Math.PI]]],Z:[[new x.Mesh(y,o),[0,0,.5],[Math.PI/2,0,0]],[new x.Mesh(_,o),[0,0,0],[Math.PI/2,0,0]],[new x.Mesh(y,o),[0,0,-.5],[-Math.PI/2,0,0]]],XY:[[new x.Mesh(new x.BoxGeometry(.15,.15,.01),h),[.15,.15,0]]],YZ:[[new x.Mesh(new x.BoxGeometry(.15,.15,.01),l),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new x.Mesh(new x.BoxGeometry(.15,.15,.01),c),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new x.Mesh(new x.BoxGeometry(.1,.1,.1),u.clone())]]},q={X:[[new x.Mesh(new x.CylinderGeometry(.2,0,.6,4),s),[.3,0,0],[0,0,-Math.PI/2]],[new x.Mesh(new x.CylinderGeometry(.2,0,.6,4),s),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new x.Mesh(new x.CylinderGeometry(.2,0,.6,4),s),[0,.3,0]],[new x.Mesh(new x.CylinderGeometry(.2,0,.6,4),s),[0,-.3,0],[0,0,Math.PI]]],Z:[[new x.Mesh(new x.CylinderGeometry(.2,0,.6,4),s),[0,0,.3],[Math.PI/2,0,0]],[new x.Mesh(new x.CylinderGeometry(.2,0,.6,4),s),[0,0,-.3],[-Math.PI/2,0,0]]],XY:[[new x.Mesh(new x.BoxGeometry(.2,.2,.01),s),[.15,.15,0]]],YZ:[[new x.Mesh(new x.BoxGeometry(.2,.2,.01),s),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new x.Mesh(new x.BoxGeometry(.2,.2,.01),s),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new x.Mesh(new x.BoxGeometry(.2,.2,.2),s),[0,0,0]]]},j={X:[[new x.Line(g,i.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new x.Line(g,i.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new x.Line(g,i.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]};function X(Z){const ve=new x.Object3D;for(const ue in Z)for(let ge=Z[ue].length;ge--;){const ie=Z[ue][ge][0].clone(),we=Z[ue][ge][1],ke=Z[ue][ge][2],nt=Z[ue][ge][3],_e=Z[ue][ge][4];ie.name=ue,ie.tag=_e,we&&ie.position.set(we[0],we[1],we[2]),ke&&ie.rotation.set(ke[0],ke[1],ke[2]),nt&&ie.scale.set(nt[0],nt[1],nt[2]),ie.updateMatrix();const rt=ie.geometry.clone();rt.applyMatrix4(ie.matrix),ie.geometry=rt,ie.renderOrder=1/0,ie.position.set(0,0,0),ie.rotation.set(0,0,0),ie.scale.set(1,1,1),ve.add(ie)}return ve}this.gizmo={},this.picker={},this.helper={},this.add(this.gizmo.translate=X(T)),this.add(this.gizmo.rotate=X(R)),this.add(this.gizmo.scale=X($)),this.add(this.picker.translate=X(M)),this.add(this.picker.rotate=X(z)),this.add(this.picker.scale=X(q)),this.add(this.helper.translate=X(w)),this.add(this.helper.rotate=X(P)),this.add(this.helper.scale=X(j)),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:Oo;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 r=i[n];r.visible=!0,r.rotation.set(0,0,0),r.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),r.scale.set(1,1,1).multiplyScalar(o*this.size/4),r.tag==="helper"){r.visible=!1,r.name==="AXIS"?(r.visible=!!this.axis,this.axis==="X"&&(Ve.setFromEuler(_o.set(0,0,0)),r.quaternion.copy(s).multiply(Ve),Math.abs(De.copy(ea).applyQuaternion(s).dot(this.eye))>.9&&(r.visible=!1)),this.axis==="Y"&&(Ve.setFromEuler(_o.set(0,0,Math.PI/2)),r.quaternion.copy(s).multiply(Ve),Math.abs(De.copy(tn).applyQuaternion(s).dot(this.eye))>.9&&(r.visible=!1)),this.axis==="Z"&&(Ve.setFromEuler(_o.set(0,Math.PI/2,0)),r.quaternion.copy(s).multiply(Ve),Math.abs(De.copy(ta).applyQuaternion(s).dot(this.eye))>.9&&(r.visible=!1)),this.axis==="XYZE"&&(Ve.setFromEuler(_o.set(0,Math.PI/2,0)),De.copy(this.rotationAxis),r.quaternion.setFromRotationMatrix(Wf.lookAt(Hf,De,tn)),r.quaternion.multiply(Ve),r.visible=this.dragging),this.axis==="E"&&(r.visible=!1)):r.name==="START"?(r.position.copy(this.worldPositionStart),r.visible=this.dragging):r.name==="END"?(r.position.copy(this.worldPosition),r.visible=this.dragging):r.name==="DELTA"?(r.position.copy(this.worldPositionStart),r.quaternion.copy(this.worldQuaternionStart),yt.set(1e-10,1e-10,1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1),yt.applyQuaternion(this.worldQuaternionStart.clone().invert()),r.scale.copy(yt),r.visible=this.dragging):(r.quaternion.copy(s),this.dragging?r.position.copy(this.worldPositionStart):r.position.copy(this.worldPosition),this.axis&&(r.visible=this.axis.search(r.name)!==-1));continue}r.quaternion.copy(s),this.mode==="translate"||this.mode==="scale"?(r.name==="X"&&Math.abs(De.copy(ea).applyQuaternion(s).dot(this.eye))>.99&&(r.scale.set(1e-10,1e-10,1e-10),r.visible=!1),r.name==="Y"&&Math.abs(De.copy(tn).applyQuaternion(s).dot(this.eye))>.99&&(r.scale.set(1e-10,1e-10,1e-10),r.visible=!1),r.name==="Z"&&Math.abs(De.copy(ta).applyQuaternion(s).dot(this.eye))>.99&&(r.scale.set(1e-10,1e-10,1e-10),r.visible=!1),r.name==="XY"&&Math.abs(De.copy(ta).applyQuaternion(s).dot(this.eye))<.2&&(r.scale.set(1e-10,1e-10,1e-10),r.visible=!1),r.name==="YZ"&&Math.abs(De.copy(ea).applyQuaternion(s).dot(this.eye))<.2&&(r.scale.set(1e-10,1e-10,1e-10),r.visible=!1),r.name==="XZ"&&Math.abs(De.copy(tn).applyQuaternion(s).dot(this.eye))<.2&&(r.scale.set(1e-10,1e-10,1e-10),r.visible=!1)):this.mode==="rotate"&&(bo.copy(s),De.copy(this.eye).applyQuaternion(Ve.copy(s).invert()),r.name.search("E")!==-1&&r.quaternion.setFromRotationMatrix(Wf.lookAt(this.eye,Hf,tn)),r.name==="X"&&(Ve.setFromAxisAngle(ea,Math.atan2(-De.y,De.z)),Ve.multiplyQuaternions(bo,Ve),r.quaternion.copy(Ve)),r.name==="Y"&&(Ve.setFromAxisAngle(tn,Math.atan2(De.x,De.z)),Ve.multiplyQuaternions(bo,Ve),r.quaternion.copy(Ve)),r.name==="Z"&&(Ve.setFromAxisAngle(ta,Math.atan2(De.y,De.x)),Ve.multiplyQuaternions(bo,Ve),r.quaternion.copy(Ve))),r.visible=r.visible&&(r.name.indexOf("X")===-1||this.showX),r.visible=r.visible&&(r.name.indexOf("Y")===-1||this.showY),r.visible=r.visible&&(r.name.indexOf("Z")===-1||this.showZ),r.visible=r.visible&&(r.name.indexOf("E")===-1||this.showX&&this.showY&&this.showZ),r.material._color=r.material._color||r.material.color.clone(),r.material._opacity=r.material._opacity||r.material.opacity,r.material.color.copy(r.material._color),r.material.opacity=r.material._opacity,this.enabled&&this.axis&&(r.name===this.axis||this.axis.split("").some(function(l){return r.name===l}))&&(r.material.color.setHex(16776960),r.material.opacity=1)}super.updateMatrixWorld(e)}}class hN extends x.Mesh{constructor(){super(new x.PlaneGeometry(1e5,1e5,2,2),new x.MeshBasicMaterial({visible:!1,wireframe:!0,side:x.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"),To.copy(ea).applyQuaternion(t==="local"?this.worldQuaternion:Oo),$r.copy(tn).applyQuaternion(t==="local"?this.worldQuaternion:Oo),jr.copy(ta).applyQuaternion(t==="local"?this.worldQuaternion:Oo),De.copy($r),this.mode){case"translate":case"scale":switch(this.axis){case"X":De.copy(this.eye).cross(To),Ns.copy(To).cross(De);break;case"Y":De.copy(this.eye).cross($r),Ns.copy($r).cross(De);break;case"Z":De.copy(this.eye).cross(jr),Ns.copy(jr).cross(De);break;case"XY":Ns.copy(jr);break;case"YZ":Ns.copy(To);break;case"XZ":De.copy(jr),Ns.copy($r);break;case"XYZ":case"E":Ns.set(0,0,0);break}break;case"rotate":default:Ns.set(0,0,0)}Ns.length()===0?this.quaternion.copy(this.cameraQuaternion):($f.lookAt(yt.set(0,0,0),Ns,De),this.quaternion.setFromRotationMatrix($f)),super.updateMatrixWorld(e)}}class xt extends x.EventDispatcher{static DRAG_START="Transform::dragStart";static DRAG_END="Transform::dragEnd";static _instance;app;three;activeCamera;controls=new Map;visibility=new Map;setApp(e,t){this.app=e,this.three=t,this.app.addEventListener(Q.SET_SCENE,this.setScene)}clear(){for(const e of this.controls.values()){e.detach(),e.disconnect();const t=e.getHelper();Ls(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 sN(this.activeCamera,s),t.getHelper().name=e,t.setSpace("local"),this.controls.set(e,t),this.visibility.set(e,!0),t.addEventListener("mouseDown",()=>{this.dispatchEvent({type:xt.DRAG_START})}),t.addEventListener("mouseUp",()=>{this.dispatchEvent({type:xt.DRAG_END})}),t.addEventListener("dragging-changed",i=>{ft.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(),Ls(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 xt._instance||(xt._instance=new xt),xt._instance}}const uN=new x.BoxGeometry,ih=new x.Vector2;class Vh extends x.Object3D{curve=new x.CatmullRomCurve3;line;draggable;curvePos;tension=.5;closed=!1;subdivide=50;curveType;offset=1;lineMaterial;_camera;_curvePercentage=0;_draggableScale=10;_transform;raycaster;draggedMat=new x.MeshBasicMaterial;parentGroup;group;constructor(e,t){const s=new x.Color(xs(.5,1,Math.random()),xs(.5,1,Math.random()),xs(.5,1,Math.random()));super(),this.name=e,this.lineMaterial=new x.LineBasicMaterial({color:s}),this.line=new x.Line(new x.BufferGeometry,this.lineMaterial),this.line.name="line",this.add(this.line),this._camera=t,this.curveType="catmullrom",this.draggedMat.color=s,this.draggable=new x.Object3D,this.draggable.name="draggablePoints",this.add(this.draggable),this.curvePos=new x.Mesh(new x.SphereGeometry(1.5),new x.MeshBasicMaterial({color:s})),this.curvePos.name="curvePos",this.curvePos.scale.setScalar(this._draggableScale),this.curvePos.visible=!1,this.add(this.curvePos),this.raycaster=new x.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),xt.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([ss(t.position.x,3),ss(t.position.y,3),ss(t.position.z,3)])}),Yf({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])}else this.addPoint(new x.Vector3(-50,0,0),!1),this.addPoint(new x.Vector3(50,0,0))};addPoint=(e,t=!0)=>{const s=this.draggable.children.length,i=new x.Mesh(uN,this.draggedMat);return i.name=`point_${s}`,i.position.copy(e),i.scale.setScalar(this._draggableScale),this.draggable.add(i),t&&this.updateSpline(),i};addNextPt=()=>{const e=this.draggable.children.length,t=new x.Vector3(xs(-this.offset,this.offset,Math.random()),xs(-this.offset,this.offset,Math.random()),xs(-this.offset,this.offset,Math.random()));e>0&&t.add(this.draggable.children[e-1].position);const s=this.addPoint(t);this._transform?.attach(s),this.group.current?.setField("Current Point",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.group.current?.setField("Current Point",t.position)}Ls(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)};updateSpline=()=>{this.curve=new x.CatmullRomCurve3(this.points,this.closed,this.curveType,this.tension),this.line.geometry.setFromPoints(this.getPoints()),this.curvePos.position.copy(this.getPointAt(this._curvePercentage))};onMouseClick=e=>{if(!ft.instance||this._transform&&!this._transform.getHelper().visible)return;const s=ft.instance.currentWindow.current.getBoundingClientRect();ih.x=(e.clientX-s.x)/s.width*2-1,ih.y=-((e.clientY-s.y)/s.height)*2+1,this.raycaster.setFromCamera(ih,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.group.current?.setField("Current Point",n.position))}};getPointAt(e){return this.curve.getPointAt(e)}getPoints(){return this.curve.getPoints(this.subdivide)}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))}onUpdateTransform=()=>{if(this._transform?.object&&this.group){const e=this._transform?.object;e.name.search("point")>-1&&this.group.current?.setField("Current Point",e.position)}this.updateSpline()};initDebug(e){const t=this.draggable.children;this.parentGroup=e,this._transform=xt.instance.add(this.name),this._transform.camera=this._camera,this._transform.addEventListener("objectChange",this.onUpdateTransform),this._transform.attach(t.length>0?t[t.length-1]:this),ft.instance?.scene.add(this._transform.getHelper());const s=t.length>0?t[t.length-1].position:{x:0,y:0,z:0};this.group=e.addGroup({title:this.name,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:100,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:s}],onUpdate:(i,n)=>{switch(i){case"Closed":this.closed=n,this.updateSpline();break;case"Visible":this.visible=n;break;case"Color":this.lineMaterial.color.setStyle(n),this.draggedMat.color.setStyle(n);break;case"Curve":this.curveType=n,this.updateSpline();break;case"Draggable Scale":this.draggableScale=n;break;case"Subdivide":this.subdivide=n,this.updateSpline();break;case"Tension":this.tension=n,this.updateSpline();break;case"New Pt Offset":this.offset=n;break;case"Curve At":this.curvePos.position.copy(this.getPointAt(n));break;case"Show Position":this.curvePos.visible=n;break;case"Show Points":this.draggable.visible=n;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":Ls(this);break;case"Current Point":if(this.group.current&&this._transform?.object){const r=this._transform?.object;r.name.search("point")>-1&&(r.position.copy(n),this.updateSpline())}break}}}),this.draggable.children.forEach(i=>{this.debugPoint(i)})}debugPoint=e=>{e.name,e.visible=this.draggable.visible}}let So=0;class Iy extends x.Object3D{defaultScale=10;_camera;group=null;app;constructor(e,t){super(),this.name="Spline Editor",this._camera=e,this.app=t,this.app.addEventListener(Q.ADD_SPLINE,this.onAddSpline)}initDebug(){this.group=Re.addEditorGroup({title:this.name,items:[{type:"button",prop:"New Spline"},{type:"boolean",prop:"Show Points",value:!0},{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"Show Points":this.showPoints(t);break;case"Visible":this.visible=t;break;case"Default Scale":this.defaultScale=t;break}}})}dispose(){this.app.removeEventListener(Q.ADD_SPLINE,this.onAddSpline),Re.removeEditorGroup(this.name)}addSpline(e){e.draggableScale=this.defaultScale,e.hideTransform(),this.group?.current!==null&&e.initDebug(this.group.current),this.add(e)}createSpline=(e=[])=>{const t=`Spline ${So+1}`,s=new Vh(t,this._camera);return s.addPoints(e),this.addSpline(s),So++,s};createSplineFromArray=e=>{const t=[];return e.forEach(s=>{t.push(new x.Vector3(s[0],s[1],s[2]))}),this.createSpline(t)};createSplineFromCatmullRom=e=>this.createSpline(e.points);createSplineFromJSON=e=>{const t=this.createSplineFromArray(e.points);return t.name=e.name,t.closed=e.closed,t.subdivide=e.subdivide,t.tension=e.tension,t.type=e.type,t.updateSpline(),t};showPoints=(e=!0)=>{this.children.forEach(t=>{t.showPoints(e)})};onAddSpline=e=>{const t=JSON.parse(e.value),s=`Spline ${So+1}`,i=[];t.points.forEach(r=>{i.push(new x.Vector3(r[0],r[1],r[2]))});const n=new Vh(s,this.camera);n.addPoints(i),this.addSpline(n),So++};get camera(){return this._camera}set camera(e){this._camera=e,this.children.forEach(t=>{const s=t;s.camera=e})}}const jf=["Single","Side by Side","Stacked","Quad"],dN="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",pN="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==",fN="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAYAAACpF6WWAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAQ0lEQVQ4jWP8////fwYqAxYozUhFM/8zkaKYWIWkGEq0b0ZdSjQY5i79TyWagRGaTUdzFEEw6lLqGzqwLoVVJ1StpwA9sBwbUqAh5gAAAABJRU5ErkJggg==";class ft extends W.Component{static instance=null;app;scene;renderer;currentScene;cameras=new Map;controls=new Map;currentCamera;currentWindow;cameraHelpers=new Map;lightHelpers=new Map;helpersContainer=new x.Group;grid=new KR;interactionHelper=new x.AxesHelper(25);currentTransform;splineEditor;depthMaterial=new x.MeshDepthMaterial;normalsMaterial=new x.MeshNormalMaterial;uvMaterial=new tN;wireframeMaterial=new x.MeshBasicMaterial({opacity:.33,transparent:!0,wireframe:!0});playing=!1;rafID=-1;cameraControlsRafID=-1;width=0;height=0;sceneSet=!1;tlCam=null;trCam=null;blCam=null;brCam=null;tlRender="Renderer";trRender="Renderer";blRender="Renderer";brRender="Renderer";cameraVisibility=!0;lightVisibility=!0;gridVisibility=!0;selectedItem=void 0;debugCamera;raycaster=new x.Raycaster;pointer=new x.Vector2;cameraControls=void 0;canvasRef;containerRef;tlWindow;trWindow;blWindow;brWindow;constructor(e){super(e),this.app=e.app,this.app.addEventListener(Q.ADD_RENDERER,this.setupRenderer),this.scene=new x.Scene,this.scene.name=this.scene.uuid="Debug Scene",this.canvasRef=W.createRef(),this.containerRef=W.createRef(),this.tlWindow=W.createRef(),this.trWindow=W.createRef(),this.blWindow=W.createRef(),this.brWindow=W.createRef();const t=e.three.app.appID,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:x.Vector2,Vector3:x.Vector3,Vector4:x.Vector4,Quaternion:x.Quaternion,Matrix4:x.Matrix4,Spherical:x.Spherical,Box3:x.Box3,Sphere:x.Sphere,Raycaster:x.Raycaster};Ds.install({THREE:n}),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 l=localStorage.getItem(this.expandedGridVisibility);l!==null&&(this.gridVisibility=l==="open"),this.grid.visible=this.gridVisibility,this.saveExpandedGridVisibility(),ft.instance=this}componentDidMount(){this.enable(),this.assignControls(),this.resize(),this.play(),xt.instance.setApp(this.props.app,this.props.three),xt.instance.activeCamera=this.debugCamera}componentDidUpdate(e,t,s){t.mode!==this.state.mode&&(this.assignControls(),this.resize())}componentWillUnmount(){this.disable(),Re.removeEditorGroup("View Settings")}render(){const e=[];return this.cameras.forEach((t,s)=>{e.push(s)}),C.jsxs("div",{className:"multiview",children:[C.jsx("canvas",{ref:this.canvasRef}),C.jsxs("div",{className:`cameras ${this.state.mode==="Single"||this.state.mode==="Stacked"?"single":""}`,ref:this.containerRef,children:[this.state.mode==="Single"&&C.jsx(C.Fragment,{children:C.jsx(Xi,{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")&&C.jsxs(C.Fragment,{children:[C.jsx(Xi,{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)}}),C.jsx(Xi,{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"&&C.jsxs(C.Fragment,{children:[C.jsx(Xi,{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)}}),C.jsx(Xi,{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)}}),C.jsx(Xi,{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)}}),C.jsx(Xi,{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)}})]})]}),C.jsxs("div",{className:"settings",children:[C.jsx(il,{title:"View",index:jf.indexOf(this.state.mode),options:jf,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})}}),C.jsx(il,{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})}}),C.jsx(eh,{name:"cameraHelper",icon:dN,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)}}}),C.jsx(eh,{name:"lightHelper",icon:pN,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)}}}),C.jsx(eh,{name:"gridHelper",icon:fN,selected:this.gridVisibility,height:21,width:21,onClick:t=>{this.gridVisibility=t,this.saveExpandedGridVisibility(),this.grid.visible=t}})]},this.state.lastUpdate)]})}setupRenderer=e=>{this.renderer&&this.renderer.dispose();const t=this.canvasRef.current,s=e.value;s.type==="WebGLRenderer"?(this.renderer=new x.WebGLRenderer({canvas:t,stencil:!1}),this.grid.visible=!0):s.type==="WebGPURenderer"&&(this.renderer=new $c({canvas:t,stencil:!1}),this.grid.visible=!1),this.renderer&&(this.renderer.autoClear=!1,this.renderer.shadowMap.enabled=!0,this.renderer.setPixelRatio(devicePixelRatio),this.renderer.setClearColor(0),this.resize(),this.props.three.renderer=this.renderer)};setupScene(){this.scene.name="Debug Scene",this.scene.uuid="Debug Scene",this.helpersContainer.name="helpers",this.scene.add(this.helpersContainer),this.grid.position.y=-1,this.helpersContainer.add(this.grid),this.interactionHelper.name="interactionHelper",this.interactionHelper.visible=!1,this.helpersContainer.add(this.interactionHelper);const e=(n,r)=>{const o=new x.OrthographicCamera(-100,100,100,-100,0,3e3);return o.name=n,o.position.copy(r),o.lookAt(0,0,0),this.cameras.set(n,o),o},t=1e3;e("Top",new x.Vector3(0,t,0)),e("Bottom",new x.Vector3(0,-t,0)),e("Left",new x.Vector3(-t,0,0)),e("Right",new x.Vector3(t,0,0)),e("Front",new x.Vector3(0,0,t)),e("Back",new x.Vector3(0,0,-t)),e("Orthographic",new x.Vector3(t,t,t)),e("UI",new x.Vector3),this.debugCamera=new x.PerspectiveCamera(60,1,50,5e3),this.debugCamera.name="Debug",this.debugCamera.position.set(500,500,500),this.debugCamera.lookAt(0,0,0),this.cameras.set("Debug",this.debugCamera),this.currentCamera=this.debugCamera;const s=localStorage,i=this.props.three.app.appID;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"))}setupTools(){this.splineEditor=new Iy(this.currentCamera,this.app),this.splineEditor.initDebug(),this.scene.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})}update(){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.sceneSet&&this.props.onSceneUpdate(this.currentScene)}draw(){switch(this.renderer&&(this.renderer instanceof x.WebGLRenderer?this.renderer?.clear():this.renderer instanceof $c&&this.renderer?.clearAsync()),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.app.addEventListener(Q.SET_SCENE,this.sceneUpdate),this.app.addEventListener(Q.ADD_CAMERA,this.addCamera),this.app.addEventListener(Q.REMOVE_CAMERA,this.removeCamera),this.app.addEventListener(Q.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.app.removeEventListener(Q.SET_SCENE,this.sceneUpdate),this.app.removeEventListener(Q.ADD_CAMERA,this.addCamera),this.app.removeEventListener(Q.REMOVE_CAMERA,this.removeCamera),this.app.removeEventListener(Q.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.sceneSet&&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(r=>{r instanceof x.OrthographicCamera?(r.left=s/-2,r.right=s/2,r.top=i/2,r.bottom=i/-2,r.name==="UI"&&(r.position.x=this.width/2,r.position.y=this.height/-2,r.position.z=100),r.updateProjectionMatrix()):r instanceof x.PerspectiveCamera&&(r.aspect=n,r.updateProjectionMatrix()),this.cameraHelpers.get(r.name)?.update()})};sceneUpdate=e=>{this.clearLightHelpers(),this.scene.remove(this.currentScene),Ls(this.currentScene);const t=this.props.scenes.get(e.value.name);if(t!==void 0){const s=new t;this.props.onSceneSet!==void 0&&this.props.onSceneSet(s),this.currentScene=s,this.props.three.scene=this.currentScene,this.scene.add(this.currentScene),this.sceneSet=!0,this.addLightHelpers()}};addCamera=e=>{const t=e.value,s=this.props.three.scene?.getObjectByProperty("uuid",t.uuid);if(s!==void 0){const i=s;this.cameras.set(t.name,i);const n=new x.CameraHelper(i);n.visible=this.cameraVisibility,this.cameraHelpers.set(i.name,n),this.scene.add(n),this.setState({lastUpdate:Date.now()})}};removeCamera=e=>{const t=this.cameraHelpers.get(e.value.name);t!==void 0&&(this.scene.remove(t),t.dispose()),this.cameras.delete(e.value.name),this.setState({lastUpdate:Date.now()})};onMouseMove=e=>{const t=new x.Vector2;this.renderer?.getSize(t);const s=Math.min(e.clientX,t.x),i=Math.min(e.clientY,t.y);this.pointer.x=Qi(s,0,t.x,-1,1),this.pointer.y=Qi(i,0,t.y,1,-1);const n=t.x/2,r=t.y/2,o=()=>{s<n?this.pointer.x=Qi(s,0,n,-1,1):this.pointer.x=Qi(s,n,t.x,-1,1)},l=()=>{i<r?this.pointer.y=Qi(i,0,r,1,-1):this.pointer.y=Qi(i,r,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,r),this.state.interactionMode==="Orbit")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")return;const t=new x.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 Ds(this.currentCamera,this.currentWindow.current),this.selectedItem instanceof x.Mesh||this.selectedItem instanceof x.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 Ds(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 Ds(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 Ds(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 Ds(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 Ds(this.currentCamera,this.currentWindow.current),this.cameraControls.rotateTo(Lo(45),Lo(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=this.currentScene.getObjectByProperty("uuid",e.value.uuid),this.selectedItem!==void 0&&(this.currentTransform!==void 0&&(this.currentTransform.removeEventListener("objectChange",this.onUpdateTransform),xt.instance.remove(this.currentTransform.getHelper().name)),this.currentTransform=xt.instance.add(e.value.name),this.currentTransform.attach(this.selectedItem),this.scene.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),El.instance.update())};clearLightHelpers=()=>{this.lightHelpers.forEach(e=>{this.helpersContainer.remove(e),e.dispose()}),this.lightHelpers.clear()};addLightHelpers=()=>{this.currentScene!==void 0&&this.currentScene.traverse(e=>{if(e.type.search("Light")>-1){let t;switch(e.type){case"DirectionalLight":t=new x.DirectionalLightHelper(e,100),t.name=`${e.name}Helper`,t.visible=this.lightVisibility,this.lightHelpers.set(e.name,t),this.helpersContainer.add(t);break;case"HemisphereLight":t=new x.HemisphereLightHelper(e,250),t.name=`${e.name}Helper`,t.visible=this.lightVisibility,this.lightHelpers.set(e.name,t),this.helpersContainer.add(t);break;case"RectAreaLight":t=new PR(e),t.name=`${e.name}Helper`,t.visible=this.lightVisibility,this.lightHelpers.set(e.name,t),this.helpersContainer.add(t);break;case"PointLight":t=new x.PointLightHelper(e,100),t.name=`${e.name}Helper`,t.visible=this.lightVisibility,this.lightHelpers.set(e.name,t),this.helpersContainer.add(t);break;case"SpotLight":t=new x.SpotLightHelper(e),t.name=`${e.name}Helper`,t.visible=this.lightVisibility,this.lightHelpers.set(e.name,t),this.helpersContainer.add(t);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 DR(e,t);switch(i.enableDamping=!0,i.dampingFactor=.05,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.scene.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.scene.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),xt.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 x.Clock;i.start(),this.selectedItem.getWorldPosition(e.target0);const n=()=>{const r=i.getDelta();this.cameraControls&&this.cameraControls.update(r),t&&(e.target.lerp(e.target0,s),e.object.position.lerp(e.position0,s),e.object.zoom=ir(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,r){switch(n.name){case"Left":case"Right":this.grid.rotation.z=Math.PI/2;break;case"Front":case"Back":this.grid.rotation.x=Math.PI/2;break}this.scene.overrideMaterial=r,this.renderer&&(this.renderer?.setViewport(e,t,s,i),this.renderer?.setScissor(e,t,s,i),this.renderer instanceof x.WebGLRenderer?this.renderer?.render(this.scene,n):this.renderer instanceof $c&&this.renderer?.renderAsync(this.scene,n)),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);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 n=this.height-i;this.drawTo(0,n,this.width,i,this.tlCam,e),this.drawTo(0,0,this.width,i,this.trCam,t)}};drawQuad=()=>{const e=this.getSceneOverride(this.tlRender),t=this.getSceneOverride(this.trRender),s=this.getSceneOverride(this.blRender),i=this.getSceneOverride(this.brRender),n=Math.floor(this.width/2),r=Math.floor(this.height/2);let o=0,l=0;l=this.height-r,o=0,this.drawTo(o,l,n,r,this.tlCam,e),o=n,this.drawTo(o,l,n,r,this.trCam,t),l=0,o=0,this.scene.overrideMaterial=s,this.drawTo(o,l,n,r,this.blCam,s),o=n,this.drawTo(o,l,n,r,this.brCam,i)};get appID(){return this.props.three.app.appID}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 El extends W.Component{static instance;app;matrix=new x.Matrix4;position=new x.Vector3;rotation=new x.Euler;scale=new x.Vector3;open=!1;constructor(e){super(e),this.app=e.app;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)),El.instance=this}update(){if(ft.instance){const e=ft.instance.selectedItem;if(e===void 0)return;this.position.x=ss(e.position.x,3),this.position.y=ss(e.position.y,3),this.position.z=ss(e.position.z,3),this.rotation.copy(e.rotation),this.scale.x=ss(e.scale.x,3),this.scale.y=ss(e.scale.y,3),this.scale.z=ss(e.scale.z,3),this.setState({lastUpdated:Date.now()})}}render(){return C.jsx(cs,{app:this.app,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);qe(n,e,s)}};saveExpanded(){localStorage.setItem(this.expandedName,this.open?"open":"closed")}get expandedName(){return`${this.props.three.app.appID}_transform`}}function qf(a){switch(a){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 a}function mN(a,e,t){function s(){return`${t.app.appID}_light`}const i=localStorage.getItem(s()),n=i!==null?i==="open":!1;function r(l){localStorage.setItem(s(),l?"open":"closed")}const o=[];if(a.lightInfo!==void 0)for(const l in a.lightInfo){const c=a.lightInfo[l];c!==void 0&&(c.isColor!==void 0?o.push({title:qf(l),prop:l,type:"color",value:c,onChange:(h,u)=>{const d=new x.Color(u);t.updateObject(a.uuid,h,d);const p=t.getScene(a.uuid);if(p!==null){const f=p.getObjectByProperty("uuid",a.uuid);qe(f,h,d)}}}):o.push({title:qf(l),prop:l,type:typeof c,value:c,step:typeof c=="number"?.01:void 0,onChange:(h,u)=>{t.updateObject(a.uuid,h,u);const d=t.getScene(a.uuid);if(d!==null){const p=d.getObjectByProperty("uuid",a.uuid);qe(p,h,u)}}}))}return C.jsx(cs,{app:e,title:"Light",items:o,expanded:n,onToggle:l=>{r(l)}})}function gN(a){const e=a.object,t=a.three;function s(){return`${t.app.appID}_animation`}const i=localStorage.getItem(s()),n=i!==null?i==="open":!1;function r(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 h;const u=t.getScene(e.uuid);if(u!==null){const d=u.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:(y,g)=>{p.timeScale=g,t.updateObject(e.uuid,"mixer.timeScale",g)}}];m.push({title:"Stop All",type:"button",onChange:()=>{p.stopAllAction(),t.requestMethod(e.uuid,"stopAllAction",void 0,"mixer")}}),o.push({title:"Mixer",items:m}),h=new x.SkeletonHelper(d),ft.instance?.scene.add(h)}}}return W.useEffect(()=>()=>{h!==void 0&&Ls(h)},[]),C.jsx(cs,{app:a.app,title:"Animation",items:o,expanded:n,onToggle:d=>{r(d)}})}const Hh={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:[]};let pt={...Hh};function Ly(a){const[e,t]=W.useState(-1);W.useEffect(()=>{function r(l){pt={...l.value},t(Date.now())}function o(){pt={...Hh},t(Date.now())}return a.app.addEventListener(Q.SET_SCENE,o),a.app.addEventListener(Q.SET_OBJECT,r),()=>{a.app.removeEventListener(Q.SET_SCENE,o),a.app.removeEventListener(Q.SET_OBJECT,r)}},[]);const s=pt.type.toLowerCase(),i=pt.animations.length>0||pt.mixer!==void 0,n=s.search("mesh")>-1||s.search("line")>-1||s.search("points")>-1;return C.jsx(pa,{app:a.app,label:"Inspector",button:pt.uuid.length>0?C.jsx("button",{className:"remove",onClick:()=>{xt.instance.remove(pt.name),pt={...Hh},t(Date.now())}}):void 0,children:C.jsx("div",{id:"Inspector",className:a.class,children:pt.uuid.length>0&&C.jsxs(C.Fragment,{children:[C.jsxs(C.Fragment,{children:[C.jsx(vo,{type:"string",title:"Name",prop:"name",value:pt.name,disabled:!0}),C.jsx(vo,{type:"string",title:"Type",prop:"type",value:pt.type,disabled:!0}),C.jsx(vo,{type:"string",title:"UUID",prop:"uuid",value:pt.uuid,disabled:!0})]}),C.jsxs(C.Fragment,{children:[C.jsx(El,{object:pt,app:a.app,three:a.three}),i?C.jsx(gN,{app:a.app,object:pt,three:a.three}):null,s.search("camera")>-1?Ux(pt,a.app,a.three):null,s.search("light")>-1?mN(pt,a.app,a.three):null,n?Bx(pt,a.app,a.three):null]})]})},e)},"Inspector")}class yN extends W.Component{app;autoClear=!0;autoClearColor=!0;autoClearDepth=!0;autoClearStencil=!0;outputColorSpace=x.SRGBColorSpace;localClippingEnabled=!1;clearColor=new x.Color(0);clearAlpha=1;toneMapping=x.NoToneMapping;toneMappingExposure=1;type="";constructor(e){super(e),this.app=e.app;const t=localStorage.getItem(this.expandedName),s=t!==null?t==="open":!1;if(this.state={expanded:s,lastUpdated:Date.now()},this.saveExpanded(s),ft.instance){const i=ft.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 x.WebGLRenderer&&(this.localClippingEnabled=i.localClippingEnabled,i.getClearColor(this.clearColor)))}this.app.addEventListener(Q.ADD_RENDERER,this.onAddRenderer)}componentwillunmount(){this.app.removeEventListener(Q.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,x.LinearSRGBColorSpace),x.ColorManagement.enabled=t.colorManagement,ft.instance){const s=ft.instance.renderer;s&&(s.autoClear=this.autoClear,s.autoClearColor=this.autoClearColor,s.autoClearDepth=this.autoClearDepth,s.autoClearStencil=this.autoClearStencil,s.outputColorSpace=this.outputColorSpace,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(ft.instance){const t=ft.instance.renderer;t&&(t.autoClear=this.autoClear,t.autoClearColor=this.autoClearColor,t.autoClearDepth=this.autoClearDepth,t.autoClearStencil=this.autoClearStencil,t.outputColorSpace=this.outputColorSpace,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:x.ColorManagement.enabled,toneMapping:this.toneMapping,toneMappingExposure:this.toneMappingExposure}))}};return C.jsx(cs,{app:this.app,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:"Clear Management",value:x.ColorManagement.enabled,onChange:(t,s)=>{x.ColorManagement.enabled=s,e()}},{type:"option",title:"Color Space",value:this.outputColorSpace,options:[{title:"No Color Space",value:x.NoColorSpace},{title:"SRB Color Space",value:x.SRGBColorSpace},{title:"Linear SRB Color Space",value:x.LinearSRGBColorSpace}],onChange:(t,s)=>{this.outputColorSpace=s,e()}},{type:"option",title:"Tone Mapping",value:this.toneMapping,options:[{title:"None ",value:x.NoToneMapping},{title:"Linear ",value:x.LinearToneMapping},{title:"Reinhard",value:x.ReinhardToneMapping},{title:"Cineon ",value:x.CineonToneMapping},{title:"ACES Filmic",value:x.ACESFilmicToneMapping},{title:"AgX",value:x.AgXToneMapping},{title:"Neutral",value:x.NeutralToneMapping},{title:"Custom",value:x.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}],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.app.appID}_renderer`}}function Uy(a){const[e]=W.useState([]),[t]=W.useState([]),[s,i]=W.useState(0),n=l=>{const c=l.value;e.push(c),t.push(C.jsx(pa,{app:a.app,label:`Scene: ${c.name}`,scene:c,open:!0,onRefresh:()=>{a.three.refreshScene(c.name)},children:C.jsx(oh,{app:a.app,child:c,scene:c,three:a.three})},Math.random())),i(Date.now())},r=l=>{const c=l.value;for(let h=0;h<e.length;h++)if(c.uuid===e[h].uuid){e[h]=c,t[h]=C.jsx(pa,{app:a.app,label:`Scene: ${c.name}`,scene:c,open:!0,onRefresh:()=>{a.three.refreshScene(c.name)},children:C.jsx(oh,{app:a.app,child:c,scene:c,three:a.three})},Math.random()),i(Date.now());return}},o=l=>{const c=l.value;for(let h=0;h<e.length;h++)if(c.uuid===e[h].uuid){e.splice(h,1),t.splice(h,1),i(Date.now());return}};return W.useEffect(()=>(a.app.addEventListener(Q.ADD_SCENE,n),a.app.addEventListener(Q.REFRESH_SCENE,r),a.app.addEventListener(Q.REMOVE_SCENE,o),()=>{a.app.removeEventListener(Q.ADD_SCENE,n),a.app.removeEventListener(Q.REFRESH_SCENE,r),a.app.removeEventListener(Q.REMOVE_SCENE,o)}),[]),C.jsxs("div",{id:"SidePanel",children:[C.jsx("div",{className:"scenes",children:t},s),C.jsx(Ly,{app:a.app,three:a.three}),C.jsx(yN,{app:a.app,three:a.three}),C.jsx(Re,{app:a.app,three:a.three})]})}function xN(a){return W.useEffect(()=>{function e(o){let l=null;return a.three.scenes.forEach(c=>{o.search(c.uuid)>-1&&(l=c)}),l}const t=o=>{const l=o.value,c=e(l),h=c?.getObjectByProperty("uuid",l);h!==void 0?a.three.setObject(h):console.log(`Hermes - can't find object: ${l}`,c)},s=(o,l,c)=>{const h=e(o),u=h?.getObjectByProperty("uuid",o);u!==void 0?qe(u,l,c):console.log(`Hermes - can't set object: ${o}`,h)},i=o=>{const l=o.value,{key:c,value:h,uuid:u}=l;s(u,c,h)},n=o=>{const l=o.value,h=e(l.uuid)?.getObjectByProperty("uuid",l.uuid);if(h!==void 0){const u=d=>{const p=l.key.split(".");switch(p.length){case 1:h[p[0]]=d;break;case 2:h[p[0]][p[1]]=d;break;case 3:h[p[0]][p[1]][p[2]]=d;break;case 4:h[p[0]][p[1]][p[2]][p[3]]=d;break;case 5:h[p[0]][p[1]][p[2]][p[3]][p[4]]=d;break}h.material.needsUpdate=!0};l.value.src.length>0?tm(l.value.src).then(d=>{d.offset.set(l.value.offset[0],l.value.offset[1]),d.repeat.set(l.value.repeat[0],l.value.repeat[1]),u(d)}):u(null)}},r=o=>{const{key:l,uuid:c,value:h,subitem:u}=o.value,p=e(c)?.getObjectByProperty("uuid",c);if(p!==void 0)try{u!==void 0?Q0(p,u)[l](h):p[l](h)}catch(f){console.log("Error requesting method:"),console.log(f),console.log(l),console.log(h)}};return a.app.addEventListener(Q.GET_OBJECT,t),a.app.addEventListener(Q.UPDATE_OBJECT,i),a.app.addEventListener(Q.CREATE_TEXTURE,n),a.app.addEventListener(Q.REQUEST_METHOD,r),()=>{a.app.removeEventListener(Q.GET_OBJECT,t),a.app.removeEventListener(Q.UPDATE_OBJECT,i),a.app.removeEventListener(Q.CREATE_TEXTURE,n),a.app.removeEventListener(Q.REQUEST_METHOD,r)}},[]),null}function ky(a){return C.jsxs("div",{className:"editor",ref:a.ref,style:a.style,children:[C.jsx("div",{className:"header",children:a.header}),a.children,C.jsx("div",{className:"footer",children:a.footer})]})}function _N(a){return C.jsx(ky,{children:C.jsxs(C.Fragment,{children:[C.jsx(ft,{app:a.app,three:a.three,scenes:a.scenes,onSceneResize:a.onSceneResize,onSceneSet:a.onSceneSet,onSceneUpdate:a.onSceneUpdate}),C.jsx(Uy,{app:a.app,three:a.three})]})})}exports.Accordion=pa;exports.AppRunner=z0;exports.Application=k0;exports.BaseRemote=nl;exports.BaseScene=G0;exports.ChildObject=qh;exports.ContainerObject=oh;exports.Draggable=im;exports.DraggableItem=sm;exports.Dropdown=nm;exports.DropdownItem=rm;exports.Editor=ky;exports.ElementProxy=L0;exports.ElementProxyReceiver=em;exports.ExportTexture=sa;exports.Inspector=Ly;exports.MultiView=ft;exports.NavButton=jh;exports.ProxyManager=U0;exports.QualityType=Kf;exports.RemoteComponents=V0;exports.RemoteTheatre=q0;exports.RemoteThree=J0;exports.SceneInspector=xN;exports.SidePanel=Uy;exports.Spline=Vh;exports.SplineEditor=Iy;exports.ThreeEditor=_N;exports.ToolEvents=Q;exports.Transform=xt;exports.WebworkerEventHandlers=B0;exports.capitalize=da;exports.clamp=Si;exports.colorToHex=nh;exports.copyToClipboard=Yf;exports.cubicBezier=M0;exports.customizeTheatreElements=W0;exports.damp=b0;exports.defaultTheatreCallback=u0;exports.detectMaxFrameRate=Jf;exports.detectSettings=y0;exports.dispose=Ls;exports.disposeMaterial=Wh;exports.disposeTexture=rh;exports.distance=_0;exports.hierarchyUUID=Io;exports.isColor=Zf;exports.map=x0;exports.mix=ir;exports.noop=ua;exports.normalize=Bo;exports.parseModelLite=C0;exports.randomID=Xf;exports.resetThreeObjects=ah;exports.round=ss;exports.roundTo=T0;exports.theatreEditorApp=H0;
|