minecraft-renderer 0.1.85 → 0.1.87
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/threeWorker.js
CHANGED
|
@@ -8637,7 +8637,7 @@ void main() {
|
|
|
8637
8637
|
gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );
|
|
8638
8638
|
}`;function Cje(i,e,t){let n=new _b,r=new yn,s=new yn,a=new ni,o=new $R({depthPacking:Lze}),l=new YR,c={},u=t.maxTextureSize,d={[Qa]:fs,[fs]:Qa,[Ns]:Ns},f=new s0({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new yn},radius:{value:4}},vertexShader:Ije,fragmentShader:Rje}),v=f.clone();v.defines.HORIZONTAL_PASS=1;let g=new Ud;g.setAttribute("position",new ea(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let b=new Nn(g,f),y=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=Xge;let _=this.type;this.render=function(A,T,P){if(y.enabled===!1||y.autoUpdate===!1&&y.needsUpdate===!1||A.length===0)return;let I=i.getRenderTarget(),k=i.getActiveCubeFace(),L=i.getActiveMipmapLevel(),B=i.state;B.setBlending(zc),B.buffers.color.setClear(1,1,1,1),B.buffers.depth.setTest(!0),B.setScissorTest(!1);let U=_!==e0&&this.type===e0,O=_===e0&&this.type!==e0;for(let V=0,F=A.length;V<F;V++){let J=A[V],$=J.shadow;if($===void 0){console.warn("THREE.WebGLShadowMap:",J,"has no shadow.");continue}if($.autoUpdate===!1&&$.needsUpdate===!1)continue;r.copy($.mapSize);let ne=$.getFrameExtents();if(r.multiply(ne),s.copy($.mapSize),(r.x>u||r.y>u)&&(r.x>u&&(s.x=Math.floor(u/ne.x),r.x=s.x*ne.x,$.mapSize.x=s.x),r.y>u&&(s.y=Math.floor(u/ne.y),r.y=s.y*ne.y,$.mapSize.y=s.y)),$.map===null||U===!0||O===!0){let j=this.type!==e0?{minFilter:Gi,magFilter:Gi}:{};$.map!==null&&$.map.dispose(),$.map=new i0(r.x,r.y,j),$.map.texture.name=J.name+".shadowMap",$.camera.updateProjectionMatrix()}i.setRenderTarget($.map),i.clear();let se=$.getViewportCount();for(let j=0;j<se;j++){let q=$.getViewport(j);a.set(s.x*q.x,s.y*q.y,s.x*q.z,s.y*q.w),B.viewport(a),$.updateMatrices(J,j),n=$.getFrustum(),S(T,P,$.camera,J,this.type)}$.isPointLightShadow!==!0&&this.type===e0&&x($,P),$.needsUpdate=!1}_=this.type,y.needsUpdate=!1,i.setRenderTarget(I,k,L)};function x(A,T){let P=e.update(b);f.defines.VSM_SAMPLES!==A.blurSamples&&(f.defines.VSM_SAMPLES=A.blurSamples,v.defines.VSM_SAMPLES=A.blurSamples,f.needsUpdate=!0,v.needsUpdate=!0),A.mapPass===null&&(A.mapPass=new i0(r.x,r.y)),f.uniforms.shadow_pass.value=A.map.texture,f.uniforms.resolution.value=A.mapSize,f.uniforms.radius.value=A.radius,i.setRenderTarget(A.mapPass),i.clear(),i.renderBufferDirect(T,null,P,f,b,null),v.uniforms.shadow_pass.value=A.mapPass.texture,v.uniforms.resolution.value=A.mapSize,v.uniforms.radius.value=A.radius,i.setRenderTarget(A.map),i.clear(),i.renderBufferDirect(T,null,P,v,b,null)}function w(A,T,P,I){let k=null,L=P.isPointLight===!0?A.customDistanceMaterial:A.customDepthMaterial;if(L!==void 0)k=L;else if(k=P.isPointLight===!0?l:o,i.localClippingEnabled&&T.clipShadows===!0&&Array.isArray(T.clippingPlanes)&&T.clippingPlanes.length!==0||T.displacementMap&&T.displacementScale!==0||T.alphaMap&&T.alphaTest>0||T.map&&T.alphaTest>0){let B=k.uuid,U=T.uuid,O=c[B];O===void 0&&(O={},c[B]=O);let V=O[U];V===void 0&&(V=k.clone(),O[U]=V),k=V}if(k.visible=T.visible,k.wireframe=T.wireframe,I===e0?k.side=T.shadowSide!==null?T.shadowSide:T.side:k.side=T.shadowSide!==null?T.shadowSide:d[T.side],k.alphaMap=T.alphaMap,k.alphaTest=T.alphaTest,k.map=T.map,k.clipShadows=T.clipShadows,k.clippingPlanes=T.clippingPlanes,k.clipIntersection=T.clipIntersection,k.displacementMap=T.displacementMap,k.displacementScale=T.displacementScale,k.displacementBias=T.displacementBias,k.wireframeLinewidth=T.wireframeLinewidth,k.linewidth=T.linewidth,P.isPointLight===!0&&k.isMeshDistanceMaterial===!0){let B=i.properties.get(k);B.light=P}return k}function S(A,T,P,I,k){if(A.visible===!1)return;if(A.layers.test(T.layers)&&(A.isMesh||A.isLine||A.isPoints)&&(A.castShadow||A.receiveShadow&&k===e0)&&(!A.frustumCulled||n.intersectsObject(A))){A.modelViewMatrix.multiplyMatrices(P.matrixWorldInverse,A.matrixWorld);let U=e.update(A),O=A.material;if(Array.isArray(O)){let V=U.groups;for(let F=0,J=V.length;F<J;F++){let $=V[F],ne=O[$.materialIndex];if(ne&&ne.visible){let se=w(A,ne,I,k);i.renderBufferDirect(P,null,U,se,A,$)}}}else if(O.visible){let V=w(A,O,I,k);i.renderBufferDirect(P,null,U,V,A,null)}}let B=A.children;for(let U=0,O=B.length;U<O;U++)S(B[U],T,P,I,k)}}function Pje(i,e,t){let n=t.isWebGL2;function r(){let de=!1,Xe=new ni,Ce=null,le=new ni(0,0,0,0);return{setMask:function(Le){Ce!==Le&&!de&&(i.colorMask(Le,Le,Le,Le),Ce=Le)},setLocked:function(Le){de=Le},setClear:function(Le,Oe,et,Ze,Ye){Ye===!0&&(Le*=Ze,Oe*=Ze,et*=Ze),Xe.set(Le,Oe,et,Ze),le.equals(Xe)===!1&&(i.clearColor(Le,Oe,et,Ze),le.copy(Xe))},reset:function(){de=!1,Ce=null,le.set(-1,0,0,0)}}}function s(){let de=!1,Xe=null,Ce=null,le=null;return{setTest:function(Le){Le?Q(i.DEPTH_TEST):ue(i.DEPTH_TEST)},setMask:function(Le){Xe!==Le&&!de&&(i.depthMask(Le),Xe=Le)},setFunc:function(Le){if(Ce!==Le){switch(Le){case lze:i.depthFunc(i.NEVER);break;case cze:i.depthFunc(i.ALWAYS);break;case uze:i.depthFunc(i.LESS);break;case kR:i.depthFunc(i.LEQUAL);break;case dze:i.depthFunc(i.EQUAL);break;case fze:i.depthFunc(i.GEQUAL);break;case hze:i.depthFunc(i.GREATER);break;case mze:i.depthFunc(i.NOTEQUAL);break;default:i.depthFunc(i.LEQUAL)}Ce=Le}},setLocked:function(Le){de=Le},setClear:function(Le){le!==Le&&(i.clearDepth(Le),le=Le)},reset:function(){de=!1,Xe=null,Ce=null,le=null}}}function a(){let de=!1,Xe=null,Ce=null,le=null,Le=null,Oe=null,et=null,Ze=null,Ye=null;return{setTest:function(rt){de||(rt?Q(i.STENCIL_TEST):ue(i.STENCIL_TEST))},setMask:function(rt){Xe!==rt&&!de&&(i.stencilMask(rt),Xe=rt)},setFunc:function(rt,It,Kt){(Ce!==rt||le!==It||Le!==Kt)&&(i.stencilFunc(rt,It,Kt),Ce=rt,le=It,Le=Kt)},setOp:function(rt,It,Kt){(Oe!==rt||et!==It||Ze!==Kt)&&(i.stencilOp(rt,It,Kt),Oe=rt,et=It,Ze=Kt)},setLocked:function(rt){de=rt},setClear:function(rt){Ye!==rt&&(i.clearStencil(rt),Ye=rt)},reset:function(){de=!1,Xe=null,Ce=null,le=null,Le=null,Oe=null,et=null,Ze=null,Ye=null}}}let o=new r,l=new s,c=new a,u=new WeakMap,d=new WeakMap,f={},v={},g=new WeakMap,b=[],y=null,_=!1,x=null,w=null,S=null,A=null,T=null,P=null,I=null,k=!1,L=null,B=null,U=null,O=null,V=null,F=i.getParameter(i.MAX_COMBINED_TEXTURE_IMAGE_UNITS),J=!1,$=0,ne=i.getParameter(i.VERSION);ne.indexOf("WebGL")!==-1?($=parseFloat(/^WebGL (\d)/.exec(ne)[1]),J=$>=1):ne.indexOf("OpenGL ES")!==-1&&($=parseFloat(/^OpenGL ES (\d)/.exec(ne)[1]),J=$>=2);let se=null,j={},q=i.getParameter(i.SCISSOR_BOX),z=i.getParameter(i.VIEWPORT),K=new ni().fromArray(q),re=new ni().fromArray(z);function Z(de,Xe,Ce,le){let Le=new Uint8Array(4),Oe=i.createTexture();i.bindTexture(de,Oe),i.texParameteri(de,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(de,i.TEXTURE_MAG_FILTER,i.NEAREST);for(let et=0;et<Ce;et++)n&&(de===i.TEXTURE_3D||de===i.TEXTURE_2D_ARRAY)?i.texImage3D(Xe,0,i.RGBA,1,1,le,0,i.RGBA,i.UNSIGNED_BYTE,Le):i.texImage2D(Xe+et,0,i.RGBA,1,1,0,i.RGBA,i.UNSIGNED_BYTE,Le);return Oe}let Y={};Y[i.TEXTURE_2D]=Z(i.TEXTURE_2D,i.TEXTURE_2D,1),Y[i.TEXTURE_CUBE_MAP]=Z(i.TEXTURE_CUBE_MAP,i.TEXTURE_CUBE_MAP_POSITIVE_X,6),n&&(Y[i.TEXTURE_2D_ARRAY]=Z(i.TEXTURE_2D_ARRAY,i.TEXTURE_2D_ARRAY,1,1),Y[i.TEXTURE_3D]=Z(i.TEXTURE_3D,i.TEXTURE_3D,1,1)),o.setClear(0,0,0,1),l.setClear(1),c.setClear(0),Q(i.DEPTH_TEST),l.setFunc(kR),ke(!1),je(Tve),Q(i.CULL_FACE),ge(zc);function Q(de){f[de]!==!0&&(i.enable(de),f[de]=!0)}function ue(de){f[de]!==!1&&(i.disable(de),f[de]=!1)}function me(de,Xe){return v[de]!==Xe?(i.bindFramebuffer(de,Xe),v[de]=Xe,n&&(de===i.DRAW_FRAMEBUFFER&&(v[i.FRAMEBUFFER]=Xe),de===i.FRAMEBUFFER&&(v[i.DRAW_FRAMEBUFFER]=Xe)),!0):!1}function we(de,Xe){let Ce=b,le=!1;if(de)if(Ce=g.get(Xe),Ce===void 0&&(Ce=[],g.set(Xe,Ce)),de.isWebGLMultipleRenderTargets){let Le=de.texture;if(Ce.length!==Le.length||Ce[0]!==i.COLOR_ATTACHMENT0){for(let Oe=0,et=Le.length;Oe<et;Oe++)Ce[Oe]=i.COLOR_ATTACHMENT0+Oe;Ce.length=Le.length,le=!0}}else Ce[0]!==i.COLOR_ATTACHMENT0&&(Ce[0]=i.COLOR_ATTACHMENT0,le=!0);else Ce[0]!==i.BACK&&(Ce[0]=i.BACK,le=!0);le&&(t.isWebGL2?i.drawBuffers(Ce):e.get("WEBGL_draw_buffers").drawBuffersWEBGL(Ce))}function ye(de){return y!==de?(i.useProgram(de),y=de,!0):!1}let pe={[x5]:i.FUNC_ADD,[KVe]:i.FUNC_SUBTRACT,[ZVe]:i.FUNC_REVERSE_SUBTRACT};if(n)pe[Pve]=i.MIN,pe[Lve]=i.MAX;else{let de=e.get("EXT_blend_minmax");de!==null&&(pe[Pve]=de.MIN_EXT,pe[Lve]=de.MAX_EXT)}let Ge={[QVe]:i.ZERO,[eze]:i.ONE,[tze]:i.SRC_COLOR,[$ge]:i.SRC_ALPHA,[oze]:i.SRC_ALPHA_SATURATE,[sze]:i.DST_COLOR,[rze]:i.DST_ALPHA,[nze]:i.ONE_MINUS_SRC_COLOR,[Yge]:i.ONE_MINUS_SRC_ALPHA,[aze]:i.ONE_MINUS_DST_COLOR,[ize]:i.ONE_MINUS_DST_ALPHA};function ge(de,Xe,Ce,le,Le,Oe,et,Ze){if(de===zc){_===!0&&(ue(i.BLEND),_=!1);return}if(_===!1&&(Q(i.BLEND),_=!0),de!==JVe){if(de!==x||Ze!==k){if((w!==x5||T!==x5)&&(i.blendEquation(i.FUNC_ADD),w=x5,T=x5),Ze)switch(de){case E5:i.blendFuncSeparate(i.ONE,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA);break;case Ive:i.blendFunc(i.ONE,i.ONE);break;case Rve:i.blendFuncSeparate(i.ZERO,i.ONE_MINUS_SRC_COLOR,i.ZERO,i.ONE);break;case Cve:i.blendFuncSeparate(i.ZERO,i.SRC_COLOR,i.ZERO,i.SRC_ALPHA);break;default:console.error("THREE.WebGLState: Invalid blending: ",de);break}else switch(de){case E5:i.blendFuncSeparate(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA);break;case Ive:i.blendFunc(i.SRC_ALPHA,i.ONE);break;case Rve:i.blendFuncSeparate(i.ZERO,i.ONE_MINUS_SRC_COLOR,i.ZERO,i.ONE);break;case Cve:i.blendFunc(i.ZERO,i.SRC_COLOR);break;default:console.error("THREE.WebGLState: Invalid blending: ",de);break}S=null,A=null,P=null,I=null,x=de,k=Ze}return}Le=Le||Xe,Oe=Oe||Ce,et=et||le,(Xe!==w||Le!==T)&&(i.blendEquationSeparate(pe[Xe],pe[Le]),w=Xe,T=Le),(Ce!==S||le!==A||Oe!==P||et!==I)&&(i.blendFuncSeparate(Ge[Ce],Ge[le],Ge[Oe],Ge[et]),S=Ce,A=le,P=Oe,I=et),x=de,k=!1}function Ie(de,Xe){de.side===Ns?ue(i.CULL_FACE):Q(i.CULL_FACE);let Ce=de.side===fs;Xe&&(Ce=!Ce),ke(Ce),de.blending===E5&&de.transparent===!1?ge(zc):ge(de.blending,de.blendEquation,de.blendSrc,de.blendDst,de.blendEquationAlpha,de.blendSrcAlpha,de.blendDstAlpha,de.premultipliedAlpha),l.setFunc(de.depthFunc),l.setTest(de.depthTest),l.setMask(de.depthWrite),o.setMask(de.colorWrite);let le=de.stencilWrite;c.setTest(le),le&&(c.setMask(de.stencilWriteMask),c.setFunc(de.stencilFunc,de.stencilRef,de.stencilFuncMask),c.setOp(de.stencilFail,de.stencilZFail,de.stencilZPass)),He(de.polygonOffset,de.polygonOffsetFactor,de.polygonOffsetUnits),de.alphaToCoverage===!0?Q(i.SAMPLE_ALPHA_TO_COVERAGE):ue(i.SAMPLE_ALPHA_TO_COVERAGE)}function ke(de){L!==de&&(de?i.frontFace(i.CW):i.frontFace(i.CCW),L=de)}function je(de){de!==XVe?(Q(i.CULL_FACE),de!==B&&(de===Tve?i.cullFace(i.BACK):de===$Ve?i.cullFace(i.FRONT):i.cullFace(i.FRONT_AND_BACK))):ue(i.CULL_FACE),B=de}function he(de){de!==U&&(J&&i.lineWidth(de),U=de)}function He(de,Xe,Ce){de?(Q(i.POLYGON_OFFSET_FILL),(O!==Xe||V!==Ce)&&(i.polygonOffset(Xe,Ce),O=Xe,V=Ce)):ue(i.POLYGON_OFFSET_FILL)}function ae(de){de?Q(i.SCISSOR_TEST):ue(i.SCISSOR_TEST)}function Qe(de){de===void 0&&(de=i.TEXTURE0+F-1),se!==de&&(i.activeTexture(de),se=de)}function $e(de,Xe,Ce){Ce===void 0&&(se===null?Ce=i.TEXTURE0+F-1:Ce=se);let le=j[Ce];le===void 0&&(le={type:void 0,texture:void 0},j[Ce]=le),(le.type!==de||le.texture!==Xe)&&(se!==Ce&&(i.activeTexture(Ce),se=Ce),i.bindTexture(de,Xe||Y[de]),le.type=de,le.texture=Xe)}function te(){let de=j[se];de!==void 0&&de.type!==void 0&&(i.bindTexture(de.type,null),de.type=void 0,de.texture=void 0)}function D(){try{i.compressedTexImage2D.apply(i,arguments)}catch(de){console.error("THREE.WebGLState:",de)}}function ee(){try{i.compressedTexImage3D.apply(i,arguments)}catch(de){console.error("THREE.WebGLState:",de)}}function C(){try{i.texSubImage2D.apply(i,arguments)}catch(de){console.error("THREE.WebGLState:",de)}}function E(){try{i.texSubImage3D.apply(i,arguments)}catch(de){console.error("THREE.WebGLState:",de)}}function R(){try{i.compressedTexSubImage2D.apply(i,arguments)}catch(de){console.error("THREE.WebGLState:",de)}}function N(){try{i.compressedTexSubImage3D.apply(i,arguments)}catch(de){console.error("THREE.WebGLState:",de)}}function H(){try{i.texStorage2D.apply(i,arguments)}catch(de){console.error("THREE.WebGLState:",de)}}function G(){try{i.texStorage3D.apply(i,arguments)}catch(de){console.error("THREE.WebGLState:",de)}}function oe(){try{i.texImage2D.apply(i,arguments)}catch(de){console.error("THREE.WebGLState:",de)}}function fe(){try{i.texImage3D.apply(i,arguments)}catch(de){console.error("THREE.WebGLState:",de)}}function _e(de){K.equals(de)===!1&&(i.scissor(de.x,de.y,de.z,de.w),K.copy(de))}function Re(de){re.equals(de)===!1&&(i.viewport(de.x,de.y,de.z,de.w),re.copy(de))}function Te(de,Xe){let Ce=d.get(Xe);Ce===void 0&&(Ce=new WeakMap,d.set(Xe,Ce));let le=Ce.get(de);le===void 0&&(le=i.getUniformBlockIndex(Xe,de.name),Ce.set(de,le))}function De(de,Xe){let le=d.get(Xe).get(de);u.get(Xe)!==le&&(i.uniformBlockBinding(Xe,le,de.__bindingPointIndex),u.set(Xe,le))}function qe(){i.disable(i.BLEND),i.disable(i.CULL_FACE),i.disable(i.DEPTH_TEST),i.disable(i.POLYGON_OFFSET_FILL),i.disable(i.SCISSOR_TEST),i.disable(i.STENCIL_TEST),i.disable(i.SAMPLE_ALPHA_TO_COVERAGE),i.blendEquation(i.FUNC_ADD),i.blendFunc(i.ONE,i.ZERO),i.blendFuncSeparate(i.ONE,i.ZERO,i.ONE,i.ZERO),i.colorMask(!0,!0,!0,!0),i.clearColor(0,0,0,0),i.depthMask(!0),i.depthFunc(i.LESS),i.clearDepth(1),i.stencilMask(4294967295),i.stencilFunc(i.ALWAYS,0,4294967295),i.stencilOp(i.KEEP,i.KEEP,i.KEEP),i.clearStencil(0),i.cullFace(i.BACK),i.frontFace(i.CCW),i.polygonOffset(0,0),i.activeTexture(i.TEXTURE0),i.bindFramebuffer(i.FRAMEBUFFER,null),n===!0&&(i.bindFramebuffer(i.DRAW_FRAMEBUFFER,null),i.bindFramebuffer(i.READ_FRAMEBUFFER,null)),i.useProgram(null),i.lineWidth(1),i.scissor(0,0,i.canvas.width,i.canvas.height),i.viewport(0,0,i.canvas.width,i.canvas.height),f={},se=null,j={},v={},g=new WeakMap,b=[],y=null,_=!1,x=null,w=null,S=null,A=null,T=null,P=null,I=null,k=!1,L=null,B=null,U=null,O=null,V=null,K.set(0,0,i.canvas.width,i.canvas.height),re.set(0,0,i.canvas.width,i.canvas.height),o.reset(),l.reset(),c.reset()}return{buffers:{color:o,depth:l,stencil:c},enable:Q,disable:ue,bindFramebuffer:me,drawBuffers:we,useProgram:ye,setBlending:ge,setMaterial:Ie,setFlipSided:ke,setCullFace:je,setLineWidth:he,setPolygonOffset:He,setScissorTest:ae,activeTexture:Qe,bindTexture:$e,unbindTexture:te,compressedTexImage2D:D,compressedTexImage3D:ee,texImage2D:oe,texImage3D:fe,updateUBOMapping:Te,uniformBlockBinding:De,texStorage2D:H,texStorage3D:G,texSubImage2D:C,texSubImage3D:E,compressedTexSubImage2D:R,compressedTexSubImage3D:N,scissor:_e,viewport:Re,reset:qe}}function Lje(i,e,t,n,r,s,a){let o=r.isWebGL2,l=r.maxTextures,c=r.maxCubemapSize,u=r.maxTextureSize,d=r.maxSamples,f=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,v=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),g=new WeakMap,b,y=new WeakMap,_=!1;try{_=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function x(te,D){return _?new OffscreenCanvas(te,D):ob("canvas")}function w(te,D,ee,C){let E=1;if((te.width>C||te.height>C)&&(E=C/Math.max(te.width,te.height)),E<1||D===!0)if(typeof HTMLImageElement<"u"&&te instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&te instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&te instanceof ImageBitmap){let R=D?BR:Math.floor,N=R(E*te.width),H=R(E*te.height);b===void 0&&(b=x(N,H));let G=ee?x(N,H):b;return G.width=N,G.height=H,G.getContext("2d").drawImage(te,0,0,N,H),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+te.width+"x"+te.height+") to ("+N+"x"+H+")."),G}else return"data"in te&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+te.width+"x"+te.height+")."),te;return te}function S(te){return dge(te.width)&&dge(te.height)}function A(te){return o?!1:te.wrapS!==Ka||te.wrapT!==Ka||te.minFilter!==Gi&&te.minFilter!==Qs}function T(te,D){return te.generateMipmaps&&D&&te.minFilter!==Gi&&te.minFilter!==Qs}function P(te){i.generateMipmap(te)}function I(te,D,ee,C,E=!1){if(o===!1)return D;if(te!==null){if(i[te]!==void 0)return i[te];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+te+"'")}let R=D;return D===i.RED&&(ee===i.FLOAT&&(R=i.R32F),ee===i.HALF_FLOAT&&(R=i.R16F),ee===i.UNSIGNED_BYTE&&(R=i.R8)),D===i.RED_INTEGER&&(ee===i.UNSIGNED_BYTE&&(R=i.R8UI),ee===i.UNSIGNED_SHORT&&(R=i.R16UI),ee===i.UNSIGNED_INT&&(R=i.R32UI),ee===i.BYTE&&(R=i.R8I),ee===i.SHORT&&(R=i.R16I),ee===i.INT&&(R=i.R32I)),D===i.RG&&(ee===i.FLOAT&&(R=i.RG32F),ee===i.HALF_FLOAT&&(R=i.RG16F),ee===i.UNSIGNED_BYTE&&(R=i.RG8)),D===i.RGBA&&(ee===i.FLOAT&&(R=i.RGBA32F),ee===i.HALF_FLOAT&&(R=i.RGBA16F),ee===i.UNSIGNED_BYTE&&(R=C===tr&&E===!1?i.SRGB8_ALPHA8:i.RGBA8),ee===i.UNSIGNED_SHORT_4_4_4_4&&(R=i.RGBA4),ee===i.UNSIGNED_SHORT_5_5_5_1&&(R=i.RGB5_A1)),(R===i.R16F||R===i.R32F||R===i.RG16F||R===i.RG32F||R===i.RGBA16F||R===i.RGBA32F)&&e.get("EXT_color_buffer_float"),R}function k(te,D,ee){return T(te,ee)===!0||te.isFramebufferTexture&&te.minFilter!==Gi&&te.minFilter!==Qs?Math.log2(Math.max(D.width,D.height))+1:te.mipmaps!==void 0&&te.mipmaps.length>0?te.mipmaps.length:te.isCompressedTexture&&Array.isArray(te.image)?D.mipmaps.length:1}function L(te){return te===Gi||te===Bve||te===KI?i.NEAREST:i.LINEAR}function B(te){let D=te.target;D.removeEventListener("dispose",B),O(D),D.isVideoTexture&&g.delete(D)}function U(te){let D=te.target;D.removeEventListener("dispose",U),F(D)}function O(te){let D=n.get(te);if(D.__webglInit===void 0)return;let ee=te.source,C=y.get(ee);if(C){let E=C[D.__cacheKey];E.usedTimes--,E.usedTimes===0&&V(te),Object.keys(C).length===0&&y.delete(ee)}n.remove(te)}function V(te){let D=n.get(te);i.deleteTexture(D.__webglTexture);let ee=te.source,C=y.get(ee);delete C[D.__cacheKey],a.memory.textures--}function F(te){let D=te.texture,ee=n.get(te),C=n.get(D);if(C.__webglTexture!==void 0&&(i.deleteTexture(C.__webglTexture),a.memory.textures--),te.depthTexture&&te.depthTexture.dispose(),te.isWebGLCubeRenderTarget)for(let E=0;E<6;E++){if(Array.isArray(ee.__webglFramebuffer[E]))for(let R=0;R<ee.__webglFramebuffer[E].length;R++)i.deleteFramebuffer(ee.__webglFramebuffer[E][R]);else i.deleteFramebuffer(ee.__webglFramebuffer[E]);ee.__webglDepthbuffer&&i.deleteRenderbuffer(ee.__webglDepthbuffer[E])}else{if(Array.isArray(ee.__webglFramebuffer))for(let E=0;E<ee.__webglFramebuffer.length;E++)i.deleteFramebuffer(ee.__webglFramebuffer[E]);else i.deleteFramebuffer(ee.__webglFramebuffer);if(ee.__webglDepthbuffer&&i.deleteRenderbuffer(ee.__webglDepthbuffer),ee.__webglMultisampledFramebuffer&&i.deleteFramebuffer(ee.__webglMultisampledFramebuffer),ee.__webglColorRenderbuffer)for(let E=0;E<ee.__webglColorRenderbuffer.length;E++)ee.__webglColorRenderbuffer[E]&&i.deleteRenderbuffer(ee.__webglColorRenderbuffer[E]);ee.__webglDepthRenderbuffer&&i.deleteRenderbuffer(ee.__webglDepthRenderbuffer)}if(te.isWebGLMultipleRenderTargets)for(let E=0,R=D.length;E<R;E++){let N=n.get(D[E]);N.__webglTexture&&(i.deleteTexture(N.__webglTexture),a.memory.textures--),n.remove(D[E])}n.remove(D),n.remove(te)}let J=0;function $(){J=0}function ne(){let te=J;return te>=l&&console.warn("THREE.WebGLTextures: Trying to use "+te+" texture units while this GPU supports only "+l),J+=1,te}function se(te){let D=[];return D.push(te.wrapS),D.push(te.wrapT),D.push(te.wrapR||0),D.push(te.magFilter),D.push(te.minFilter),D.push(te.anisotropy),D.push(te.internalFormat),D.push(te.format),D.push(te.type),D.push(te.generateMipmaps),D.push(te.premultiplyAlpha),D.push(te.flipY),D.push(te.unpackAlignment),D.push(te.colorSpace),D.join()}function j(te,D){let ee=n.get(te);if(te.isVideoTexture&&Qe(te),te.isRenderTargetTexture===!1&&te.version>0&&ee.__version!==te.version){let C=te.image;if(C===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(C.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{me(ee,te,D);return}}t.bindTexture(i.TEXTURE_2D,ee.__webglTexture,i.TEXTURE0+D)}function q(te,D){let ee=n.get(te);if(te.version>0&&ee.__version!==te.version){me(ee,te,D);return}t.bindTexture(i.TEXTURE_2D_ARRAY,ee.__webglTexture,i.TEXTURE0+D)}function z(te,D){let ee=n.get(te);if(te.version>0&&ee.__version!==te.version){me(ee,te,D);return}t.bindTexture(i.TEXTURE_3D,ee.__webglTexture,i.TEXTURE0+D)}function K(te,D){let ee=n.get(te);if(te.version>0&&ee.__version!==te.version){we(ee,te,D);return}t.bindTexture(i.TEXTURE_CUBE_MAP,ee.__webglTexture,i.TEXTURE0+D)}let re={[RR]:i.REPEAT,[Ka]:i.CLAMP_TO_EDGE,[CR]:i.MIRRORED_REPEAT},Z={[Gi]:i.NEAREST,[Bve]:i.NEAREST_MIPMAP_NEAREST,[KI]:i.NEAREST_MIPMAP_LINEAR,[Qs]:i.LINEAR,[wze]:i.LINEAR_MIPMAP_NEAREST,[Gv]:i.LINEAR_MIPMAP_LINEAR},Y={[Oze]:i.NEVER,[qze]:i.ALWAYS,[Nze]:i.LESS,[Fze]:i.LEQUAL,[Uze]:i.EQUAL,[Hze]:i.GEQUAL,[Vze]:i.GREATER,[zze]:i.NOTEQUAL};function Q(te,D,ee){if(ee?(i.texParameteri(te,i.TEXTURE_WRAP_S,re[D.wrapS]),i.texParameteri(te,i.TEXTURE_WRAP_T,re[D.wrapT]),(te===i.TEXTURE_3D||te===i.TEXTURE_2D_ARRAY)&&i.texParameteri(te,i.TEXTURE_WRAP_R,re[D.wrapR]),i.texParameteri(te,i.TEXTURE_MAG_FILTER,Z[D.magFilter]),i.texParameteri(te,i.TEXTURE_MIN_FILTER,Z[D.minFilter])):(i.texParameteri(te,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(te,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),(te===i.TEXTURE_3D||te===i.TEXTURE_2D_ARRAY)&&i.texParameteri(te,i.TEXTURE_WRAP_R,i.CLAMP_TO_EDGE),(D.wrapS!==Ka||D.wrapT!==Ka)&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping."),i.texParameteri(te,i.TEXTURE_MAG_FILTER,L(D.magFilter)),i.texParameteri(te,i.TEXTURE_MIN_FILTER,L(D.minFilter)),D.minFilter!==Gi&&D.minFilter!==Qs&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.")),D.compareFunction&&(i.texParameteri(te,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE),i.texParameteri(te,i.TEXTURE_COMPARE_FUNC,Y[D.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){let C=e.get("EXT_texture_filter_anisotropic");if(D.magFilter===Gi||D.minFilter!==KI&&D.minFilter!==Gv||D.type===Vc&&e.has("OES_texture_float_linear")===!1||o===!1&&D.type===Wv&&e.has("OES_texture_half_float_linear")===!1)return;(D.anisotropy>1||n.get(D).__currentAnisotropy)&&(i.texParameterf(te,C.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(D.anisotropy,r.getMaxAnisotropy())),n.get(D).__currentAnisotropy=D.anisotropy)}}function ue(te,D){let ee=!1;te.__webglInit===void 0&&(te.__webglInit=!0,D.addEventListener("dispose",B));let C=D.source,E=y.get(C);E===void 0&&(E={},y.set(C,E));let R=se(D);if(R!==te.__cacheKey){E[R]===void 0&&(E[R]={texture:i.createTexture(),usedTimes:0},a.memory.textures++,ee=!0),E[R].usedTimes++;let N=E[te.__cacheKey];N!==void 0&&(E[te.__cacheKey].usedTimes--,N.usedTimes===0&&V(D)),te.__cacheKey=R,te.__webglTexture=E[R].texture}return ee}function me(te,D,ee){let C=i.TEXTURE_2D;(D.isDataArrayTexture||D.isCompressedArrayTexture)&&(C=i.TEXTURE_2D_ARRAY),D.isData3DTexture&&(C=i.TEXTURE_3D);let E=ue(te,D),R=D.source;t.bindTexture(C,te.__webglTexture,i.TEXTURE0+ee);let N=n.get(R);if(R.version!==N.__version||E===!0){t.activeTexture(i.TEXTURE0+ee),i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,D.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,D.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,D.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,i.NONE);let H=A(D)&&S(D.image)===!1,G=w(D.image,H,!1,u);G=$e(D,G);let oe=S(G)||o,fe=s.convert(D.format,D.colorSpace),_e=s.convert(D.type),Re=I(D.internalFormat,fe,_e,D.colorSpace,D.isVideoTexture);Q(C,D,oe);let Te,De=D.mipmaps,qe=o&&D.isVideoTexture!==!0,de=N.__version===void 0||E===!0,Xe=k(D,G,oe);if(D.isDepthTexture)Re=i.DEPTH_COMPONENT,o?D.type===Vc?Re=i.DEPTH_COMPONENT32F:D.type===Fc?Re=i.DEPTH_COMPONENT24:D.type===Pd?Re=i.DEPTH24_STENCIL8:Re=i.DEPTH_COMPONENT16:D.type===Vc&&console.error("WebGLRenderer: Floating point depth texture requires WebGL2."),D.format===Ld&&Re===i.DEPTH_COMPONENT&&D.type!==fC&&D.type!==Fc&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),D.type=Fc,_e=s.convert(D.type)),D.format===I5&&Re===i.DEPTH_COMPONENT&&(Re=i.DEPTH_STENCIL,D.type!==Pd&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),D.type=Pd,_e=s.convert(D.type))),de&&(qe?t.texStorage2D(i.TEXTURE_2D,1,Re,G.width,G.height):t.texImage2D(i.TEXTURE_2D,0,Re,G.width,G.height,0,fe,_e,null));else if(D.isDataTexture)if(De.length>0&&oe){qe&&de&&t.texStorage2D(i.TEXTURE_2D,Xe,Re,De[0].width,De[0].height);for(let Ce=0,le=De.length;Ce<le;Ce++)Te=De[Ce],qe?t.texSubImage2D(i.TEXTURE_2D,Ce,0,0,Te.width,Te.height,fe,_e,Te.data):t.texImage2D(i.TEXTURE_2D,Ce,Re,Te.width,Te.height,0,fe,_e,Te.data);D.generateMipmaps=!1}else qe?(de&&t.texStorage2D(i.TEXTURE_2D,Xe,Re,G.width,G.height),t.texSubImage2D(i.TEXTURE_2D,0,0,0,G.width,G.height,fe,_e,G.data)):t.texImage2D(i.TEXTURE_2D,0,Re,G.width,G.height,0,fe,_e,G.data);else if(D.isCompressedTexture)if(D.isCompressedArrayTexture){qe&&de&&t.texStorage3D(i.TEXTURE_2D_ARRAY,Xe,Re,De[0].width,De[0].height,G.depth);for(let Ce=0,le=De.length;Ce<le;Ce++)Te=De[Ce],D.format!==Za?fe!==null?qe?t.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,Ce,0,0,0,Te.width,Te.height,G.depth,fe,Te.data,0,0):t.compressedTexImage3D(i.TEXTURE_2D_ARRAY,Ce,Re,Te.width,Te.height,G.depth,0,Te.data,0,0):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):qe?t.texSubImage3D(i.TEXTURE_2D_ARRAY,Ce,0,0,0,Te.width,Te.height,G.depth,fe,_e,Te.data):t.texImage3D(i.TEXTURE_2D_ARRAY,Ce,Re,Te.width,Te.height,G.depth,0,fe,_e,Te.data)}else{qe&&de&&t.texStorage2D(i.TEXTURE_2D,Xe,Re,De[0].width,De[0].height);for(let Ce=0,le=De.length;Ce<le;Ce++)Te=De[Ce],D.format!==Za?fe!==null?qe?t.compressedTexSubImage2D(i.TEXTURE_2D,Ce,0,0,Te.width,Te.height,fe,Te.data):t.compressedTexImage2D(i.TEXTURE_2D,Ce,Re,Te.width,Te.height,0,Te.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):qe?t.texSubImage2D(i.TEXTURE_2D,Ce,0,0,Te.width,Te.height,fe,_e,Te.data):t.texImage2D(i.TEXTURE_2D,Ce,Re,Te.width,Te.height,0,fe,_e,Te.data)}else if(D.isDataArrayTexture)qe?(de&&t.texStorage3D(i.TEXTURE_2D_ARRAY,Xe,Re,G.width,G.height,G.depth),t.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,0,G.width,G.height,G.depth,fe,_e,G.data)):t.texImage3D(i.TEXTURE_2D_ARRAY,0,Re,G.width,G.height,G.depth,0,fe,_e,G.data);else if(D.isData3DTexture)qe?(de&&t.texStorage3D(i.TEXTURE_3D,Xe,Re,G.width,G.height,G.depth),t.texSubImage3D(i.TEXTURE_3D,0,0,0,0,G.width,G.height,G.depth,fe,_e,G.data)):t.texImage3D(i.TEXTURE_3D,0,Re,G.width,G.height,G.depth,0,fe,_e,G.data);else if(D.isFramebufferTexture){if(de)if(qe)t.texStorage2D(i.TEXTURE_2D,Xe,Re,G.width,G.height);else{let Ce=G.width,le=G.height;for(let Le=0;Le<Xe;Le++)t.texImage2D(i.TEXTURE_2D,Le,Re,Ce,le,0,fe,_e,null),Ce>>=1,le>>=1}}else if(De.length>0&&oe){qe&&de&&t.texStorage2D(i.TEXTURE_2D,Xe,Re,De[0].width,De[0].height);for(let Ce=0,le=De.length;Ce<le;Ce++)Te=De[Ce],qe?t.texSubImage2D(i.TEXTURE_2D,Ce,0,0,fe,_e,Te):t.texImage2D(i.TEXTURE_2D,Ce,Re,fe,_e,Te);D.generateMipmaps=!1}else qe?(de&&t.texStorage2D(i.TEXTURE_2D,Xe,Re,G.width,G.height),t.texSubImage2D(i.TEXTURE_2D,0,0,0,fe,_e,G)):t.texImage2D(i.TEXTURE_2D,0,Re,fe,_e,G);T(D,oe)&&P(C),N.__version=R.version,D.onUpdate&&D.onUpdate(D)}te.__version=D.version}function we(te,D,ee){if(D.image.length!==6)return;let C=ue(te,D),E=D.source;t.bindTexture(i.TEXTURE_CUBE_MAP,te.__webglTexture,i.TEXTURE0+ee);let R=n.get(E);if(E.version!==R.__version||C===!0){t.activeTexture(i.TEXTURE0+ee),i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,D.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,D.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,D.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,i.NONE);let N=D.isCompressedTexture||D.image[0].isCompressedTexture,H=D.image[0]&&D.image[0].isDataTexture,G=[];for(let Ce=0;Ce<6;Ce++)!N&&!H?G[Ce]=w(D.image[Ce],!1,!0,c):G[Ce]=H?D.image[Ce].image:D.image[Ce],G[Ce]=$e(D,G[Ce]);let oe=G[0],fe=S(oe)||o,_e=s.convert(D.format,D.colorSpace),Re=s.convert(D.type),Te=I(D.internalFormat,_e,Re,D.colorSpace),De=o&&D.isVideoTexture!==!0,qe=R.__version===void 0||C===!0,de=k(D,oe,fe);Q(i.TEXTURE_CUBE_MAP,D,fe);let Xe;if(N){De&&qe&&t.texStorage2D(i.TEXTURE_CUBE_MAP,de,Te,oe.width,oe.height);for(let Ce=0;Ce<6;Ce++){Xe=G[Ce].mipmaps;for(let le=0;le<Xe.length;le++){let Le=Xe[le];D.format!==Za?_e!==null?De?t.compressedTexSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Ce,le,0,0,Le.width,Le.height,_e,Le.data):t.compressedTexImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Ce,le,Te,Le.width,Le.height,0,Le.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):De?t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Ce,le,0,0,Le.width,Le.height,_e,Re,Le.data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Ce,le,Te,Le.width,Le.height,0,_e,Re,Le.data)}}}else{Xe=D.mipmaps,De&&qe&&(Xe.length>0&&de++,t.texStorage2D(i.TEXTURE_CUBE_MAP,de,Te,G[0].width,G[0].height));for(let Ce=0;Ce<6;Ce++)if(H){De?t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Ce,0,0,0,G[Ce].width,G[Ce].height,_e,Re,G[Ce].data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Ce,0,Te,G[Ce].width,G[Ce].height,0,_e,Re,G[Ce].data);for(let le=0;le<Xe.length;le++){let Oe=Xe[le].image[Ce].image;De?t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Ce,le+1,0,0,Oe.width,Oe.height,_e,Re,Oe.data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Ce,le+1,Te,Oe.width,Oe.height,0,_e,Re,Oe.data)}}else{De?t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Ce,0,0,0,_e,Re,G[Ce]):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Ce,0,Te,_e,Re,G[Ce]);for(let le=0;le<Xe.length;le++){let Le=Xe[le];De?t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Ce,le+1,0,0,_e,Re,Le.image[Ce]):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Ce,le+1,Te,_e,Re,Le.image[Ce])}}}T(D,fe)&&P(i.TEXTURE_CUBE_MAP),R.__version=E.version,D.onUpdate&&D.onUpdate(D)}te.__version=D.version}function ye(te,D,ee,C,E,R){let N=s.convert(ee.format,ee.colorSpace),H=s.convert(ee.type),G=I(ee.internalFormat,N,H,ee.colorSpace);if(!n.get(D).__hasExternalTextures){let fe=Math.max(1,D.width>>R),_e=Math.max(1,D.height>>R);E===i.TEXTURE_3D||E===i.TEXTURE_2D_ARRAY?t.texImage3D(E,R,G,fe,_e,D.depth,0,N,H,null):t.texImage2D(E,R,G,fe,_e,0,N,H,null)}t.bindFramebuffer(i.FRAMEBUFFER,te),ae(D)?f.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,C,E,n.get(ee).__webglTexture,0,He(D)):(E===i.TEXTURE_2D||E>=i.TEXTURE_CUBE_MAP_POSITIVE_X&&E<=i.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&i.framebufferTexture2D(i.FRAMEBUFFER,C,E,n.get(ee).__webglTexture,R),t.bindFramebuffer(i.FRAMEBUFFER,null)}function pe(te,D,ee){if(i.bindRenderbuffer(i.RENDERBUFFER,te),D.depthBuffer&&!D.stencilBuffer){let C=i.DEPTH_COMPONENT16;if(ee||ae(D)){let E=D.depthTexture;E&&E.isDepthTexture&&(E.type===Vc?C=i.DEPTH_COMPONENT32F:E.type===Fc&&(C=i.DEPTH_COMPONENT24));let R=He(D);ae(D)?f.renderbufferStorageMultisampleEXT(i.RENDERBUFFER,R,C,D.width,D.height):i.renderbufferStorageMultisample(i.RENDERBUFFER,R,C,D.width,D.height)}else i.renderbufferStorage(i.RENDERBUFFER,C,D.width,D.height);i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,te)}else if(D.depthBuffer&&D.stencilBuffer){let C=He(D);ee&&ae(D)===!1?i.renderbufferStorageMultisample(i.RENDERBUFFER,C,i.DEPTH24_STENCIL8,D.width,D.height):ae(D)?f.renderbufferStorageMultisampleEXT(i.RENDERBUFFER,C,i.DEPTH24_STENCIL8,D.width,D.height):i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_STENCIL,D.width,D.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.RENDERBUFFER,te)}else{let C=D.isWebGLMultipleRenderTargets===!0?D.texture:[D.texture];for(let E=0;E<C.length;E++){let R=C[E],N=s.convert(R.format,R.colorSpace),H=s.convert(R.type),G=I(R.internalFormat,N,H,R.colorSpace),oe=He(D);ee&&ae(D)===!1?i.renderbufferStorageMultisample(i.RENDERBUFFER,oe,G,D.width,D.height):ae(D)?f.renderbufferStorageMultisampleEXT(i.RENDERBUFFER,oe,G,D.width,D.height):i.renderbufferStorage(i.RENDERBUFFER,G,D.width,D.height)}}i.bindRenderbuffer(i.RENDERBUFFER,null)}function Ge(te,D){if(D&&D.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(t.bindFramebuffer(i.FRAMEBUFFER,te),!(D.depthTexture&&D.depthTexture.isDepthTexture))throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");(!n.get(D.depthTexture).__webglTexture||D.depthTexture.image.width!==D.width||D.depthTexture.image.height!==D.height)&&(D.depthTexture.image.width=D.width,D.depthTexture.image.height=D.height,D.depthTexture.needsUpdate=!0),j(D.depthTexture,0);let C=n.get(D.depthTexture).__webglTexture,E=He(D);if(D.depthTexture.format===Ld)ae(D)?f.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_2D,C,0,E):i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_2D,C,0);else if(D.depthTexture.format===I5)ae(D)?f.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.TEXTURE_2D,C,0,E):i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.TEXTURE_2D,C,0);else throw new Error("Unknown depthTexture format")}function ge(te){let D=n.get(te),ee=te.isWebGLCubeRenderTarget===!0;if(te.depthTexture&&!D.__autoAllocateDepthBuffer){if(ee)throw new Error("target.depthTexture not supported in Cube render targets");Ge(D.__webglFramebuffer,te)}else if(ee){D.__webglDepthbuffer=[];for(let C=0;C<6;C++)t.bindFramebuffer(i.FRAMEBUFFER,D.__webglFramebuffer[C]),D.__webglDepthbuffer[C]=i.createRenderbuffer(),pe(D.__webglDepthbuffer[C],te,!1)}else t.bindFramebuffer(i.FRAMEBUFFER,D.__webglFramebuffer),D.__webglDepthbuffer=i.createRenderbuffer(),pe(D.__webglDepthbuffer,te,!1);t.bindFramebuffer(i.FRAMEBUFFER,null)}function Ie(te,D,ee){let C=n.get(te);D!==void 0&&ye(C.__webglFramebuffer,te,te.texture,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,0),ee!==void 0&&ge(te)}function ke(te){let D=te.texture,ee=n.get(te),C=n.get(D);te.addEventListener("dispose",U),te.isWebGLMultipleRenderTargets!==!0&&(C.__webglTexture===void 0&&(C.__webglTexture=i.createTexture()),C.__version=D.version,a.memory.textures++);let E=te.isWebGLCubeRenderTarget===!0,R=te.isWebGLMultipleRenderTargets===!0,N=S(te)||o;if(E){ee.__webglFramebuffer=[];for(let H=0;H<6;H++)if(o&&D.mipmaps&&D.mipmaps.length>0){ee.__webglFramebuffer[H]=[];for(let G=0;G<D.mipmaps.length;G++)ee.__webglFramebuffer[H][G]=i.createFramebuffer()}else ee.__webglFramebuffer[H]=i.createFramebuffer()}else{if(o&&D.mipmaps&&D.mipmaps.length>0){ee.__webglFramebuffer=[];for(let H=0;H<D.mipmaps.length;H++)ee.__webglFramebuffer[H]=i.createFramebuffer()}else ee.__webglFramebuffer=i.createFramebuffer();if(R)if(r.drawBuffers){let H=te.texture;for(let G=0,oe=H.length;G<oe;G++){let fe=n.get(H[G]);fe.__webglTexture===void 0&&(fe.__webglTexture=i.createTexture(),a.memory.textures++)}}else console.warn("THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.");if(o&&te.samples>0&&ae(te)===!1){let H=R?D:[D];ee.__webglMultisampledFramebuffer=i.createFramebuffer(),ee.__webglColorRenderbuffer=[],t.bindFramebuffer(i.FRAMEBUFFER,ee.__webglMultisampledFramebuffer);for(let G=0;G<H.length;G++){let oe=H[G];ee.__webglColorRenderbuffer[G]=i.createRenderbuffer(),i.bindRenderbuffer(i.RENDERBUFFER,ee.__webglColorRenderbuffer[G]);let fe=s.convert(oe.format,oe.colorSpace),_e=s.convert(oe.type),Re=I(oe.internalFormat,fe,_e,oe.colorSpace,te.isXRRenderTarget===!0),Te=He(te);i.renderbufferStorageMultisample(i.RENDERBUFFER,Te,Re,te.width,te.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+G,i.RENDERBUFFER,ee.__webglColorRenderbuffer[G])}i.bindRenderbuffer(i.RENDERBUFFER,null),te.depthBuffer&&(ee.__webglDepthRenderbuffer=i.createRenderbuffer(),pe(ee.__webglDepthRenderbuffer,te,!0)),t.bindFramebuffer(i.FRAMEBUFFER,null)}}if(E){t.bindTexture(i.TEXTURE_CUBE_MAP,C.__webglTexture),Q(i.TEXTURE_CUBE_MAP,D,N);for(let H=0;H<6;H++)if(o&&D.mipmaps&&D.mipmaps.length>0)for(let G=0;G<D.mipmaps.length;G++)ye(ee.__webglFramebuffer[H][G],te,D,i.COLOR_ATTACHMENT0,i.TEXTURE_CUBE_MAP_POSITIVE_X+H,G);else ye(ee.__webglFramebuffer[H],te,D,i.COLOR_ATTACHMENT0,i.TEXTURE_CUBE_MAP_POSITIVE_X+H,0);T(D,N)&&P(i.TEXTURE_CUBE_MAP),t.unbindTexture()}else if(R){let H=te.texture;for(let G=0,oe=H.length;G<oe;G++){let fe=H[G],_e=n.get(fe);t.bindTexture(i.TEXTURE_2D,_e.__webglTexture),Q(i.TEXTURE_2D,fe,N),ye(ee.__webglFramebuffer,te,fe,i.COLOR_ATTACHMENT0+G,i.TEXTURE_2D,0),T(fe,N)&&P(i.TEXTURE_2D)}t.unbindTexture()}else{let H=i.TEXTURE_2D;if((te.isWebGL3DRenderTarget||te.isWebGLArrayRenderTarget)&&(o?H=te.isWebGL3DRenderTarget?i.TEXTURE_3D:i.TEXTURE_2D_ARRAY:console.error("THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.")),t.bindTexture(H,C.__webglTexture),Q(H,D,N),o&&D.mipmaps&&D.mipmaps.length>0)for(let G=0;G<D.mipmaps.length;G++)ye(ee.__webglFramebuffer[G],te,D,i.COLOR_ATTACHMENT0,H,G);else ye(ee.__webglFramebuffer,te,D,i.COLOR_ATTACHMENT0,H,0);T(D,N)&&P(H),t.unbindTexture()}te.depthBuffer&&ge(te)}function je(te){let D=S(te)||o,ee=te.isWebGLMultipleRenderTargets===!0?te.texture:[te.texture];for(let C=0,E=ee.length;C<E;C++){let R=ee[C];if(T(R,D)){let N=te.isWebGLCubeRenderTarget?i.TEXTURE_CUBE_MAP:i.TEXTURE_2D,H=n.get(R).__webglTexture;t.bindTexture(N,H),P(N),t.unbindTexture()}}}function he(te){if(o&&te.samples>0&&ae(te)===!1){let D=te.isWebGLMultipleRenderTargets?te.texture:[te.texture],ee=te.width,C=te.height,E=i.COLOR_BUFFER_BIT,R=[],N=te.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,H=n.get(te),G=te.isWebGLMultipleRenderTargets===!0;if(G)for(let oe=0;oe<D.length;oe++)t.bindFramebuffer(i.FRAMEBUFFER,H.__webglMultisampledFramebuffer),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+oe,i.RENDERBUFFER,null),t.bindFramebuffer(i.FRAMEBUFFER,H.__webglFramebuffer),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0+oe,i.TEXTURE_2D,null,0);t.bindFramebuffer(i.READ_FRAMEBUFFER,H.__webglMultisampledFramebuffer),t.bindFramebuffer(i.DRAW_FRAMEBUFFER,H.__webglFramebuffer);for(let oe=0;oe<D.length;oe++){R.push(i.COLOR_ATTACHMENT0+oe),te.depthBuffer&&R.push(N);let fe=H.__ignoreDepthValues!==void 0?H.__ignoreDepthValues:!1;if(fe===!1&&(te.depthBuffer&&(E|=i.DEPTH_BUFFER_BIT),te.stencilBuffer&&(E|=i.STENCIL_BUFFER_BIT)),G&&i.framebufferRenderbuffer(i.READ_FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.RENDERBUFFER,H.__webglColorRenderbuffer[oe]),fe===!0&&(i.invalidateFramebuffer(i.READ_FRAMEBUFFER,[N]),i.invalidateFramebuffer(i.DRAW_FRAMEBUFFER,[N])),G){let _e=n.get(D[oe]).__webglTexture;i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,_e,0)}i.blitFramebuffer(0,0,ee,C,0,0,ee,C,E,i.NEAREST),v&&i.invalidateFramebuffer(i.READ_FRAMEBUFFER,R)}if(t.bindFramebuffer(i.READ_FRAMEBUFFER,null),t.bindFramebuffer(i.DRAW_FRAMEBUFFER,null),G)for(let oe=0;oe<D.length;oe++){t.bindFramebuffer(i.FRAMEBUFFER,H.__webglMultisampledFramebuffer),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+oe,i.RENDERBUFFER,H.__webglColorRenderbuffer[oe]);let fe=n.get(D[oe]).__webglTexture;t.bindFramebuffer(i.FRAMEBUFFER,H.__webglFramebuffer),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0+oe,i.TEXTURE_2D,fe,0)}t.bindFramebuffer(i.DRAW_FRAMEBUFFER,H.__webglMultisampledFramebuffer)}}function He(te){return Math.min(d,te.samples)}function ae(te){let D=n.get(te);return o&&te.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&D.__useRenderToTexture!==!1}function Qe(te){let D=a.render.frame;g.get(te)!==D&&(g.set(te,D),te.update())}function $e(te,D){let ee=te.colorSpace,C=te.format,E=te.type;return te.isCompressedTexture===!0||te.isVideoTexture===!0||te.format===PR||ee!==Wo&&ee!==Dd&&(ee===tr||ee===xb?o===!1?e.has("EXT_sRGB")===!0&&C===Za?(te.format=PR,te.minFilter=Qs,te.generateMipmaps=!1):D=lb.sRGBToLinear(D):(C!==Za||E!==qc)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",ee)),D}this.allocateTextureUnit=ne,this.resetTextureUnits=$,this.setTexture2D=j,this.setTexture2DArray=q,this.setTexture3D=z,this.setTextureCube=K,this.rebindTextures=Ie,this.setupRenderTarget=ke,this.updateRenderTargetMipmap=je,this.updateMultisampleRenderTarget=he,this.setupDepthRenderbuffer=ge,this.setupFrameBufferTexture=ye,this.useMultisampledRTT=ae}var Bje=0,Ur=1;function Dje(i,e,t){let n=t.isWebGL2;function r(s,a=Dd){let o,l=a===tr||a===xb?Ur:Bje;if(s===qc)return i.UNSIGNED_BYTE;if(s===Qge)return i.UNSIGNED_SHORT_4_4_4_4;if(s===e6e)return i.UNSIGNED_SHORT_5_5_5_1;if(s===Sze)return i.BYTE;if(s===Eze)return i.SHORT;if(s===fC)return i.UNSIGNED_SHORT;if(s===Zge)return i.INT;if(s===Fc)return i.UNSIGNED_INT;if(s===Vc)return i.FLOAT;if(s===Wv)return n?i.HALF_FLOAT:(o=e.get("OES_texture_half_float"),o!==null?o.HALF_FLOAT_OES:null);if(s===Mze)return i.ALPHA;if(s===Za)return i.RGBA;if(s===Aze)return i.LUMINANCE;if(s===kze)return i.LUMINANCE_ALPHA;if(s===Ld)return i.DEPTH_COMPONENT;if(s===I5)return i.DEPTH_STENCIL;if(s===PR)return o=e.get("EXT_sRGB"),o!==null?o.SRGB_ALPHA_EXT:null;if(s===Tze)return i.RED;if(s===t6e)return i.RED_INTEGER;if(s===Ize)return i.RG;if(s===n6e)return i.RG_INTEGER;if(s===r6e)return i.RGBA_INTEGER;if(s===ZI||s===QI||s===eR||s===tR)if(l===Ur)if(o=e.get("WEBGL_compressed_texture_s3tc_srgb"),o!==null){if(s===ZI)return o.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(s===QI)return o.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(s===eR)return o.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(s===tR)return o.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(o=e.get("WEBGL_compressed_texture_s3tc"),o!==null){if(s===ZI)return o.COMPRESSED_RGB_S3TC_DXT1_EXT;if(s===QI)return o.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(s===eR)return o.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(s===tR)return o.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(s===Dve||s===Ove||s===Nve||s===Uve)if(o=e.get("WEBGL_compressed_texture_pvrtc"),o!==null){if(s===Dve)return o.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(s===Ove)return o.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(s===Nve)return o.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(s===Uve)return o.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(s===Rze)return o=e.get("WEBGL_compressed_texture_etc1"),o!==null?o.COMPRESSED_RGB_ETC1_WEBGL:null;if(s===Fve||s===Vve)if(o=e.get("WEBGL_compressed_texture_etc"),o!==null){if(s===Fve)return l===Ur?o.COMPRESSED_SRGB8_ETC2:o.COMPRESSED_RGB8_ETC2;if(s===Vve)return l===Ur?o.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:o.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(s===zve||s===Hve||s===qve||s===Gve||s===Wve||s===jve||s===Xve||s===$ve||s===Yve||s===Jve||s===Kve||s===Zve||s===Qve||s===ege)if(o=e.get("WEBGL_compressed_texture_astc"),o!==null){if(s===zve)return l===Ur?o.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:o.COMPRESSED_RGBA_ASTC_4x4_KHR;if(s===Hve)return l===Ur?o.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:o.COMPRESSED_RGBA_ASTC_5x4_KHR;if(s===qve)return l===Ur?o.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:o.COMPRESSED_RGBA_ASTC_5x5_KHR;if(s===Gve)return l===Ur?o.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:o.COMPRESSED_RGBA_ASTC_6x5_KHR;if(s===Wve)return l===Ur?o.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:o.COMPRESSED_RGBA_ASTC_6x6_KHR;if(s===jve)return l===Ur?o.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:o.COMPRESSED_RGBA_ASTC_8x5_KHR;if(s===Xve)return l===Ur?o.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:o.COMPRESSED_RGBA_ASTC_8x6_KHR;if(s===$ve)return l===Ur?o.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:o.COMPRESSED_RGBA_ASTC_8x8_KHR;if(s===Yve)return l===Ur?o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:o.COMPRESSED_RGBA_ASTC_10x5_KHR;if(s===Jve)return l===Ur?o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:o.COMPRESSED_RGBA_ASTC_10x6_KHR;if(s===Kve)return l===Ur?o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:o.COMPRESSED_RGBA_ASTC_10x8_KHR;if(s===Zve)return l===Ur?o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:o.COMPRESSED_RGBA_ASTC_10x10_KHR;if(s===Qve)return l===Ur?o.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:o.COMPRESSED_RGBA_ASTC_12x10_KHR;if(s===ege)return l===Ur?o.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:o.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(s===nR||s===tge||s===nge)if(o=e.get("EXT_texture_compression_bptc"),o!==null){if(s===nR)return l===Ur?o.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:o.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(s===tge)return o.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(s===nge)return o.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(s===Cze||s===rge||s===ige||s===sge)if(o=e.get("EXT_texture_compression_rgtc"),o!==null){if(s===nR)return o.COMPRESSED_RED_RGTC1_EXT;if(s===rge)return o.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(s===ige)return o.COMPRESSED_RED_GREEN_RGTC2_EXT;if(s===sge)return o.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return s===Pd?n?i.UNSIGNED_INT_24_8:(o=e.get("WEBGL_depth_texture"),o!==null?o.UNSIGNED_INT_24_8_WEBGL:null):i[s]!==void 0?i[s]:null}return{convert:r}}var JR=class extends Os{constructor(e=[]){super(),this.isArrayCamera=!0,this.cameras=e}},Fr=class extends jo{constructor(){super(),this.isGroup=!0,this.type="Group"}},Oje={type:"move"},qv=class{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Fr,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 Fr,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new Ve,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new Ve),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Fr,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new Ve,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new Ve),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){let t=this._hand;if(t)for(let n of e.hand.values())this._getHandJoint(t,n)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),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,n){let r=null,s=null,a=null,o=this._targetRay,l=this._grip,c=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(c&&e.hand){a=!0;for(let b of e.hand.values()){let y=t.getJointPose(b,n),_=this._getHandJoint(c,b);y!==null&&(_.matrix.fromArray(y.transform.matrix),_.matrix.decompose(_.position,_.rotation,_.scale),_.matrixWorldNeedsUpdate=!0,_.jointRadius=y.radius),_.visible=y!==null}let u=c.joints["index-finger-tip"],d=c.joints["thumb-tip"],f=u.position.distanceTo(d.position),v=.02,g=.005;c.inputState.pinching&&f>v+g?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!c.inputState.pinching&&f<=v-g&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(s=t.getPose(e.gripSpace,n),s!==null&&(l.matrix.fromArray(s.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,s.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(s.linearVelocity)):l.hasLinearVelocity=!1,s.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(s.angularVelocity)):l.hasAngularVelocity=!1));o!==null&&(r=t.getPose(e.targetRaySpace,n),r===null&&s!==null&&(r=s),r!==null&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(Oje)))}return o!==null&&(o.visible=r!==null),l!==null&&(l.visible=s!==null),c!==null&&(c.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){let n=new Fr;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}},KR=class extends eo{constructor(e,t,n,r,s,a,o,l,c,u){if(u=u!==void 0?u:Ld,u!==Ld&&u!==I5)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");n===void 0&&u===Ld&&(n=Fc),n===void 0&&u===I5&&(n=Pd),super(null,r,s,a,o,l,u,n,c),this.isDepthTexture=!0,this.image={width:e,height:t},this.magFilter=o!==void 0?o:Gi,this.minFilter=l!==void 0?l:Gi,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.compareFunction=e.compareFunction,this}toJSON(e){let t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}},ZR=class extends Gc{constructor(e,t){super();let n=this,r=null,s=1,a=null,o="local-floor",l=1,c=null,u=null,d=null,f=null,v=null,g=null,b=t.getContextAttributes(),y=null,_=null,x=[],w=[],S=new Os;S.layers.enable(1),S.viewport=new ni;let A=new Os;A.layers.enable(2),A.viewport=new ni;let T=[S,A],P=new JR;P.layers.enable(1),P.layers.enable(2);let I=null,k=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(q){let z=x[q];return z===void 0&&(z=new qv,x[q]=z),z.getTargetRaySpace()},this.getControllerGrip=function(q){let z=x[q];return z===void 0&&(z=new qv,x[q]=z),z.getGripSpace()},this.getHand=function(q){let z=x[q];return z===void 0&&(z=new qv,x[q]=z),z.getHandSpace()};function L(q){let z=w.indexOf(q.inputSource);if(z===-1)return;let K=x[z];K!==void 0&&(K.update(q.inputSource,q.frame,c||a),K.dispatchEvent({type:q.type,data:q.inputSource}))}function B(){r.removeEventListener("select",L),r.removeEventListener("selectstart",L),r.removeEventListener("selectend",L),r.removeEventListener("squeeze",L),r.removeEventListener("squeezestart",L),r.removeEventListener("squeezeend",L),r.removeEventListener("end",B),r.removeEventListener("inputsourceschange",U);for(let q=0;q<x.length;q++){let z=w[q];z!==null&&(w[q]=null,x[q].disconnect(z))}I=null,k=null,e.setRenderTarget(y),v=null,f=null,d=null,r=null,_=null,j.stop(),n.isPresenting=!1,n.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(q){s=q,n.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(q){o=q,n.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return c||a},this.setReferenceSpace=function(q){c=q},this.getBaseLayer=function(){return f!==null?f:v},this.getBinding=function(){return d},this.getFrame=function(){return g},this.getSession=function(){return r},this.setSession=async function(q){if(r=q,r!==null){if(y=e.getRenderTarget(),r.addEventListener("select",L),r.addEventListener("selectstart",L),r.addEventListener("selectend",L),r.addEventListener("squeeze",L),r.addEventListener("squeezestart",L),r.addEventListener("squeezeend",L),r.addEventListener("end",B),r.addEventListener("inputsourceschange",U),b.xrCompatible!==!0&&await t.makeXRCompatible(),r.renderState.layers===void 0||e.capabilities.isWebGL2===!1){let z={antialias:r.renderState.layers===void 0?b.antialias:!0,alpha:!0,depth:b.depth,stencil:b.stencil,framebufferScaleFactor:s};v=new XRWebGLLayer(r,t,z),r.updateRenderState({baseLayer:v}),_=new i0(v.framebufferWidth,v.framebufferHeight,{format:Za,type:qc,colorSpace:e.outputColorSpace,stencilBuffer:b.stencil})}else{let z=null,K=null,re=null;b.depth&&(re=b.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,z=b.stencil?I5:Ld,K=b.stencil?Pd:Fc);let Z={colorFormat:t.RGBA8,depthFormat:re,scaleFactor:s};d=new XRWebGLBinding(r,t),f=d.createProjectionLayer(Z),r.updateRenderState({layers:[f]}),_=new i0(f.textureWidth,f.textureHeight,{format:Za,type:qc,depthTexture:new KR(f.textureWidth,f.textureHeight,K,void 0,void 0,void 0,void 0,void 0,void 0,z),stencilBuffer:b.stencil,colorSpace:e.outputColorSpace,samples:b.antialias?4:0});let Y=e.properties.get(_);Y.__ignoreDepthValues=f.ignoreDepthValues}_.isXRRenderTarget=!0,this.setFoveation(l),c=null,a=await r.requestReferenceSpace(o),j.setContext(r),j.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(r!==null)return r.environmentBlendMode};function U(q){for(let z=0;z<q.removed.length;z++){let K=q.removed[z],re=w.indexOf(K);re>=0&&(w[re]=null,x[re].disconnect(K))}for(let z=0;z<q.added.length;z++){let K=q.added[z],re=w.indexOf(K);if(re===-1){for(let Y=0;Y<x.length;Y++)if(Y>=w.length){w.push(K),re=Y;break}else if(w[Y]===null){w[Y]=K,re=Y;break}if(re===-1)break}let Z=x[re];Z&&Z.connect(K)}}let O=new Ve,V=new Ve;function F(q,z,K){O.setFromMatrixPosition(z.matrixWorld),V.setFromMatrixPosition(K.matrixWorld);let re=O.distanceTo(V),Z=z.projectionMatrix.elements,Y=K.projectionMatrix.elements,Q=Z[14]/(Z[10]-1),ue=Z[14]/(Z[10]+1),me=(Z[9]+1)/Z[5],we=(Z[9]-1)/Z[5],ye=(Z[8]-1)/Z[0],pe=(Y[8]+1)/Y[0],Ge=Q*ye,ge=Q*pe,Ie=re/(-ye+pe),ke=Ie*-ye;z.matrixWorld.decompose(q.position,q.quaternion,q.scale),q.translateX(ke),q.translateZ(Ie),q.matrixWorld.compose(q.position,q.quaternion,q.scale),q.matrixWorldInverse.copy(q.matrixWorld).invert();let je=Q+Ie,he=ue+Ie,He=Ge-ke,ae=ge+(re-ke),Qe=me*ue/he*je,$e=we*ue/he*je;q.projectionMatrix.makePerspective(He,ae,Qe,$e,je,he),q.projectionMatrixInverse.copy(q.projectionMatrix).invert()}function J(q,z){z===null?q.matrixWorld.copy(q.matrix):q.matrixWorld.multiplyMatrices(z.matrixWorld,q.matrix),q.matrixWorldInverse.copy(q.matrixWorld).invert()}this.updateCamera=function(q){if(r===null)return;P.near=A.near=S.near=q.near,P.far=A.far=S.far=q.far,(I!==P.near||k!==P.far)&&(r.updateRenderState({depthNear:P.near,depthFar:P.far}),I=P.near,k=P.far);let z=q.parent,K=P.cameras;J(P,z);for(let re=0;re<K.length;re++)J(K[re],z);K.length===2?F(P,S,A):P.projectionMatrix.copy(S.projectionMatrix),$(q,P,z)};function $(q,z,K){K===null?q.matrix.copy(z.matrixWorld):(q.matrix.copy(K.matrixWorld),q.matrix.invert(),q.matrix.multiply(z.matrixWorld)),q.matrix.decompose(q.position,q.quaternion,q.scale),q.updateMatrixWorld(!0),q.projectionMatrix.copy(z.projectionMatrix),q.projectionMatrixInverse.copy(z.projectionMatrixInverse),q.isPerspectiveCamera&&(q.fov=LR*2*Math.atan(1/q.projectionMatrix.elements[5]),q.zoom=1)}this.getCamera=function(){return P},this.getFoveation=function(){if(!(f===null&&v===null))return l},this.setFoveation=function(q){l=q,f!==null&&(f.fixedFoveation=q),v!==null&&v.fixedFoveation!==void 0&&(v.fixedFoveation=q)};let ne=null;function se(q,z){if(u=z.getViewerPose(c||a),g=z,u!==null){let K=u.views;v!==null&&(e.setRenderTargetFramebuffer(_,v.framebuffer),e.setRenderTarget(_));let re=!1;K.length!==P.cameras.length&&(P.cameras.length=0,re=!0);for(let Z=0;Z<K.length;Z++){let Y=K[Z],Q=null;if(v!==null)Q=v.getViewport(Y);else{let me=d.getViewSubImage(f,Y);Q=me.viewport,Z===0&&(e.setRenderTargetTextures(_,me.colorTexture,f.ignoreDepthValues?void 0:me.depthStencilTexture),e.setRenderTarget(_))}let ue=T[Z];ue===void 0&&(ue=new Os,ue.layers.enable(Z),ue.viewport=new ni,T[Z]=ue),ue.matrix.fromArray(Y.transform.matrix),ue.matrix.decompose(ue.position,ue.quaternion,ue.scale),ue.projectionMatrix.fromArray(Y.projectionMatrix),ue.projectionMatrixInverse.copy(ue.projectionMatrix).invert(),ue.viewport.set(Q.x,Q.y,Q.width,Q.height),Z===0&&(P.matrix.copy(ue.matrix),P.matrix.decompose(P.position,P.quaternion,P.scale)),re===!0&&P.cameras.push(ue)}}for(let K=0;K<x.length;K++){let re=w[K],Z=x[K];re!==null&&Z!==void 0&&Z.update(re,z,c||a)}ne&&ne(q,z),z.detectedPlanes&&n.dispatchEvent({type:"planesdetected",data:z}),g=null}let j=new c6e;j.setAnimationLoop(se),this.setAnimationLoop=function(q){ne=q},this.dispose=function(){}}};function Nje(i,e){function t(y,_){y.matrixAutoUpdate===!0&&y.updateMatrix(),_.value.copy(y.matrix)}function n(y,_){_.color.getRGB(y.fogColor.value,l6e(i)),_.isFog?(y.fogNear.value=_.near,y.fogFar.value=_.far):_.isFogExp2&&(y.fogDensity.value=_.density)}function r(y,_,x,w,S){_.isMeshBasicMaterial||_.isMeshLambertMaterial?s(y,_):_.isMeshToonMaterial?(s(y,_),d(y,_)):_.isMeshPhongMaterial?(s(y,_),u(y,_)):_.isMeshStandardMaterial?(s(y,_),f(y,_),_.isMeshPhysicalMaterial&&v(y,_,S)):_.isMeshMatcapMaterial?(s(y,_),g(y,_)):_.isMeshDepthMaterial?s(y,_):_.isMeshDistanceMaterial?(s(y,_),b(y,_)):_.isMeshNormalMaterial?s(y,_):_.isLineBasicMaterial?(a(y,_),_.isLineDashedMaterial&&o(y,_)):_.isPointsMaterial?l(y,_,x,w):_.isSpriteMaterial?c(y,_):_.isShadowMaterial?(y.color.value.copy(_.color),y.opacity.value=_.opacity):_.isShaderMaterial&&(_.uniformsNeedUpdate=!1)}function s(y,_){y.opacity.value=_.opacity,_.color&&y.diffuse.value.copy(_.color),_.emissive&&y.emissive.value.copy(_.emissive).multiplyScalar(_.emissiveIntensity),_.map&&(y.map.value=_.map,t(_.map,y.mapTransform)),_.alphaMap&&(y.alphaMap.value=_.alphaMap,t(_.alphaMap,y.alphaMapTransform)),_.bumpMap&&(y.bumpMap.value=_.bumpMap,t(_.bumpMap,y.bumpMapTransform),y.bumpScale.value=_.bumpScale,_.side===fs&&(y.bumpScale.value*=-1)),_.normalMap&&(y.normalMap.value=_.normalMap,t(_.normalMap,y.normalMapTransform),y.normalScale.value.copy(_.normalScale),_.side===fs&&y.normalScale.value.negate()),_.displacementMap&&(y.displacementMap.value=_.displacementMap,t(_.displacementMap,y.displacementMapTransform),y.displacementScale.value=_.displacementScale,y.displacementBias.value=_.displacementBias),_.emissiveMap&&(y.emissiveMap.value=_.emissiveMap,t(_.emissiveMap,y.emissiveMapTransform)),_.specularMap&&(y.specularMap.value=_.specularMap,t(_.specularMap,y.specularMapTransform)),_.alphaTest>0&&(y.alphaTest.value=_.alphaTest);let x=e.get(_).envMap;if(x&&(y.envMap.value=x,y.flipEnvMap.value=x.isCubeTexture&&x.isRenderTargetTexture===!1?-1:1,y.reflectivity.value=_.reflectivity,y.ior.value=_.ior,y.refractionRatio.value=_.refractionRatio),_.lightMap){y.lightMap.value=_.lightMap;let w=i._useLegacyLights===!0?Math.PI:1;y.lightMapIntensity.value=_.lightMapIntensity*w,t(_.lightMap,y.lightMapTransform)}_.aoMap&&(y.aoMap.value=_.aoMap,y.aoMapIntensity.value=_.aoMapIntensity,t(_.aoMap,y.aoMapTransform))}function a(y,_){y.diffuse.value.copy(_.color),y.opacity.value=_.opacity,_.map&&(y.map.value=_.map,t(_.map,y.mapTransform))}function o(y,_){y.dashSize.value=_.dashSize,y.totalSize.value=_.dashSize+_.gapSize,y.scale.value=_.scale}function l(y,_,x,w){y.diffuse.value.copy(_.color),y.opacity.value=_.opacity,y.size.value=_.size*x,y.scale.value=w*.5,_.map&&(y.map.value=_.map,t(_.map,y.uvTransform)),_.alphaMap&&(y.alphaMap.value=_.alphaMap,t(_.alphaMap,y.alphaMapTransform)),_.alphaTest>0&&(y.alphaTest.value=_.alphaTest)}function c(y,_){y.diffuse.value.copy(_.color),y.opacity.value=_.opacity,y.rotation.value=_.rotation,_.map&&(y.map.value=_.map,t(_.map,y.mapTransform)),_.alphaMap&&(y.alphaMap.value=_.alphaMap,t(_.alphaMap,y.alphaMapTransform)),_.alphaTest>0&&(y.alphaTest.value=_.alphaTest)}function u(y,_){y.specular.value.copy(_.specular),y.shininess.value=Math.max(_.shininess,1e-4)}function d(y,_){_.gradientMap&&(y.gradientMap.value=_.gradientMap)}function f(y,_){y.metalness.value=_.metalness,_.metalnessMap&&(y.metalnessMap.value=_.metalnessMap,t(_.metalnessMap,y.metalnessMapTransform)),y.roughness.value=_.roughness,_.roughnessMap&&(y.roughnessMap.value=_.roughnessMap,t(_.roughnessMap,y.roughnessMapTransform)),e.get(_).envMap&&(y.envMapIntensity.value=_.envMapIntensity)}function v(y,_,x){y.ior.value=_.ior,_.sheen>0&&(y.sheenColor.value.copy(_.sheenColor).multiplyScalar(_.sheen),y.sheenRoughness.value=_.sheenRoughness,_.sheenColorMap&&(y.sheenColorMap.value=_.sheenColorMap,t(_.sheenColorMap,y.sheenColorMapTransform)),_.sheenRoughnessMap&&(y.sheenRoughnessMap.value=_.sheenRoughnessMap,t(_.sheenRoughnessMap,y.sheenRoughnessMapTransform))),_.clearcoat>0&&(y.clearcoat.value=_.clearcoat,y.clearcoatRoughness.value=_.clearcoatRoughness,_.clearcoatMap&&(y.clearcoatMap.value=_.clearcoatMap,t(_.clearcoatMap,y.clearcoatMapTransform)),_.clearcoatRoughnessMap&&(y.clearcoatRoughnessMap.value=_.clearcoatRoughnessMap,t(_.clearcoatRoughnessMap,y.clearcoatRoughnessMapTransform)),_.clearcoatNormalMap&&(y.clearcoatNormalMap.value=_.clearcoatNormalMap,t(_.clearcoatNormalMap,y.clearcoatNormalMapTransform),y.clearcoatNormalScale.value.copy(_.clearcoatNormalScale),_.side===fs&&y.clearcoatNormalScale.value.negate())),_.iridescence>0&&(y.iridescence.value=_.iridescence,y.iridescenceIOR.value=_.iridescenceIOR,y.iridescenceThicknessMinimum.value=_.iridescenceThicknessRange[0],y.iridescenceThicknessMaximum.value=_.iridescenceThicknessRange[1],_.iridescenceMap&&(y.iridescenceMap.value=_.iridescenceMap,t(_.iridescenceMap,y.iridescenceMapTransform)),_.iridescenceThicknessMap&&(y.iridescenceThicknessMap.value=_.iridescenceThicknessMap,t(_.iridescenceThicknessMap,y.iridescenceThicknessMapTransform))),_.transmission>0&&(y.transmission.value=_.transmission,y.transmissionSamplerMap.value=x.texture,y.transmissionSamplerSize.value.set(x.width,x.height),_.transmissionMap&&(y.transmissionMap.value=_.transmissionMap,t(_.transmissionMap,y.transmissionMapTransform)),y.thickness.value=_.thickness,_.thicknessMap&&(y.thicknessMap.value=_.thicknessMap,t(_.thicknessMap,y.thicknessMapTransform)),y.attenuationDistance.value=_.attenuationDistance,y.attenuationColor.value.copy(_.attenuationColor)),_.anisotropy>0&&(y.anisotropyVector.value.set(_.anisotropy*Math.cos(_.anisotropyRotation),_.anisotropy*Math.sin(_.anisotropyRotation)),_.anisotropyMap&&(y.anisotropyMap.value=_.anisotropyMap,t(_.anisotropyMap,y.anisotropyMapTransform))),y.specularIntensity.value=_.specularIntensity,y.specularColor.value.copy(_.specularColor),_.specularColorMap&&(y.specularColorMap.value=_.specularColorMap,t(_.specularColorMap,y.specularColorMapTransform)),_.specularIntensityMap&&(y.specularIntensityMap.value=_.specularIntensityMap,t(_.specularIntensityMap,y.specularIntensityMapTransform))}function g(y,_){_.matcap&&(y.matcap.value=_.matcap)}function b(y,_){let x=e.get(_).light;y.referencePosition.value.setFromMatrixPosition(x.matrixWorld),y.nearDistance.value=x.shadow.camera.near,y.farDistance.value=x.shadow.camera.far}return{refreshFogUniforms:n,refreshMaterialUniforms:r}}function Uje(i,e,t,n){let r={},s={},a=[],o=t.isWebGL2?i.getParameter(i.MAX_UNIFORM_BUFFER_BINDINGS):0;function l(x,w){let S=w.program;n.uniformBlockBinding(x,S)}function c(x,w){let S=r[x.id];S===void 0&&(g(x),S=u(x),r[x.id]=S,x.addEventListener("dispose",y));let A=w.program;n.updateUBOMapping(x,A);let T=e.render.frame;s[x.id]!==T&&(f(x),s[x.id]=T)}function u(x){let w=d();x.__bindingPointIndex=w;let S=i.createBuffer(),A=x.__size,T=x.usage;return i.bindBuffer(i.UNIFORM_BUFFER,S),i.bufferData(i.UNIFORM_BUFFER,A,T),i.bindBuffer(i.UNIFORM_BUFFER,null),i.bindBufferBase(i.UNIFORM_BUFFER,w,S),S}function d(){for(let x=0;x<o;x++)if(a.indexOf(x)===-1)return a.push(x),x;return console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function f(x){let w=r[x.id],S=x.uniforms,A=x.__cache;i.bindBuffer(i.UNIFORM_BUFFER,w);for(let T=0,P=S.length;T<P;T++){let I=S[T];if(v(I,T,A)===!0){let k=I.__offset,L=Array.isArray(I.value)?I.value:[I.value],B=0;for(let U=0;U<L.length;U++){let O=L[U],V=b(O);typeof O=="number"?(I.__data[0]=O,i.bufferSubData(i.UNIFORM_BUFFER,k+B,I.__data)):O.isMatrix3?(I.__data[0]=O.elements[0],I.__data[1]=O.elements[1],I.__data[2]=O.elements[2],I.__data[3]=O.elements[0],I.__data[4]=O.elements[3],I.__data[5]=O.elements[4],I.__data[6]=O.elements[5],I.__data[7]=O.elements[0],I.__data[8]=O.elements[6],I.__data[9]=O.elements[7],I.__data[10]=O.elements[8],I.__data[11]=O.elements[0]):(O.toArray(I.__data,B),B+=V.storage/Float32Array.BYTES_PER_ELEMENT)}i.bufferSubData(i.UNIFORM_BUFFER,k,I.__data)}}i.bindBuffer(i.UNIFORM_BUFFER,null)}function v(x,w,S){let A=x.value;if(S[w]===void 0){if(typeof A=="number")S[w]=A;else{let T=Array.isArray(A)?A:[A],P=[];for(let I=0;I<T.length;I++)P.push(T[I].clone());S[w]=P}return!0}else if(typeof A=="number"){if(S[w]!==A)return S[w]=A,!0}else{let T=Array.isArray(S[w])?S[w]:[S[w]],P=Array.isArray(A)?A:[A];for(let I=0;I<T.length;I++){let k=T[I];if(k.equals(P[I])===!1)return k.copy(P[I]),!0}}return!1}function g(x){let w=x.uniforms,S=0,A=16,T=0;for(let P=0,I=w.length;P<I;P++){let k=w[P],L={boundary:0,storage:0},B=Array.isArray(k.value)?k.value:[k.value];for(let U=0,O=B.length;U<O;U++){let V=B[U],F=b(V);L.boundary+=F.boundary,L.storage+=F.storage}if(k.__data=new Float32Array(L.storage/Float32Array.BYTES_PER_ELEMENT),k.__offset=S,P>0){T=S%A;let U=A-T;T!==0&&U-L.boundary<0&&(S+=A-T,k.__offset=S)}S+=L.storage}return T=S%A,T>0&&(S+=A-T),x.__size=S,x.__cache={},this}function b(x){let w={boundary:0,storage:0};return typeof x=="number"?(w.boundary=4,w.storage=4):x.isVector2?(w.boundary=8,w.storage=8):x.isVector3||x.isColor?(w.boundary=16,w.storage=12):x.isVector4?(w.boundary=16,w.storage=16):x.isMatrix3?(w.boundary=48,w.storage=48):x.isMatrix4?(w.boundary=64,w.storage=64):x.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",x),w}function y(x){let w=x.target;w.removeEventListener("dispose",y);let S=a.indexOf(w.__bindingPointIndex);a.splice(S,1),i.deleteBuffer(r[w.id]),delete r[w.id],delete s[w.id]}function _(){for(let x in r)i.deleteBuffer(r[x]);a=[],r={},s={}}return{bind:l,update:c,dispose:_}}var QR=class{constructor(e={}){let{canvas:t=Wze(),context:n=null,depth:r=!0,stencil:s=!0,alpha:a=!1,antialias:o=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:c=!1,powerPreference:u="default",failIfMajorPerformanceCaveat:d=!1}=e;this.isWebGLRenderer=!0;let f;n!==null?f=n.getContextAttributes().alpha:f=a;let v=new Uint32Array(4),g=new Int32Array(4),b=null,y=null,_=[],x=[];this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.outputColorSpace=tr,this._useLegacyLights=!1,this.toneMapping=Hc,this.toneMappingExposure=1;let w=this,S=!1,A=0,T=0,P=null,I=-1,k=null,L=new ni,B=new ni,U=null,O=new Bn(0),V=0,F=t.width,J=t.height,$=1,ne=null,se=null,j=new ni(0,0,F,J),q=new ni(0,0,F,J),z=!1,K=new _b,re=!1,Z=!1,Y=null,Q=new Ti,ue=new yn,me=new Ve,we={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};function ye(){return P===null?$:1}let pe=n;function Ge(ie,Me){for(let Be=0;Be<ie.length;Be++){let Ae=ie[Be],Ue=t.getContext(Ae,Me);if(Ue!==null)return Ue}return null}try{let ie={alpha:!0,depth:r,stencil:s,antialias:o,premultipliedAlpha:l,preserveDrawingBuffer:c,powerPreference:u,failIfMajorPerformanceCaveat:d};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${dC}`),t.addEventListener("webglcontextlost",Xe,!1),t.addEventListener("webglcontextrestored",Ce,!1),t.addEventListener("webglcontextcreationerror",le,!1),pe===null){let Me=["webgl2","webgl","experimental-webgl"];if(w.isWebGL1Renderer===!0&&Me.shift(),pe=Ge(Me,ie),pe===null)throw Ge(Me)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}typeof WebGLRenderingContext<"u"&&pe instanceof WebGLRenderingContext&&console.warn("THREE.WebGLRenderer: WebGL 1 support was deprecated in r153 and will be removed in r163."),pe.getShaderPrecisionFormat===void 0&&(pe.getShaderPrecisionFormat=function(){return{rangeMin:1,rangeMax:1,precision:1}})}catch(ie){throw console.error("THREE.WebGLRenderer: "+ie.message),ie}let ge,Ie,ke,je,he,He,ae,Qe,$e,te,D,ee,C,E,R,N,H,G,oe,fe,_e,Re,Te,De;function qe(){ge=new iWe(pe),Ie=new ZGe(pe,ge,e),ge.init(Ie),Re=new Dje(pe,ge,Ie),ke=new Pje(pe,ge,Ie),je=new oWe(pe),he=new bje,He=new Lje(pe,ge,ke,he,Ie,Re,je),ae=new eWe(w),Qe=new rWe(w),$e=new gHe(pe,Ie),Te=new JGe(pe,ge,$e,Ie),te=new sWe(pe,$e,je,Te),D=new dWe(pe,te,$e,je),oe=new uWe(pe,Ie,He),N=new QGe(he),ee=new yje(w,ae,Qe,ge,Ie,Te,N),C=new Nje(w,he),E=new wje,R=new Tje(ge,Ie),G=new YGe(w,ae,Qe,ke,D,f,l),H=new Cje(w,D,Ie),De=new Uje(pe,je,Ie,ke),fe=new KGe(pe,ge,je,Ie),_e=new aWe(pe,ge,je,Ie),je.programs=ee.programs,w.capabilities=Ie,w.extensions=ge,w.properties=he,w.renderLists=E,w.shadowMap=H,w.state=ke,w.info=je}qe();let de=new ZR(w,pe);this.xr=de,this.getContext=function(){return pe},this.getContextAttributes=function(){return pe.getContextAttributes()},this.forceContextLoss=function(){let ie=ge.get("WEBGL_lose_context");ie&&ie.loseContext()},this.forceContextRestore=function(){let ie=ge.get("WEBGL_lose_context");ie&&ie.restoreContext()},this.getPixelRatio=function(){return $},this.setPixelRatio=function(ie){ie!==void 0&&($=ie,this.setSize(F,J,!1))},this.getSize=function(ie){return ie.set(F,J)},this.setSize=function(ie,Me,Be=!0){if(de.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}F=ie,J=Me,t.width=Math.floor(ie*$),t.height=Math.floor(Me*$),Be===!0&&(t.style.width=ie+"px",t.style.height=Me+"px"),this.setViewport(0,0,ie,Me)},this.getDrawingBufferSize=function(ie){return ie.set(F*$,J*$).floor()},this.setDrawingBufferSize=function(ie,Me,Be){F=ie,J=Me,$=Be,t.width=Math.floor(ie*Be),t.height=Math.floor(Me*Be),this.setViewport(0,0,ie,Me)},this.getCurrentViewport=function(ie){return ie.copy(L)},this.getViewport=function(ie){return ie.copy(j)},this.setViewport=function(ie,Me,Be,Ae){ie.isVector4?j.set(ie.x,ie.y,ie.z,ie.w):j.set(ie,Me,Be,Ae),ke.viewport(L.copy(j).multiplyScalar($).floor())},this.getScissor=function(ie){return ie.copy(q)},this.setScissor=function(ie,Me,Be,Ae){ie.isVector4?q.set(ie.x,ie.y,ie.z,ie.w):q.set(ie,Me,Be,Ae),ke.scissor(B.copy(q).multiplyScalar($).floor())},this.getScissorTest=function(){return z},this.setScissorTest=function(ie){ke.setScissorTest(z=ie)},this.setOpaqueSort=function(ie){ne=ie},this.setTransparentSort=function(ie){se=ie},this.getClearColor=function(ie){return ie.copy(G.getClearColor())},this.setClearColor=function(){G.setClearColor.apply(G,arguments)},this.getClearAlpha=function(){return G.getClearAlpha()},this.setClearAlpha=function(){G.setClearAlpha.apply(G,arguments)},this.clear=function(ie=!0,Me=!0,Be=!0){let Ae=0;if(ie){let Ue=!1;if(P!==null){let nt=P.texture.format;Ue=nt===r6e||nt===n6e||nt===t6e}if(Ue){let nt=P.texture.type,st=nt===qc||nt===Fc||nt===fC||nt===Pd||nt===Qge||nt===e6e,pt=G.getClearColor(),ht=G.getClearAlpha(),Dt=pt.r,xt=pt.g,Rt=pt.b;st?(v[0]=Dt,v[1]=xt,v[2]=Rt,v[3]=ht,pe.clearBufferuiv(pe.COLOR,0,v)):(g[0]=Dt,g[1]=xt,g[2]=Rt,g[3]=ht,pe.clearBufferiv(pe.COLOR,0,g))}else Ae|=pe.COLOR_BUFFER_BIT}Me&&(Ae|=pe.DEPTH_BUFFER_BIT),Be&&(Ae|=pe.STENCIL_BUFFER_BIT),pe.clear(Ae)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener("webglcontextlost",Xe,!1),t.removeEventListener("webglcontextrestored",Ce,!1),t.removeEventListener("webglcontextcreationerror",le,!1),E.dispose(),R.dispose(),he.dispose(),ae.dispose(),Qe.dispose(),D.dispose(),Te.dispose(),De.dispose(),ee.dispose(),de.dispose(),de.removeEventListener("sessionstart",rt),de.removeEventListener("sessionend",It),Y&&(Y.dispose(),Y=null),Kt.stop()};function Xe(ie){ie.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),S=!0}function Ce(){console.log("THREE.WebGLRenderer: Context Restored."),S=!1;let ie=je.autoReset,Me=H.enabled,Be=H.autoUpdate,Ae=H.needsUpdate,Ue=H.type;qe(),je.autoReset=ie,H.enabled=Me,H.autoUpdate=Be,H.needsUpdate=Ae,H.type=Ue}function le(ie){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",ie.statusMessage)}function Le(ie){let Me=ie.target;Me.removeEventListener("dispose",Le),Oe(Me)}function Oe(ie){et(ie),he.remove(ie)}function et(ie){let Me=he.get(ie).programs;Me!==void 0&&(Me.forEach(function(Be){ee.releaseProgram(Be)}),ie.isShaderMaterial&&ee.releaseShaderCache(ie))}this.renderBufferDirect=function(ie,Me,Be,Ae,Ue,nt){Me===null&&(Me=we);let st=Ue.isMesh&&Ue.matrixWorld.determinant()<0,pt=ut(ie,Me,Be,Ae,Ue);ke.setMaterial(Ae,st);let ht=Be.index,Dt=1;if(Ae.wireframe===!0){if(ht=te.getWireframeAttribute(Be),ht===void 0)return;Dt=2}let xt=Be.drawRange,Rt=Be.attributes.position,Ct=xt.start*Dt,W=(xt.start+xt.count)*Dt;nt!==null&&(Ct=Math.max(Ct,nt.start*Dt),W=Math.min(W,(nt.start+nt.count)*Dt)),ht!==null?(Ct=Math.max(Ct,0),W=Math.min(W,ht.count)):Rt!=null&&(Ct=Math.max(Ct,0),W=Math.min(W,Rt.count));let be=W-Ct;if(be<0||be===1/0)return;Te.setup(Ue,Ae,pt,Be,ht);let Pe,Ee=fe;if(ht!==null&&(Pe=$e.get(ht),Ee=_e,Ee.setIndex(Pe)),Ue.isMesh)Ae.wireframe===!0?(ke.setLineWidth(Ae.wireframeLinewidth*ye()),Ee.setMode(pe.LINES)):Ee.setMode(pe.TRIANGLES);else if(Ue.isLine){let xe=Ae.linewidth;xe===void 0&&(xe=1),ke.setLineWidth(xe*ye()),Ue.isLineSegments?Ee.setMode(pe.LINES):Ue.isLineLoop?Ee.setMode(pe.LINE_LOOP):Ee.setMode(pe.LINE_STRIP)}else Ue.isPoints?Ee.setMode(pe.POINTS):Ue.isSprite&&Ee.setMode(pe.TRIANGLES);if(Ue.isInstancedMesh)Ee.renderInstances(Ct,be,Ue.count);else if(Be.isInstancedBufferGeometry){let xe=Be._maxInstanceCount!==void 0?Be._maxInstanceCount:1/0,ot=Math.min(Be.instanceCount,xe);Ee.renderInstances(Ct,be,ot)}else Ee.render(Ct,be)},this.compile=function(ie,Me){function Be(Ae,Ue,nt){Ae.transparent===!0&&Ae.side===Ns&&Ae.forceSinglePass===!1?(Ae.side=fs,Ae.needsUpdate=!0,Ne(Ae,Ue,nt),Ae.side=Qa,Ae.needsUpdate=!0,Ne(Ae,Ue,nt),Ae.side=Ns):Ne(Ae,Ue,nt)}y=R.get(ie),y.init(),x.push(y),ie.traverseVisible(function(Ae){Ae.isLight&&Ae.layers.test(Me.layers)&&(y.pushLight(Ae),Ae.castShadow&&y.pushShadow(Ae))}),y.setupLights(w._useLegacyLights),ie.traverse(function(Ae){let Ue=Ae.material;if(Ue)if(Array.isArray(Ue))for(let nt=0;nt<Ue.length;nt++){let st=Ue[nt];Be(st,ie,Ae)}else Be(Ue,ie,Ae)}),x.pop(),y=null};let Ze=null;function Ye(ie){Ze&&Ze(ie)}function rt(){Kt.stop()}function It(){Kt.start()}let Kt=new c6e;Kt.setAnimationLoop(Ye),typeof self<"u"&&Kt.setContext(self),this.setAnimationLoop=function(ie){Ze=ie,de.setAnimationLoop(ie),ie===null?Kt.stop():Kt.start()},de.addEventListener("sessionstart",rt),de.addEventListener("sessionend",It),this.render=function(ie,Me){if(Me!==void 0&&Me.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(S===!0)return;ie.matrixWorldAutoUpdate===!0&&ie.updateMatrixWorld(),Me.parent===null&&Me.matrixWorldAutoUpdate===!0&&Me.updateMatrixWorld(),de.enabled===!0&&de.isPresenting===!0&&(de.cameraAutoUpdate===!0&&de.updateCamera(Me),Me=de.getCamera()),ie.isScene===!0&&ie.onBeforeRender(w,ie,Me,P),y=R.get(ie,x.length),y.init(),x.push(y),Q.multiplyMatrices(Me.projectionMatrix,Me.matrixWorldInverse),K.setFromProjectionMatrix(Q),Z=this.localClippingEnabled,re=N.init(this.clippingPlanes,Z),b=E.get(ie,_.length),b.init(),_.push(b),vn(ie,Me,0,w.sortObjects),b.finish(),w.sortObjects===!0&&b.sort(ne,se),this.info.render.frame++,re===!0&&N.beginShadows();let Be=y.state.shadowsArray;if(H.render(Be,ie,Me),re===!0&&N.endShadows(),this.info.autoReset===!0&&this.info.reset(),G.render(b,ie),y.setupLights(w._useLegacyLights),Me.isArrayCamera){let Ae=Me.cameras;for(let Ue=0,nt=Ae.length;Ue<nt;Ue++){let st=Ae[Ue];Pi(b,ie,st,st.viewport)}}else Pi(b,ie,Me);P!==null&&(He.updateMultisampleRenderTarget(P),He.updateRenderTargetMipmap(P)),ie.isScene===!0&&ie.onAfterRender(w,ie,Me),Te.resetDefaultState(),I=-1,k=null,x.pop(),x.length>0?y=x[x.length-1]:y=null,_.pop(),_.length>0?b=_[_.length-1]:b=null};function vn(ie,Me,Be,Ae){if(ie.visible===!1)return;if(ie.layers.test(Me.layers)){if(ie.isGroup)Be=ie.renderOrder;else if(ie.isLOD)ie.autoUpdate===!0&&ie.update(Me);else if(ie.isLight)y.pushLight(ie),ie.castShadow&&y.pushShadow(ie);else if(ie.isSprite){if(!ie.frustumCulled||K.intersectsSprite(ie)){Ae&&me.setFromMatrixPosition(ie.matrixWorld).applyMatrix4(Q);let st=D.update(ie),pt=ie.material;pt.visible&&b.push(ie,st,pt,Be,me.z,null)}}else if((ie.isMesh||ie.isLine||ie.isPoints)&&(!ie.frustumCulled||K.intersectsObject(ie))){let st=D.update(ie),pt=ie.material;if(Ae&&(ie.boundingSphere!==void 0?(ie.boundingSphere===null&&ie.computeBoundingSphere(),me.copy(ie.boundingSphere.center)):(st.boundingSphere===null&&st.computeBoundingSphere(),me.copy(st.boundingSphere.center)),me.applyMatrix4(ie.matrixWorld).applyMatrix4(Q)),Array.isArray(pt)){let ht=st.groups;for(let Dt=0,xt=ht.length;Dt<xt;Dt++){let Rt=ht[Dt],Ct=pt[Rt.materialIndex];Ct&&Ct.visible&&b.push(ie,st,Ct,Be,me.z,Rt)}}else pt.visible&&b.push(ie,st,pt,Be,me.z,null)}}let nt=ie.children;for(let st=0,pt=nt.length;st<pt;st++)vn(nt[st],Me,Be,Ae)}function Pi(ie,Me,Be,Ae){let Ue=ie.opaque,nt=ie.transmissive,st=ie.transparent;y.setupLightsView(Be),re===!0&&N.setGlobalState(w.clippingPlanes,Be),nt.length>0&&ve(Ue,nt,Me,Be),Ae&&ke.viewport(L.copy(Ae)),Ue.length>0&&ce(Ue,Me,Be),nt.length>0&&ce(nt,Me,Be),st.length>0&&ce(st,Me,Be),ke.buffers.depth.setTest(!0),ke.buffers.depth.setMask(!0),ke.buffers.color.setMask(!0),ke.setPolygonOffset(!1)}function ve(ie,Me,Be,Ae){let Ue=Ie.isWebGL2;Y===null&&(Y=new i0(1,1,{generateMipmaps:!0,type:ge.has("EXT_color_buffer_half_float")?Wv:qc,minFilter:Gv,samples:Ue?4:0})),w.getDrawingBufferSize(ue),Ue?Y.setSize(ue.x,ue.y):Y.setSize(BR(ue.x),BR(ue.y));let nt=w.getRenderTarget();w.setRenderTarget(Y),w.getClearColor(O),V=w.getClearAlpha(),V<1&&w.setClearColor(16777215,.5),w.clear();let st=w.toneMapping;w.toneMapping=Hc,ce(ie,Be,Ae),He.updateMultisampleRenderTarget(Y),He.updateRenderTargetMipmap(Y);let pt=!1;for(let ht=0,Dt=Me.length;ht<Dt;ht++){let xt=Me[ht],Rt=xt.object,Ct=xt.geometry,W=xt.material,be=xt.group;if(W.side===Ns&&Rt.layers.test(Ae.layers)){let Pe=W.side;W.side=fs,W.needsUpdate=!0,Se(Rt,Be,Ae,Ct,W,be),W.side=Pe,W.needsUpdate=!0,pt=!0}}pt===!0&&(He.updateMultisampleRenderTarget(Y),He.updateRenderTargetMipmap(Y)),w.setRenderTarget(nt),w.setClearColor(O,V),w.toneMapping=st}function ce(ie,Me,Be){let Ae=Me.isScene===!0?Me.overrideMaterial:null;for(let Ue=0,nt=ie.length;Ue<nt;Ue++){let st=ie[Ue],pt=st.object,ht=st.geometry,Dt=Ae===null?st.material:Ae,xt=st.group;pt.layers.test(Be.layers)&&Se(pt,Me,Be,ht,Dt,xt)}}function Se(ie,Me,Be,Ae,Ue,nt){ie.onBeforeRender(w,Me,Be,Ae,Ue,nt),ie.modelViewMatrix.multiplyMatrices(Be.matrixWorldInverse,ie.matrixWorld),ie.normalMatrix.getNormalMatrix(ie.modelViewMatrix),Ue.onBeforeRender(w,Me,Be,Ae,ie,nt),Ue.transparent===!0&&Ue.side===Ns&&Ue.forceSinglePass===!1?(Ue.side=fs,Ue.needsUpdate=!0,w.renderBufferDirect(Be,Me,Ae,Ue,ie,nt),Ue.side=Qa,Ue.needsUpdate=!0,w.renderBufferDirect(Be,Me,Ae,Ue,ie,nt),Ue.side=Ns):w.renderBufferDirect(Be,Me,Ae,Ue,ie,nt),ie.onAfterRender(w,Me,Be,Ae,Ue,nt)}function Ne(ie,Me,Be){Me.isScene!==!0&&(Me=we);let Ae=he.get(ie),Ue=y.state.lights,nt=y.state.shadowsArray,st=Ue.state.version,pt=ee.getParameters(ie,Ue.state,nt,Me,Be),ht=ee.getProgramCacheKey(pt),Dt=Ae.programs;Ae.environment=ie.isMeshStandardMaterial?Me.environment:null,Ae.fog=Me.fog,Ae.envMap=(ie.isMeshStandardMaterial?Qe:ae).get(ie.envMap||Ae.environment),Dt===void 0&&(ie.addEventListener("dispose",Le),Dt=new Map,Ae.programs=Dt);let xt=Dt.get(ht);if(xt!==void 0){if(Ae.currentProgram===xt&&Ae.lightsStateVersion===st)return Fe(ie,pt),xt}else pt.uniforms=ee.getUniforms(ie),ie.onBuild(Be,pt,w),ie.onBeforeCompile(pt,w),xt=ee.acquireProgram(pt,ht),Dt.set(ht,xt),Ae.uniforms=pt.uniforms;let Rt=Ae.uniforms;(!ie.isShaderMaterial&&!ie.isRawShaderMaterial||ie.clipping===!0)&&(Rt.clippingPlanes=N.uniform),Fe(ie,pt),Ae.needsLights=rn(ie),Ae.lightsStateVersion=st,Ae.needsLights&&(Rt.ambientLightColor.value=Ue.state.ambient,Rt.lightProbe.value=Ue.state.probe,Rt.directionalLights.value=Ue.state.directional,Rt.directionalLightShadows.value=Ue.state.directionalShadow,Rt.spotLights.value=Ue.state.spot,Rt.spotLightShadows.value=Ue.state.spotShadow,Rt.rectAreaLights.value=Ue.state.rectArea,Rt.ltc_1.value=Ue.state.rectAreaLTC1,Rt.ltc_2.value=Ue.state.rectAreaLTC2,Rt.pointLights.value=Ue.state.point,Rt.pointLightShadows.value=Ue.state.pointShadow,Rt.hemisphereLights.value=Ue.state.hemi,Rt.directionalShadowMap.value=Ue.state.directionalShadowMap,Rt.directionalShadowMatrix.value=Ue.state.directionalShadowMatrix,Rt.spotShadowMap.value=Ue.state.spotShadowMap,Rt.spotLightMatrix.value=Ue.state.spotLightMatrix,Rt.spotLightMap.value=Ue.state.spotLightMap,Rt.pointShadowMap.value=Ue.state.pointShadowMap,Rt.pointShadowMatrix.value=Ue.state.pointShadowMatrix);let Ct=xt.getUniforms(),W=A5.seqWithValue(Ct.seq,Rt);return Ae.currentProgram=xt,Ae.uniformsList=W,xt}function Fe(ie,Me){let Be=he.get(ie);Be.outputColorSpace=Me.outputColorSpace,Be.instancing=Me.instancing,Be.instancingColor=Me.instancingColor,Be.skinning=Me.skinning,Be.morphTargets=Me.morphTargets,Be.morphNormals=Me.morphNormals,Be.morphColors=Me.morphColors,Be.morphTargetsCount=Me.morphTargetsCount,Be.numClippingPlanes=Me.numClippingPlanes,Be.numIntersection=Me.numClipIntersection,Be.vertexAlphas=Me.vertexAlphas,Be.vertexTangents=Me.vertexTangents,Be.toneMapping=Me.toneMapping}function ut(ie,Me,Be,Ae,Ue){Me.isScene!==!0&&(Me=we),He.resetTextureUnits();let nt=Me.fog,st=Ae.isMeshStandardMaterial?Me.environment:null,pt=P===null?w.outputColorSpace:P.isXRRenderTarget===!0?P.texture.colorSpace:Wo,ht=(Ae.isMeshStandardMaterial?Qe:ae).get(Ae.envMap||st),Dt=Ae.vertexColors===!0&&!!Be.attributes.color&&Be.attributes.color.itemSize===4,xt=!!Be.attributes.tangent&&(!!Ae.normalMap||Ae.anisotropy>0),Rt=!!Be.morphAttributes.position,Ct=!!Be.morphAttributes.normal,W=!!Be.morphAttributes.color,be=Hc;Ae.toneMapped&&(P===null||P.isXRRenderTarget===!0)&&(be=w.toneMapping);let Pe=Be.morphAttributes.position||Be.morphAttributes.normal||Be.morphAttributes.color,Ee=Pe!==void 0?Pe.length:0,xe=he.get(Ae),ot=y.state.lights;if(re===!0&&(Z===!0||ie!==k)){let un=ie===k&&Ae.id===I;N.setState(Ae,ie,un)}let tt=!1;Ae.version===xe.__version?(xe.needsLights&&xe.lightsStateVersion!==ot.state.version||xe.outputColorSpace!==pt||Ue.isInstancedMesh&&xe.instancing===!1||!Ue.isInstancedMesh&&xe.instancing===!0||Ue.isSkinnedMesh&&xe.skinning===!1||!Ue.isSkinnedMesh&&xe.skinning===!0||Ue.isInstancedMesh&&xe.instancingColor===!0&&Ue.instanceColor===null||Ue.isInstancedMesh&&xe.instancingColor===!1&&Ue.instanceColor!==null||xe.envMap!==ht||Ae.fog===!0&&xe.fog!==nt||xe.numClippingPlanes!==void 0&&(xe.numClippingPlanes!==N.numPlanes||xe.numIntersection!==N.numIntersection)||xe.vertexAlphas!==Dt||xe.vertexTangents!==xt||xe.morphTargets!==Rt||xe.morphNormals!==Ct||xe.morphColors!==W||xe.toneMapping!==be||Ie.isWebGL2===!0&&xe.morphTargetsCount!==Ee)&&(tt=!0):(tt=!0,xe.__version=Ae.version);let it=xe.currentProgram;tt===!0&&(it=Ne(Ae,Me,Ue));let vt=!1,gt=!1,Tt=!1,wt=it.getUniforms(),yt=xe.uniforms;if(ke.useProgram(it.program)&&(vt=!0,gt=!0,Tt=!0),Ae.id!==I&&(I=Ae.id,gt=!0),vt||k!==ie){wt.setValue(pe,"projectionMatrix",ie.projectionMatrix),wt.setValue(pe,"viewMatrix",ie.matrixWorldInverse);let un=wt.map.cameraPosition;un!==void 0&&un.setValue(pe,me.setFromMatrixPosition(ie.matrixWorld)),Ie.logarithmicDepthBuffer&&wt.setValue(pe,"logDepthBufFC",2/(Math.log(ie.far+1)/Math.LN2)),(Ae.isMeshPhongMaterial||Ae.isMeshToonMaterial||Ae.isMeshLambertMaterial||Ae.isMeshBasicMaterial||Ae.isMeshStandardMaterial||Ae.isShaderMaterial)&&wt.setValue(pe,"isOrthographic",ie.isOrthographicCamera===!0),k!==ie&&(k=ie,gt=!0,Tt=!0)}if(Ue.isSkinnedMesh){wt.setOptional(pe,Ue,"bindMatrix"),wt.setOptional(pe,Ue,"bindMatrixInverse");let un=Ue.skeleton;un&&(Ie.floatVertexTextures?(un.boneTexture===null&&un.computeBoneTexture(),wt.setValue(pe,"boneTexture",un.boneTexture,He),wt.setValue(pe,"boneTextureSize",un.boneTextureSize)):console.warn("THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required."))}let Zt=Be.morphAttributes;if((Zt.position!==void 0||Zt.normal!==void 0||Zt.color!==void 0&&Ie.isWebGL2===!0)&&oe.update(Ue,Be,it),(gt||xe.receiveShadow!==Ue.receiveShadow)&&(xe.receiveShadow=Ue.receiveShadow,wt.setValue(pe,"receiveShadow",Ue.receiveShadow)),Ae.isMeshGouraudMaterial&&Ae.envMap!==null&&(yt.envMap.value=ht,yt.flipEnvMap.value=ht.isCubeTexture&&ht.isRenderTargetTexture===!1?-1:1),gt&&(wt.setValue(pe,"toneMappingExposure",w.toneMappingExposure),xe.needsLights&&Bt(yt,Tt),nt&&Ae.fog===!0&&C.refreshFogUniforms(yt,nt),C.refreshMaterialUniforms(yt,Ae,$,J,Y),A5.upload(pe,xe.uniformsList,yt,He)),Ae.isShaderMaterial&&Ae.uniformsNeedUpdate===!0&&(A5.upload(pe,xe.uniformsList,yt,He),Ae.uniformsNeedUpdate=!1),Ae.isSpriteMaterial&&wt.setValue(pe,"center",Ue.center),wt.setValue(pe,"modelViewMatrix",Ue.modelViewMatrix),wt.setValue(pe,"normalMatrix",Ue.normalMatrix),wt.setValue(pe,"modelMatrix",Ue.matrixWorld),Ae.isShaderMaterial||Ae.isRawShaderMaterial){let un=Ae.uniformsGroups;for(let Dn=0,bn=un.length;Dn<bn;Dn++)if(Ie.isWebGL2){let qn=un[Dn];De.update(qn,it),De.bind(qn,it)}else console.warn("THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.")}return it}function Bt(ie,Me){ie.ambientLightColor.needsUpdate=Me,ie.lightProbe.needsUpdate=Me,ie.directionalLights.needsUpdate=Me,ie.directionalLightShadows.needsUpdate=Me,ie.pointLights.needsUpdate=Me,ie.pointLightShadows.needsUpdate=Me,ie.spotLights.needsUpdate=Me,ie.spotLightShadows.needsUpdate=Me,ie.rectAreaLights.needsUpdate=Me,ie.hemisphereLights.needsUpdate=Me}function rn(ie){return ie.isMeshLambertMaterial||ie.isMeshToonMaterial||ie.isMeshPhongMaterial||ie.isMeshStandardMaterial||ie.isShadowMaterial||ie.isShaderMaterial&&ie.lights===!0}this.getActiveCubeFace=function(){return A},this.getActiveMipmapLevel=function(){return T},this.getRenderTarget=function(){return P},this.setRenderTargetTextures=function(ie,Me,Be){he.get(ie.texture).__webglTexture=Me,he.get(ie.depthTexture).__webglTexture=Be;let Ae=he.get(ie);Ae.__hasExternalTextures=!0,Ae.__hasExternalTextures&&(Ae.__autoAllocateDepthBuffer=Be===void 0,Ae.__autoAllocateDepthBuffer||ge.has("WEBGL_multisampled_render_to_texture")===!0&&(console.warn("THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided"),Ae.__useRenderToTexture=!1))},this.setRenderTargetFramebuffer=function(ie,Me){let Be=he.get(ie);Be.__webglFramebuffer=Me,Be.__useDefaultFramebuffer=Me===void 0},this.setRenderTarget=function(ie,Me=0,Be=0){P=ie,A=Me,T=Be;let Ae=!0,Ue=null,nt=!1,st=!1;if(ie){let ht=he.get(ie);ht.__useDefaultFramebuffer!==void 0?(ke.bindFramebuffer(pe.FRAMEBUFFER,null),Ae=!1):ht.__webglFramebuffer===void 0?He.setupRenderTarget(ie):ht.__hasExternalTextures&&He.rebindTextures(ie,he.get(ie.texture).__webglTexture,he.get(ie.depthTexture).__webglTexture);let Dt=ie.texture;(Dt.isData3DTexture||Dt.isDataArrayTexture||Dt.isCompressedArrayTexture)&&(st=!0);let xt=he.get(ie).__webglFramebuffer;ie.isWebGLCubeRenderTarget?(Array.isArray(xt[Me])?Ue=xt[Me][Be]:Ue=xt[Me],nt=!0):Ie.isWebGL2&&ie.samples>0&&He.useMultisampledRTT(ie)===!1?Ue=he.get(ie).__webglMultisampledFramebuffer:Array.isArray(xt)?Ue=xt[Be]:Ue=xt,L.copy(ie.viewport),B.copy(ie.scissor),U=ie.scissorTest}else L.copy(j).multiplyScalar($).floor(),B.copy(q).multiplyScalar($).floor(),U=z;if(ke.bindFramebuffer(pe.FRAMEBUFFER,Ue)&&Ie.drawBuffers&&Ae&&ke.drawBuffers(ie,Ue),ke.viewport(L),ke.scissor(B),ke.setScissorTest(U),nt){let ht=he.get(ie.texture);pe.framebufferTexture2D(pe.FRAMEBUFFER,pe.COLOR_ATTACHMENT0,pe.TEXTURE_CUBE_MAP_POSITIVE_X+Me,ht.__webglTexture,Be)}else if(st){let ht=he.get(ie.texture),Dt=Me||0;pe.framebufferTextureLayer(pe.FRAMEBUFFER,pe.COLOR_ATTACHMENT0,ht.__webglTexture,Be||0,Dt)}I=-1},this.readRenderTargetPixels=function(ie,Me,Be,Ae,Ue,nt,st){if(!(ie&&ie.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let pt=he.get(ie).__webglFramebuffer;if(ie.isWebGLCubeRenderTarget&&st!==void 0&&(pt=pt[st]),pt){ke.bindFramebuffer(pe.FRAMEBUFFER,pt);try{let ht=ie.texture,Dt=ht.format,xt=ht.type;if(Dt!==Za&&Re.convert(Dt)!==pe.getParameter(pe.IMPLEMENTATION_COLOR_READ_FORMAT)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}let Rt=xt===Wv&&(ge.has("EXT_color_buffer_half_float")||Ie.isWebGL2&&ge.has("EXT_color_buffer_float"));if(xt!==qc&&Re.convert(xt)!==pe.getParameter(pe.IMPLEMENTATION_COLOR_READ_TYPE)&&!(xt===Vc&&(Ie.isWebGL2||ge.has("OES_texture_float")||ge.has("WEBGL_color_buffer_float")))&&!Rt){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}Me>=0&&Me<=ie.width-Ae&&Be>=0&&Be<=ie.height-Ue&&pe.readPixels(Me,Be,Ae,Ue,Re.convert(Dt),Re.convert(xt),nt)}finally{let ht=P!==null?he.get(P).__webglFramebuffer:null;ke.bindFramebuffer(pe.FRAMEBUFFER,ht)}}},this.copyFramebufferToTexture=function(ie,Me,Be=0){let Ae=Math.pow(2,-Be),Ue=Math.floor(Me.image.width*Ae),nt=Math.floor(Me.image.height*Ae);He.setTexture2D(Me,0),pe.copyTexSubImage2D(pe.TEXTURE_2D,Be,0,0,ie.x,ie.y,Ue,nt),ke.unbindTexture()},this.copyTextureToTexture=function(ie,Me,Be,Ae=0){let Ue=Me.image.width,nt=Me.image.height,st=Re.convert(Be.format),pt=Re.convert(Be.type);He.setTexture2D(Be,0),pe.pixelStorei(pe.UNPACK_FLIP_Y_WEBGL,Be.flipY),pe.pixelStorei(pe.UNPACK_PREMULTIPLY_ALPHA_WEBGL,Be.premultiplyAlpha),pe.pixelStorei(pe.UNPACK_ALIGNMENT,Be.unpackAlignment),Me.isDataTexture?pe.texSubImage2D(pe.TEXTURE_2D,Ae,ie.x,ie.y,Ue,nt,st,pt,Me.image.data):Me.isCompressedTexture?pe.compressedTexSubImage2D(pe.TEXTURE_2D,Ae,ie.x,ie.y,Me.mipmaps[0].width,Me.mipmaps[0].height,st,Me.mipmaps[0].data):pe.texSubImage2D(pe.TEXTURE_2D,Ae,ie.x,ie.y,st,pt,Me.image),Ae===0&&Be.generateMipmaps&&pe.generateMipmap(pe.TEXTURE_2D),ke.unbindTexture()},this.copyTextureToTexture3D=function(ie,Me,Be,Ae,Ue=0){if(w.isWebGL1Renderer){console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.");return}let nt=ie.max.x-ie.min.x+1,st=ie.max.y-ie.min.y+1,pt=ie.max.z-ie.min.z+1,ht=Re.convert(Ae.format),Dt=Re.convert(Ae.type),xt;if(Ae.isData3DTexture)He.setTexture3D(Ae,0),xt=pe.TEXTURE_3D;else if(Ae.isDataArrayTexture)He.setTexture2DArray(Ae,0),xt=pe.TEXTURE_2D_ARRAY;else{console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.");return}pe.pixelStorei(pe.UNPACK_FLIP_Y_WEBGL,Ae.flipY),pe.pixelStorei(pe.UNPACK_PREMULTIPLY_ALPHA_WEBGL,Ae.premultiplyAlpha),pe.pixelStorei(pe.UNPACK_ALIGNMENT,Ae.unpackAlignment);let Rt=pe.getParameter(pe.UNPACK_ROW_LENGTH),Ct=pe.getParameter(pe.UNPACK_IMAGE_HEIGHT),W=pe.getParameter(pe.UNPACK_SKIP_PIXELS),be=pe.getParameter(pe.UNPACK_SKIP_ROWS),Pe=pe.getParameter(pe.UNPACK_SKIP_IMAGES),Ee=Be.isCompressedTexture?Be.mipmaps[0]:Be.image;pe.pixelStorei(pe.UNPACK_ROW_LENGTH,Ee.width),pe.pixelStorei(pe.UNPACK_IMAGE_HEIGHT,Ee.height),pe.pixelStorei(pe.UNPACK_SKIP_PIXELS,ie.min.x),pe.pixelStorei(pe.UNPACK_SKIP_ROWS,ie.min.y),pe.pixelStorei(pe.UNPACK_SKIP_IMAGES,ie.min.z),Be.isDataTexture||Be.isData3DTexture?pe.texSubImage3D(xt,Ue,Me.x,Me.y,Me.z,nt,st,pt,ht,Dt,Ee.data):Be.isCompressedArrayTexture?(console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture."),pe.compressedTexSubImage3D(xt,Ue,Me.x,Me.y,Me.z,nt,st,pt,ht,Ee.data)):pe.texSubImage3D(xt,Ue,Me.x,Me.y,Me.z,nt,st,pt,ht,Dt,Ee),pe.pixelStorei(pe.UNPACK_ROW_LENGTH,Rt),pe.pixelStorei(pe.UNPACK_IMAGE_HEIGHT,Ct),pe.pixelStorei(pe.UNPACK_SKIP_PIXELS,W),pe.pixelStorei(pe.UNPACK_SKIP_ROWS,be),pe.pixelStorei(pe.UNPACK_SKIP_IMAGES,Pe),Ue===0&&Ae.generateMipmaps&&pe.generateMipmap(xt),ke.unbindTexture()},this.initTexture=function(ie){ie.isCubeTexture?He.setTextureCube(ie,0):ie.isData3DTexture?He.setTexture3D(ie,0):ie.isDataArrayTexture||ie.isCompressedArrayTexture?He.setTexture2DArray(ie,0):He.setTexture2D(ie,0),ke.unbindTexture()},this.resetState=function(){A=0,T=0,P=null,ke.reset(),Te.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return n0}get physicallyCorrectLights(){return console.warn("THREE.WebGLRenderer: The property .physicallyCorrectLights has been removed. Set renderer.useLegacyLights instead."),!this.useLegacyLights}set physicallyCorrectLights(e){console.warn("THREE.WebGLRenderer: The property .physicallyCorrectLights has been removed. Set renderer.useLegacyLights instead."),this.useLegacyLights=!e}get outputEncoding(){return console.warn("THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead."),this.outputColorSpace===tr?Bd:i6e}set outputEncoding(e){console.warn("THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead."),this.outputColorSpace=e===Bd?tr:Wo}get useLegacyLights(){return console.warn("THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733."),this._useLegacyLights}set useLegacyLights(e){console.warn("THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733."),this._useLegacyLights=e}},eC=class extends QR{};eC.prototype.isWebGL1Renderer=!0;var jc=class extends Nd{constructor(e){super(),this.isMeshStandardMaterial=!0,this.defines={STANDARD:""},this.type="MeshStandardMaterial",this.color=new Bn(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 Bn(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=s6e,this.normalScale=new yn(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,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.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}};function Uc(i,e,t){return m6e(i)?new i.constructor(i.subarray(e,t!==void 0?t:i.length)):i.slice(e,t)}function rb(i,e,t){return!i||!t&&i.constructor===e?i:typeof e.BYTES_PER_ELEMENT=="number"?new e(i):Array.prototype.slice.call(i)}function m6e(i){return ArrayBuffer.isView(i)&&!(i instanceof DataView)}var C5=class{constructor(e,t,n,r){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=r!==void 0?r:new t.constructor(n),this.sampleValues=t,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(e){let t=this.parameterPositions,n=this._cachedIndex,r=t[n],s=t[n-1];n:{e:{let a;t:{r:if(!(e<r)){for(let o=n+2;;){if(r===void 0){if(e<s)break r;return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}if(n===o)break;if(s=r,r=t[++n],e<r)break e}a=t.length;break t}if(!(e>=s)){let o=t[1];e<o&&(n=2,s=o);for(let l=n-2;;){if(s===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(n===l)break;if(r=s,s=t[--n-1],e>=s)break e}a=n,n=0;break t}break n}for(;n<a;){let o=n+a>>>1;e<t[o]?a=o:n=o+1}if(r=t[n],s=t[n-1],s===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(r===void 0)return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}this._cachedIndex=n,this.intervalChanged_(n,s,r)}return this.interpolate_(n,s,e,r)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(e){let t=this.resultBuffer,n=this.sampleValues,r=this.valueSize,s=e*r;for(let a=0;a!==r;++a)t[a]=n[s+a];return t}interpolate_(){throw new Error("call to abstract method")}intervalChanged_(){}},tC=class extends C5{constructor(e,t,n,r){super(e,t,n,r),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:age,endingEnd:age}}intervalChanged_(e,t,n){let r=this.parameterPositions,s=e-2,a=e+1,o=r[s],l=r[a];if(o===void 0)switch(this.getSettings_().endingStart){case oge:s=e,o=2*t-n;break;case lge:s=r.length-2,o=t+r[s]-r[s+1];break;default:s=e,o=n}if(l===void 0)switch(this.getSettings_().endingEnd){case oge:a=e,l=2*n-t;break;case lge:a=1,l=n+r[1]-r[0];break;default:a=e-1,l=t}let c=(n-t)*.5,u=this.valueSize;this._weightPrev=c/(t-o),this._weightNext=c/(l-n),this._offsetPrev=s*u,this._offsetNext=a*u}interpolate_(e,t,n,r){let s=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=e*o,c=l-o,u=this._offsetPrev,d=this._offsetNext,f=this._weightPrev,v=this._weightNext,g=(n-t)/(r-t),b=g*g,y=b*g,_=-f*y+2*f*b-f*g,x=(1+f)*y+(-1.5-2*f)*b+(-.5+f)*g+1,w=(-1-v)*y+(1.5+v)*b+.5*g,S=v*y-v*b;for(let A=0;A!==o;++A)s[A]=_*a[u+A]+x*a[c+A]+w*a[l+A]+S*a[d+A];return s}},nC=class extends C5{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e,t,n,r){let s=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=e*o,c=l-o,u=(n-t)/(r-t),d=1-u;for(let f=0;f!==o;++f)s[f]=a[c+f]*d+a[l+f]*u;return s}},rC=class extends C5{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e){return this.copySampleValue_(e-1)}},to=class{constructor(e,t,n,r){if(e===void 0)throw new Error("THREE.KeyframeTrack: track name is undefined");if(t===void 0||t.length===0)throw new Error("THREE.KeyframeTrack: no keyframes in track named "+e);this.name=e,this.times=rb(t,this.TimeBufferType),this.values=rb(n,this.ValueBufferType),this.setInterpolation(r||this.DefaultInterpolation)}static toJSON(e){let t=e.constructor,n;if(t.toJSON!==this.toJSON)n=t.toJSON(e);else{n={name:e.name,times:rb(e.times,Array),values:rb(e.values,Array)};let r=e.getInterpolation();r!==e.DefaultInterpolation&&(n.interpolation=r)}return n.type=e.ValueTypeName,n}InterpolantFactoryMethodDiscrete(e){return new rC(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodLinear(e){return new nC(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodSmooth(e){return new tC(this.times,this.values,this.getValueSize(),e)}setInterpolation(e){let t;switch(e){case ib:t=this.InterpolantFactoryMethodDiscrete;break;case sb:t=this.InterpolantFactoryMethodLinear;break;case rR:t=this.InterpolantFactoryMethodSmooth;break}if(t===void 0){let n="unsupported interpolation for "+this.ValueTypeName+" keyframe track named "+this.name;if(this.createInterpolant===void 0)if(e!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);else throw new Error(n);return console.warn("THREE.KeyframeTrack:",n),this}return this.createInterpolant=t,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return ib;case this.InterpolantFactoryMethodLinear:return sb;case this.InterpolantFactoryMethodSmooth:return rR}}getValueSize(){return this.values.length/this.times.length}shift(e){if(e!==0){let t=this.times;for(let n=0,r=t.length;n!==r;++n)t[n]+=e}return this}scale(e){if(e!==1){let t=this.times;for(let n=0,r=t.length;n!==r;++n)t[n]*=e}return this}trim(e,t){let n=this.times,r=n.length,s=0,a=r-1;for(;s!==r&&n[s]<e;)++s;for(;a!==-1&&n[a]>t;)--a;if(++a,s!==0||a!==r){s>=a&&(a=Math.max(a,1),s=a-1);let o=this.getValueSize();this.times=Uc(n,s,a),this.values=Uc(this.values,s*o,a*o)}return this}validate(){let e=!0,t=this.getValueSize();t-Math.floor(t)!==0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),e=!1);let n=this.times,r=this.values,s=n.length;s===0&&(console.error("THREE.KeyframeTrack: Track is empty.",this),e=!1);let a=null;for(let o=0;o!==s;o++){let l=n[o];if(typeof l=="number"&&isNaN(l)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,o,l),e=!1;break}if(a!==null&&a>l){console.error("THREE.KeyframeTrack: Out of order keys.",this,o,l,a),e=!1;break}a=l}if(r!==void 0&&m6e(r))for(let o=0,l=r.length;o!==l;++o){let c=r[o];if(isNaN(c)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,o,c),e=!1;break}}return e}optimize(){let e=Uc(this.times),t=Uc(this.values),n=this.getValueSize(),r=this.getInterpolation()===rR,s=e.length-1,a=1;for(let o=1;o<s;++o){let l=!1,c=e[o],u=e[o+1];if(c!==u&&(o!==1||c!==e[0]))if(r)l=!0;else{let d=o*n,f=d-n,v=d+n;for(let g=0;g!==n;++g){let b=t[d+g];if(b!==t[f+g]||b!==t[v+g]){l=!0;break}}}if(l){if(o!==a){e[a]=e[o];let d=o*n,f=a*n;for(let v=0;v!==n;++v)t[f+v]=t[d+v]}++a}}if(s>0){e[a]=e[s];for(let o=s*n,l=a*n,c=0;c!==n;++c)t[l+c]=t[o+c];++a}return a!==e.length?(this.times=Uc(e,0,a),this.values=Uc(t,0,a*n)):(this.times=e,this.values=t),this}clone(){let e=Uc(this.times,0),t=Uc(this.values,0),n=this.constructor,r=new n(this.name,e,t);return r.createInterpolant=this.createInterpolant,r}};to.prototype.TimeBufferType=Float32Array;to.prototype.ValueBufferType=Float32Array;to.prototype.DefaultInterpolation=sb;var Fd=class extends to{};Fd.prototype.ValueTypeName="bool";Fd.prototype.ValueBufferType=Array;Fd.prototype.DefaultInterpolation=ib;Fd.prototype.InterpolantFactoryMethodLinear=void 0;Fd.prototype.InterpolantFactoryMethodSmooth=void 0;var iC=class extends to{};iC.prototype.ValueTypeName="color";var sC=class extends to{};sC.prototype.ValueTypeName="number";var aC=class extends C5{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e,t,n,r){let s=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=(n-t)/(r-t),c=e*o;for(let u=c+o;c!==u;c+=4)Wc.slerpFlat(s,0,a,c-o,a,c,l);return s}},Xv=class extends to{InterpolantFactoryMethodLinear(e){return new aC(this.times,this.values,this.getValueSize(),e)}};Xv.prototype.ValueTypeName="quaternion";Xv.prototype.DefaultInterpolation=sb;Xv.prototype.InterpolantFactoryMethodSmooth=void 0;var Vd=class extends to{};Vd.prototype.ValueTypeName="string";Vd.prototype.ValueBufferType=Array;Vd.prototype.DefaultInterpolation=ib;Vd.prototype.InterpolantFactoryMethodLinear=void 0;Vd.prototype.InterpolantFactoryMethodSmooth=void 0;var oC=class extends to{};oC.prototype.ValueTypeName="vector";var lC=class{constructor(e,t,n){let r=this,s=!1,a=0,o=0,l,c=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=n,this.itemStart=function(u){o++,s===!1&&r.onStart!==void 0&&r.onStart(u,a,o),s=!0},this.itemEnd=function(u){a++,r.onProgress!==void 0&&r.onProgress(u,a,o),a===o&&(s=!1,r.onLoad!==void 0&&r.onLoad())},this.itemError=function(u){r.onError!==void 0&&r.onError(u)},this.resolveURL=function(u){return l?l(u):u},this.setURLModifier=function(u){return l=u,this},this.addHandler=function(u,d){return c.push(u,d),this},this.removeHandler=function(u){let d=c.indexOf(u);return d!==-1&&c.splice(d,2),this},this.getHandler=function(u){for(let d=0,f=c.length;d<f;d+=2){let v=c[d],g=c[d+1];if(v.global&&(v.lastIndex=0),v.test(u))return g}return null}}},Fje=new lC,cC=class{constructor(e){this.manager=e!==void 0?e:Fje,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={}}load(){}loadAsync(e,t){let n=this;return new Promise(function(r,s){n.load(e,r,t,s)})}parse(){}setCrossOrigin(e){return this.crossOrigin=e,this}setWithCredentials(e){return this.withCredentials=e,this}setPath(e){return this.path=e,this}setResourcePath(e){return this.resourcePath=e,this}setRequestHeader(e){return this.requestHeader=e,this}};cC.DEFAULT_MATERIAL_NAME="__DEFAULT";var mC="\\[\\]\\.:\\/",Vje=new RegExp("["+mC+"]","g"),pC="[^"+mC+"]",zje="[^"+mC.replace("\\.","")+"]",Hje=/((?:WC+[\/:])*)/.source.replace("WC",pC),qje=/(WCOD+)?/.source.replace("WCOD",zje),Gje=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",pC),Wje=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",pC),jje=new RegExp("^"+Hje+qje+Gje+Wje+"$"),Xje=["material","materials","bones","map"],uC=class{constructor(e,t,n){let r=n||er.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,r)}getValue(e,t){this.bind();let n=this._targetGroup.nCachedObjects_,r=this._bindings[n];r!==void 0&&r.getValue(e,t)}setValue(e,t){let n=this._bindings;for(let r=this._targetGroup.nCachedObjects_,s=n.length;r!==s;++r)n[r].setValue(e,t)}bind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].bind()}unbind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].unbind()}},er=class i{constructor(e,t,n){this.path=t,this.parsedPath=n||i.parseTrackName(t),this.node=i.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,n){return e&&e.isAnimationObjectGroup?new i.Composite(e,t,n):new i(e,t,n)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(Vje,"")}static parseTrackName(e){let t=jje.exec(e);if(t===null)throw new Error("PropertyBinding: Cannot parse trackName: "+e);let n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},r=n.nodeName&&n.nodeName.lastIndexOf(".");if(r!==void 0&&r!==-1){let s=n.nodeName.substring(r+1);Xje.indexOf(s)!==-1&&(n.nodeName=n.nodeName.substring(0,r),n.objectName=s)}if(n.propertyName===null||n.propertyName.length===0)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+e);return n}static findNode(e,t){if(t===void 0||t===""||t==="."||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){let n=e.skeleton.getBoneByName(t);if(n!==void 0)return n}if(e.children){let n=function(s){for(let a=0;a<s.length;a++){let o=s[a];if(o.name===t||o.uuid===t)return o;let l=n(o.children);if(l)return l}return null},r=n(e.children);if(r)return r}return null}_getValue_unavailable(){}_setValue_unavailable(){}_getValue_direct(e,t){e[t]=this.targetObject[this.propertyName]}_getValue_array(e,t){let n=this.resolvedProperty;for(let r=0,s=n.length;r!==s;++r)e[t++]=n[r]}_getValue_arrayElement(e,t){e[t]=this.resolvedProperty[this.propertyIndex]}_getValue_toArray(e,t){this.resolvedProperty.toArray(e,t)}_setValue_direct(e,t){this.targetObject[this.propertyName]=e[t]}_setValue_direct_setNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.needsUpdate=!0}_setValue_direct_setMatrixWorldNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_array(e,t){let n=this.resolvedProperty;for(let r=0,s=n.length;r!==s;++r)n[r]=e[t++]}_setValue_array_setNeedsUpdate(e,t){let n=this.resolvedProperty;for(let r=0,s=n.length;r!==s;++r)n[r]=e[t++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(e,t){let n=this.resolvedProperty;for(let r=0,s=n.length;r!==s;++r)n[r]=e[t++];this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_arrayElement(e,t){this.resolvedProperty[this.propertyIndex]=e[t]}_setValue_arrayElement_setNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.needsUpdate=!0}_setValue_arrayElement_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_fromArray(e,t){this.resolvedProperty.fromArray(e,t)}_setValue_fromArray_setNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.needsUpdate=!0}_setValue_fromArray_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.matrixWorldNeedsUpdate=!0}_getValue_unbound(e,t){this.bind(),this.getValue(e,t)}_setValue_unbound(e,t){this.bind(),this.setValue(e,t)}bind(){let e=this.node,t=this.parsedPath,n=t.objectName,r=t.propertyName,s=t.propertyIndex;if(e||(e=i.findNode(this.rootNode,t.nodeName),this.node=e),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!e){console.warn("THREE.PropertyBinding: No target node found for track: "+this.path+".");return}if(n){let c=t.objectIndex;switch(n){case"materials":if(!e.material){console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!e.material.materials){console.error("THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.",this);return}e=e.material.materials;break;case"bones":if(!e.skeleton){console.error("THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.",this);return}e=e.skeleton.bones;for(let u=0;u<e.length;u++)if(e[u].name===c){c=u;break}break;case"map":if("map"in e){e=e.map;break}if(!e.material){console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!e.material.map){console.error("THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.",this);return}e=e.material.map;break;default:if(e[n]===void 0){console.error("THREE.PropertyBinding: Can not bind to objectName of node undefined.",this);return}e=e[n]}if(c!==void 0){if(e[c]===void 0){console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.",this,e);return}e=e[c]}}let a=e[r];if(a===void 0){let c=t.nodeName;console.error("THREE.PropertyBinding: Trying to update property for track: "+c+"."+r+" but it wasn't found.",e);return}let o=this.Versioning.None;this.targetObject=e,e.needsUpdate!==void 0?o=this.Versioning.NeedsUpdate:e.matrixWorldNeedsUpdate!==void 0&&(o=this.Versioning.MatrixWorldNeedsUpdate);let l=this.BindingType.Direct;if(s!==void 0){if(r==="morphTargetInfluences"){if(!e.geometry){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.",this);return}if(!e.geometry.morphAttributes){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.",this);return}e.morphTargetDictionary[s]!==void 0&&(s=e.morphTargetDictionary[s])}l=this.BindingType.ArrayElement,this.resolvedProperty=a,this.propertyIndex=s}else a.fromArray!==void 0&&a.toArray!==void 0?(l=this.BindingType.HasFromToArray,this.resolvedProperty=a):Array.isArray(a)?(l=this.BindingType.EntireArray,this.resolvedProperty=a):this.propertyName=r;this.getValue=this.GetterByBindingType[l],this.setValue=this.SetterByBindingTypeAndVersioning[l][o]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}};er.Composite=uC;er.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3};er.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2};er.prototype.GetterByBindingType=[er.prototype._getValue_direct,er.prototype._getValue_array,er.prototype._getValue_arrayElement,er.prototype._getValue_toArray];er.prototype.SetterByBindingTypeAndVersioning=[[er.prototype._setValue_direct,er.prototype._setValue_direct_setNeedsUpdate,er.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[er.prototype._setValue_array,er.prototype._setValue_array_setNeedsUpdate,er.prototype._setValue_array_setMatrixWorldNeedsUpdate],[er.prototype._setValue_arrayElement,er.prototype._setValue_arrayElement_setNeedsUpdate,er.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[er.prototype._setValue_fromArray,er.prototype._setValue_fromArray_setNeedsUpdate,er.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];var Jhn=new Float32Array(1);typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:dC}}));typeof window<"u"&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=dC);function xC(i,e,t,n,r,s,a,o){let l=(P,I,k,L)=>[new yn(P/a,1-L/o),new yn(k/a,1-L/o),new yn(k/a,1-I/o),new yn(P/a,1-I/o)],c=l(e+s,t,e+n+s,t+s),u=l(e+n+s,t,e+n*2+s,t+s),d=l(e,t+s,e+s,t+s+r),f=l(e+s,t+s,e+n+s,t+s+r),v=l(e+n+s,t+s,e+n+s*2,t+r+s),g=l(e+n+s*2,t+s,e+n*2+s*2,t+r+s),b=i.attributes.uv,y=[v[3],v[2],v[0],v[1]],_=[d[3],d[2],d[0],d[1]],x=[c[3],c[2],c[0],c[1]],w=[u[0],u[1],u[3],u[2]],S=[f[3],f[2],f[0],f[1]],A=[g[3],g[2],g[0],g[1]],T=[];for(let P of[y,_,x,w,S,A])for(let I of P)T.push(I.x,I.y);b.set(new Float32Array(T)),b.needsUpdate=!0}function ta(i,e,t,n,r,s){xC(i,e,t,n,r,s,64,64)}function vC(i,e,t,n,r,s){xC(i,e,t,n,r,s,64,32)}var a0=class extends Fr{constructor(e,t){super(),Object.defineProperty(this,"innerLayer",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"outerLayer",{enumerable:!0,configurable:!0,writable:!0,value:t}),e.name="inner",t.name="outer"}},gC=class extends Fr{constructor(){super(),Object.defineProperty(this,"head",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"rightArm",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"leftArm",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"rightLeg",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"leftLeg",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"modelListeners",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"slim",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_map",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"layer1Material",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"layer1MaterialBiased",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"layer2Material",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"layer2MaterialBiased",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.layer1Material=new jc({side:Qa}),this.layer2Material=new jc({side:Ns,transparent:!0,alphaTest:1e-5}),this.layer1MaterialBiased=this.layer1Material.clone(),this.layer1MaterialBiased.polygonOffset=!0,this.layer1MaterialBiased.polygonOffsetFactor=1,this.layer1MaterialBiased.polygonOffsetUnits=1,this.layer2MaterialBiased=this.layer2Material.clone(),this.layer2MaterialBiased.polygonOffset=!0,this.layer2MaterialBiased.polygonOffsetFactor=1,this.layer2MaterialBiased.polygonOffsetUnits=1;let e=new mr(8,8,8);ta(e,0,0,8,8,8);let t=new Nn(e,this.layer1Material),n=new mr(9,9,9);ta(n,32,0,8,8,8);let r=new Nn(n,this.layer2Material);this.head=new a0(t,r),this.head.name="head",this.head.add(t,r),t.position.y=4,r.position.y=4,this.add(this.head);let s=new mr(8,12,4);ta(s,16,16,8,12,4);let a=new Nn(s,this.layer1Material),o=new mr(8.5,12.5,4.5);ta(o,16,32,8,12,4);let l=new Nn(o,this.layer2Material);this.body=new a0(a,l),this.body.name="body",this.body.add(a,l),this.body.position.y=-6,this.add(this.body);let c=new mr,u=new Nn(c,this.layer1MaterialBiased);this.modelListeners.push(()=>{u.scale.x=this.slim?3:4,u.scale.y=12,u.scale.z=4,ta(c,40,16,this.slim?3:4,12,4)});let d=new mr,f=new Nn(d,this.layer2MaterialBiased);this.modelListeners.push(()=>{f.scale.x=this.slim?3.5:4.5,f.scale.y=12.5,f.scale.z=4.5,ta(d,40,32,this.slim?3:4,12,4)});let v=new Fr;v.add(u,f),this.modelListeners.push(()=>{v.position.x=this.slim?-.5:-1}),v.position.y=-4,this.rightArm=new a0(u,f),this.rightArm.name="rightArm",this.rightArm.add(v),this.rightArm.position.x=-5,this.rightArm.position.y=-2,this.add(this.rightArm);let g=new mr,b=new Nn(g,this.layer1MaterialBiased);this.modelListeners.push(()=>{b.scale.x=this.slim?3:4,b.scale.y=12,b.scale.z=4,ta(g,32,48,this.slim?3:4,12,4)});let y=new mr,_=new Nn(y,this.layer2MaterialBiased);this.modelListeners.push(()=>{_.scale.x=this.slim?3.5:4.5,_.scale.y=12.5,_.scale.z=4.5,ta(y,48,48,this.slim?3:4,12,4)});let x=new Fr;x.add(b,_),this.modelListeners.push(()=>{x.position.x=this.slim?.5:1}),x.position.y=-4,this.leftArm=new a0(b,_),this.leftArm.name="leftArm",this.leftArm.add(x),this.leftArm.position.x=5,this.leftArm.position.y=-2,this.add(this.leftArm);let w=new mr(4,12,4);ta(w,0,16,4,12,4);let S=new Nn(w,this.layer1MaterialBiased),A=new mr(4.5,12.5,4.5);ta(A,0,32,4,12,4);let T=new Nn(A,this.layer2MaterialBiased),P=new Fr;P.add(S,T),P.position.y=-6,this.rightLeg=new a0(S,T),this.rightLeg.name="rightLeg",this.rightLeg.add(P),this.rightLeg.position.x=-1.9,this.rightLeg.position.y=-12,this.rightLeg.position.z=-.1,this.add(this.rightLeg);let I=new mr(4,12,4);ta(I,16,48,4,12,4);let k=new Nn(I,this.layer1MaterialBiased),L=new mr(4.5,12.5,4.5);ta(L,0,48,4,12,4);let B=new Nn(L,this.layer2MaterialBiased),U=new Fr;U.add(k,B),U.position.y=-6,this.leftLeg=new a0(k,B),this.leftLeg.name="leftLeg",this.leftLeg.add(U),this.leftLeg.position.x=1.9,this.leftLeg.position.y=-12,this.leftLeg.position.z=-.1,this.add(this.leftLeg),this.modelType="default"}get map(){return this._map}set map(e){this._map=e,this.layer1Material.map=e,this.layer1Material.needsUpdate=!0,this.layer1MaterialBiased.map=e,this.layer1MaterialBiased.needsUpdate=!0,this.layer2Material.map=e,this.layer2Material.needsUpdate=!0,this.layer2MaterialBiased.map=e,this.layer2MaterialBiased.needsUpdate=!0}get modelType(){return this.slim?"slim":"default"}set modelType(e){this.slim=e==="slim",this.modelListeners.forEach(t=>t())}getBodyParts(){return this.children.filter(e=>e instanceof a0)}setInnerLayerVisible(e){this.getBodyParts().forEach(t=>t.innerLayer.visible=e)}setOuterLayerVisible(e){this.getBodyParts().forEach(t=>t.outerLayer.visible=e)}resetJoints(){this.head.rotation.set(0,0,0),this.leftArm.rotation.set(0,0,0),this.rightArm.rotation.set(0,0,0),this.leftLeg.rotation.set(0,0,0),this.rightLeg.rotation.set(0,0,0),this.body.rotation.set(0,0,0),this.head.position.y=0,this.body.position.y=-6,this.body.position.z=0,this.rightArm.position.x=-5,this.rightArm.position.y=-2,this.rightArm.position.z=0,this.leftArm.position.x=5,this.leftArm.position.y=-2,this.leftArm.position.z=0,this.rightLeg.position.x=-1.9,this.rightLeg.position.y=-12,this.rightLeg.position.z=-.1,this.leftLeg.position.x=1.9,this.leftLeg.position.y=-12,this.leftLeg.position.z=-.1}},_C=class extends Fr{constructor(){super(),Object.defineProperty(this,"cape",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"material",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.material=new jc({side:Ns,transparent:!0,alphaTest:1e-5});let e=new mr(10,16,1);vC(e,0,0,10,16,1),this.cape=new Nn(e,this.material),this.cape.position.y=-8,this.cape.position.z=.5,this.add(this.cape)}get map(){return this.material.map}set map(e){this.material.map=e,this.material.needsUpdate=!0}},yC=class extends Fr{constructor(){super(),Object.defineProperty(this,"leftWing",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"rightWing",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"material",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.material=new jc({side:Ns,transparent:!0,alphaTest:1e-5});let e=new mr(12,22,4);vC(e,22,0,10,20,2);let t=new Nn(e,this.material);t.position.x=-5,t.position.y=-10,t.position.z=-1,this.leftWing=new Fr,this.leftWing.add(t),this.add(this.leftWing);let n=new mr(12,22,4);vC(n,22,0,10,20,2);let r=new Nn(n,this.material);r.scale.x=-1,r.position.x=5,r.position.y=-10,r.position.z=-1,this.rightWing=new Fr,this.rightWing.add(r),this.add(this.rightWing),this.leftWing.position.x=5,this.leftWing.rotation.x=.2617994,this.resetJoints()}resetJoints(){this.leftWing.rotation.y=.01,this.leftWing.rotation.z=.2617994,this.updateRightWing()}updateRightWing(){this.rightWing.position.x=-this.leftWing.position.x,this.rightWing.position.y=this.leftWing.position.y,this.rightWing.rotation.x=this.leftWing.rotation.x,this.rightWing.rotation.y=-this.leftWing.rotation.y,this.rightWing.rotation.z=-this.leftWing.rotation.z}get map(){return this.material.map}set map(e){this.material.map=e,this.material.needsUpdate=!0}},bC=class extends Fr{constructor(){super(),Object.defineProperty(this,"rightEar",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"leftEar",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"material",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.material=new jc({side:Qa});let e=new mr(8,8,4/3);xC(e,0,0,6,6,1,14,7),this.rightEar=new Nn(e,this.material),this.rightEar.name="rightEar",this.rightEar.position.x=-6,this.add(this.rightEar),this.leftEar=new Nn(e,this.material),this.leftEar.name="leftEar",this.leftEar.position.x=6,this.add(this.leftEar)}get map(){return this.material.map}set map(e){this.material.map=e,this.material.needsUpdate=!0}},p6e=10.8*Math.PI/180,L5=class extends Fr{constructor(){super(),Object.defineProperty(this,"skin",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cape",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"elytra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ears",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.skin=new gC,this.skin.name="skin",this.skin.position.y=8,this.add(this.skin),this.cape=new _C,this.cape.name="cape",this.cape.position.y=8,this.cape.position.z=-2,this.cape.rotation.x=p6e,this.cape.rotation.y=Math.PI,this.add(this.cape),this.elytra=new yC,this.elytra.name="elytra",this.elytra.position.y=8,this.elytra.position.z=-2,this.elytra.visible=!1,this.add(this.elytra),this.ears=new bC,this.ears.name="ears",this.ears.position.y=10,this.ears.position.z=2/3,this.ears.visible=!1,this.skin.head.add(this.ears)}get backEquipment(){return this.cape.visible?"cape":this.elytra.visible?"elytra":null}set backEquipment(e){this.cape.visible=e==="cape",this.elytra.visible=e==="elytra"}resetJoints(){this.skin.resetJoints(),this.cape.rotation.x=p6e,this.cape.position.y=8,this.cape.position.z=-2,this.elytra.position.y=8,this.elytra.position.z=-2,this.elytra.rotation.x=0,this.elytra.resetJoints()}};h();p();m();h();p();m();var Sb=class{constructor(){Object.defineProperty(this,"speed",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"paused",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"progress",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"currentId",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"progress0",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"animationObjects",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}update(e,t){if(this.paused)return;let n=t*this.speed;this.animate(e,n),this.animationObjects.forEach((r,s)=>{let a=this.progress0.get(s);r(e,this.progress-a,s)}),this.progress+=n}addAnimation(e){let t=this.currentId++;return this.progress0.set(t,this.progress),this.animationObjects.set(t,e),t}removeAnimation(e){e!=null&&(this.animationObjects.delete(e),this.progress0.delete(e))}};h();p();m();h();p();m();var $je=Object.defineProperty,Yje=(i,e,t)=>e in i?$je(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,nr=(i,e,t)=>(Yje(i,typeof e!="symbol"?e+"":e,t),t);function wC(i){let e=[i];if(i.extra&&i.extra.length!==0)for(let t of i.extra)e.push(...wC(t));return e}var Vt=class{constructor(i,e,t,n,r,s){this.key=i,this.value=e,this.name=t,this.code=n,this.cssForeground=r,this.cssBackground=s}applyToStyle(i){i[this.key]=this.value}matchStyle(i){return i[this.key]===this.value}static fromCode(i){let t="0123456789abcdefklmnor".indexOf(i);if(t)return this.list[t]}toString(){return`${Vt.CONTROL_STRING}${this.code}`}},rr=Vt;nr(rr,"CONTROL_STRING","\xA7");nr(rr,"BLACK",new Vt("color","black","BLACK","0",{color:"#000000"},{color:"#000000"}));nr(rr,"DARK_BLUE",new Vt("color","dark_blue","DARK_BLUE","1",{color:"#0000AA"},{color:"#00002A"}));nr(rr,"DARK_GREEN",new Vt("color","dark_green","DARK_GREEN","2",{color:"#00AA00"},{color:"#002A00"}));nr(rr,"DARK_AQUA",new Vt("color","dark_aqua","DARK_AQUA","3",{color:"#00AAAA"},{color:"#002A2A"}));nr(rr,"DARK_RED",new Vt("color","dark_red","DARK_RED","4",{color:"#AA0000"},{color:"#2A0000"}));nr(rr,"DARK_PURPLE",new Vt("color","dark_purple","DARK_PURPLE","5",{color:"#AA00AA"},{color:"#2A002A"}));nr(rr,"GOLD",new Vt("color","gold","GOLD","6",{color:"#FFAA00"},{color:"#2A2A00"}));nr(rr,"GRAY",new Vt("color","gray","GRAY","7",{color:"#AAAAAA"},{color:"#2A2A2A"}));nr(rr,"DARK_GRAY",new Vt("color","dark_gray","DARK_GRAY","8",{color:"#555555"},{color:"#151515"}));nr(rr,"BLUE",new Vt("color","blue","BLUE","9",{color:"#5555FF"},{color:"#15153F"}));nr(rr,"GREEN",new Vt("color","green","GREEN","a",{color:"#55FF55"},{color:"#153F15"}));nr(rr,"AQUA",new Vt("color","aqua","AQUA","b",{color:"#55FFFF"},{color:"#153F3F"}));nr(rr,"RED",new Vt("color","red","RED","c",{color:"#FF5555"},{color:"#3F1515"}));nr(rr,"LIGHT_PURPLE",new Vt("color","light_purple","LIGHT_PURPLE","d",{color:"#FF55FF"},{color:"#3F153F"}));nr(rr,"YELLOW",new Vt("color","yellow","YELLOW","e",{color:"#FFFF55"},{color:"#3F3F15"}));nr(rr,"WHITE",new Vt("color","white","WHITE","f",{color:"#FFFFFF"},{color:"#3F3F3F"}));nr(rr,"OBFUSCATED",new Vt("obfuscated",!0,"OBFUSCATED","k",{}));nr(rr,"BOLD",new Vt("bold",!0,"BOLD","l",{"font-weight":"bold"}));nr(rr,"STRIKETHROUGH",new Vt("strikethrough",!0,"STRIKETHROUGH","m",{"text-decoration":"line-through"}));nr(rr,"UNDERLINE",new Vt("underlined",!0,"UNDERLINE","n",{"text-decoration":"underline"}));nr(rr,"ITALIC",new Vt("italic",!0,"ITALIC","o",{"font-style":"italic"}));nr(rr,"RESET",{name:"RESET",code:"r",applyToStyle(i){i.bold=!1,i.strikethrough=!1,i.underlined=!1,i.italic=!1,i.obfuscated=!1,i.color=void 0},matchStyle(i){return!1},cssBackground:{},cssForeground:{},toString(){return`${Vt.CONTROL_STRING}r`}});nr(rr,"list",[Vt.BLACK,Vt.DARK_BLUE,Vt.DARK_GREEN,Vt.DARK_AQUA,Vt.DARK_RED,Vt.DARK_PURPLE,Vt.GOLD,Vt.GRAY,Vt.DARK_GRAY,Vt.BLUE,Vt.GREEN,Vt.AQUA,Vt.RED,Vt.LIGHT_PURPLE,Vt.YELLOW,Vt.WHITE,Vt.OBFUSCATED,Vt.BOLD,Vt.STRIKETHROUGH,Vt.UNDERLINE,Vt.ITALIC,Vt.RESET]);var ng=Yr(sv(),1);AC();var r_e=Yr(A6e(),1),dP=Yr(V8(),1);h();p();m();var gXe=(i,e)=>{try{return JSON.parse(i)}catch(t){return console.warn(`Failed to parse ${e}`,t),null}},_Xe={black:"#000000",dark_blue:"#0000AA",dark_green:"#00AA00",dark_aqua:"#00AAAA",dark_red:"#AA0000",dark_purple:"#AA00AA",gold:"#FFAA00",gray:"#AAAAAA",dark_gray:"#555555",blue:"#5555FF",green:"#55FF55",aqua:"#55FFFF",red:"#FF5555",light_purple:"#FF55FF",yellow:"#FFFF55",white:"#FFFFFF"},k6e=(i,e,t,n=s=>{},r=(s,a)=>yi(s,a))=>{let o=[16,9],l=o[0]-o[1],c=l/16,u="front_text"in i?i.front_text.messages:[i.Text1,i.Text2,i.Text3,i.Text4];if(!u.some(g=>g!=="null"))return;let d=r(16*40,l*40),f=d.getContext("2d");n(f);let v=("front_text"in i?i.front_text.color:i.Color)||"black";for(let[g,b]of u.slice(0,4).entries())b!=="null"&&kC(b,t,d,64,v,64*(g+1)+(e?0:-8));return d},kC=(i,e,t,n,r,s=0)=>{let a=!1,o=typeof i=="string"&&(i?.startsWith("{")||i?.startsWith('"'))?gXe(i??'""',"sign text"):i;if(!o||typeof o!="object"&&typeof o!="string")return;let l=t.getContext("2d");if(!l)throw new Error("Could not get 2d context");l.imageSmoothingEnabled=!1,l.font=`${n}px mojangles`;let c=new e(o),u=[],d=!1,f="",v=s,g=[],b=(w,S)=>{w.text!==null&&w.text!==void 0&&typeof w.text!="string"&&console.warn("renderText received non-string text value:",typeof w.text,w.text);let A=w.text===null||w.text===void 0?void 0:String(w.text),T={color:w.color??S?.color,underlined:w.underlined??S?.underlined,strikethrough:w.strikethrough??S?.strikethrough,bold:w.bold??S?.bold,italic:w.italic??S?.italic};if(d=d||T.underlined||T.strikethrough||!1,A?.includes(`
|
|
8639
8639
|
`))for(let P of A.split(`
|
|
8640
|
-
`))y(P,T),v+=n,f="";else A&&y(A,T);if(w.extra)for(let P of w.extra)b(P,T)},y=(w,S)=>{a||(a=w.trim()!==""),f+=w,g[v]=l.measureText(f).width;let A=S.color??r;A.startsWith("#")||(A=_Xe[A.toLowerCase()]||A),u.push({fontStyle:`${S.bold?"bold":""} ${S.italic?"italic":""}`,fillStyle:A,underlineStyle:S.underlined??!1,strikeStyle:S.strikethrough??!1,offset:v,text:w})};if(b(c),!d&&!c.toString().trim())return;let _=0,x=0;for(let{fillStyle:w,fontStyle:S,underlineStyle:A,strikeStyle:T,offset:P,text:I}of u){x!==P&&(_=0),x=P,l.fillStyle=w,l.textRendering="optimizeLegibility",l.font=`${S} ${n}px mojangles`;let k=g[P]??l.measureText(I).width,L=(t.width-k)/2+_;l.fillText(I,L,P),T&&(l.lineWidth=n/8,l.strokeStyle=w,l.beginPath(),l.moveTo(L,P-l.lineWidth*2.5),l.lineTo(L+l.measureText(I).width,P-l.lineWidth*2.5),l.stroke()),A&&(l.lineWidth=n/8,l.strokeStyle=w,l.beginPath(),l.moveTo(L,P+l.lineWidth),l.lineTo(L+l.measureText(I).width,P+l.lineWidth),l.stroke()),_+=l.measureText(I).width}return a};h();p();m();h();p();m();var yXe=i=>Math.max(0,Math.min(1,i)),bXe=(i,e,t)=>i+(e-i)*t;function xXe(i){let e=i?.elytra;if(!e)return;if(typeof e.updateRightWing=="function"){e.updateRightWing();return}if(typeof e.updateRightWingRotation=="function"){e.updateRightWingRotation();return}let t=e.leftWing,n=e.rightWing;!t?.rotation||!n?.rotation||typeof n.rotation.copy=="function"&&(n.rotation.copy(t.rotation),n.rotation.z*=-1)}var Qv=class extends Sb{switchAnimationCallback;isRunning=!1;isMoving=!0;isCrouched=!1;_dt=0;_phase=0;_moveBlend=0;_swingTime=null;_swingDuration=.25;_defaults=null;update(e,t){this._dt=t,super.update(e,t)}swingArm(){(this._swingTime===null||this._swingTime>=this._swingDuration/2)&&(this._swingTime=0)}_captureDefaults(e){this._defaults={bodyPos:e.skin.body.position.clone(),bodyRot:e.skin.body.rotation.clone(),leftArmPos:e.skin.leftArm.position.clone(),leftArmRot:e.skin.leftArm.rotation.clone(),rightArmPos:e.skin.rightArm.position.clone(),rightArmRot:e.skin.rightArm.rotation.clone(),leftLegPos:e.skin.leftLeg.position.clone(),leftLegRot:e.skin.leftLeg.rotation.clone(),rightLegPos:e.skin.rightLeg.position.clone(),rightLegRot:e.skin.rightLeg.rotation.clone(),headPos:e.skin.head.position.clone(),headRot:e.skin.head.rotation.clone(),capePos:e.cape.position.clone(),capeRot:e.cape.rotation.clone(),elytraPos:e.elytra.position.clone(),elytraRot:e.elytra.rotation.clone()}}_applyDefaults(e){let t=this._defaults;t&&(e.skin.body.position.copy(t.bodyPos),e.skin.body.rotation.copy(t.bodyRot),e.skin.leftArm.position.copy(t.leftArmPos),e.skin.leftArm.rotation.copy(t.leftArmRot),e.skin.rightArm.position.copy(t.rightArmPos),e.skin.rightArm.rotation.copy(t.rightArmRot),e.skin.leftLeg.position.copy(t.leftLegPos),e.skin.leftLeg.rotation.copy(t.leftLegRot),e.skin.rightLeg.position.copy(t.rightLegPos),e.skin.rightLeg.rotation.copy(t.rightLegRot),e.skin.head.position.copy(t.headPos),e.skin.head.rotation.copy(t.headRot),e.cape.position.copy(t.capePos),e.cape.rotation.copy(t.capeRot),e.elytra.position.copy(t.elytraPos),e.elytra.rotation.copy(t.elytraRot))}animate(e){let t=this._dt||0;this._defaults||this._captureDefaults(e),this._applyDefaults(e);let n=this.isMoving?1:0,r=Math.min(1,t*20);this._moveBlend+=(n-this._moveBlend)*r;let s=this.isRunning?10:8;this._phase+=t*s*this._moveBlend;let a=this._phase+(this.isRunning?Math.PI*.5:0),o=!1;SXe(e,this.isCrouched?1:0);let l=this.isRunning?Math.cos(a):Math.sin(a);if(Math.abs(l)<.02&&this.switchAnimationCallback&&(o=!0),this.isRunning?(e.skin.leftLeg.rotation.x
|
|
8640
|
+
`))y(P,T),v+=n,f="";else A&&y(A,T);if(w.extra)for(let P of w.extra)b(P,T)},y=(w,S)=>{a||(a=w.trim()!==""),f+=w,g[v]=l.measureText(f).width;let A=S.color??r;A.startsWith("#")||(A=_Xe[A.toLowerCase()]||A),u.push({fontStyle:`${S.bold?"bold":""} ${S.italic?"italic":""}`,fillStyle:A,underlineStyle:S.underlined??!1,strikeStyle:S.strikethrough??!1,offset:v,text:w})};if(b(c),!d&&!c.toString().trim())return;let _=0,x=0;for(let{fillStyle:w,fontStyle:S,underlineStyle:A,strikeStyle:T,offset:P,text:I}of u){x!==P&&(_=0),x=P,l.fillStyle=w,l.textRendering="optimizeLegibility",l.font=`${S} ${n}px mojangles`;let k=g[P]??l.measureText(I).width,L=(t.width-k)/2+_;l.fillText(I,L,P),T&&(l.lineWidth=n/8,l.strokeStyle=w,l.beginPath(),l.moveTo(L,P-l.lineWidth*2.5),l.lineTo(L+l.measureText(I).width,P-l.lineWidth*2.5),l.stroke()),A&&(l.lineWidth=n/8,l.strokeStyle=w,l.beginPath(),l.moveTo(L,P+l.lineWidth),l.lineTo(L+l.measureText(I).width,P+l.lineWidth),l.stroke()),_+=l.measureText(I).width}return a};h();p();m();h();p();m();var yXe=i=>Math.max(0,Math.min(1,i)),bXe=(i,e,t)=>i+(e-i)*t;function xXe(i){let e=i?.elytra;if(!e)return;if(typeof e.updateRightWing=="function"){e.updateRightWing();return}if(typeof e.updateRightWingRotation=="function"){e.updateRightWingRotation();return}let t=e.leftWing,n=e.rightWing;!t?.rotation||!n?.rotation||typeof n.rotation.copy=="function"&&(n.rotation.copy(t.rotation),n.rotation.z*=-1)}var Qv=class extends Sb{switchAnimationCallback;isRunning=!1;isMoving=!0;isCrouched=!1;_dt=0;_phase=0;_moveBlend=0;_swingTime=null;_swingDuration=.25;_defaults=null;update(e,t){this._dt=t,super.update(e,t)}swingArm(){(this._swingTime===null||this._swingTime>=this._swingDuration/2)&&(this._swingTime=0)}_captureDefaults(e){this._defaults={bodyPos:e.skin.body.position.clone(),bodyRot:e.skin.body.rotation.clone(),leftArmPos:e.skin.leftArm.position.clone(),leftArmRot:e.skin.leftArm.rotation.clone(),rightArmPos:e.skin.rightArm.position.clone(),rightArmRot:e.skin.rightArm.rotation.clone(),leftLegPos:e.skin.leftLeg.position.clone(),leftLegRot:e.skin.leftLeg.rotation.clone(),rightLegPos:e.skin.rightLeg.position.clone(),rightLegRot:e.skin.rightLeg.rotation.clone(),headPos:e.skin.head.position.clone(),headRot:e.skin.head.rotation.clone(),capePos:e.cape.position.clone(),capeRot:e.cape.rotation.clone(),elytraPos:e.elytra.position.clone(),elytraRot:e.elytra.rotation.clone()}}_applyDefaults(e){let t=this._defaults;t&&(e.skin.body.position.copy(t.bodyPos),e.skin.body.rotation.copy(t.bodyRot),e.skin.leftArm.position.copy(t.leftArmPos),e.skin.leftArm.rotation.copy(t.leftArmRot),e.skin.rightArm.position.copy(t.rightArmPos),e.skin.rightArm.rotation.copy(t.rightArmRot),e.skin.leftLeg.position.copy(t.leftLegPos),e.skin.leftLeg.rotation.copy(t.leftLegRot),e.skin.rightLeg.position.copy(t.rightLegPos),e.skin.rightLeg.rotation.copy(t.rightLegRot),e.skin.head.position.copy(t.headPos),e.skin.head.rotation.copy(t.headRot),e.cape.position.copy(t.capePos),e.cape.rotation.copy(t.capeRot),e.elytra.position.copy(t.elytraPos),e.elytra.rotation.copy(t.elytraRot))}animate(e){let t=this._dt||0;this._defaults||this._captureDefaults(e),this._applyDefaults(e);let n=this.isMoving?1:0,r=Math.min(1,t*20);this._moveBlend+=(n-this._moveBlend)*r;let s=this.isRunning?10:8;this._phase+=t*s*this._moveBlend;let a=this._phase+(this.isRunning?Math.PI*.5:0),o=!1;SXe(e,this.isCrouched?1:0);let l=this.isRunning?Math.cos(a):Math.sin(a);if(Math.abs(l)<.02&&this.switchAnimationCallback&&(o=!0),this.isRunning?(e.skin.leftLeg.rotation.x+=Math.cos(a+Math.PI)*1.3*this._moveBlend,e.skin.rightLeg.rotation.x+=Math.cos(a)*1.3*this._moveBlend):(e.skin.leftLeg.rotation.x+=Math.sin(a)*.5*this._moveBlend,e.skin.rightLeg.rotation.x+=Math.sin(a+Math.PI)*.5*this._moveBlend),this.isRunning){e.skin.leftArm.rotation.x+=Math.cos(a)*1.5*this._moveBlend,e.skin.rightArm.rotation.x+=Math.cos(a+Math.PI)*1.5*this._moveBlend;let c=Math.PI*.1;e.skin.leftArm.rotation.z+=(Math.cos(a)*.1+c)*this._moveBlend,e.skin.rightArm.rotation.z+=(Math.cos(a+Math.PI)*.1-c)*this._moveBlend}else{e.skin.leftArm.rotation.x+=Math.sin(a+Math.PI)*.5*this._moveBlend,e.skin.rightArm.rotation.x+=Math.sin(a)*.5*this._moveBlend;let c=Math.PI*.02;e.skin.leftArm.rotation.z+=(Math.cos(a)*.03+c)*this._moveBlend,e.skin.rightArm.rotation.z+=(Math.cos(a+Math.PI)*.03-c)*this._moveBlend}if(this._swingTime!==null){this._swingTime+=t;let c=Math.min(this._swingTime/this._swingDuration,1);wXe.animate(c,e,this.isMoving),c>=1&&(this._swingTime=null)}if(this.isRunning&&(e.rotation.z=Math.cos(a+Math.PI)*.01*this._moveBlend),this.isRunning){let c=Math.PI*.3;e.cape.rotation.x+=(Math.sin(a*2)*.1+c)*this._moveBlend}else{let c=Math.PI*.06;e.cape.rotation.x+=(Math.sin(a/1.5)*.06+c)*this._moveBlend}if(o){let c=this.switchAnimationCallback;this.switchAnimationCallback=null,c?.()}}},wXe={animate(i,e,t){if(!e?.skin?.rightArm?.rotation)return;let n=Math.sin(i*Math.PI);if(e.skin.rightArm.rotation.x=-.4537860552*2-2*n*.3,!t){let r=.01*Math.PI+.06;e.skin.rightArm.rotation.z=-n*.403+r,e.skin.body.rotation.y=-n*.06,e.skin.leftArm.rotation.x=-n*.077,e.skin.leftArm.rotation.z=-n*.015+.13-.05,e.skin.leftArm.position.z=n*.3,e.skin.leftArm.position.x=5-n*.05}}};function SXe(i,e){let t=i?.skin,n=i?.cape,r=i?.elytra;if(!t||!n)return;let s=yXe(e),a=Math.abs(Math.sin(s*Math.PI/2));if(a<=1e-6)return;t.body.rotation.x+=.4537860552*a,t.body.position.z+=(1.3256181-3.4500310377)*a,t.body.position.y+=-2.103677462*a,n.position.y+=-1.851236166577372*a,n.rotation.x+=.294220265771*a,n.position.z+=(3.786619432-3.4500310377)*a,r?.position&&r.position.copy(n.position),r?.rotation&&r.rotation.copy(n.rotation),r?.rotation&&(r.rotation.x-=10.8*Math.PI/180),r?.leftWing?.rotation&&(r.leftWing.rotation.z=bXe(.72,.26179944+.4582006,a)),xXe(i),t.head.position.y+=-3.618325234674*a;let o=.1*a,l=(3.618325234674-3.4500310377)*a,c=-2.53943318*a;t.leftArm.position.z+=l,t.rightArm.position.z+=l,t.leftArm.rotation.x+=.410367746202*a,t.rightArm.rotation.x+=.410367746202*a,t.leftArm.rotation.z+=o,t.rightArm.rotation.z+=-o,t.leftArm.position.y+=c,t.rightArm.position.y+=c,t.rightLeg.position.z+=-3.4500310377*a,t.leftLeg.position.z+=-3.4500310377*a}var EXe=-2e-4;function MXe(i){i.uniforms.uLogDepthBias={value:EXe},i.fragmentShader=i.fragmentShader.replace("#include <logdepthbuf_pars_fragment>",`#include <logdepthbuf_pars_fragment>
|
|
8641
8641
|
uniform float uLogDepthBias;`),i.fragmentShader=i.fragmentShader.replace("#include <logdepthbuf_fragment>",`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )
|
|
8642
8642
|
gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5 + uLogDepthBias;
|
|
8643
8643
|
#endif`)}function T6e(i){i.userData.logDepthBiasApplied||(i.userData.logDepthBiasApplied=!0,i.onBeforeCompile=MXe,i.needsUpdate=!0)}function TC(i){let e=i.skin,t=[e.layer1Material,e.layer1MaterialBiased,e.layer2Material,e.layer2MaterialBiased];for(let n of t)n.transparent=!1,n.alphaTest=.1,n.depthWrite=!0;T6e(e.layer1MaterialBiased),T6e(e.layer2MaterialBiased)}h();p();m();Lt();function AXe(i,e){if(typeof document<"u"){let t=document.createElement("canvas");return t.width=i,t.height=e,t}return new OffscreenCanvas(i,e)}function kXe(i,e){let{depth:t,pixelSize:n}=e;if(i.width<=0||i.height<=0)throw new Error(`Invalid canvas dimensions: ${i.width}x${i.height}`);let s=i.getContext("2d").getImageData(0,0,i.width,i.height),{data:a}=s,o=i.width,l=i.height,c=t/2,u=n??1/Math.max(o,l),d=(P,I)=>{if(P<0||I<0||P>=o||I>=l)return!1;let k=(I*o+P)*4;return a[k+3]>128},f=[],v=[],g=[],b=[],y=0,_=(P,I,k,L,B,U,O,V)=>(f.push(P,I,k),g.push(L,B),b.push(U,O,V),y++),x=(P,I,k,L)=>{v.push(P,I,k,P,k,L)},w=(P,I)=>{let k=(P/o-.5)*u*o,L=-(I/l-.5)*u*l;return{x:k,y:L}},S=Array.from({length:l+1},()=>Array.from({length:o+1},()=>null)),A=Array.from({length:l+1},()=>Array.from({length:o+1},()=>null));for(let P=0;P<=l;P++)for(let I=0;I<=o;I++){let{x:k,y:L}=w(I-.5,P-.5),B=I/o,U=P/l,O=!1,V=[[I-1,P-1],[I,P-1],[I-1,P],[I,P]];for(let[F,J]of V)if(d(F,J)){O=!0;break}O&&(S[P][I]=_(k,L,c,B,U,0,0,1),A[P][I]=_(k,L,-c,B,U,0,0,-1))}for(let P=0;P<l;P++)for(let I=0;I<o;I++){if(!d(I,P))continue;let k=S[P][I],L=S[P][I+1],B=S[P+1][I+1],U=S[P+1][I],O=A[P][I],V=A[P][I+1],F=A[P+1][I+1],J=A[P+1][I];k!==null&&L!==null&&B!==null&&U!==null&&x(k,L,B,U),O!==null&&V!==null&&F!==null&&J!==null&&x(V,O,J,F)}for(let P=0;P<l;P++)for(let I=0;I<o;I++){if(!d(I,P))continue;let k=(I+.5)/o,L=(P+.5)/l;if(!d(I-1,P)){let B=S[P][I],U=S[P+1][I],O=A[P][I],V=A[P+1][I];if(B!==null&&U!==null&&O!==null&&V!==null){let F=_(f[B*3],f[B*3+1],f[B*3+2],k,L,-1,0,0),J=_(f[U*3],f[U*3+1],f[U*3+2],k,L,-1,0,0),$=_(f[V*3],f[V*3+1],f[V*3+2],k,L,-1,0,0),ne=_(f[O*3],f[O*3+1],f[O*3+2],k,L,-1,0,0);x(F,J,$,ne)}}if(!d(I+1,P)){let B=S[P+1][I+1],U=S[P][I+1],O=A[P+1][I+1],V=A[P][I+1];if(B!==null&&U!==null&&O!==null&&V!==null){let F=_(f[B*3],f[B*3+1],f[B*3+2],k,L,1,0,0),J=_(f[U*3],f[U*3+1],f[U*3+2],k,L,1,0,0),$=_(f[V*3],f[V*3+1],f[V*3+2],k,L,1,0,0),ne=_(f[O*3],f[O*3+1],f[O*3+2],k,L,1,0,0);x(F,J,$,ne)}}if(!d(I,P-1)){let B=S[P][I],U=S[P][I+1],O=A[P][I],V=A[P][I+1];if(B!==null&&U!==null&&O!==null&&V!==null){let F=_(f[B*3],f[B*3+1],f[B*3+2],k,L,0,-1,0),J=_(f[U*3],f[U*3+1],f[U*3+2],k,L,0,-1,0),$=_(f[V*3],f[V*3+1],f[V*3+2],k,L,0,-1,0),ne=_(f[O*3],f[O*3+1],f[O*3+2],k,L,0,-1,0);x(F,J,$,ne)}}if(!d(I,P+1)){let B=S[P+1][I+1],U=S[P+1][I],O=A[P+1][I+1],V=A[P+1][I];if(B!==null&&U!==null&&O!==null&&V!==null){let F=_(f[B*3],f[B*3+1],f[B*3+2],k,L,0,1,0),J=_(f[U*3],f[U*3+1],f[U*3+2],k,L,0,1,0),$=_(f[V*3],f[V*3+1],f[V*3+2],k,L,0,1,0),ne=_(f[O*3],f[O*3+1],f[O*3+2],k,L,0,1,0);x(F,J,$,ne)}}}let T=new dt;return T.setAttribute("position",new Je(f,3)),T.setAttribute("uv",new Je(g,2)),T.setAttribute("normal",new Je(b,3)),T.setIndex(v),T.computeVertexNormals(),{geometry:T,totalVertices:y,totalTriangles:v.length/3}}function TXe(i,e){let{u:t,v:n,sizeX:r,sizeY:s}=e,a=Math.max(1,Math.floor(r*i.image.width)),o=Math.max(1,Math.floor(s*i.image.height)),l=AXe(a,o),c=l.getContext("2d");if(!c)throw new Error("Failed to get 2d context for item texture canvas");return c.imageSmoothingEnabled=!1,c.drawImage(i.image,t*i.image.width,n*i.image.height,r*i.image.width,s*i.image.height,0,0,l.width,l.height),l}function I6e(i,e,t={}){let{faceCamera:n=!1,use3D:r=!0,depth:s=.04}=t,{u:a,v:o,sizeX:l,sizeY:c}=e;if(n){let b=i.clone();b.flipY=!0,b.offset.set(a,1-o-c),b.repeat.set(l,c),b.needsUpdate=!0,b.magFilter=ct,b.minFilter=ct;let y=new bs({map:b,transparent:!0,alphaTest:.1});return{mesh:new Zi(y),itemsTexture:b,cleanup(){b.dispose()}}}if(r)try{let b=TXe(i,e),{geometry:y}=kXe(b,{depth:s}),_=new On(b);_.magFilter=ct,_.minFilter=ct,_.wrapS=_.wrapT=jn,_.flipY=!1,_.needsUpdate=!0;let x=new Kr({map:_,side:In,transparent:!0,alphaTest:.1});return{mesh:new Ke(y,x),itemsTexture:_,cleanup(){_.dispose(),y.dispose(),x.map&&x.map.dispose(),x.dispose()}}}catch(b){console.warn("Failed to create 3D item mesh, falling back to 2D:",b)}let u=i.clone();u.flipY=!0,u.offset.set(a,1-o-c),u.repeat.set(l,c),u.needsUpdate=!0,u.magFilter=ct,u.minFilter=ct;let d=u.clone();d.repeat.x*=-1,d.needsUpdate=!0,d.offset.set(a+l,1-o-c);let f=new Kr({map:u,transparent:!0,alphaTest:.1}),v=new Kr({map:d,transparent:!0,alphaTest:.1});return{mesh:new Ke(new Sn(1,1,0),[new _t({color:0}),new _t({color:0}),new _t({color:0}),new _t({color:0}),f,v]),itemsTexture:u,itemsTextureFlipped:d,cleanup(){u.dispose(),d.dispose(),f.dispose(),v.dispose()}}}h();p();m();Lt();h();p();m();h();p();m();Lt();var R6e=parseInt(Ma.replace(/\D+/g,""));h();p();m();Lt();var IXe=/^[og]\s*(.+)?/,RXe=/^mtllib /,CXe=/^usemtl /,PXe=/^usemap /,C6e=new X,IC=new X,P6e=new X,L6e=new X,na=new X;function LXe(){let i={objects:[],object:{},vertices:[],normals:[],colors:[],uvs:[],materials:{},materialLibraries:[],startObject:function(e,t){if(this.object&&this.object.fromDeclaration===!1){this.object.name=e,this.object.fromDeclaration=t!==!1;return}let n=this.object&&typeof this.object.currentMaterial=="function"?this.object.currentMaterial():void 0;if(this.object&&typeof this.object._finalize=="function"&&this.object._finalize(!0),this.object={name:e||"",fromDeclaration:t!==!1,geometry:{vertices:[],normals:[],colors:[],uvs:[],hasUVIndices:!1},materials:[],smooth:!0,startMaterial:function(r,s){let a=this._finalize(!1);a&&(a.inherited||a.groupCount<=0)&&this.materials.splice(a.index,1);let o={index:this.materials.length,name:r||"",mtllib:Array.isArray(s)&&s.length>0?s[s.length-1]:"",smooth:a!==void 0?a.smooth:this.smooth,groupStart:a!==void 0?a.groupEnd:0,groupEnd:-1,groupCount:-1,inherited:!1,clone:function(l){let c={index:typeof l=="number"?l:this.index,name:this.name,mtllib:this.mtllib,smooth:this.smooth,groupStart:0,groupEnd:-1,groupCount:-1,inherited:!1};return c.clone=this.clone.bind(c),c}};return this.materials.push(o),o},currentMaterial:function(){if(this.materials.length>0)return this.materials[this.materials.length-1]},_finalize:function(r){let s=this.currentMaterial();if(s&&s.groupEnd===-1&&(s.groupEnd=this.geometry.vertices.length/3,s.groupCount=s.groupEnd-s.groupStart,s.inherited=!1),r&&this.materials.length>1)for(let a=this.materials.length-1;a>=0;a--)this.materials[a].groupCount<=0&&this.materials.splice(a,1);return r&&this.materials.length===0&&this.materials.push({name:"",smooth:this.smooth}),s}},n&&n.name&&typeof n.clone=="function"){let r=n.clone(0);r.inherited=!0,this.object.materials.push(r)}this.objects.push(this.object)},finalize:function(){this.object&&typeof this.object._finalize=="function"&&this.object._finalize(!0)},parseVertexIndex:function(e,t){let n=parseInt(e,10);return(n>=0?n-1:n+t/3)*3},parseNormalIndex:function(e,t){let n=parseInt(e,10);return(n>=0?n-1:n+t/3)*3},parseUVIndex:function(e,t){let n=parseInt(e,10);return(n>=0?n-1:n+t/2)*2},addVertex:function(e,t,n){let r=this.vertices,s=this.object.geometry.vertices;s.push(r[e+0],r[e+1],r[e+2]),s.push(r[t+0],r[t+1],r[t+2]),s.push(r[n+0],r[n+1],r[n+2])},addVertexPoint:function(e){let t=this.vertices;this.object.geometry.vertices.push(t[e+0],t[e+1],t[e+2])},addVertexLine:function(e){let t=this.vertices;this.object.geometry.vertices.push(t[e+0],t[e+1],t[e+2])},addNormal:function(e,t,n){let r=this.normals,s=this.object.geometry.normals;s.push(r[e+0],r[e+1],r[e+2]),s.push(r[t+0],r[t+1],r[t+2]),s.push(r[n+0],r[n+1],r[n+2])},addFaceNormal:function(e,t,n){let r=this.vertices,s=this.object.geometry.normals;C6e.fromArray(r,e),IC.fromArray(r,t),P6e.fromArray(r,n),na.subVectors(P6e,IC),L6e.subVectors(C6e,IC),na.cross(L6e),na.normalize(),s.push(na.x,na.y,na.z),s.push(na.x,na.y,na.z),s.push(na.x,na.y,na.z)},addColor:function(e,t,n){let r=this.colors,s=this.object.geometry.colors;r[e]!==void 0&&s.push(r[e+0],r[e+1],r[e+2]),r[t]!==void 0&&s.push(r[t+0],r[t+1],r[t+2]),r[n]!==void 0&&s.push(r[n+0],r[n+1],r[n+2])},addUV:function(e,t,n){let r=this.uvs,s=this.object.geometry.uvs;s.push(r[e+0],r[e+1]),s.push(r[t+0],r[t+1]),s.push(r[n+0],r[n+1])},addDefaultUV:function(){let e=this.object.geometry.uvs;e.push(0,0),e.push(0,0),e.push(0,0)},addUVLine:function(e){let t=this.uvs;this.object.geometry.uvs.push(t[e+0],t[e+1])},addFace:function(e,t,n,r,s,a,o,l,c){let u=this.vertices.length,d=this.parseVertexIndex(e,u),f=this.parseVertexIndex(t,u),v=this.parseVertexIndex(n,u);if(this.addVertex(d,f,v),this.addColor(d,f,v),o!==void 0&&o!==""){let g=this.normals.length;d=this.parseNormalIndex(o,g),f=this.parseNormalIndex(l,g),v=this.parseNormalIndex(c,g),this.addNormal(d,f,v)}else this.addFaceNormal(d,f,v);if(r!==void 0&&r!==""){let g=this.uvs.length;d=this.parseUVIndex(r,g),f=this.parseUVIndex(s,g),v=this.parseUVIndex(a,g),this.addUV(d,f,v),this.object.geometry.hasUVIndices=!0}else this.addDefaultUV()},addPointGeometry:function(e){this.object.geometry.type="Points";let t=this.vertices.length;for(let n=0,r=e.length;n<r;n++){let s=this.parseVertexIndex(e[n],t);this.addVertexPoint(s),this.addColor(s)}},addLineGeometry:function(e,t){this.object.geometry.type="Line";let n=this.vertices.length,r=this.uvs.length;for(let s=0,a=e.length;s<a;s++)this.addVertexLine(this.parseVertexIndex(e[s],n));for(let s=0,a=t.length;s<a;s++)this.addUVLine(this.parseUVIndex(t[s],r))}};return i.startObject("",!1),i}var O5=class extends _r{constructor(e){super(e),this.materials=null}load(e,t,n,r){let s=this,a=new Zr(this.manager);a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(o){try{t(s.parse(o))}catch(l){r?r(l):console.error(l),s.manager.itemError(e)}},n,r)}setMaterials(e){return this.materials=e,this}parse(e){let t=new LXe;e.indexOf(`\r
|
|
@@ -29558,7 +29558,7 @@ void main() {
|
|
|
29558
29558
|
vFogDepth = -mvPosition.z;
|
|
29559
29559
|
#endif
|
|
29560
29560
|
}
|
|
29561
|
-
`,TP={u_atlas:{value:null},u_originDelta:{value:new X},u_cameraOriginFrac:{value:new X},u_skyLevel:{value:1},u_lightCurve:{value:Ri.curve},u_minBrightness:{value:Ri.minBrightness},u_lightGamma:{value:Ri.gamma}};function $_e(){return new Xn({vertexShader:kYe,fragmentShader:kP,uniforms:Gs.merge([at.fog,TP]),transparent:!0,depthWrite:!0,depthTest:!0,vertexColors:!0,glslVersion:Eo,fog:!0})}function Y_e(){return new Xn({vertexShader:X_e,fragmentShader:kP,uniforms:Gs.merge([at.fog,TP]),transparent:!1,depthWrite:!0,depthTest:!0,vertexColors:!0,glslVersion:Eo,fog:!0})}function J_e(){return new Xn({vertexShader:X_e,fragmentShader:kP,uniforms:Gs.merge([at.fog,TP]),transparent:!0,depthWrite:!0,depthTest:!0,vertexColors:!0,glslVersion:Eo,fog:!0})}function i9(i,e,t,n,r){let{originDelta:s,cameraOriginFrac:a}=$d(e,t,n,r),o=i.uniforms.u_originDelta;o?.value?.set&&o.value.set(s.x,s.y,s.z);let l=i.uniforms.u_cameraOriginFrac;l?.value?.set&&l.value.set(a.x,a.y,a.z)}function s9(i,e){let t=i.uniforms.u_skyLevel;t&&(t.value=e)}function a9(i,e){if(e.curve!==void 0){let t=i.uniforms.u_lightCurve;t&&(t.value=e.curve)}if(e.minBrightness!==void 0){let t=i.uniforms.u_minBrightness;t&&(t.value=e.minBrightness)}if(e.gamma!==void 0){let t=i.uniforms.u_lightGamma;t&&(t.value=e.gamma)}}h();p();m();var TYe=8,IYe=.01;function IP(i,e,t,n,r){i.matrix.makeTranslation(e-r.x,t-r.y,n-r.z),i.matrixWorldNeedsUpdate=!0,i.frustumCulled=!1}function o9(i,e,t,n,r,s,a,o,l,c){let u=i-n,d=e-r,f=t-s,v=TYe+IYe;return l.set(u-v,d-v,f-v),c.set(u+v,d+v,f+v),o.set(l,c),{visible:a.intersectsBox(o),distSq:u*u+d*d+f*f}}function K_e(i,e,t,n,r,s,a,o,l,c,u){let{visible:d,distSq:f}=o9(e,t,n,r,s,a,o,l,c,u);i.visible=d,i.renderOrder=-f}EP();h();p();m();Lt();h();p();m();h();p();m();h();p();m();Lt();h();p();m();function Q_e(){return{counts:new Int32Array(c0),offsets:new Int32Array(c0)}}function RYe(i,e){if(i.counts.length>=e)return;let t=i.counts.length;for(;t<e;)t*=2;i.counts=new Int32Array(t),i.offsets=new Int32Array(t)}function e4e(i){let e=i.getExtension("WEBGL_multi_draw");return e?{tier:"A",ext:e}:{tier:"B",ext:null}}var Z_e=!1;function t4e(i,e){Z_e||!e||(Z_e=!0,console.info("[globalLegacyBuffer] legacy multi_draw tier",i))}function n4e(i,e,t,n){let r=t.length;if(r===0)return;RYe(n,r);let s=i.TRIANGLES,a=i.UNSIGNED_INT;for(let o=0;o<r;o++){let l=t[o];n.counts[o]=l.indexCount,n.offsets[o]=l.indexStart*4}if(e.tier==="A"&&e.ext){e.ext.multiDrawElementsWEBGL(s,n.counts,0,a,n.offsets,0,r);return}for(let o=0;o<r;o++)i.drawElements(s,n.counts[o],a,n.offsets[o])}var Ci=4,Tr=6,Cn=3,Us=2,Ir=1,CYe=128e3,PYe=128e3,r4e=5e3,LYe=.25,i4e=Ci*(Cn*3+Ir*2+Us)*4+Tr*4,RP=.75,c0=64;function CP(i,e,t){for(let n of i)for(let r=n.start;r<n.start+n.count;r++){let s=!1;for(let a of e)if(r>=a.start&&r<a.start+a.count){s=!0;break}s||console.error("[GlobalLegacyBuffer] draw span covers non-live quad",{buffer:t,quad:r,span:n,liveRanges:e})}}function l9(i,e){if(e.length===0)return i;let t=[];for(let n of i){let r=[n];for(let s of e){let a=[];for(let o of r){let l=o.start+o.count-1;if(s.end<o.start||s.start>l){a.push(o);continue}s.start>o.start&&a.push({start:o.start,count:s.start-o.start}),s.end<l&&a.push({start:s.end+1,count:l-s.end})}r=a}t.push(...r)}return t.filter(n=>n.count>0)}var ug=class{mesh;material;growthIncrementQuads;capacityQuads;positions;colors;skyLights;blockLights;uvs;aOrigin;indices;sectionSlots=new Map;freeList=[];highWatermark=0;pendingRanges=[];_spanScratch=[];renderOrigin={x:0,y:0,z:0};layoutVersion=0;pendingMove=null;pendingReplace=new Map;uploadEpoch=0;visibleIndexSpans=[];_drawScratch=Q_e();multiDrawCaps=null;debugOverlay=!1;constructor(e,t,n){this.material=e,this.growthIncrementQuads=n?.growthIncrementQuads??PYe,this.capacityQuads=n?.initialCapacityQuads??CYe;let r=this.capacityQuads*Ci;this.positions=new Float32Array(r*Cn),this.colors=new Float32Array(r*Cn),this.skyLights=new Float32Array(r*Ir),this.blockLights=new Float32Array(r*Ir),this.uvs=new Float32Array(r*Us),this.aOrigin=new Float32Array(r*Cn),this.indices=new Uint32Array(this.capacityQuads*Tr);let s=new dt,a=(l,c,u)=>{let d=new Mt(l,c);return d.setUsage(So),s.setAttribute(u,d),d};a(this.positions,Cn,"position"),a(this.colors,Cn,"color"),a(this.skyLights,Ir,"a_skyLight"),a(this.blockLights,Ir,"a_blockLight"),a(this.uvs,Us,"uv"),a(this.aOrigin,Cn,"a_origin");let o=new Mt(this.indices,1);o.setUsage(So),s.setIndex(o),s.setDrawRange(0,0),s.boundingSphere=new Tn(new X,1/0),this.mesh=new Ke(s,[e]),this.mesh.name=n?.name??"globalLegacyOpaque",this.mesh.frustumCulled=!1,this.mesh.matrixAutoUpdate=!1,this.mesh.matrix.identity(),this.mesh.position.set(0,0,0),t.add(this.mesh),this.syncDefaultDrawGroups(),this.mesh.onAfterRender=(l,c,u,d,f)=>{if(this.visibleIndexSpans.length===0)return;let v=l.getContext();this.multiDrawCaps||(this.multiDrawCaps=e4e(v),t4e(this.multiDrawCaps.tier,this.debugOverlay)),n4e(v,this.multiDrawCaps,this.visibleIndexSpans,this._drawScratch)}}setDebugOverlay(e){this.debugOverlay=e}suppressThreeDraw(){this.mesh.geometry.setDrawRange(0,3)}setVisibleIndexSpans(e){this.visibleIndexSpans=e}getVisibleIndexSpans(){return this.visibleIndexSpans}syncDefaultDrawGroups(){let e=this.mesh.geometry;e.clearGroups();let t=this.highWatermark*Tr;t>0&&e.addGroup(0,t,0),e.setDrawRange(0,t)}addSection(e,t,n,r,s){let a=t.positions.length/Cn,o=a/Ci;if(a===0||o*Ci!==a)return this.removeSection(e),!1;if(t.indices.length%Tr!==0||t.indices.length/Tr!==o)return!1;let l=this.sectionSlots.has(e),c;if(l){let A=this.sectionSlots.get(e),T=this.pendingReplace.get(e),P=this.pendingMove?.key===e?this.pendingMove:void 0;T?(this.zeroAndFreeSlot(A.start,A.count),c={start:T.oldStart,count:T.oldCount},this.pendingReplace.delete(e)):P?(this.zeroAndFreeSlot(A.start,A.count),c={start:P.oldStart,count:P.count},this.pendingMove=null):c=A}o>this.capacityQuads&&this.growCapacity(o);let u=this.takeFreeSlot(o);u||(this.highWatermark+o>this.capacityQuads&&this.growCapacity(this.highWatermark+o),u={start:this.highWatermark,count:o},this.highWatermark+=o);let d=u.start*Ci,f=d*Cn,v=d*Us,g=d*Ir;this.positions.set(t.positions,f),this.colors.set(t.colors,f),this.skyLights.set(t.skyLights,g),this.blockLights.set(t.blockLights,g),this.uvs.set(t.uvs,v);let b=f,y=n-this.renderOrigin.x,_=r-this.renderOrigin.y,x=s-this.renderOrigin.z;for(let A=0;A<a;A++){let T=b+A*Cn;this.aOrigin[T]=y,this.aOrigin[T+1]=_,this.aOrigin[T+2]=x}let w=u.start*Tr,S=d;for(let A=0;A<t.indices.length;A++)this.indices[w+A]=t.indices[A]+S;return this.sectionSlots.set(e,u),l&&c&&this.pendingReplace.set(e,{oldStart:c.start,oldCount:c.count}),this.markDirty(u.start,u.start+o-1),this.syncDefaultDrawGroups(),this.layoutVersion++,!0}getLayoutVersion(){return this.layoutVersion}getUploadEpoch(){return this.uploadEpoch}hasPendingReplace(){return this.pendingReplace.size>0}canUseFullDrawShortcut(){return this.pendingRanges.length===0&&this.interiorFreeQuads()===0&&this.pendingMove===null&&this.pendingReplace.size===0}isRangeFullyUploaded(e,t){return this.rangeFullyUploaded(e,t)}getPendingDirtyRanges(){return this.pendingRanges}getSectionDrawStart(e){let t=this.sectionSlots.get(e);if(!t)return;if(this.pendingMove?.key===e)return this.pendingMove.oldStart;let n=this.pendingReplace.get(e);if(n)return n.oldStart;if(this.rangeFullyUploaded(t.start,t.start+t.count-1))return t.start}getSectionDrawCount(e){let t=this.sectionSlots.get(e);if(!t)return;if(this.pendingMove?.key===e)return this.pendingMove.count;let n=this.pendingReplace.get(e);if(n)return n.oldCount;if(this.rangeFullyUploaded(t.start,t.start+t.count-1))return t.count}getPendingMove(){return this.pendingMove}compactStep(){if(this.pendingMove){let{newStart:o,count:l}=this.pendingMove;this.rangeFullyUploaded(o,o+l-1)&&this.finalizePendingMove();return}for(let o of[...this.pendingReplace.keys()]){let l=this.sectionSlots.get(o);l&&this.rangeFullyUploaded(l.start,l.start+l.count-1)&&this.finalizePendingReplace(o)}if(this.highWatermark===0||this.interiorFreeQuads()/this.highWatermark<=LYe)return;let t=this.findMovableSection(r4e);if(!t)return;let n=this.findLowestInteriorHole(t.start,t.count);if(!n)return;let r=this.reserveFreeSlotAt(n.index,t.count),s=t.start,a=r.start;this.copySectionRange(s,a,t.count),this.sectionSlots.set(t.key,{start:a,count:t.count}),this.markDirty(a,a+t.count-1),this.pendingMove={key:t.key,oldStart:s,newStart:a,count:t.count},this.layoutVersion++}updateDrawSpans(e,t){if(this.visibleIndexSpans=[],this.highWatermark===0)return;let n=this._spanScratch;n.length=0;let r=0;for(let a of e){let o=this.getSectionDrawStart(a.key),l=this.getSectionDrawCount(a.key),c=this.sectionSlots.get(a.key);o===void 0||l===void 0||!c||(n.push({start:o,count:l}),r+=l)}if(n.length===0)return;let s=(a,o)=>{this.visibleIndexSpans.push({indexStart:a*Tr,indexCount:o*Tr})};if(t==="opaque"){let a,o=n.map(c=>({...c})),l=this.canUseFullDrawShortcut()&&r>=this.highWatermark*RP;l?a=[{start:0,count:this.highWatermark}]:(n.sort((c,u)=>c.start-u.start),this.mergeOpaqueSpans(n),a=n),a=l9(a,this.pendingRanges),l||CP(a,o,this.mesh.name);for(let c of a)s(c.start,c.count)}else{e.sort((a,o)=>o.distSq-a.distSq);for(let a of e){let o=this.getSectionDrawStart(a.key),l=this.getSectionDrawCount(a.key);o===void 0||l===void 0||s(o,l)}}}mergeOpaqueSpans(e){if(e.length<2)return;let t=0;for(;t<e.length-1;){let n=e[t],r=e[t+1];n.start+n.count===r.start?(n.count=r.start+r.count-n.start,e.splice(t+1,1)):t++}}hasSection(e){return this.sectionSlots.has(e)}getSectionSlot(e){return this.sectionSlots.get(e)}takeSectionData(e){let t=this.getSectionGeometryData(e);if(t)return this.removeSection(e),t}getSectionGeometryData(e){let t=this.sectionSlots.get(e);if(!t)return;let n=t.count*Ci,r=t.start*Ci,s=r*Cn,a=r*Us,o=t.start*Tr,l=t.count*Tr,c=r*Ir,u=this.positions.slice(s,s+n*Cn),d=this.colors.slice(s,s+n*Cn),f=this.skyLights.slice(c,c+n*Ir),v=this.blockLights.slice(c,c+n*Ir),g=this.uvs.slice(a,a+n*Us),b=this.indices.slice(o,o+l),y=r;for(let S=0;S<b.length;S++)b[S]=b[S]-y;let _=this.aOrigin[s]+this.renderOrigin.x,x=this.aOrigin[s+1]+this.renderOrigin.y,w=this.aOrigin[s+2]+this.renderOrigin.z;return{positions:u,colors:d,skyLights:f,blockLights:v,uvs:g,indices:b,sx:_,sy:x,sz:w}}removeSection(e){let t=this.sectionSlots.get(e);if(!t)return;if(this.pendingReplace.has(e)){let s=this.pendingReplace.get(e);this.zeroAndFreeSlot(s.oldStart,s.oldCount),this.pendingReplace.delete(e)}if(this.pendingMove?.key===e){let{oldStart:s,count:a}=this.pendingMove;this.zeroAndFreeSlot(s,a),this.pendingMove=null}let n=t.start*Tr,r=t.count*Tr;for(let s=0;s<r;s++)this.indices[n+s]=0;this.markDirty(t.start,t.start+t.count-1),this.sectionSlots.delete(e),this.insertFreeSlot(t),this.shrinkHighWatermark(),this.syncDefaultDrawGroups(),this.layoutVersion++}hasPendingUploads(){return this.pendingRanges.length>0}uploadDirtyRange(){let e=this.pendingRanges[0];if(!e)return;let t=e.start,n=Math.min(e.end-e.start+1,r4e),r=t*Ci,s=n*Ci,a=t*Tr,o=n*Tr,l=this.mesh.geometry,c=l.getAttribute("position");c.clearUpdateRanges(),c.addUpdateRange(r*Cn,s*Cn),c.needsUpdate=!0;let u=l.getAttribute("color");u.clearUpdateRanges(),u.addUpdateRange(r*Cn,s*Cn),u.needsUpdate=!0;let d=l.getAttribute("a_skyLight");d.clearUpdateRanges(),d.addUpdateRange(r*Ir,s*Ir),d.needsUpdate=!0;let f=l.getAttribute("a_blockLight");f.clearUpdateRanges(),f.addUpdateRange(r*Ir,s*Ir),f.needsUpdate=!0;let v=l.getAttribute("uv");v.clearUpdateRanges(),v.addUpdateRange(r*Us,s*Us),v.needsUpdate=!0;let g=l.getAttribute("a_origin");g.clearUpdateRanges(),g.addUpdateRange(r*Cn,s*Cn),g.needsUpdate=!0;let b=l.index;b.clearUpdateRanges(),b.addUpdateRange(a,o),b.needsUpdate=!0,t+n>e.end?this.pendingRanges.shift():e.start=t+n,this.uploadEpoch++}setRenderOrigin(e){this.renderOrigin={...e}}rebase(e){if(this.highWatermark!==0){for(let t of this.sectionSlots.values()){let n=t.start*Ci,r=t.count*Ci,s=n*Cn;for(let a=0;a<r;a++){let o=s+a*Cn;this.aOrigin[o]-=e.x,this.aOrigin[o+1]-=e.y,this.aOrigin[o+2]-=e.z}}this.markDirty(0,this.highWatermark-1),this.renderOrigin.x+=e.x,this.renderOrigin.y+=e.y,this.renderOrigin.z+=e.z}}setCameraOrigin(e,t,n){let{originDelta:r,cameraOriginFrac:s}=$d(this.renderOrigin,e,t,n),a=this.material.uniforms.u_originDelta;a?.value?.set&&a.value.set(r.x,r.y,r.z);let o=this.material.uniforms.u_cameraOriginFrac;o?.value?.set&&o.value.set(s.x,s.y,s.z)}getHighWatermark(){return this.highWatermark}getCapacityQuads(){return this.capacityQuads}getSectionCount(){return this.sectionSlots.size}getMemoryBytes(){return this.capacityQuads*i4e}getUsedMemoryBytes(){return this.highWatermark*i4e}reset(){this.sectionSlots.clear(),this.freeList.length=0,this.highWatermark=0,this.pendingRanges.length=0,this.pendingMove=null,this.pendingReplace.clear(),this.uploadEpoch=0,this.visibleIndexSpans=[],this.syncDefaultDrawGroups()}dispose(){this.mesh.parent?.remove(this.mesh),this.mesh.geometry.dispose(),this.reset()}markDirty(e,t){this.pendingRanges.push({start:e,end:t}),this.pendingRanges.sort((n,r)=>n.start-r.start),this.mergePendingRanges()}mergePendingRanges(){if(this.pendingRanges.length<2)return;let e=[],t=this.pendingRanges[0];for(let n=1;n<this.pendingRanges.length;n++){let r=this.pendingRanges[n];r.start<=t.end+1?t={start:t.start,end:Math.max(t.end,r.end)}:(e.push(t),t=r)}e.push(t),this.pendingRanges=e}takeFreeSlot(e){for(let t=0;t<this.freeList.length;t++){let n=this.freeList[t];if(n.count>=e){if(this.freeList.splice(t,1),n.count===e)return n;let r={start:n.start,count:e};return this.insertFreeSlot({start:n.start+e,count:n.count-e}),r}}}insertFreeSlot(e){this.freeList.push(e),this.freeList.sort((t,n)=>t.start-n.start),this.mergeFreeList()}mergeFreeList(){if(this.freeList.length<2)return;let e=[],t=this.freeList[0];for(let n=1;n<this.freeList.length;n++){let r=this.freeList[n];t.start+t.count===r.start?t={start:t.start,count:t.count+r.count}:(e.push(t),t=r)}e.push(t),this.freeList=e}shrinkHighWatermark(){for(;this.highWatermark>0;){let e=this.highWatermark-1,t=this.freeList.find(r=>r.start<=e&&r.start+r.count>e);if(!t||t.start+t.count!==this.highWatermark)break;this.highWatermark=t.start;let n=this.freeList.indexOf(t);this.freeList.splice(n,1)}}interiorFreeQuads(){let e=0;for(let t of this.freeList)t.start<this.highWatermark&&(e+=t.count);return e}findMovableSection(e){let t=[];for(let[s,a]of this.sectionSlots)t.push({key:s,start:a.start,count:a.count});if(t.length===0)return;t.sort((s,a)=>a.start!==s.start?a.start-s.start:a.start+a.count-(s.start+s.count));let n=t[0];if(n.count<=e&&this.findLowestInteriorHole(n.start,n.count))return n;let r=t.filter(s=>s.count<=e).sort((s,a)=>a.count-s.count);for(let s of r)if(this.findLowestInteriorHole(s.start,s.count))return s}findLowestInteriorHole(e,t){for(let n=0;n<this.freeList.length;n++){let r=this.freeList[n];if(r.start<e&&r.count>=t)return{start:r.start,count:r.count,index:n}}}reserveFreeSlotAt(e,t){let n=this.freeList[e];if(this.freeList.splice(e,1),n.count===t)return{start:n.start,count:t};let r={start:n.start,count:t};return this.insertFreeSlot({start:n.start+t,count:n.count-t}),r}copySectionRange(e,t,n){let r=e*Ci,s=t*Ci,a=n*Ci,o=s-r,l=r*Cn,c=s*Cn,u=a*Cn;this.positions.copyWithin(c,l,l+u),this.colors.copyWithin(c,l,l+u),this.aOrigin.copyWithin(c,l,l+u);let d=r*Ir,f=s*Ir,v=a*Ir;this.skyLights.copyWithin(f,d,d+v),this.blockLights.copyWithin(f,d,d+v);let g=r*Us,b=s*Us,y=a*Us;this.uvs.copyWithin(b,g,g+y);let _=e*Tr,x=t*Tr,w=n*Tr;for(let S=0;S<w;S++)this.indices[x+S]=this.indices[_+S]+o}rangeFullyUploaded(e,t){for(let n of this.pendingRanges)if(n.start<=t&&n.end>=e)return!1;return!0}zeroAndFreeSlot(e,t){let n=e*Tr,r=t*Tr;for(let s=0;s<r;s++)this.indices[n+s]=0;this.markDirty(e,e+t-1),this.insertFreeSlot({start:e,count:t})}finalizePendingReplace(e){let t=this.pendingReplace.get(e);t&&(this.zeroAndFreeSlot(t.oldStart,t.oldCount),this.pendingReplace.delete(e),this.shrinkHighWatermark(),this.syncDefaultDrawGroups(),this.layoutVersion++,this.uploadEpoch++)}finalizePendingMove(){let e=this.pendingMove;if(!e)return;let{oldStart:t,count:n}=e;this.zeroAndFreeSlot(t,n),this.shrinkHighWatermark(),this.syncDefaultDrawGroups(),this.pendingMove=null,this.layoutVersion++,this.uploadEpoch++}growCapacity(e){this.pendingMove&&this.finalizePendingMove();for(let y of[...this.pendingReplace.keys()])this.finalizePendingReplace(y);let t=this.capacityQuads;for(;t<e;)t+=this.growthIncrementQuads;let n=this.capacityQuads*Ci,r=t*Ci,s=new Float32Array(r*Cn),a=new Float32Array(r*Cn),o=new Float32Array(r*Ir),l=new Float32Array(r*Ir),c=new Float32Array(r*Us),u=new Float32Array(r*Cn),d=new Uint32Array(t*Tr);s.set(this.positions),a.set(this.colors),o.set(this.skyLights),l.set(this.blockLights),c.set(this.uvs),u.set(this.aOrigin),d.set(this.indices),this.positions=s,this.colors=a,this.skyLights=o,this.blockLights=l,this.uvs=c,this.aOrigin=u,this.indices=d,this.capacityQuads=t;let f=this.mesh.geometry,v=(y,_,x)=>{f.getAttribute(x)&&f.deleteAttribute(x);let S=new Mt(y,_);S.setUsage(So),f.setAttribute(x,S)};v(this.positions,Cn,"position"),v(this.colors,Cn,"color"),v(this.skyLights,Ir,"a_skyLight"),v(this.blockLights,Ir,"a_blockLight"),v(this.uvs,Us,"uv"),v(this.aOrigin,Cn,"a_origin"),f.index&&f.setIndex(null);let b=new Mt(this.indices,1);b.setUsage(So),f.setIndex(b),this.pendingRanges.length=0}};function BYe(i){if(i.length<2)return;let e=0;for(;e<i.length-1;){let t=i[e],n=i[e+1];t.start+t.count===n.start?(t.count=n.start+n.count-t.start,i.splice(e+1,1)):e++}}function s4e(i,e,t=!0,n,r=[]){if(i.length===0||e===0)return[];let s=0;for(let l of i)s+=l.count;let a;if(t&&s>=e*RP)a=[{start:0,count:e}];else{a=i.map(c=>({start:c.start,count:c.count})),a.sort((c,u)=>c.start-u.start);let l=a.map(c=>({...c}));return BYe(a),a=l9(a,r),CP(a,l,"globalBlockBuffer"),a}return l9(a,r)}Kc();function o4e(){return{firsts:new Int32Array(c0),counts:new Int32Array(c0),instanceCounts:new Int32Array(c0),baseInstances:new Int32Array(c0)}}function l4e(i){let e=i.getExtension("WEBGL_multi_draw_instanced_base_vertex_base_instance");if(e)return{tier:"A",ext:e};let t=i.getExtension("WEBGL_draw_instanced_base_vertex_base_instance");return t?{tier:"B",ext:t}:{tier:"C",ext:null}}var a4e=!1;function c4e(i,e){a4e||!e||(a4e=!0,console.info("[globalBlockBuffer] cube multi_draw tier",i))}function u4e(i,e,t,n,r){let s=t.length;if(s===0)return;let a=i.TRIANGLES;if(e.tier==="A"&&e.ext){let o=e.ext;for(let l=0;l<s;l++){let c=t[l];n.firsts[l]=0,n.counts[l]=l0,n.instanceCounts[l]=c.count,n.baseInstances[l]=c.start}o.multiDrawArraysInstancedBaseInstanceWEBGL(a,n.firsts,0,n.counts,0,n.instanceCounts,0,n.baseInstances,0,s);return}if(e.tier==="B"&&e.ext){let o=e.ext;for(let l=0;l<s;l++){let c=t[l];o.drawArraysInstancedBaseInstanceWEBGL(a,0,l0,c.count,c.start)}return}r?.(i,t)}Kc();z5();var DYe=512e3,OYe=1e6,d4e=15e3,NYe=.25,dg=F_e(),f4e=16,c9=class{mesh;capacityFaces;w0;w1;w2;w3;sectionSlots=new Map;freeList=[];highWatermark=0;pendingRanges=[];pendingMove=null;pendingReplace=new Map;uploadEpoch=0;visibleSpans=[];_drawScratch=o4e();multiDrawCaps=null;tierCVao=null;tierCAttrs=null;tierCGl=null;debugOverlay=!1;layoutVersion=0;constructor(e,t){this.capacityFaces=DYe,this.w0=new Uint32Array(this.capacityFaces),this.w1=new Uint32Array(this.capacityFaces),this.w2=new Uint32Array(this.capacityFaces),this.w3=new Uint32Array(this.capacityFaces),this.w2.fill(dg);let n=new Sa,r=new Float32Array(l0*3);n.setAttribute("position",new Mt(r,3));let s=a=>{let o=new Ar(a,1);return o.setUsage(So),o};n.setAttribute("a_w0",s(this.w0)),n.setAttribute("a_w1",s(this.w1)),n.setAttribute("a_w2",s(this.w2)),n.setAttribute("a_w3",s(this.w3)),n.instanceCount=0,this.mesh=new Ke(n,e),this.mesh.name="globalShaderCubes",this.mesh.frustumCulled=!1,this.mesh.matrixAutoUpdate=!1,this.mesh.matrix.identity(),this.mesh.position.set(0,0,0),t.add(this.mesh),this.mesh.onAfterRender=(a,o,l,c,u)=>{if(this.visibleSpans.length===0)return;let d=u,f=a.getContext();this.multiDrawCaps||(this.multiDrawCaps=l4e(f),c4e(this.multiDrawCaps.tier,this.debugOverlay)),u4e(f,this.multiDrawCaps,this.visibleSpans,this._drawScratch,this.multiDrawCaps.tier==="C"?(v,g)=>this.drawTierCSpans(v,g,a,d):void 0)}}setDebugOverlay(e){this.debugOverlay=e}suppressThreeDraw(){let e=this.mesh.geometry;e.setDrawRange(0,l0),e.instanceCount=0}setVisibleSpans(e){this.visibleSpans=e}getVisibleSpans(){return this.visibleSpans}forEachSectionSlot(e){for(let[t,n]of this.sectionSlots)e(t,n)}getSectionDrawStart(e){let t=this.sectionSlots.get(e);if(!t)return;if(this.pendingMove?.key===e)return this.pendingMove.oldStart;let n=this.pendingReplace.get(e);if(n)return n.oldStart;if(this.rangeFullyUploaded(t.start,t.start+t.count-1))return t.start}getSectionDrawCount(e){let t=this.sectionSlots.get(e);if(!t)return;if(this.pendingMove?.key===e)return this.pendingMove.count;let n=this.pendingReplace.get(e);if(n)return n.oldCount;if(this.rangeFullyUploaded(t.start,t.start+t.count-1))return t.count}getUploadEpoch(){return this.uploadEpoch}hasPendingReplace(){return this.pendingReplace.size>0}canUseFullDrawShortcut(){return this.pendingRanges.length===0&&this.interiorFreeFaces()===0&&this.pendingMove===null&&this.pendingReplace.size===0}isRangeFullyUploaded(e,t){return this.rangeFullyUploaded(e,t)}getPendingDirtyRanges(){return this.pendingRanges}getHighWatermark(){return this.highWatermark}getCapacityFaces(){return this.capacityFaces}getSectionCount(){return this.sectionSlots.size}getMemoryBytes(){return this.capacityFaces*f4e}getUsedMemoryBytes(){return this.highWatermark*f4e}hasPendingUploads(){return this.pendingRanges.length>0}getPendingMove(){return this.pendingMove}addSection(e,t,n){if(n<=0){this.removeSection(e);return}let r=this.sectionSlots.has(e),s;if(r){let l=this.sectionSlots.get(e),c=this.pendingReplace.get(e),u=this.pendingMove?.key===e?this.pendingMove:void 0;c?(this.zeroAndFreeSlot(l.start,l.count),s={start:c.oldStart,count:c.oldCount},this.pendingReplace.delete(e)):u?(this.zeroAndFreeSlot(l.start,l.count),s={start:u.oldStart,count:u.count},this.pendingMove=null):s=l}n>this.capacityFaces&&this.growCapacity(n);let a=this.takeFreeSlot(n);a||(this.highWatermark+n>this.capacityFaces&&this.growCapacity(this.highWatermark+n),a={start:this.highWatermark,count:n},this.highWatermark+=n);let o=4;for(let l=0;l<n;l++){let c=a.start+l,u=l*o;this.w0[c]=t[u],this.w1[c]=t[u+1],this.w2[c]=t[u+2],this.w3[c]=t[u+3]}this.sectionSlots.set(e,a),r&&s&&this.pendingReplace.set(e,{oldStart:s.start,oldCount:s.count}),this.markDirty(a.start,a.start+n-1),this.mesh.geometry.instanceCount=this.highWatermark,this.layoutVersion++}getLayoutVersion(){return this.layoutVersion}hasSection(e){return this.sectionSlots.has(e)}getSectionSlot(e){return this.sectionSlots.get(e)}getW0(){return this.w0}takeSectionData(e){let t=this.sectionSlots.get(e);if(!t)return;let n=4,r=new Uint32Array(t.count*n);for(let s=0;s<t.count;s++){let a=t.start+s,o=s*n;r[o]=this.w0[a],r[o+1]=this.w1[a],r[o+2]=this.w2[a],r[o+3]=this.w3[a]}return this.removeSection(e),{words:r,count:t.count}}removeSection(e){let t=this.sectionSlots.get(e);if(t){if(this.pendingReplace.has(e)){let n=this.pendingReplace.get(e);this.zeroAndFreeSlot(n.oldStart,n.oldCount),this.pendingReplace.delete(e)}if(this.pendingMove?.key===e){let{oldStart:n,count:r}=this.pendingMove;this.zeroAndFreeSlot(n,r),this.pendingMove=null}for(let n=t.start;n<t.start+t.count;n++)this.w0[n]=0,this.w1[n]=0,this.w2[n]=dg,this.w3[n]=0;this.markDirty(t.start,t.start+t.count-1),this.sectionSlots.delete(e),this.insertFreeSlot(t),this.shrinkHighWatermark(),this.mesh.geometry.instanceCount=this.highWatermark,this.layoutVersion++}}compactStep(){if(this.pendingMove){let{newStart:o,count:l}=this.pendingMove;this.rangeFullyUploaded(o,o+l-1)&&this.finalizePendingMove();return}for(let o of[...this.pendingReplace.keys()]){let l=this.sectionSlots.get(o);l&&this.rangeFullyUploaded(l.start,l.start+l.count-1)&&this.finalizePendingReplace(o)}if(this.highWatermark===0||this.interiorFreeFaces()/this.highWatermark<=NYe)return;let t=this.findMovableSection(d4e);if(!t)return;let n=this.findLowestInteriorHole(t.start,t.count);if(!n)return;let r=this.reserveFreeSlotAt(n.index,t.count),s=t.start,a=r.start;this.copySectionRange(s,a,t.count),this.sectionSlots.set(t.key,{start:a,count:t.count}),this.markDirty(a,a+t.count-1),this.pendingMove={key:t.key,oldStart:s,newStart:a,count:t.count},this.layoutVersion++}uploadDirtyRange(){let e=this.pendingRanges[0];if(!e)return;let t=e.start,n=Math.min(e.end-e.start+1,d4e),r=this.mesh.geometry;for(let s of["a_w0","a_w1","a_w2","a_w3"]){let a=r.getAttribute(s);a.clearUpdateRanges(),a.addUpdateRange(t,n),a.needsUpdate=!0}t+n>e.end?this.pendingRanges.shift():e.start=t+n,this.uploadEpoch++}setCameraOrigin(e,t,n,r){let{originDelta:s,cameraOriginFrac:a}=$d(e,t,n,r),o=Kb(e),l=this.mesh.material.uniforms.u_originDelta;l?.value?.set&&l.value.set(s.x,s.y,s.z);let c=this.mesh.material.uniforms.u_cameraOriginFrac;c?.value?.set&&c.value.set(a.x,a.y,a.z);let u=this.mesh.material.uniforms.u_sectionOriginRel;u?.value?.set&&u.value.set(o.x,o.y,o.z)}reset(){this.sectionSlots.clear(),this.freeList.length=0,this.highWatermark=0,this.pendingRanges.length=0,this.pendingMove=null,this.pendingReplace.clear(),this.uploadEpoch=0,this.visibleSpans=[],this.w0.fill(0),this.w1.fill(0),this.w2.fill(dg),this.w3.fill(0),this.mesh.geometry.instanceCount=0,this.invalidateTierCVao()}dispose(){this.invalidateTierCVao(),this.mesh.parent?.remove(this.mesh),this.mesh.geometry.dispose(),this.reset()}invalidateTierCVao(){this.tierCVao&&this.tierCGl&&this.tierCGl.deleteVertexArray(this.tierCVao),this.tierCVao=null,this.tierCAttrs=null}drawTierCSpans(e,t,n,r){if(this.ensureTierCVao(e,n,r),!this.tierCVao||!this.tierCAttrs)return;let s=this.tierCAttrs;e.bindVertexArray(this.tierCVao);for(let a of t){let o=a.start*4,l=c=>{e.bindBuffer(e.ARRAY_BUFFER,c.buffer),e.vertexAttribIPointer(c.loc,1,e.UNSIGNED_INT,4,o)};l(s.w0),l(s.w1),l(s.w2),l(s.w3),e.drawArraysInstanced(e.TRIANGLES,0,l0,a.count)}e.bindVertexArray(null)}ensureTierCVao(e,t,n){this.tierCGl=e;let a=t.properties.get(n).currentProgram.program,o=e.getAttribLocation(a,"a_w0"),l=e.getAttribLocation(a,"a_w1"),c=e.getAttribLocation(a,"a_w2"),u=e.getAttribLocation(a,"a_w3"),d=w=>w<0?null:e.getVertexAttrib(w,e.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING),f=d(o);if(this.tierCVao&&this.tierCAttrs&&f&&this.tierCAttrs.w0.buffer!==f&&this.invalidateTierCVao(),this.tierCVao)return;let v=d(o),g=d(l),b=d(c),y=d(u);if(!v||!g||!b||!y)return;let _=e.createVertexArray();if(!_)return;e.bindVertexArray(_);let x=(w,S)=>{e.enableVertexAttribArray(w),e.bindBuffer(e.ARRAY_BUFFER,S),e.vertexAttribIPointer(w,1,e.UNSIGNED_INT,4,0),e.vertexAttribDivisor(w,1)};x(o,v),x(l,g),x(c,b),x(u,y),e.bindVertexArray(null),this.tierCVao=_,this.tierCAttrs={w0:{loc:o,buffer:v},w1:{loc:l,buffer:g},w2:{loc:c,buffer:b},w3:{loc:u,buffer:y}}}markDirty(e,t){this.pendingRanges.push({start:e,end:t}),this.pendingRanges.sort((n,r)=>n.start-r.start),this.mergePendingRanges()}mergePendingRanges(){if(this.pendingRanges.length<2)return;let e=[],t=this.pendingRanges[0];for(let n=1;n<this.pendingRanges.length;n++){let r=this.pendingRanges[n];r.start<=t.end+1?t={start:t.start,end:Math.max(t.end,r.end)}:(e.push(t),t=r)}e.push(t),this.pendingRanges=e}takeFreeSlot(e){for(let t=0;t<this.freeList.length;t++){let n=this.freeList[t];if(n.count>=e){if(this.freeList.splice(t,1),n.count===e)return n;let r={start:n.start,count:e};return this.insertFreeSlot({start:n.start+e,count:n.count-e}),r}}}insertFreeSlot(e){this.freeList.push(e),this.freeList.sort((t,n)=>t.start-n.start),this.mergeFreeList()}mergeFreeList(){if(this.freeList.length<2)return;let e=[],t=this.freeList[0];for(let n=1;n<this.freeList.length;n++){let r=this.freeList[n];t.start+t.count===r.start?t={start:t.start,count:t.count+r.count}:(e.push(t),t=r)}e.push(t),this.freeList=e}interiorFreeFaces(){let e=0;for(let t of this.freeList)t.start<this.highWatermark&&(e+=t.count);return e}findMovableSection(e){let t=[];for(let[s,a]of this.sectionSlots)t.push({key:s,start:a.start,count:a.count});if(t.length===0)return;t.sort((s,a)=>a.start!==s.start?a.start-s.start:a.start+a.count-(s.start+s.count));let n=t[0];if(n.count<=e&&this.findLowestInteriorHole(n.start,n.count))return n;let r=t.filter(s=>s.count<=e).sort((s,a)=>a.count-s.count);for(let s of r)if(this.findLowestInteriorHole(s.start,s.count))return s}findLowestInteriorHole(e,t){for(let n=0;n<this.freeList.length;n++){let r=this.freeList[n];if(r.start<e&&r.count>=t)return{start:r.start,count:r.count,index:n}}}reserveFreeSlotAt(e,t){let n=this.freeList[e];if(this.freeList.splice(e,1),n.count===t)return{start:n.start,count:t};let r={start:n.start,count:t};return this.insertFreeSlot({start:n.start+t,count:n.count-t}),r}copySectionRange(e,t,n){this.w0.copyWithin(t,e,e+n),this.w1.copyWithin(t,e,e+n),this.w2.copyWithin(t,e,e+n),this.w3.copyWithin(t,e,e+n)}rangeFullyUploaded(e,t){for(let n of this.pendingRanges)if(n.start<=t&&n.end>=e)return!1;return!0}zeroAndFreeSlot(e,t){for(let n=e;n<e+t;n++)this.w0[n]=0,this.w1[n]=0,this.w2[n]=dg,this.w3[n]=0;this.markDirty(e,e+t-1),this.insertFreeSlot({start:e,count:t})}finalizePendingReplace(e){let t=this.pendingReplace.get(e);t&&(this.zeroAndFreeSlot(t.oldStart,t.oldCount),this.pendingReplace.delete(e),this.shrinkHighWatermark(),this.mesh.geometry.instanceCount=this.highWatermark,this.layoutVersion++,this.uploadEpoch++)}finalizePendingMove(){let e=this.pendingMove;if(!e)return;let{oldStart:t,count:n}=e;this.zeroAndFreeSlot(t,n),this.shrinkHighWatermark(),this.mesh.geometry.instanceCount=this.highWatermark,this.pendingMove=null,this.layoutVersion++,this.uploadEpoch++}shrinkHighWatermark(){for(;this.highWatermark>0;){let e=this.highWatermark-1,t=this.freeList.find(r=>r.start<=e&&r.start+r.count>e);if(!t||t.start+t.count!==this.highWatermark)break;this.highWatermark=t.start;let n=this.freeList.indexOf(t);this.freeList.splice(n,1)}}growCapacity(e){this.pendingMove&&this.finalizePendingMove();for(let c of[...this.pendingReplace.keys()])this.finalizePendingReplace(c);console.warn("[globalBlockBuffer] growing faces",this.capacityFaces,"->","(need",e,")");let t=this.capacityFaces;for(;t<e;)t+=OYe;console.warn("[globalBlockBuffer] growing faces",this.capacityFaces,"->",t);let n=new Uint32Array(t),r=new Uint32Array(t),s=new Uint32Array(t),a=new Uint32Array(t);n.set(this.w0),r.set(this.w1),s.set(this.w2),a.set(this.w3),s.fill(dg,this.w0.length),this.w0=n,this.w1=r,this.w2=s,this.w3=a,this.capacityFaces=t;let o=this.mesh.geometry,l=(c,u)=>{let d=o.getAttribute(u);d&&(o.deleteAttribute(u),"dispose"in d&&typeof d.dispose=="function"&&d.dispose());let f=new Ar(c,1);f.setUsage(So),o.setAttribute(u,f)};l(this.w0,"a_w0"),l(this.w1,"a_w1"),l(this.w2,"a_w2"),l(this.w3,"a_w3"),this.pendingRanges.length=0,this.invalidateTierCVao()}};h();p();m();z5();Kc();function h4e(i,e,t,n,r){if(e<=0)return;let s=t-8,a=n-8,o=r-8,l=t9,c=16,u=16,d=16,f=-1,v=-1,g=-1;for(let A=0;A<e;A++){let T=i[A*l],P=T&(1<<Xd.LX_BITS)-1,I=T>>Xd.LY_SHIFT&(1<<Xd.LY_BITS)-1,k=T>>Xd.LZ_SHIFT&(1<<Xd.LZ_BITS)-1;P<c&&(c=P),I<u&&(u=I),k<d&&(d=k),P>f&&(f=P),I>v&&(v=I),k>g&&(g=k)}if(f<0)return;let b=s+c,y=a+u,_=o+d,x=s+f+1,w=a+v+1,S=o+g+1;return{minX:b,minY:y,minZ:_,maxX:x,maxY:w,maxZ:S,cx:(b+x)*.5,cy:(y+w)*.5,cz:(_+S)*.5}}function UYe(i,e,t,n,r,s,a,o,l){return i>=n&&i<=a&&e>=r&&e<=o&&t>=s&&t<=l}function m4e(i,e,t,n,r,s,a,o,l,c,u,d,f){if(UYe(i,e,t,a,o,l,c,u,d))return;let v=0,g=f;if(Math.abs(n)<1e-8){if(i<a||i>c)return}else{let b=1/n,y=(a-i)*b,_=(c-i)*b;if(y>_){let x=y;y=_,_=x}if(v=Math.max(v,y),g=Math.min(g,_),v>g)return}if(Math.abs(r)<1e-8){if(e<o||e>u)return}else{let b=1/r,y=(o-e)*b,_=(u-e)*b;if(y>_){let x=y;y=_,_=x}if(v=Math.max(v,y),g=Math.min(g,_),v>g)return}if(Math.abs(s)<1e-8){if(t<l||t>d)return}else{let b=1/s,y=(l-t)*b,_=(d-t)*b;if(y>_){let x=y;y=_,_=x}if(v=Math.max(v,y),g=Math.min(g,_),v>g)return}return v<=g&&v>=0?v:void 0}function p4e(i,e,t,n,r,s,a,o,l,c,u,d,f){let v=f;if(Math.abs(n)>=1e-8){let g=n>0?(c-i)/n:(a-i)/n;g>1e-6&&(v=Math.min(v,g))}else if(i<a||i>c)return;if(Math.abs(r)>=1e-8){let g=r>0?(u-e)/r:(o-e)/r;g>1e-6&&(v=Math.min(v,g))}else if(e<o||e>u)return;if(Math.abs(s)>=1e-8){let g=s>0?(d-t)/s:(l-t)/s;g>1e-6&&(v=Math.min(v,g))}else if(t<l||t>d)return;return v<=f?v:void 0}h();p();m();Lt();h();p();m();$b();var u9=class{entries=new Set;skyLevel=1;lightmapParams={...Ri};register(e){this.entries.add(e),this.applyBrightness(e)}unregister(e){for(let t of this.entries)if(t.material===e){this.entries.delete(t);break}}setSkyLevel(e){this.skyLevel=e,this.refreshAll()}setLightmapParams(e){this.lightmapParams={...this.lightmapParams,...e},this.refreshAll()}getSkyLevel(){return this.skyLevel}refreshAll(){for(let e of this.entries)this.applyBrightness(e)}applyBrightness(e){let t=yP(e.blockLightNorm,e.skyLightNorm,this.skyLevel,this.lightmapParams);e.material.color.setScalar(t)}};function v4e(i,e,t,n,r=Ri){let s=yP(e,t,n,r);return i.color.setScalar(s),s}var g4e=20,_4e=40,FYe={white_banner:15,orange_banner:14,magenta_banner:13,light_blue_banner:12,yellow_banner:11,lime_banner:10,pink_banner:9,gray_banner:8,light_gray_banner:7,cyan_banner:6,purple_banner:5,blue_banner:4,brown_banner:3,green_banner:2,red_banner:1,black_banner:0},y4e={0:"#1d1d21",1:"#b02e26",2:"#5e7c16",3:"#835432",4:"#3c44aa",5:"#8932b8",6:"#169c9c",7:"#9d9d97",8:"#474f52",9:"#f38baa",10:"#80c71f",11:"#fed83d",12:"#3ab3da",13:"#c74ebd",14:"#f9801d",15:"#f9fffe"};function VYe(i){let e=i.replace("_wall_banner","_banner");return FYe[e]??15}var zYe=(i,e,t,n,r,s,a)=>{switch(i.fillStyle=t,e){case"bs":i.fillRect(n,r,s,a);break;case"ls":i.fillRect(n,r,s/3,a);break;case"rs":i.fillRect(n+s*2/3,r,s/3,a);break;case"ts":i.fillRect(n,r,s,a/3);break;case"ms":i.fillRect(n,r+a/3,s,a/3);break;case"drs":i.fillRect(n,r,s/2,a/2);break;case"dls":i.fillRect(n+s/2,r,s/2,a/2);break;case"ss":for(let o=0;o<s;o+=2)i.fillRect(n+o,r,1,a);break;case"cr":i.fillRect(n,r+a/3,s,a/3),i.fillRect(n+s/3,r,s/3,a);break;case"sc":i.fillRect(n,r+a/2-1,s,2),i.fillRect(n+s/2-1,r,2,a);break;default:i.fillRect(n,r,s,a)}};function HYe(i,e){if(!e||e.length===0)return`banner_${i}_empty`;let t=e.map(n=>`${n.Pattern??"bs"}_${n.Color??0}`).join(",");return`banner_${i}_${t}`}var qYe=(i,e,t=(n,r)=>yi(n,r))=>{let r=t(g4e*1,_4e*1),s=r.getContext("2d");if(!s){console.warn("Failed to get 2d context for banner rendering");return}if(s.imageSmoothingEnabled=!1,e?.Patterns&&e.Patterns.length>0)for(let a of e.Patterns){let o=a.Color??0,l=a.Pattern??"bs",c=y4e[o]||y4e[0];zYe(s,l,c,0,0,g4e*1,_4e*1)}return r},d9=new Map;function b4e(i,e,t){let n=VYe(e),r=HYe(n,t?.Patterns),s=d9.get(r);if(s)return s.refCount++,s.texture;let a=qYe(n,t);if(!a)return;let o=new sn(a);return o.magFilter=ct,o.minFilter=ct,o.needsUpdate=!0,d9.set(r,{texture:o,refCount:1}),o}function x4e(i){for(let[e,t]of d9.entries())if(t.texture===i){t.refCount--,t.refCount<=0&&(t.texture.dispose(),d9.delete(e));return}}function w4e(i,e,t,n,r=0,s=1,a=1){let u,d,f;t?(u=(-14.6+13.4)/2/16-.5,d=1-14.75/16-.5,f=1/2):(u=(1.4+29.4)/2/16,d=1-7.25/16-.5,f=0);let v=new _t({map:n,transparent:!0});v4e(v,r,s,a);let g=new Ke(new zn(.85,1.75),v);g.renderOrder=999;let b=.5/16,y=.25/16;t?g.position.set(0,u,d+y+.004):g.position.set(0,u,d+b/2+.004);let _=new bt;return _.rotation.set(0,-Ot.degToRad(e*(t?90:45/2)),0),_.add(g),_.bannerTexture=n,_.bannerMaterial=v,_.position.set(i.x+.5,i.y+f,i.z+.5),_}h();p();m();Lt();var S4e=Yr(V8(),1);var H5=new Map;function GYe(i,e,t){let n,r;return i&&"front_text"in i?(n=i.front_text?.messages??[],r=i.front_text?.color||"black"):(n=[i?.Text1,i?.Text2,i?.Text3,i?.Text4],r=i?.Color||"black"),`${e?1:0}|${t?1:0}|${r}|${n.join("\0")}`}function E4e(i,e,t,n=!1){let r=GYe(e,t,n),s=H5.get(r);if(s)return s.refCount++,s.texture;let a=(0,S4e.default)(i.version),o=k6e(e,t,a);if(!o)return;let l=new sn(o);return l.magFilter=ct,l.minFilter=ct,l.needsUpdate=!0,H5.set(r,{texture:l,refCount:1}),l}function M4e(i){for(let[e,t]of H5.entries())if(t.texture===i){t.refCount--,t.refCount<=0&&(t.texture.dispose(),H5.delete(e));return}}function A4e(){for(let[,i]of H5)i.texture.dispose();H5.clear()}var ro=class ro{constructor(e,t,n,r,s=3){this.worldRenderer=e;this.scene=t;this.material=n;this.worldHeight=r;this.updateViewDistance(s),this.signHeadsRenderer=new PP(e),this.initializePool()}renderOrigin={x:0,y:0,z:0};meshPool=[];activeSections=new Map;sectionObjects={};waitingChunksToDisplay={};pendingNearReveal=new Map;nearRevealTimers=new Map;nearRevealGraceTimers=new Map;poolSize;maxPoolSize;minPoolSize;signHeadsRenderer;blockEntityLightRegistry=new u9;chunkBoxMaterial=new _t({color:0,transparent:!0,opacity:0});cubeShaderMaterial=null;legacyShaderMaterial=null;globalLegacyShaderMaterial=null;globalLegacyBlendShaderMaterial=null;_legacyCullFrustum=new va;_legacyCullProjScreen=new Et;_legacyCullBox=new kn;_legacyCullBoxMin=new X;_legacyCullBoxMax=new X;_visibleSectionSpans=[];legacyCullSections=new Map;_lastCullFingerprint="";lastBufferStateKey="";cullDirty=!0;_lastCullCamPos=new X;_lastCullCamQuat=new qt;_cullViewQuat=new qt;_cullCamInitialized=!1;globalBlockBuffer=null;globalLegacyBuffer=null;globalLegacyBlendBuffer=null;shaderSectionRaycastBoxes=new Map;hits=0;misses=0;bypassPooling=!1;renderTimes=[];maxRenderTimeSamples=30;_performanceOverrideDistance;lastPerformanceCheck=0;performanceCheckInterval=2e3;get performanceOverrideDistance(){return this._performanceOverrideDistance??0}set performanceOverrideDistance(e){this._performanceOverrideDistance=e,this.updateSectionsVisibility()}initializePool(){for(let e=0;e<this.poolSize;e++){let t=new dt,n=new Ke(t,this.getLegacyShaderMaterial());n.visible=!1,n.matrixAutoUpdate=!1,n.name="pooled-section-mesh";let r={mesh:n,inUse:!1,lastUsedTime:0};this.meshPool.push(r)}}sectionHasRenderableContent(e){return e.positions.length>0||(e.blend?.positions.length??0)>0?!0:this.isShaderCubesGpuEnabled()?(e.shaderCubes?.count??0)>0:!1}isShaderCubesGpuEnabled(){return this.worldRenderer.shaderCubeBlocksEnabled()}syncCubeShaderUniforms(){if(!this.isShaderCubesGpuEnabled())return;let e=this.cubeShaderMaterial??this.getCubeShaderMaterial();if(!e)return;let t=this.material.map??null;e.uniforms.u_atlas.value=t;let n=n9();if(!n)return;let{tintPalette:r}=n;r.isReady()||r.createTexture(),e.uniforms.u_tintPalette.value=r.getTexture(),e.uniforms.u_debugMode.value=this.worldRenderer.worldRendererConfig.shaderCubeDebugMode??0,e.needsUpdate=!0}syncLegacyShaderUniforms(){let e=this.material.map??null;this.legacyShaderMaterial&&(this.legacyShaderMaterial.uniforms.u_atlas.value=e,this.legacyShaderMaterial.needsUpdate=!0),this.globalLegacyShaderMaterial&&(this.globalLegacyShaderMaterial.uniforms.u_atlas.value=e,this.globalLegacyShaderMaterial.needsUpdate=!0),this.globalLegacyBlendShaderMaterial&&(this.globalLegacyBlendShaderMaterial.uniforms.u_atlas.value=e,this.globalLegacyBlendShaderMaterial.needsUpdate=!0)}setSkyLevel(e){let t=this.cubeShaderMaterial??(this.isShaderCubesGpuEnabled()?this.getCubeShaderMaterial():null);t&&Jb(t,e),this.legacyShaderMaterial&&s9(this.legacyShaderMaterial,e),this.globalLegacyShaderMaterial&&s9(this.globalLegacyShaderMaterial,e),this.globalLegacyBlendShaderMaterial&&s9(this.globalLegacyBlendShaderMaterial,e),this.blockEntityLightRegistry.setSkyLevel(e)}setShadingTheme(e,t){let n=this.cubeShaderMaterial??(this.isShaderCubesGpuEnabled()?this.getCubeShaderMaterial():null);n&&bP(n,e,t)}setBlockLightmapParams(e){let t=this.cubeShaderMaterial??(this.isShaderCubesGpuEnabled()?this.getCubeShaderMaterial():null);t&&B_e(t,e),this.legacyShaderMaterial&&a9(this.legacyShaderMaterial,e),this.globalLegacyShaderMaterial&&a9(this.globalLegacyShaderMaterial,e),this.globalLegacyBlendShaderMaterial&&a9(this.globalLegacyBlendShaderMaterial,e),this.blockEntityLightRegistry.setLightmapParams(e)}getLegacyShaderMaterial(){return this.legacyShaderMaterial||(this.legacyShaderMaterial=$_e(),this.syncLegacyShaderUniforms()),this.legacyShaderMaterial}getGlobalLegacyShaderMaterial(){return this.globalLegacyShaderMaterial||(this.globalLegacyShaderMaterial=Y_e(),this.syncLegacyShaderUniforms()),this.globalLegacyShaderMaterial}getGlobalLegacyBuffer(){return this.globalLegacyBuffer||(this.globalLegacyBuffer=new ug(this.getGlobalLegacyShaderMaterial(),this.scene),this.globalLegacyBuffer.setRenderOrigin(this.renderOrigin)),this.globalLegacyBuffer}getGlobalLegacyBlendShaderMaterial(){return this.globalLegacyBlendShaderMaterial||(this.globalLegacyBlendShaderMaterial=J_e(),this.syncLegacyShaderUniforms()),this.globalLegacyBlendShaderMaterial}getGlobalLegacyBlendBuffer(){return this.globalLegacyBlendBuffer||(this.globalLegacyBlendBuffer=new ug(this.getGlobalLegacyBlendShaderMaterial(),this.scene,{name:"globalLegacyBlend",initialCapacityQuads:32e3,growthIncrementQuads:32e3}),this.globalLegacyBlendBuffer.setRenderOrigin(this.renderOrigin)),this.globalLegacyBlendBuffer}getRenderOrigin(){return this.renderOrigin}maybeRebase(e){let t=this.renderOrigin;if(Math.abs(e.x-t.x)<=ro.REBASE_THRESHOLD&&Math.abs(e.y-t.y)<=ro.REBASE_THRESHOLD&&Math.abs(e.z-t.z)<=ro.REBASE_THRESHOLD)return;let n={x:Math.round(e.x/16)*16,y:Math.round(e.y/16)*16,z:Math.round(e.z/16)*16},r={x:n.x-t.x,y:n.y-t.y,z:n.z-t.z};this.globalLegacyBuffer?.rebase(r),this.globalLegacyBlendBuffer?.rebase(r);for(let s of this.activeSections.values()){let a=s.sectionKey;if(!a)continue;let o=this.sectionObjects[a];o&&IP(s.mesh,o.worldX??0,o.worldY??0,o.worldZ??0,n)}this.renderOrigin=n,this.globalLegacyBuffer?.setRenderOrigin(n),this.globalLegacyBlendBuffer?.setRenderOrigin(n)}sectionUsesPooledLegacyMesh(e){return this.activeSections.has(e)}registerLegacyCullSection(e,t,n,r){this.legacyCullSections.set(e,{worldX:t,worldY:n,worldZ:r})}maybeUnregisterLegacyCullSection(e){let t=this.globalLegacyBuffer?.hasSection(e)??!1,n=this.globalLegacyBlendBuffer?.hasSection(e)??!1;!t&&!n&&this.legacyCullSections.delete(e)}updatePooledLegacyCullState(e,t,n){for(let r of this.activeSections.values()){let s=r.sectionKey;if(!s)continue;let a=this.sectionObjects[s];a&&K_e(r.mesh,a.worldX??0,a.worldY??0,a.worldZ??0,e,t,n,this._legacyCullFrustum,this._legacyCullBox,this._legacyCullBoxMin,this._legacyCullBoxMax)}}updateSectionCullAndSort(e,t,n,r){this._legacyCullProjScreen.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),this._legacyCullFrustum.setFromProjectionMatrix(this._legacyCullProjScreen);let s=this._visibleSectionSpans;s.length=0;for(let[b]of this.legacyCullSections){let y=this.sectionObjects[b];if(!y?.visible||y.worldX===void 0)continue;let{visible:_,distSq:x}=o9(y.worldX,y.worldY??0,y.worldZ??0,t,n,r,this._legacyCullFrustum,this._legacyCullBox,this._legacyCullBoxMin,this._legacyCullBoxMax);_&&s.push({key:b,distSq:x})}let a=this.globalLegacyBuffer,o=this.globalLegacyBlendBuffer,l=this.globalBlockBuffer,c=[];for(let b of s)a?.hasSection(b.key)&&c.push(b.key);c.sort();let u=s.filter(b=>o?.hasSection(b.key));u.sort((b,y)=>y.distSq-b.distSq);let d=u.map(b=>b.key),f=[],v=[];l&&l.forEachSectionSlot((b,y)=>{if(!this.sectionObjects[b]?.visible)return;let x=this.shaderSectionRaycastBoxes.get(b);if(!x)return;let{visible:w}=o9(x.sectionCenterX,x.sectionCenterY,x.sectionCenterZ,t,n,r,this._legacyCullFrustum,this._legacyCullBox,this._legacyCullBoxMin,this._legacyCullBoxMax);if(!w)return;f.push(b);let S=l.getSectionDrawStart(b),A=l.getSectionDrawCount(b);S!==void 0&&A!==void 0&&v.push({start:S,count:A})}),f.sort();let g=[c.join(","),d.join(","),f.join(","),a?.getLayoutVersion()??0,o?.getLayoutVersion()??0,l?.getLayoutVersion()??0,a?.getUploadEpoch()??0,o?.getUploadEpoch()??0,l?.getUploadEpoch()??0].join("|");if(g===this._lastCullFingerprint&&!this.hasPendingBufferWork()){this.updatePooledLegacyCullState(t,n,r);return}if(this._lastCullFingerprint=g,a?.updateDrawSpans(s,"opaque"),o?.updateDrawSpans(s,"sortedBlend"),l){let b=s4e(v,l.getHighWatermark(),l.canUseFullDrawShortcut(),(y,_)=>l.isRangeFullyUploaded(y,_),l.getPendingDirtyRanges());l.setVisibleSpans(b)}this.lastBufferStateKey=this.bufferStateKey(),this.updatePooledLegacyCullState(t,n,r)}bufferStateKey(){let e=this.globalBlockBuffer,t=this.globalLegacyBuffer,n=this.globalLegacyBlendBuffer;return[t?.getLayoutVersion()??0,t?.getUploadEpoch()??0,n?.getLayoutVersion()??0,n?.getUploadEpoch()??0,e?.getLayoutVersion()??0,e?.getUploadEpoch()??0].join("|")}markCullDirtyIfBufferStateChanged(){this.bufferStateKey()!==this.lastBufferStateKey&&this.markCullDirty()}markCullDirty(){this.cullDirty=!0}hasPendingBufferWork(){return[this.globalLegacyBuffer,this.globalLegacyBlendBuffer,this.globalBlockBuffer].some(t=>t!=null&&(t.hasPendingUploads()||t.hasPendingReplace()||t.getPendingMove()!=null))}updateCullDirtyFromCamera(e,t,n,r){if(e.getWorldQuaternion(this._cullViewQuat),!this._cullCamInitialized){this._lastCullCamPos.set(t,n,r),this._lastCullCamQuat.copy(this._cullViewQuat),this._cullCamInitialized=!0,this.cullDirty=!0;return}let s=this._lastCullCamPos.x!==t||this._lastCullCamPos.y!==n||this._lastCullCamPos.z!==r,a=this._lastCullCamQuat.x!==this._cullViewQuat.x||this._lastCullCamQuat.y!==this._cullViewQuat.y||this._lastCullCamQuat.z!==this._cullViewQuat.z||this._lastCullCamQuat.w!==this._cullViewQuat.w;(s||a)&&(this._lastCullCamPos.set(t,n,r),this._lastCullCamQuat.copy(this._cullViewQuat),this.markCullDirty())}clearCullDirty(){this.cullDirty=!1}setLegacyCameraOrigin(e,t,n){let r=this.renderOrigin;i9(this.getLegacyShaderMaterial(),r,e,t,n),i9(this.getGlobalLegacyShaderMaterial(),r,e,t,n),i9(this.getGlobalLegacyBlendShaderMaterial(),r,e,t,n),this.globalLegacyBuffer?.setCameraOrigin(e,t,n),this.globalLegacyBlendBuffer?.setCameraOrigin(e,t,n);let s=this.cubeShaderMaterial;if(s){let{originDelta:a,cameraOriginFrac:o}=$d(r,e,t,n),l=Kb(r),c=s.uniforms.u_originDelta;c?.value?.set&&c.value.set(a.x,a.y,a.z);let u=s.uniforms.u_cameraOriginFrac;u?.value?.set&&u.value.set(o.x,o.y,o.z);let d=s.uniforms.u_sectionOriginRel;d?.value?.set&&d.value.set(l.x,l.y,l.z)}}getCubeShaderMaterial(){if(!this.isShaderCubesGpuEnabled())return null;if(!this.cubeShaderMaterial){this.cubeShaderMaterial=Yb(),this.syncCubeShaderUniforms();let e=this.worldRenderer.worldRendererConfig;bP(this.cubeShaderMaterial,e.shadingTheme,e.cardinalLight)}return this.cubeShaderMaterial}getGlobalBlockBuffer(){let e=this.getCubeShaderMaterial();return e?(this.globalBlockBuffer||(this.globalBlockBuffer=new c9(e,this.scene)),this.globalBlockBuffer):null}shouldDeferLegacyOpaqueToPerSection(e){return this.shouldDeferShaderToPerSection(e)}shouldDeferShaderToPerSection(e){return this.worldRenderer.getModule("futuristicReveal")?.shouldDeferSectionGeometry?.(e)===!0}migrateDeferredShaderToGlobal(e){let t=this.sectionObjects[e];if(!t?.deferredShaderCubes)return;let{words:n,count:r}=t.deferredShaderCubes,s=t.worldX,a=t.worldY,o=t.worldZ;s!==void 0&&a!==void 0&&o!==void 0&&this.registerShaderSectionRaycastBox(e,n,r,s,a,o),this.getGlobalBlockBuffer()?.addSection(e,n,r),this.markCullDirty();let c=t.mesh===t.shaderMesh;t.shaderMesh&&(SP(t.shaderMesh),t.remove(t.shaderMesh),t.shaderMesh=void 0),delete t.deferredShaderCubes,c&&(t.mesh=void 0)}migrateDeferredLegacyToGlobal(e){let t=this.sectionObjects[e];if(t){if(t.deferredLegacyOpaque){let{positions:n,colors:r,skyLights:s,blockLights:a,uvs:o,indices:l}=t.deferredLegacyOpaque,c=t.worldX,u=t.worldY,d=t.worldZ;c!==void 0&&u!==void 0&&d!==void 0&&this.getGlobalLegacyBuffer().addSection(e,{positions:n,colors:r,skyLights:s,blockLights:a,uvs:o,indices:l},c,u,d)&&this.registerLegacyCullSection(e,c,u,d),delete t.deferredLegacyOpaque}if(t.deferredLegacyBlend){let{positions:n,colors:r,skyLights:s,blockLights:a,uvs:o,indices:l}=t.deferredLegacyBlend,c=t.worldX,u=t.worldY,d=t.worldZ;c!==void 0&&u!==void 0&&d!==void 0&&this.getGlobalLegacyBlendBuffer().addSection(e,{positions:n,colors:r,skyLights:s,blockLights:a,uvs:o,indices:l},c,u,d)&&this.registerLegacyCullSection(e,c,u,d),delete t.deferredLegacyBlend,t.hasBlendMesh=!1}if(!t.hasBlendMesh){let n=t.mesh===this.activeSections.get(e)?.mesh;this.releasePooledMesh(e),n&&(t.mesh=t.shaderMesh??void 0)}this.markCullDirty()}}registerShaderSectionRaycastBox(e,t,n,r,s,a){let o=h4e(t,n,r,s,a);o?this.shaderSectionRaycastBoxes.set(e,{box:o,sectionCenterX:r,sectionCenterY:s,sectionCenterZ:a}):this.shaderSectionRaycastBoxes.delete(e)}unregisterShaderSectionRaycastBox(e){this.shaderSectionRaycastBoxes.delete(e)}uploadLegacyPooledMesh(e,t,n,r,s){let{mesh:a}=e,o=t;return this.updateGeometryAttribute(a.geometry,"position",o.positions,3),this.updateGeometryAttribute(a.geometry,"normal",o.normals,3),this.updateGeometryAttribute(a.geometry,"color",o.colors,3),this.updateGeometryAttribute(a.geometry,"a_skyLight",o.skyLights,1),this.updateGeometryAttribute(a.geometry,"a_blockLight",o.blockLights,1),this.updateGeometryAttribute(a.geometry,"uv",o.uvs,2),a.geometry.index=new Mt(o.indices,1),a.geometry.boundingBox=new kn(new X(-8,-8,-8),new X(8,8,8)),a.geometry.boundingSphere=new Tn(new X(0,0,0),Math.sqrt(3*8**2)),IP(a,n,r,s,this.renderOrigin),a.visible=!1,a.name="mesh",e.lastUsedTime=performance.now(),a}acquirePooledSectionMesh(e){let t=this.activeSections.get(e);if(!t){if(t=this.acquireMesh(),!t)return console.warn(`ChunkMeshManager: No available mesh in pool for section ${e}`),null;this.activeSections.set(e,t),t.sectionKey=e}return t}updateSection(e,t){let n=t.positions.length>0,r=(t.blend?.positions.length??0)>0,s=n||r,a=t.shaderCubes,o=this.isShaderCubesGpuEnabled()&&(a?.count??0)>0,l=n&&this.shouldDeferLegacyOpaqueToPerSection(e),c=r&&this.shouldDeferLegacyOpaqueToPerSection(e),u=o&&this.shouldDeferShaderToPerSection(e),d=n&&!l,f=r&&!c,v=o&&!!a&&!u;if(!s&&!o)return this.releaseSection(e),null;let g=this.sectionObjects[e],b=g!=null;g&&this.cleanupSection(e,{forRemesh:!0}),b&&(v||this.globalBlockBuffer?.removeSection(e),d||this.globalLegacyBuffer?.removeSection(e),f||this.globalLegacyBlendBuffer?.removeSection(e),o&&a||this.unregisterShaderSectionRaycastBox(e),!d&&!f&&this.maybeUnregisterLegacyCullSection(e)),r||this.releasePooledMesh(e);let y,_,x,w=!1;if(n){let B={positions:t.positions,colors:t.colors,skyLights:t.skyLights,blockLights:t.blockLights,uvs:t.uvs,indices:t.indices};if(l){if(_={positions:new Float32Array(B.positions),colors:new Float32Array(B.colors),skyLights:new Float32Array(B.skyLights),blockLights:new Float32Array(B.blockLights),uvs:new Float32Array(B.uvs),indices:B.indices instanceof Uint32Array?new Uint32Array(B.indices):new Uint16Array(B.indices)},!r){let U=this.acquirePooledSectionMesh(e);if(!U)return null;y=this.uploadLegacyPooledMesh(U,t,t.sx,t.sy,t.sz)}}else if(this.getGlobalLegacyBuffer().addSection(e,B,t.sx,t.sy,t.sz))this.registerLegacyCullSection(e,t.sx,t.sy,t.sz);else{let O=this.acquirePooledSectionMesh(e);if(!O)return null;y=this.uploadLegacyPooledMesh(O,t,t.sx,t.sy,t.sz)}}if(r&&t.blend){let B={positions:t.blend.positions,colors:t.blend.colors,skyLights:t.blend.skyLights,blockLights:t.blend.blockLights,uvs:t.blend.uvs,indices:t.blend.indices};if(c){x={positions:new Float32Array(B.positions),colors:new Float32Array(B.colors),skyLights:new Float32Array(B.skyLights),blockLights:new Float32Array(B.blockLights),uvs:new Float32Array(B.uvs),indices:B.indices instanceof Uint32Array?new Uint32Array(B.indices):new Uint16Array(B.indices)};let U=this.acquirePooledSectionMesh(e);if(!U)return null;let O=this.uploadLegacyPooledMesh(U,t.blend,t.sx,t.sy,t.sz);y=y??O,w=!0}else if(this.getGlobalLegacyBlendBuffer().addSection(e,B,t.sx,t.sy,t.sz))this.registerLegacyCullSection(e,t.sx,t.sy,t.sz);else{console.warn(`ChunkMeshManager: blend invariant violation for section ${e}, using pooled mesh fallback`);let O=this.acquirePooledSectionMesh(e);if(!O)return null;let V=this.uploadLegacyPooledMesh(O,t.blend,t.sx,t.sy,t.sz);y=y??V,w=!0}}let S=o?this.getCubeShaderMaterial():null,A;o&&a&&(u&&S?(A=r9(a,S),A.visible=!0):this.getGlobalBlockBuffer()?.addSection(e,a.words,a.count)),g=new bt,y&&(g.add(y),g.mesh=y),A&&(g.add(A),g.shaderMesh=A,a&&(g.deferredShaderCubes={words:a.words,count:a.count}),g.mesh||(g.mesh=A)),_&&(g.deferredLegacyOpaque=_),x&&(g.deferredLegacyBlend=x),o&&a&&this.registerShaderSectionRaycastBox(e,a.words,a.count,t.sx,t.sy,t.sz);let T=0;n&&(T+=t.positions.length/3/4),r&&t.blend&&(T+=t.blend.positions.length/3/4),o&&a&&(T+=a.count),g.tilesCount=T,g.hasBlendMesh=w,g.blocksCount=t.blocksCount,g.worldX=t.sx,g.worldY=t.sy,g.worldZ=t.sz,g.sectionKey=e,g.name="chunk";try{if(Object.keys(t.signs).length>0){let B=new bt;B.name="signs";for(let[U,{isWall:O,isHanging:V,rotation:F}]of Object.entries(t.signs)){let J=this.worldRenderer.blockEntities[U];if(!J)continue;let[$,ne,se]=U.split(","),j=this.signHeadsRenderer.renderSign(new kt(+$,+ne,+se),F,O,V,f9.simplify(J));j&&B.add(j)}g.add(B),g.signsContainer=B}if(Object.keys(t.heads).length>0){let B=new bt;B.name="heads";for(let[U,{isWall:O,rotation:V}]of Object.entries(t.heads)){let F=this.worldRenderer.blockEntities[U];if(!F)continue;let[J,$,ne]=U.split(","),se=this.signHeadsRenderer.renderHead(new kt(+J,+$,+ne),V,O,f9.simplify(F));se&&B.add(se)}g.add(B),g.headsContainer=B}if(Object.keys(t.banners).length>0){let B=new bt;B.name="banners",g.bannersContainer=B,g.add(B);for(let[U,O]of Object.entries(t.banners)){let{isWall:V,rotation:F,blockName:J,blockLightNorm:$=0,skyLightNorm:ne=1}=O,se=this.worldRenderer.blockEntities[U];if(!se)continue;let[j,q,z]=U.split(","),K=b4e(this.worldRenderer,J,f9.simplify(se));if(!K)continue;let re=this.blockEntityLightRegistry.getSkyLevel(),Z=w4e(new kt(+j,+q,+z),F,V,K,$,ne,re);Z.bannerMaterial&&this.blockEntityLightRegistry.register({material:Z.bannerMaterial,blockLightNorm:$,skyLightNorm:ne});let{x:Y,y:Q,z:ue}=Z.position;this.worldRenderer.sceneOrigin.track(Z),Z.position.set(Y,Q,ue),B.add(Z)}}}catch(B){console.error("ChunkMeshManager: Error adding signs, heads, or banners to section",B)}this.sectionObjects[e]=g,this.scene.add(g),g.matrixAutoUpdate=!1,this.worldRenderer.displayOptions?.inWorldRenderingConfig?.showChunkBorders&&this.updateBoxHelper(e,!0);let P=e.split(","),I=`${P[0]},${P[2]}`,k=!!this.worldRenderer.displayOptions?.inWorldRenderingConfig?._renderByChunks,L=!!this.worldRenderer.worldRendererConfig?.wasmMesher;if((k||L)&&!this.worldRenderer.finishedChunks[I]){g.visible=!1,g._waitingForChunkDisplay=!0;let B=this.waitingChunksToDisplay[I]??(this.waitingChunksToDisplay[I]=[]);B.includes(e)||B.push(e)}return this.markCullDirty(),g}finishChunkDisplay(e){if(!this.waitingChunksToDisplay[e]){this.tryRevealPending();return}if(this.isWasmGateActive()&&this.isBlockedByNearer(e,0)){this.pendingNearReveal.set(e,Date.now()),this.armNearRevealTimer(e),this.armExpectedGraceTimer(e),this.tryRevealPending();return}this.flushChunkDisplay(e),this.tryRevealPending()}flushChunkDisplay(e){let t=this.waitingChunksToDisplay[e];if(this.pendingNearReveal.delete(e),this.clearNearRevealTimer(e),this.clearExpectedGraceTimer(e),!!t){for(let n of t){let r=this.sectionObjects[n];r&&(r._waitingForChunkDisplay=!1,r.visible=!0)}delete this.waitingChunksToDisplay[e],this.markCullDirty()}}tryRevealPending(){if(this.pendingNearReveal.size===0)return;let e=Date.now();for(let[t,n]of[...this.pendingNearReveal])this.isBlockedByNearer(t,e-n)||this.flushChunkDisplay(t)}onChunkRemovedFromGate(e){this.pendingNearReveal.delete(e),this.clearNearRevealTimer(e),this.clearExpectedGraceTimer(e),delete this.waitingChunksToDisplay[e],this.tryRevealPending()}isWasmGateActive(){return!!this.worldRenderer.worldRendererConfig?.wasmMesher}isBlockedByNearer(e,t){let n=this.worldRenderer.viewerChunkPosition;if(!n)return!1;let r=e.split(",");if(r.length!==2)return!1;let s=Number(r[0]),a=Number(r[1]),o=Math.floor(n.x/16),l=Math.floor(n.z/16),c=(s>>4)-o,u=(a>>4)-l,d=c*c+u*u;if(d===0)return!1;let f=this.worldRenderer.finishedChunks,v=this.worldRenderer.loadedChunks,g=this.worldRenderer.viewDistance;if(t<ro.EXPECTED_NEAR_GRACE_MS&&g>0){let y=g*g,_=Math.min(g,Math.ceil(Math.sqrt(Math.max(0,d-1))));for(let x=-_;x<=_;x++)for(let w=-_;w<=_;w++){let S=x*x+w*w;if(S>=d||S>y)continue;let A=o+x<<4,T=l+w<<4,P=`${A},${T}`;if(P!==e&&v[P]&&!f[P])return!0}return!1}for(let y in v){if(y===e||f[y])continue;let _=y.split(",");if(_.length!==2)continue;let x=(Number(_[0])>>4)-o,w=(Number(_[1])>>4)-l;if(x*x+w*w<d)return!0}return!1}armNearRevealTimer(e){if(this.nearRevealTimers.has(e))return;let t=setTimeout(()=>{this.nearRevealTimers.delete(e),this.pendingNearReveal.has(e)&&(console.warn(`[chunk-reveal] safety timeout for ${e} \u2014 a nearer pending column never finished, force-revealing`),this.flushChunkDisplay(e),this.tryRevealPending())},ro.NEAR_REVEAL_TIMEOUT_MS);this.nearRevealTimers.set(e,t)}clearNearRevealTimer(e){let t=this.nearRevealTimers.get(e);t&&(clearTimeout(t),this.nearRevealTimers.delete(e))}armExpectedGraceTimer(e){if(this.nearRevealGraceTimers.has(e))return;let t=setTimeout(()=>{this.nearRevealGraceTimers.delete(e),this.pendingNearReveal.has(e)&&this.tryRevealPending()},ro.EXPECTED_NEAR_GRACE_MS+50);this.nearRevealGraceTimers.set(e,t)}clearExpectedGraceTimer(e){let t=this.nearRevealGraceTimers.get(e);t&&(clearTimeout(t),this.nearRevealGraceTimers.delete(e))}cleanupSection(e,t){let n=this.sectionObjects[e];if(n){if(n._waitingForChunkDisplay){let r=e.split(","),s=`${r[0]},${r[2]}`,a=this.waitingChunksToDisplay[s];if(a){let o=a.indexOf(e);o!==-1&&a.splice(o,1),a.length===0&&delete this.waitingChunksToDisplay[s]}}if(n.bannersContainer){for(let r of n.bannersContainer.children){let s=r;s.bannerMaterial&&this.blockEntityLightRegistry.unregister(s.bannerMaterial),s.bannerTexture&&x4e(s.bannerTexture)}this.disposeContainer(n.bannersContainer)}if(t?.forRemesh||(this.globalBlockBuffer?.removeSection(e),this.globalLegacyBuffer?.removeSection(e),this.globalLegacyBlendBuffer?.removeSection(e),this.maybeUnregisterLegacyCullSection(e),this.unregisterShaderSectionRaycastBox(e)),this.markCullDirty(),delete n.deferredLegacyOpaque,delete n.deferredLegacyBlend,n.shaderMesh&&(SP(n.shaderMesh),n.shaderMesh=void 0),delete n.deferredShaderCubes,n.signsContainer){for(let r of n.signsContainer.children){let s=r;s.signTexture&&M4e(s.signTexture)}this.disposeContainer(n.signsContainer,!1)}if(n.headsContainer&&this.disposeContainer(n.headsContainer),this.worldRenderer.sceneOrigin.removeAndUntrackAll(n),this.scene.remove(n),n.boxHelper){this.worldRenderer.sceneOrigin.removeAndUntrack(n.boxHelper),this.scene.remove(n.boxHelper),n.boxHelper.geometry.dispose();let r=n.boxHelper.material;if(Array.isArray(r))for(let s of r)s.dispose();else r.dispose();n.boxHelper=void 0}delete this.sectionObjects[e],t?.forRemesh||this.worldRenderer.getModule("futuristicReveal")?.onSectionRemoved?.(e)}}releasePooledMesh(e){let t=this.activeSections.get(e);t&&(t.mesh.visible=!1,t.inUse=!1,t.sectionKey=void 0,t.lastUsedTime=0,this.clearGeometry(t.mesh.geometry),this.activeSections.delete(e),this.cleanupExcessMeshes())}releaseSection(e){this.cleanupSection(e);let t=this.activeSections.get(e);return t?(t.mesh.visible=!1,t.inUse=!1,t.sectionKey=void 0,t.lastUsedTime=0,this.clearGeometry(t.mesh.geometry),this.activeSections.delete(e),this.cleanupExcessMeshes(),!0):!1}getSectionObject(e){return this.sectionObjects[e]}updateBoxHelper(e,t,n=this.chunkBoxMaterial){let r=this.sectionObjects[e];if(r)if(t){if(!r.boxHelper){let s=new Ke(new Sn(16,16,16),n),a=new Ea(s,16776960);a.name="helper";let o=r.worldX??0,l=r.worldY??0,c=r.worldZ??0;this.worldRenderer.sceneOrigin.track(a,{updateMatrix:!0}),a.position.set(o,l,c),a.updateMatrix(),this.scene.add(a),r.boxHelper=a}r.boxHelper.visible=!0}else r.boxHelper&&(r.boxHelper.visible=!1)}updateAllBoxHelpers(e){for(let t of Object.keys(this.sectionObjects))this.updateBoxHelper(t,e)}getSectionMesh(e){return this.activeSections.get(e)?.mesh}hasSection(e){return this.activeSections.has(e)}updateViewDistance(e){let t=(e*2+1)**2,n=this.worldHeight/16,r=5;if(this.minPoolSize=Math.floor(t*r),this.maxPoolSize=Math.floor(t*n)+1,this.poolSize??=this.minPoolSize,this.minPoolSize>this.poolSize){let s=Math.min(this.minPoolSize,this.maxPoolSize);this.expandPool(s)}console.log(`ChunkMeshManager: Updated view max distance to ${e}, pool: ${this.poolSize}/${this.maxPoolSize}, optimal: ${this.minPoolSize}`)}getGlobalBufferStats(){let e=n=>n?{used:n.getHighWatermark(),capacity:n.getCapacityQuads(),sections:n.getSectionCount(),usedBytes:n.getUsedMemoryBytes(),capacityBytes:n.getMemoryBytes()}:null,t=this.globalBlockBuffer;return{shaderFaces:t?{used:t.getHighWatermark(),capacity:t.getCapacityFaces(),sections:t.getSectionCount(),usedBytes:t.getUsedMemoryBytes(),capacityBytes:t.getMemoryBytes()}:null,legacyOpaque:e(this.globalLegacyBuffer),legacyBlend:e(this.globalLegacyBlendBuffer)}}getStats(){let e=this.meshPool.filter(r=>!r.inUse).length,t=this.hits+this.misses>0?(this.hits/(this.hits+this.misses)*100).toFixed(1):"0",n=this.getEstimatedMemoryUsage();return{poolSize:this.poolSize,activeCount:this.activeSections.size,freeCount:e,hitRate:`${t}%`,hits:this.hits,misses:this.misses,memoryUsage:n}}getTotalTiles(){return Object.values(this.sectionObjects).reduce((e,t)=>e+(t.tilesCount||0),0)}getTotalBlocks(){return Object.values(this.sectionObjects).reduce((e,t)=>e+(t.blocksCount||0),0)}getEstimatedMemoryUsage(){let e=0,t=0,n=0,r=0,s=0,a=0,o=0,l=this.globalBlockBuffer?.mesh.geometry;if(l)for(let f of["a_w0","a_w1","a_w2","a_w3"]){let v=l.getAttribute(f);if(v){let g=v.array.byteLength;o+=g,e+=g}}let c=this.globalLegacyBuffer?.getMemoryBytes()??0,u=this.globalLegacyBlendBuffer?.getMemoryBytes()??0;e+=c+u,t+=c+u;for(let f of Object.values(this.sectionObjects)){let v=f.shaderMesh?.geometry;if(v)for(let g of["a_w0","a_w1","a_w2","a_w3"]){let b=v.getAttribute(g);if(b){let y=b.array.byteLength;o+=y,e+=y}}}for(let f of this.meshPool)if(f.inUse&&f.mesh.geometry){let{geometry:v}=f.mesh,g=v.getAttribute("position");if(g){let x=g.array.byteLength;t+=x,e+=x}let b=v.getAttribute("normal");if(b){let x=b.array.byteLength;n+=x,e+=x}let y=v.getAttribute("color");if(y){let x=y.array.byteLength;r+=x,e+=x}let _=v.getAttribute("uv");if(_){let x=_.array.byteLength;s+=x,e+=x}if(v.index){let x=v.index.array.byteLength;a+=x,e+=x}}return{total:`${(e/(1024*1024)).toFixed(2)} MB`,breakdown:{position:`${(t/(1024*1024)).toFixed(2)} MB`,normal:`${(n/(1024*1024)).toFixed(2)} MB`,color:`${(r/(1024*1024)).toFixed(2)} MB`,uv:`${(s/(1024*1024)).toFixed(2)} MB`,index:`${(a/(1024*1024)).toFixed(2)} MB`,shaderInstances:`${(o/(1024*1024)).toFixed(2)} MB`}}}dispose(){let e=[...this.activeSections.keys()];for(let t of e)this.releaseSection(t);this.signHeadsRenderer.dispose();for(let t of this.meshPool)t.mesh.geometry.dispose();this.meshPool.length=0,this.activeSections.clear(),this.chunkBoxMaterial.dispose(),this.shaderSectionRaycastBoxes.clear(),this.lastBufferStateKey="",this.globalBlockBuffer?.dispose(),this.globalBlockBuffer=null,this.globalLegacyBuffer?.dispose(),this.globalLegacyBuffer=null,this.globalLegacyBlendBuffer?.dispose(),this.globalLegacyBlendBuffer=null,this.cubeShaderMaterial?.dispose(),this.cubeShaderMaterial=null,this.legacyShaderMaterial?.dispose(),this.legacyShaderMaterial=null,this.globalLegacyShaderMaterial?.dispose(),this.globalLegacyShaderMaterial=null,this.globalLegacyBlendShaderMaterial?.dispose(),this.globalLegacyBlendShaderMaterial=null,this.pendingNearReveal.clear();for(let t of this.nearRevealTimers.values())clearTimeout(t);this.nearRevealTimers.clear();for(let t of this.nearRevealGraceTimers.values())clearTimeout(t);this.nearRevealGraceTimers.clear()}acquireMesh(){if(this.bypassPooling){let t={mesh:new Ke(new dt,this.getLegacyShaderMaterial()),inUse:!0,lastUsedTime:performance.now()};return this.meshPool.push(t),this.poolSize++,t}for(let t of this.meshPool)if(!t.inUse)return t.inUse=!0,t.lastUsedTime=performance.now(),this.hits++,t;this.misses++;let e=Math.min(this.poolSize+16,this.maxPoolSize);e<=this.meshPool.length&&(e=this.meshPool.length+8,this.maxPoolSize=e,console.warn(`ChunkMeshManager: Pool exhausted (${this.poolSize}/${this.maxPoolSize}). Emergency expansion to ${e}`)),this.expandPool(e);for(let t=this.meshPool.length-1;t>=0;t--){let n=this.meshPool[t];if(!n.inUse)return n.inUse=!0,n.lastUsedTime=performance.now(),n}throw new Error("ChunkMeshManager: Failed to acquire mesh after pool expansion")}expandPool(e){let t=this.meshPool.length;this.poolSize=e;for(let n=t;n<e;n++){let r=new dt,s=new Ke(r,this.getLegacyShaderMaterial());s.visible=!1,s.matrixAutoUpdate=!1,s.name="pooled-section-mesh";let a={mesh:s,inUse:!1,lastUsedTime:0};this.meshPool.push(a)}}updateGeometryAttribute(e,t,n,r){let s=e.getAttribute(t);s&&s.count===n.length/r?(s.array.set(n),s.needsUpdate=!0):e.setAttribute(t,new Mt(n,r))}clearGeometry(e){let t=["position","normal","color","a_skyLight","a_blockLight","uv"];for(let n of t)e.hasAttribute(n)&&e.deleteAttribute(n);e.index&&e.setIndex(null),e.boundingBox=null,e.boundingSphere=null}cleanupExcessMeshes(){if(this.poolSize>this.maxPoolSize){let e=this.meshPool.filter(t=>!t.inUse).length;if(e>0){let t=Math.min(this.poolSize-this.maxPoolSize,e);for(let n=0;n<t;n++){let r=this.meshPool.findIndex(s=>!s.inUse);r!==-1&&(this.meshPool[r].mesh.geometry.dispose(),this.meshPool.splice(r,1),this.poolSize--)}}}}disposeContainer(e,t=!0){dr(e,t)}recordRenderTime(e){this.renderTimes.push(e),this.renderTimes.length>this.maxRenderTimeSamples&&this.renderTimes.shift();let t=performance.now();t-this.lastPerformanceCheck>this.performanceCheckInterval&&(this.checkPerformance(),this.lastPerformanceCheck=t)}getEffectiveRenderDistance(){return this.performanceOverrideDistance||this.worldRenderer.viewDistance}resetPerformanceOverride(){this.performanceOverrideDistance=void 0,this.renderTimes.length=0,console.log("ChunkMeshManager: Performance override reset")}getAverageRenderTime(){return this.renderTimes.length===0?0:this.renderTimes.reduce((e,t)=>e+t,0)/this.renderTimes.length}checkPerformance(){if(this.renderTimes.length<this.maxRenderTimeSamples)return;let e=this.getAverageRenderTime(),t=16.67,n=t*1.5;if(e>n){let r=this.worldRenderer.viewDistance,s=Math.max(1,Math.floor(r*.8));(!this.performanceOverrideDistance||s<this.performanceOverrideDistance)&&(this.performanceOverrideDistance=s,console.warn(`ChunkMeshManager: Performance degraded (${e.toFixed(2)}ms avg). Reducing effective render distance to ${s}`))}else if(this.performanceOverrideDistance&&e<t*1.1){let r=this.worldRenderer.viewDistance,s=Math.min(r,this.performanceOverrideDistance+1);s!==this.performanceOverrideDistance&&(this.performanceOverrideDistance=s>=r?void 0:s,console.log(`ChunkMeshManager: Performance improved. Restoring render distance to ${s}`))}}updateSectionsVisibility(){let e=this.worldRenderer.cameraSectionPos;for(let[t,n]of Object.entries(this.sectionObjects)){if(n._waitingForChunkDisplay){n.visible=!1;continue}if(!this.performanceOverrideDistance){n.visible=!0;continue}let[r,s,a]=t.split(",").map(Number),o={x:r/16,y:s/16,z:a/16},l=o.x-e.x,c=o.z-e.z,u=Math.floor(Math.hypot(l,c));n.visible=u<=this.performanceOverrideDistance}}};Wn(ro,"REBASE_THRESHOLD",65536),Wn(ro,"NEAR_REVEAL_TIMEOUT_MS",5e3),Wn(ro,"EXPECTED_NEAR_GRACE_MS",1500);var fg=ro,PP=class{constructor(e){this.worldRendererThree=e}dispose(){A4e()}renderHead(e,t,n,r){let s;if(r.SkullOwner?s=r.SkullOwner.Properties?.textures?.[0]?.Value:s=r.profile?.properties?.find(a=>a.name==="textures")?.value,!!s)try{let o=JSON.parse(Buffer.from(s,"base64").toString()).textures?.SKIN?.url,{skinTexturesProxy:l}=this.worldRendererThree.worldRendererConfig;l&&(o=o?.replace("http://textures.minecraft.net/",l).replace("https://textures.minecraft.net/",l));let c=$c(this.worldRendererThree,o,Yc.head),u=new bt;return n&&c.position.set(0,.3125,.3125),c.position.y-=23/16,u.add(c),this.worldRendererThree.sceneOrigin.track(u),u.position.set(e.x+.5,e.y+.045,e.z+.5),u.rotation.set(0,-Ot.degToRad(t*(n?90:45/2)),0),u.scale.set(.8,.8,.8),u}catch(a){console.error("Error decoding player texture:",a)}}renderSign(e,t,n,r,s){let a=E4e(this.worldRendererThree,s,r);if(!a)return;let o=new Ke(new zn(1,1),new _t({map:a,transparent:!0}));o.renderOrder=999;let l=7/16,c=r?1.3:1;o.scale.set(1*c,l*c,1*c);let u=(r?2:1.5)/16,d=.25/16;n&&!r?o.position.set(0,0,-.5+u+d+1e-4):o.position.set(0,0,u/2+1e-4);let f=new bt;f.rotation.set(0,-Ot.degToRad(t*(n?90:45/2)),0),f.add(o),f.signTexture=a;let v=(r?10:8)/16,g=(r?0:n?4.333:9.333)/16,b=v/2+g;return this.worldRendererThree.sceneOrigin.track(f),f.position.set(e.x+.5,e.y+b,e.z+.5),f}};h();p();m();var h9=(i,e)=>e===0?1/0:e<0?h9(-i,-e):(1-(i-Math.floor(i)))/e,WYe=(i,e,t,n,r,s,a,o,l,c,u,d)=>{let f=a-u,v=o-u,g=l-u,b=a+1+u,y=o+1+u,_=l+1+u,x=m4e(i,e,t,n,r,s,f,v,g,b,y,_,c);if(x===void 0&&(x=p4e(i,e,t,n,r,s,f,v,g,b,y,_,c)),x!==void 0)return Math.max(d,x)};function k4e(i,e,t,n,r,s,a,o,l,c){if(a<=0)return;let u=Math.floor(i),d=Math.floor(e),f=Math.floor(t),v=n>0?1:n<0?-1:0,g=r>0?1:r<0?-1:0,b=s>0?1:s<0?-1:0,y=v!==0?Math.abs(1/n):1/0,_=g!==0?Math.abs(1/r):1/0,x=b!==0?Math.abs(1/s):1/0,w=v!==0?h9(i,n):1/0,S=g!==0?h9(e,r):1/0,A=b!==0?h9(t,s):1/0,T=(k,L,B)=>{if(!c(k,L,B))return;let U=WYe(i,e,t,n,r,s,k,L,B,a,o,l);if(!(U===void 0||U>a))return{distance:U,blockX:k,blockY:L,blockZ:B}},P=T(u,d,f);if(P)return P;let I=0;for(;I<=a&&(w<S?w<A?(u+=v,I=w,w+=y):(f+=b,I=A,A+=x):S<A?(d+=g,I=S,S+=_):(f+=b,I=A,A+=x),!(I>a));)if(P=T(u,d,f),P)return P}h();p();m();h();p();m();Lt();var m9={},T4e=!1;function jYe(){if(T4e)return;let i=globalThis.loadedData?.tints;if(i){for(let e of Object.keys(i))m9[e]=XYe(i[e]);T4e=!0}}function XYe(i){let e={},t=I4e(i.default??16777215);if(i.data)for(let n of i.data){let r=I4e(n.color);for(let s of n.keys)e[s]=r}return new Proxy(e,{get(n,r){return n[r]??t}})}function I4e(i){return[(i>>16&255)/255,(i>>8&255)/255,(i&255)/255]}function R4e(i,e){return jYe(),i==="grass_block"?[1,1,1]:i==="redstone_wire"?[1,1,1]:i==="birch_leaves"||i==="spruce_leaves"||i==="lily_pad"?m9.constant?.[i]??[1,1,1]:i.includes("leaves")||i==="vine"?m9.foliage?.[e]??[1,1,1]:["short_grass","tall_grass","fern","large_fern","sugar_cane","grass"].includes(i)?m9.grass?.[e]??[1,1,1]:[1,1,1]}var $Ye=512,LP=1/20,BP=class{constructor(e){this.worldRenderer=e}particles=[];sharedMaterial;enabled=!1;tickAccumulator=0;nextParticleIndex=0;enable(){this.enabled||(this.enabled=!0,this.ensureMaterial())}disable(){this.enabled&&(this.enabled=!1)}dispose(){for(let e of this.particles)e.active&&this.worldRenderer.sceneOrigin.removeAndUntrack(e.mesh),e.mesh.geometry.dispose();this.particles=[],this.sharedMaterial?.dispose(),this.sharedMaterial=void 0,this.nextParticleIndex=0}render=e=>{if(!this.enabled)return;for(this.tickAccumulator+=e;this.tickAccumulator>=LP;)this.tickAccumulator-=LP,this.tickPhysics();let t=this.tickAccumulator/LP;this.updateVisuals(t)};spawnBlockBreakParticles(e,t,n,r,s,a="plains"){if(!this.enabled)return;let o=this.resolveBlockTexture(r);if(!o)return;let l=R4e(r,a);for(let c=0;c<4;c++)for(let u=0;u<4;u++)for(let d=0;d<4;d++){let f=e+(c+.5)/4,v=t+(u+.5)/4,g=n+(d+.5)/4,b=f-e-.5,y=v-t-.5,_=g-n-.5;b+=(Math.random()*2-1)*.4,y+=(Math.random()*2-1)*.4,_+=(Math.random()*2-1)*.4;let x=(Math.random()+Math.random()+1)*.15,w=Math.sqrt(b*b+y*y+_*_),S=b/w*x*.4,A=y/w*x*.4+.1,T=_/w*x*.4,P=Math.floor(4/(Math.random()*.9+.1));this.createParticle(f,v,g,S,A,T,P,o,s,e,n,1,l)}}tickPhysics(){for(let e of this.particles){if(!e.active)continue;if(e.prevX=e.x,e.prevY=e.y,e.prevZ=e.z,e.age++,e.age>=e.maxAge){this.deactivateParticle(e);continue}e.yd-=.04,e.x+=e.xd,e.y+=e.yd,e.z+=e.zd;let t=this.getFloorY(e);e.y<=t?(e.y=t,e.yd=0,e.onGround=!0):e.onGround=!1,e.xd*=.98,e.yd*=.98,e.zd*=.98,e.onGround&&(e.xd*=.7,e.zd*=.7)}}updateVisuals(e){let t=this.worldRenderer.camera.position;for(let n of this.particles){if(!n.active)continue;let r=n.prevX+(n.x-n.prevX)*e,s=n.prevY+(n.y-n.prevY)*e,a=n.prevZ+(n.z-n.prevZ)*e;n.mesh.position.set(r,s,a),n.mesh.lookAt(t.x,t.y,t.z)}}spawnCrackParticle(e,t,n,r,s,a,o="plains"){if(!this.enabled)return;let l=this.resolveBlockTexture(s);if(!l)return;let c=R4e(s,o),u=e+Math.random()*.8+.1,d=t+Math.random()*.8+.1,f=n+Math.random()*.8+.1;switch(r){case 0:d=t-.1;break;case 1:d=t+1+.1;break;case 2:f=n-.1;break;case 3:f=n+1+.1;break;case 4:u=e-.1;break;case 5:u=e+1+.1;break}let v=(Math.random()*2-1)*.4*.2,g=(Math.random()*2-1)*.4*.2+.1*.2,b=(Math.random()*2-1)*.4*.2,y=Math.floor(4/(Math.random()*.9+.1));this.createParticle(u,d,f,v,g,b,y,l,a,e,n,.6,c)}createParticle(e,t,n,r,s,a,o,l,c,u,d,f=1,v=[1,1,1]){this.ensureMaterial();let g=this.findInactiveParticle();g||(this.particles.length<$Ye?g=this.allocateParticle():g=this.recycleOldest());let b=Math.floor(Math.random()*4),y=Math.floor(Math.random()*4),_=l.u+b/4*l.su,x=l.v+y/4*l.sv,w=l.su/4,S=l.sv/4;this.setGeometryUVs(g.mesh.geometry,_,x,w,S),g.active=!0,g.x=e,g.y=t,g.z=n,g.prevX=e,g.prevY=t,g.prevZ=n,g.xd=r,g.yd=s,g.zd=a,g.age=0,g.maxAge=o,g.onGround=!1,g.floorMap=c,g.blockX=Math.floor(u),g.blockZ=Math.floor(d);let A=.1*(.5+Math.random()*.5)*2*f;g.mesh.scale.set(A,A,A),g.mesh.position.set(e,t,n),g.mesh.visible=!0;let T=.6*v[0],P=.6*v[1],I=.6*v[2],k=new Float32Array([T,P,I,T,P,I,T,P,I,T,P,I]),L=g.mesh.geometry.getAttribute("color");L?(L.set(k),L.needsUpdate=!0):g.mesh.geometry.setAttribute("color",new Je(k,3)),this.worldRenderer.sceneOrigin.addAndTrack(g.mesh)}allocateParticle(){let e=new zn(1,1),t=new Ke(e,this.sharedMaterial);t.visible=!1;let n={mesh:t,active:!1,x:0,y:0,z:0,prevX:0,prevY:0,prevZ:0,xd:0,yd:0,zd:0,age:0,maxAge:0,onGround:!1,floorMap:[],blockX:0,blockZ:0};return this.particles.push(n),n}findInactiveParticle(){for(let e=0;e<this.particles.length;e++){let t=(this.nextParticleIndex+e)%this.particles.length;if(!this.particles[t].active)return this.nextParticleIndex=(t+1)%this.particles.length,this.particles[t]}}recycleOldest(){let e=this.particles[0];for(let t of this.particles)t.age>e.age&&(e=t);return this.deactivateParticle(e),e}deactivateParticle(e){e.active&&(e.active=!1,e.mesh.visible=!1,this.worldRenderer.sceneOrigin.removeAndUntrack(e.mesh))}getFloorY(e){let t=Math.floor(e.x)-e.blockX,n=Math.floor(e.z)-e.blockZ;return t=Math.max(-2,Math.min(2,t)),n=Math.max(-2,Math.min(2,n)),e.floorMap[(n+2)*5+(t+2)]}resolveBlockTexture(e){let t=this.worldRenderer.resourcesManager.currentResources;if(!t)return null;let n=t.blocksAtlasJson,r=n.textures;if(r[e])return this.extractUV(r[e],n);for(let s of["_side","_top","_front","_0",""]){let a=e+s;if(r[a])return this.extractUV(r[a],n)}for(let s of Object.keys(r))if(s.startsWith(e))return this.extractUV(r[s],n);return null}extractUV(e,t){return{u:e.u,v:e.v,su:e.su??t.suSv,sv:e.sv??t.suSv}}setGeometryUVs(e,t,n,r,s){let a=e.getAttribute("uv");a.setXY(0,t,n),a.setXY(1,t+r,n),a.setXY(2,t,n+s),a.setXY(3,t+r,n+s),a.needsUpdate=!0}ensureMaterial(){if(this.sharedMaterial)return;let e=this.worldRenderer.material.map;e&&(this.sharedMaterial=new _t({map:e,vertexColors:!0,transparent:!0,alphaTest:.1}))}},C4e={id:"blockBreakParticles",controller:BP,enabledDefault:!0,cannotBeDisabled:!0,requiresHeightmap:!1};h();p();m();var DP=class{constructor(e){this.worldRenderer=e}enabled=!1;lastBobWalkDist=0;lastBobTickTime=0;enable(){this.enabled=!0}disable(){this.enabled=!1,this.worldRenderer.cameraShake.setCameraBobInput(null);let{perspective:e}=this.worldRenderer.playerStateReactive;e==="first_person"&&this.worldRenderer.camera.position.set(0,0,0)}render=()=>{if(!this.enabled)return;let e=this.worldRenderer.displayOptions.inWorldRenderingConfig,{perspective:t}=this.worldRenderer.playerStateReactive;if(e.viewBobbing&&t==="first_person"&&!this.worldRenderer.playerStateUtils.isSpectator()){this.worldRenderer.playerStateReactive.walkDist!==this.lastBobWalkDist&&(this.lastBobTickTime=performance.now(),this.lastBobWalkDist=this.worldRenderer.playerStateReactive.walkDist);let r=Math.min((performance.now()-this.lastBobTickTime)/50,1);this.worldRenderer.cameraShake.setCameraBobInput({walkDist:this.worldRenderer.playerStateReactive.walkDist,prevWalkDist:this.worldRenderer.playerStateReactive.prevWalkDist,bob:this.worldRenderer.playerStateReactive.bob,prevBob:this.worldRenderer.playerStateReactive.prevBob,partialTick:r})}else this.worldRenderer.cameraShake.setCameraBobInput(null)};dispose(){this.disable()}},P4e={id:"cameraBobbing",controller:DP,enabledDefault:!0,cannotBeDisabled:!0};h();p();m();Lt();var OP=2e3,L4e=32,B4e=32,p9=12,D4e=24,v9=1.2,YYe=-5,NP=class{constructor(e){this.worldRenderer=e;this.configUnsubs.push(this.worldRenderer.onReactiveConfigUpdated("rainColor",()=>this.syncRainAppearance()),this.worldRenderer.onReactiveConfigUpdated("rainOpacity",()=>this.syncRainAppearance()))}instancedMesh;geometry;material;particles=[];enabled=!1;dummy=new Et;tempPosition=new X;tempQuaternion=new qt;tempScale=new X;configUnsubs=[];enable(){this.enabled||(this.enabled=!0,this.instancedMesh?(this.instancedMesh.visible=!0,this.syncRainAppearance()):this.createRain())}disable(){this.enabled&&(this.enabled=!1,this.instancedMesh&&(this.instancedMesh.visible=!1))}autoEnableCheck(){return this.worldRenderer.worldRendererConfig.isRaining===!0}render=e=>{if(!this.enabled||!this.instancedMesh||!this.material)return;let t=this.worldRenderer.getCameraPosition();this.instancedMesh.position.set(0,0,0);let n=this.worldRenderer.reactiveState.world.heightmaps,{dummy:r,tempPosition:s,tempQuaternion:a,tempScale:o}=this,l=NaN,c=NaN,u;for(let d=0;d<OP;d++){let f=this.particles[d];this.instancedMesh.getMatrixAt(d,r),r.decompose(s,a,o),s.addScaledVector(f.velocity,e);let v=s.y,g=Math.sqrt(s.x*s.x+s.z*s.z),b=t.x+s.x,y=t.y+s.y,_=t.z+s.z,x=Math.floor(b/16),w=Math.floor(_/16);(x!==l||w!==c)&&(u=n[`${x},${w}`],l=x,c=w);let S=(Math.floor(b)%16+16)%16,A=(Math.floor(_)%16+16)%16,T=u?.[A*16+S];if(g>L4e||T!==void 0&&T!==-32768&&y<=T+1+f.despawnOffset||v<YYe){this.respawnParticle(s);let I=p9+Math.random()*(D4e-p9);f.velocity.set((Math.random()-.5)*v9,-I,(Math.random()-.5)*v9),f.despawnOffset=Math.random()*.5}r.compose(s,a,o),this.instancedMesh.setMatrixAt(d,r)}this.instancedMesh.instanceMatrix.needsUpdate=!0};dispose(){for(let e of this.configUnsubs)e();this.configUnsubs.length=0,this.instancedMesh&&this.worldRenderer.scene.remove(this.instancedMesh),this.geometry?.dispose(),this.material?.dispose(),this.instancedMesh=void 0,this.geometry=void 0,this.material=void 0,this.particles=[]}syncRainAppearance(){if(!this.material)return;let{rainColor:e,rainOpacity:t}=this.worldRenderer.worldRendererConfig;this.material.color.set(e),this.material.opacity=Math.max(0,Math.min(1,t)),this.material.needsUpdate=!0}createRain(){let{rainColor:e,rainOpacity:t}=this.worldRenderer.worldRendererConfig;this.geometry=new Sn(.03,.3,.03),this.material=new _t({color:e,transparent:!0,opacity:Math.max(0,Math.min(1,t)),depthWrite:!0,fog:!1}),this.instancedMesh=new cl(this.geometry,this.material,OP),this.instancedMesh.name="rain-particles",this.instancedMesh.frustumCulled=!1;let n=new Et,r=new X;for(let s=0;s<OP;s++){this.respawnParticle(r),r.y=Math.random()*B4e,n.setPosition(r),this.instancedMesh.setMatrixAt(s,n);let a=p9+Math.random()*(D4e-p9);this.particles.push({velocity:new X((Math.random()-.5)*v9,-a,(Math.random()-.5)*v9),age:0,despawnOffset:Math.random()*.5})}this.instancedMesh.instanceMatrix.needsUpdate=!0,this.worldRenderer.scene.add(this.instancedMesh)}respawnParticle(e){let t=Math.random()*Math.PI*2,n=Math.random()*L4e;e.set(Math.cos(t)*n,B4e,Math.sin(t)*n)}},O4e={id:"rain",controller:NP,enabledDefault:!1,requiresHeightmap:!0};h();p();m();Lt();var N4e=new We(13/255,234/255,238/255),JYe=9,KYe=12e3,ZYe=1500,QYe=1e4,eJe=350,tJe=650,U4e=120,F4e=280,UP=class{constructor(e){this.worldRenderer=e;e.worldRendererConfig.futuristicReveal!==!0&&(this.enabled=!1)}enabled=!0;sections=new Map;completed=new Set;globalWaveStarted=!1;globalWaveStartMs=0;finishedChunkCount=0;firstQueuedMs=null;pulseTime=0;wireframeMaterial=new Pn({color:N4e,transparent:!0,opacity:1,blending:es,depthWrite:!1});wireframeGlowMaterial=new Pn({color:N4e,transparent:!0,opacity:.55,blending:es,depthWrite:!1});autoEnableCheck(){return this.worldRenderer.worldRendererConfig.futuristicReveal===!0}enable(){this.autoEnableCheck()&&this.setEnabled(!0)}disable(){this.setEnabled(!1)}dispose(){this.reset(),this.wireframeMaterial.dispose(),this.wireframeGlowMaterial.dispose()}shouldDeferSectionGeometry(e){return this.enabled&&!this.completed.has(e)}onSectionMeshed(e,t,n){let r=n.children.find(s=>s.name==="mesh");r instanceof Ke&&this.onSectionMeshedMesh(e,t,r)}onChunkFinished(){this.enabled&&(this.finishedChunkCount++,this.tryStartGlobalWave(performance.now()))}onSectionRemoved(e){this.cancelSection(e,!0),this.completed.delete(e)}onWorldSwitched(){this.reset()}tick(e,t=performance.now()){if(!this.enabled||(this.tryStartGlobalWave(t),!this.globalWaveStarted&&this.firstQueuedMs!==null&&this.sections.size>0&&t-this.firstQueuedMs>=KYe&&this.startGlobalWave(t),this.sections.size===0))return;this.pulseTime+=e*.001;let n=[];for(let r of this.sections.values()){if(t-r.phaseStartMs>QYe){n.push(r);continue}if(r.phase==="queued"){this.globalWaveStarted&&t>=r.revealAtMs&&this.beginWireframe(r,t);continue}let s=t-r.phaseStartMs;if(r.phase==="wireframe"){this.animateWireframe(r,s),s>=r.wireframeMs&&this.beginFade(r,t);continue}if(r.phase==="fade"){let a=Math.min(1,s/r.fadeMs);this.animateFade(r,a),a>=1&&n.push(r)}}for(let r of n)this.finishSection(r)}setEnabled(e){e!==this.enabled&&(this.enabled=e,e||this.forceFinishAll())}onSectionMeshedMesh(e,t,n){if(!this.enabled||!t.positions?.length||this.completed.has(e))return;let r=this.sections.get(e);if(r){r.mesh=n,r.geometry=t,(r.phase==="wireframe"||r.phase==="fade")&&this.finishSection(r);return}let s=performance.now();this.firstQueuedMs===null&&(this.firstQueuedMs=s);let a=this.globalWaveStarted;this.sections.set(e,{key:e,geometry:t,phase:"queued",phaseStartMs:s,revealAtMs:this.globalWaveStarted?s:0,wireframeMs:a?U4e:eJe,fadeMs:a?F4e:tJe,wireframeGroup:null,mesh:n,savedMaterial:null,pulseOffset:Math.random()*Math.PI*2}),n.visible=!1,this.setShaderMeshesVisible(e,!1),this.tryStartGlobalWave(s)}reset(){this.forceFinishAll(),this.sections.clear(),this.completed.clear(),this.globalWaveStarted=!1,this.globalWaveStartMs=0,this.finishedChunkCount=0,this.firstQueuedMs=null,this.pulseTime=0}forceFinishAll(){for(let e of[...this.sections.values()])this.finishSection(e);this.sections.clear(),this.unhideAllSectionMeshes()}tryStartGlobalWave(e){if(!this.globalWaveStarted&&this.sections.size!==0){if(this.finishedChunkCount>=JYe){this.startGlobalWave(e);return}this.worldRenderer.allChunksFinished&&this.startGlobalWave(e)}}startGlobalWave(e){if(this.globalWaveStarted)return;this.globalWaveStarted=!0,this.globalWaveStartMs=e;let t=this.worldRenderer.getCameraPosition(),n=1,r=new Map;for(let[s,a]of this.sections){if(a.phase!=="queued")continue;let{sx:o,sy:l,sz:c}=a.geometry,u=Math.hypot(o-t.x,l-t.y,c-t.z);r.set(s,u),n=Math.max(n,u)}for(let[,s]of this.sections){if(s.phase!=="queued")continue;let a=r.get(s.key)??0;s.revealAtMs=e+a/n*ZYe,s.wireframeMs=U4e,s.fadeMs=F4e}}beginWireframe(e,t){let n=e.mesh??this.getSectionMesh(e.key);if(e.mesh=n,!n){this.sections.delete(e.key);return}let r=this.createWireframeGeometry(e.geometry),s=new Kn(r,this.wireframeMaterial.clone());this.worldRenderer.sceneOrigin.track(s),s.position.set(e.geometry.sx,e.geometry.sy,e.geometry.sz),s.name="scifi-wireframe",s.renderOrder=1e3;let a=new Kn(r.clone(),this.wireframeGlowMaterial.clone());this.worldRenderer.sceneOrigin.track(a),a.position.copy(s.position),a.scale.setScalar(1.02),a.name="scifi-glow",a.renderOrder=999;let o=new bt;o.name="scifi-reveal-group",o.add(s,a),this.worldRenderer.realScene.add(o),n.visible=!1,this.setShaderMeshesVisible(e.key,!1),e.wireframeGroup=o,e.phase="wireframe",e.phaseStartMs=t}beginFade(e,t){let n=e.mesh??this.getSectionMesh(e.key);if(e.mesh=n,n){n.visible=!0;let r=n.material;if(!Array.isArray(r)&&r&&typeof r.clone=="function"){e.savedMaterial=r;let s=r.clone();s.transparent=!0,s.opacity=0,s.needsUpdate=!0,n.material=s}}this.setShaderMeshesVisible(e.key,!0),e.phase="fade",e.phaseStartMs=t}animateWireframe(e,t){if(!e.wireframeGroup)return;let n=e.wireframeGroup.children[0],r=e.wireframeGroup.children[1],s=.6+.4*Math.sin(this.pulseTime*4+e.pulseOffset);if(n?.material){let a=n.material;a.opacity=s;let o=.85+.15*Math.sin(this.pulseTime*6+t*.002);a.color.setRGB(13/255*o,234/255*o,238/255*o)}r?.material&&(r.material.opacity=s*.4)}animateFade(e,t){let n=1-(1-t)**3;if(e.wireframeGroup){let s=e.wireframeGroup.children[0],a=e.wireframeGroup.children[1];s?.material&&(s.material.opacity=1-n),a?.material&&(a.material.opacity=(1-n)*.55)}let r=e.mesh;r&&e.savedMaterial&&!Array.isArray(r.material)&&(r.material.opacity=n),this.setShaderMeshesVisible(e.key,n>.001)}finishSection(e){let t=e.mesh??this.getSectionMesh(e.key);if(t){if(e.savedMaterial){let r=t.material;t.material=e.savedMaterial,r.dispose(),e.savedMaterial=null}t.visible=!0}this.setShaderMeshesVisible(e.key,!0);let{chunkMeshManager:n}=this.worldRenderer;n.migrateDeferredShaderToGlobal(e.key),n.migrateDeferredLegacyToGlobal(e.key),e.wireframeGroup&&(this.disposeWireframeGroup(e.wireframeGroup),e.wireframeGroup=null),this.sections.delete(e.key),this.completed.add(e.key)}cancelSection(e,t){let n=this.sections.get(e);if(n){if(n.wireframeGroup&&this.disposeWireframeGroup(n.wireframeGroup),t){let r=n.mesh??this.getSectionMesh(e);if(r){if(n.savedMaterial){let s=r.material;r.material=n.savedMaterial,s.dispose()}r.visible=!0}this.setShaderMeshesVisible(e,!0)}this.sections.delete(e)}}getSectionMesh(e){let t=this.worldRenderer.chunkMeshManager.sectionObjects[e];if(!t)return null;let n=t.children.find(r=>r.name==="mesh");return n instanceof Ke?n:null}getShaderMesh(e){let t=this.worldRenderer.chunkMeshManager.sectionObjects[e];if(!t)return null;let n=t.children.find(r=>r.name==="shaderMesh");return n instanceof Ke?n:null}setShaderMeshesVisible(e,t){let n=this.getShaderMesh(e);n&&(n.visible=t)}unhideAllSectionMeshes(){for(let e of Object.values(this.worldRenderer.chunkMeshManager.sectionObjects))e&&e.traverse(t=>{t instanceof Ke&&(t.name==="mesh"||t.name==="shaderMesh")&&(t.visible=!0)})}disposeWireframeGroup(e){this.worldRenderer.sceneOrigin.removeAndUntrackAll(e),this.worldRenderer.realScene.remove(e),e.traverse(t=>{let n=t;n.geometry?.dispose();let r=n.material;Array.isArray(r)?r.forEach(s=>s.dispose()):r?.dispose()}),e.clear()}createWireframeGeometry(e){let t=e.positions,n=e.indices,r=[],s=new Set;for(let o=0;o<n.length;o+=3){let l=n[o],c=n[o+1],u=n[o+2];this.addEdge(t,l,c,r,s),this.addEdge(t,c,u,r,s),this.addEdge(t,u,l,r,s)}let a=new dt;return a.setAttribute("position",new Je(r,3)),a}addEdge(e,t,n,r,s){let a=Math.min(t,n),o=Math.max(t,n),l=`${a}-${o}`;s.has(l)||(s.add(l),r.push(e[t*3],e[t*3+1],e[t*3+2],e[n*3],e[n*3+1],e[n*3+2]))}},V4e={id:"futuristicReveal",controller:UP,enabledDefault:!0};h();p();m();Lt();var nJe=parseInt(Ma.replaceAll(/\D+/g,""),10),FP=class extends Xn{constructor(){super({uniforms:{time:{value:0},fade:{value:1}},vertexShader:`
|
|
29561
|
+
`,TP={u_atlas:{value:null},u_originDelta:{value:new X},u_cameraOriginFrac:{value:new X},u_skyLevel:{value:1},u_lightCurve:{value:Ri.curve},u_minBrightness:{value:Ri.minBrightness},u_lightGamma:{value:Ri.gamma}};function $_e(){return new Xn({vertexShader:kYe,fragmentShader:kP,uniforms:Gs.merge([at.fog,TP]),transparent:!0,depthWrite:!0,depthTest:!0,vertexColors:!0,glslVersion:Eo,fog:!0})}function Y_e(){return new Xn({vertexShader:X_e,fragmentShader:kP,uniforms:Gs.merge([at.fog,TP]),transparent:!1,depthWrite:!0,depthTest:!0,vertexColors:!0,glslVersion:Eo,fog:!0})}function J_e(){return new Xn({vertexShader:X_e,fragmentShader:kP,uniforms:Gs.merge([at.fog,TP]),transparent:!0,depthWrite:!0,depthTest:!0,vertexColors:!0,glslVersion:Eo,fog:!0})}function i9(i,e,t,n,r){let{originDelta:s,cameraOriginFrac:a}=$d(e,t,n,r),o=i.uniforms.u_originDelta;o?.value?.set&&o.value.set(s.x,s.y,s.z);let l=i.uniforms.u_cameraOriginFrac;l?.value?.set&&l.value.set(a.x,a.y,a.z)}function s9(i,e){let t=i.uniforms.u_skyLevel;t&&(t.value=e)}function a9(i,e){if(e.curve!==void 0){let t=i.uniforms.u_lightCurve;t&&(t.value=e.curve)}if(e.minBrightness!==void 0){let t=i.uniforms.u_minBrightness;t&&(t.value=e.minBrightness)}if(e.gamma!==void 0){let t=i.uniforms.u_lightGamma;t&&(t.value=e.gamma)}}h();p();m();var TYe=8,IYe=.01;function IP(i,e,t,n,r){i.matrix.makeTranslation(e-r.x,t-r.y,n-r.z),i.matrixWorldNeedsUpdate=!0,i.frustumCulled=!1}function o9(i,e,t,n,r,s,a,o,l,c){let u=i-n,d=e-r,f=t-s,v=TYe+IYe;return l.set(u-v,d-v,f-v),c.set(u+v,d+v,f+v),o.set(l,c),{visible:a.intersectsBox(o),distSq:u*u+d*d+f*f}}function K_e(i,e,t,n,r,s,a,o,l,c,u){let{visible:d,distSq:f}=o9(e,t,n,r,s,a,o,l,c,u);i.visible=d,i.renderOrder=-f}EP();h();p();m();Lt();h();p();m();h();p();m();h();p();m();Lt();h();p();m();function Q_e(){return{counts:new Int32Array(c0),offsets:new Int32Array(c0)}}function RYe(i,e){if(i.counts.length>=e)return;let t=i.counts.length;for(;t<e;)t*=2;i.counts=new Int32Array(t),i.offsets=new Int32Array(t)}function e4e(i){let e=i.getExtension("WEBGL_multi_draw");return e?{tier:"A",ext:e}:{tier:"B",ext:null}}var Z_e=!1;function t4e(i,e){Z_e||!e||(Z_e=!0,console.info("[globalLegacyBuffer] legacy multi_draw tier",i))}function n4e(i,e,t,n){let r=t.length;if(r===0)return;RYe(n,r);let s=i.TRIANGLES,a=i.UNSIGNED_INT;for(let o=0;o<r;o++){let l=t[o];n.counts[o]=l.indexCount,n.offsets[o]=l.indexStart*4}if(e.tier==="A"&&e.ext){e.ext.multiDrawElementsWEBGL(s,n.counts,0,a,n.offsets,0,r);return}for(let o=0;o<r;o++)i.drawElements(s,n.counts[o],a,n.offsets[o])}var Ci=4,Tr=6,Cn=3,Us=2,Ir=1,CYe=128e3,PYe=128e3,r4e=5e3,LYe=.25,i4e=Ci*(Cn*3+Ir*2+Us)*4+Tr*4,RP=.75,c0=64;function CP(i,e,t){for(let n of i)for(let r=n.start;r<n.start+n.count;r++){let s=!1;for(let a of e)if(r>=a.start&&r<a.start+a.count){s=!0;break}s||console.error("[GlobalLegacyBuffer] draw span covers non-live quad",{buffer:t,quad:r,span:n,liveRanges:e})}}function l9(i,e){if(e.length===0)return i;let t=[];for(let n of i){let r=[n];for(let s of e){let a=[];for(let o of r){let l=o.start+o.count-1;if(s.end<o.start||s.start>l){a.push(o);continue}s.start>o.start&&a.push({start:o.start,count:s.start-o.start}),s.end<l&&a.push({start:s.end+1,count:l-s.end})}r=a}t.push(...r)}return t.filter(n=>n.count>0)}var ug=class{mesh;material;growthIncrementQuads;capacityQuads;positions;colors;skyLights;blockLights;uvs;aOrigin;indices;sectionSlots=new Map;freeList=[];highWatermark=0;pendingRanges=[];_spanScratch=[];renderOrigin={x:0,y:0,z:0};layoutVersion=0;pendingMove=null;pendingReplace=new Map;uploadEpoch=0;visibleIndexSpans=[];_drawScratch=Q_e();multiDrawCaps=null;debugOverlay=!1;constructor(e,t,n){this.material=e,this.growthIncrementQuads=n?.growthIncrementQuads??PYe,this.capacityQuads=n?.initialCapacityQuads??CYe;let r=this.capacityQuads*Ci;this.positions=new Float32Array(r*Cn),this.colors=new Float32Array(r*Cn),this.skyLights=new Float32Array(r*Ir),this.blockLights=new Float32Array(r*Ir),this.uvs=new Float32Array(r*Us),this.aOrigin=new Float32Array(r*Cn),this.indices=new Uint32Array(this.capacityQuads*Tr);let s=new dt,a=(l,c,u)=>{let d=new Mt(l,c);return d.setUsage(So),s.setAttribute(u,d),d};a(this.positions,Cn,"position"),a(this.colors,Cn,"color"),a(this.skyLights,Ir,"a_skyLight"),a(this.blockLights,Ir,"a_blockLight"),a(this.uvs,Us,"uv"),a(this.aOrigin,Cn,"a_origin");let o=new Mt(this.indices,1);o.setUsage(So),s.setIndex(o),s.setDrawRange(0,0),s.boundingSphere=new Tn(new X,1/0),this.mesh=new Ke(s,[e]),this.mesh.name=n?.name??"globalLegacyOpaque",this.mesh.frustumCulled=!1,this.mesh.matrixAutoUpdate=!1,this.mesh.matrix.identity(),this.mesh.position.set(0,0,0),t.add(this.mesh),this.syncDefaultDrawGroups(),this.mesh.onAfterRender=(l,c,u,d,f)=>{if(this.visibleIndexSpans.length===0)return;let v=l.getContext();this.multiDrawCaps||(this.multiDrawCaps=e4e(v),t4e(this.multiDrawCaps.tier,this.debugOverlay)),n4e(v,this.multiDrawCaps,this.visibleIndexSpans,this._drawScratch)}}setDebugOverlay(e){this.debugOverlay=e}suppressThreeDraw(){this.mesh.geometry.setDrawRange(0,3)}setVisibleIndexSpans(e){this.visibleIndexSpans=e}getVisibleIndexSpans(){return this.visibleIndexSpans}syncDefaultDrawGroups(){let e=this.mesh.geometry;e.clearGroups();let t=this.highWatermark*Tr;t>0&&e.addGroup(0,t,0),e.setDrawRange(0,t)}addSection(e,t,n,r,s){let a=t.positions.length/Cn,o=a/Ci;if(a===0||o*Ci!==a)return this.removeSection(e),!1;if(t.indices.length%Tr!==0||t.indices.length/Tr!==o)return!1;let l=this.sectionSlots.has(e),c;if(l){let A=this.sectionSlots.get(e),T=this.pendingReplace.get(e),P=this.pendingMove?.key===e?this.pendingMove:void 0;T?(this.zeroAndFreeSlot(A.start,A.count),c={start:T.oldStart,count:T.oldCount},this.pendingReplace.delete(e)):P?(this.zeroAndFreeSlot(A.start,A.count),c={start:P.oldStart,count:P.count},this.pendingMove=null):c=A}o>this.capacityQuads&&this.growCapacity(o);let u=this.takeFreeSlot(o);u||(this.highWatermark+o>this.capacityQuads&&this.growCapacity(this.highWatermark+o),u={start:this.highWatermark,count:o},this.highWatermark+=o);let d=u.start*Ci,f=d*Cn,v=d*Us,g=d*Ir;this.positions.set(t.positions,f),this.colors.set(t.colors,f),this.skyLights.set(t.skyLights,g),this.blockLights.set(t.blockLights,g),this.uvs.set(t.uvs,v);let b=f,y=n-this.renderOrigin.x,_=r-this.renderOrigin.y,x=s-this.renderOrigin.z;for(let A=0;A<a;A++){let T=b+A*Cn;this.aOrigin[T]=y,this.aOrigin[T+1]=_,this.aOrigin[T+2]=x}let w=u.start*Tr,S=d;for(let A=0;A<t.indices.length;A++)this.indices[w+A]=t.indices[A]+S;return this.sectionSlots.set(e,u),l&&c&&this.pendingReplace.set(e,{oldStart:c.start,oldCount:c.count}),this.markDirty(u.start,u.start+o-1),this.syncDefaultDrawGroups(),this.layoutVersion++,!0}getLayoutVersion(){return this.layoutVersion}getUploadEpoch(){return this.uploadEpoch}hasPendingReplace(){return this.pendingReplace.size>0}canUseFullDrawShortcut(){return this.pendingRanges.length===0&&this.interiorFreeQuads()===0&&this.pendingMove===null&&this.pendingReplace.size===0}isRangeFullyUploaded(e,t){return this.rangeFullyUploaded(e,t)}getPendingDirtyRanges(){return this.pendingRanges}getSectionDrawStart(e){let t=this.sectionSlots.get(e);if(!t)return;if(this.pendingMove?.key===e)return this.pendingMove.oldStart;let n=this.pendingReplace.get(e);if(n)return n.oldStart;if(this.rangeFullyUploaded(t.start,t.start+t.count-1))return t.start}getSectionDrawCount(e){let t=this.sectionSlots.get(e);if(!t)return;if(this.pendingMove?.key===e)return this.pendingMove.count;let n=this.pendingReplace.get(e);if(n)return n.oldCount;if(this.rangeFullyUploaded(t.start,t.start+t.count-1))return t.count}getPendingMove(){return this.pendingMove}compactStep(){if(this.pendingMove){let{newStart:o,count:l}=this.pendingMove;this.rangeFullyUploaded(o,o+l-1)&&this.finalizePendingMove();return}for(let o of[...this.pendingReplace.keys()]){let l=this.sectionSlots.get(o);l&&this.rangeFullyUploaded(l.start,l.start+l.count-1)&&this.finalizePendingReplace(o)}if(this.highWatermark===0||this.interiorFreeQuads()/this.highWatermark<=LYe)return;let t=this.findMovableSection(r4e);if(!t)return;let n=this.findLowestInteriorHole(t.start,t.count);if(!n)return;let r=this.reserveFreeSlotAt(n.index,t.count),s=t.start,a=r.start;this.copySectionRange(s,a,t.count),this.sectionSlots.set(t.key,{start:a,count:t.count}),this.markDirty(a,a+t.count-1),this.pendingMove={key:t.key,oldStart:s,newStart:a,count:t.count},this.layoutVersion++}updateDrawSpans(e,t){if(this.visibleIndexSpans=[],this.highWatermark===0)return;let n=this._spanScratch;n.length=0;let r=0;for(let a of e){let o=this.getSectionDrawStart(a.key),l=this.getSectionDrawCount(a.key),c=this.sectionSlots.get(a.key);o===void 0||l===void 0||!c||(n.push({start:o,count:l}),r+=l)}if(n.length===0)return;let s=(a,o)=>{this.visibleIndexSpans.push({indexStart:a*Tr,indexCount:o*Tr})};if(t==="opaque"){let a,o=n.map(c=>({...c})),l=this.canUseFullDrawShortcut()&&r>=this.highWatermark*RP;l?a=[{start:0,count:this.highWatermark}]:(n.sort((c,u)=>c.start-u.start),this.mergeOpaqueSpans(n),a=n),a=l9(a,this.pendingRanges),l||CP(a,o,this.mesh.name);for(let c of a)s(c.start,c.count)}else{e.sort((a,o)=>o.distSq-a.distSq);for(let a of e){let o=this.getSectionDrawStart(a.key),l=this.getSectionDrawCount(a.key);o===void 0||l===void 0||s(o,l)}}}mergeOpaqueSpans(e){if(e.length<2)return;let t=0;for(;t<e.length-1;){let n=e[t],r=e[t+1];n.start+n.count===r.start?(n.count=r.start+r.count-n.start,e.splice(t+1,1)):t++}}hasSection(e){return this.sectionSlots.has(e)}getSectionSlot(e){return this.sectionSlots.get(e)}takeSectionData(e){let t=this.getSectionGeometryData(e);if(t)return this.removeSection(e),t}getSectionGeometryData(e){let t=this.sectionSlots.get(e);if(!t)return;let n=t.count*Ci,r=t.start*Ci,s=r*Cn,a=r*Us,o=t.start*Tr,l=t.count*Tr,c=r*Ir,u=this.positions.slice(s,s+n*Cn),d=this.colors.slice(s,s+n*Cn),f=this.skyLights.slice(c,c+n*Ir),v=this.blockLights.slice(c,c+n*Ir),g=this.uvs.slice(a,a+n*Us),b=this.indices.slice(o,o+l),y=r;for(let S=0;S<b.length;S++)b[S]=b[S]-y;let _=this.aOrigin[s]+this.renderOrigin.x,x=this.aOrigin[s+1]+this.renderOrigin.y,w=this.aOrigin[s+2]+this.renderOrigin.z;return{positions:u,colors:d,skyLights:f,blockLights:v,uvs:g,indices:b,sx:_,sy:x,sz:w}}removeSection(e){let t=this.sectionSlots.get(e);if(!t)return;if(this.pendingReplace.has(e)){let s=this.pendingReplace.get(e);this.zeroAndFreeSlot(s.oldStart,s.oldCount),this.pendingReplace.delete(e)}if(this.pendingMove?.key===e){let{oldStart:s,count:a}=this.pendingMove;this.zeroAndFreeSlot(s,a),this.pendingMove=null}let n=t.start*Tr,r=t.count*Tr;for(let s=0;s<r;s++)this.indices[n+s]=0;this.markDirty(t.start,t.start+t.count-1),this.sectionSlots.delete(e),this.insertFreeSlot(t),this.shrinkHighWatermark(),this.syncDefaultDrawGroups(),this.layoutVersion++}hasPendingUploads(){return this.pendingRanges.length>0}uploadDirtyRange(){let e=this.pendingRanges[0];if(!e)return;let t=e.start,n=Math.min(e.end-e.start+1,r4e),r=t*Ci,s=n*Ci,a=t*Tr,o=n*Tr,l=this.mesh.geometry,c=l.getAttribute("position");c.clearUpdateRanges(),c.addUpdateRange(r*Cn,s*Cn),c.needsUpdate=!0;let u=l.getAttribute("color");u.clearUpdateRanges(),u.addUpdateRange(r*Cn,s*Cn),u.needsUpdate=!0;let d=l.getAttribute("a_skyLight");d.clearUpdateRanges(),d.addUpdateRange(r*Ir,s*Ir),d.needsUpdate=!0;let f=l.getAttribute("a_blockLight");f.clearUpdateRanges(),f.addUpdateRange(r*Ir,s*Ir),f.needsUpdate=!0;let v=l.getAttribute("uv");v.clearUpdateRanges(),v.addUpdateRange(r*Us,s*Us),v.needsUpdate=!0;let g=l.getAttribute("a_origin");g.clearUpdateRanges(),g.addUpdateRange(r*Cn,s*Cn),g.needsUpdate=!0;let b=l.index;b.clearUpdateRanges(),b.addUpdateRange(a,o),b.needsUpdate=!0,t+n>e.end?this.pendingRanges.shift():e.start=t+n,this.uploadEpoch++}setRenderOrigin(e){this.renderOrigin={...e}}rebase(e){if(this.highWatermark!==0){for(let t of this.sectionSlots.values()){let n=t.start*Ci,r=t.count*Ci,s=n*Cn;for(let a=0;a<r;a++){let o=s+a*Cn;this.aOrigin[o]-=e.x,this.aOrigin[o+1]-=e.y,this.aOrigin[o+2]-=e.z}}this.markDirty(0,this.highWatermark-1),this.renderOrigin.x+=e.x,this.renderOrigin.y+=e.y,this.renderOrigin.z+=e.z}}setCameraOrigin(e,t,n){let{originDelta:r,cameraOriginFrac:s}=$d(this.renderOrigin,e,t,n),a=this.material.uniforms.u_originDelta;a?.value?.set&&a.value.set(r.x,r.y,r.z);let o=this.material.uniforms.u_cameraOriginFrac;o?.value?.set&&o.value.set(s.x,s.y,s.z)}getHighWatermark(){return this.highWatermark}getCapacityQuads(){return this.capacityQuads}getSectionCount(){return this.sectionSlots.size}getMemoryBytes(){return this.capacityQuads*i4e}getUsedMemoryBytes(){return this.highWatermark*i4e}reset(){this.sectionSlots.clear(),this.freeList.length=0,this.highWatermark=0,this.pendingRanges.length=0,this.pendingMove=null,this.pendingReplace.clear(),this.uploadEpoch=0,this.visibleIndexSpans=[],this.syncDefaultDrawGroups()}dispose(){this.mesh.parent?.remove(this.mesh),this.mesh.geometry.dispose(),this.reset()}markDirty(e,t){this.pendingRanges.push({start:e,end:t}),this.pendingRanges.sort((n,r)=>n.start-r.start),this.mergePendingRanges()}mergePendingRanges(){if(this.pendingRanges.length<2)return;let e=[],t=this.pendingRanges[0];for(let n=1;n<this.pendingRanges.length;n++){let r=this.pendingRanges[n];r.start<=t.end+1?t={start:t.start,end:Math.max(t.end,r.end)}:(e.push(t),t=r)}e.push(t),this.pendingRanges=e}takeFreeSlot(e){for(let t=0;t<this.freeList.length;t++){let n=this.freeList[t];if(n.count>=e){if(this.freeList.splice(t,1),n.count===e)return n;let r={start:n.start,count:e};return this.insertFreeSlot({start:n.start+e,count:n.count-e}),r}}}insertFreeSlot(e){this.freeList.push(e),this.freeList.sort((t,n)=>t.start-n.start),this.mergeFreeList()}mergeFreeList(){if(this.freeList.length<2)return;let e=[],t=this.freeList[0];for(let n=1;n<this.freeList.length;n++){let r=this.freeList[n];t.start+t.count===r.start?t={start:t.start,count:t.count+r.count}:(e.push(t),t=r)}e.push(t),this.freeList=e}shrinkHighWatermark(){for(;this.highWatermark>0;){let e=this.highWatermark-1,t=this.freeList.find(r=>r.start<=e&&r.start+r.count>e);if(!t||t.start+t.count!==this.highWatermark)break;this.highWatermark=t.start;let n=this.freeList.indexOf(t);this.freeList.splice(n,1)}}interiorFreeQuads(){let e=0;for(let t of this.freeList)t.start<this.highWatermark&&(e+=t.count);return e}findMovableSection(e){let t=[];for(let[s,a]of this.sectionSlots)t.push({key:s,start:a.start,count:a.count});if(t.length===0)return;t.sort((s,a)=>a.start!==s.start?a.start-s.start:a.start+a.count-(s.start+s.count));let n=t[0];if(n.count<=e&&this.findLowestInteriorHole(n.start,n.count))return n;let r=t.filter(s=>s.count<=e).sort((s,a)=>a.count-s.count);for(let s of r)if(this.findLowestInteriorHole(s.start,s.count))return s}findLowestInteriorHole(e,t){for(let n=0;n<this.freeList.length;n++){let r=this.freeList[n];if(r.start<e&&r.count>=t)return{start:r.start,count:r.count,index:n}}}reserveFreeSlotAt(e,t){let n=this.freeList[e];if(this.freeList.splice(e,1),n.count===t)return{start:n.start,count:t};let r={start:n.start,count:t};return this.insertFreeSlot({start:n.start+t,count:n.count-t}),r}copySectionRange(e,t,n){let r=e*Ci,s=t*Ci,a=n*Ci,o=s-r,l=r*Cn,c=s*Cn,u=a*Cn;this.positions.copyWithin(c,l,l+u),this.colors.copyWithin(c,l,l+u),this.aOrigin.copyWithin(c,l,l+u);let d=r*Ir,f=s*Ir,v=a*Ir;this.skyLights.copyWithin(f,d,d+v),this.blockLights.copyWithin(f,d,d+v);let g=r*Us,b=s*Us,y=a*Us;this.uvs.copyWithin(b,g,g+y);let _=e*Tr,x=t*Tr,w=n*Tr;for(let S=0;S<w;S++)this.indices[x+S]=this.indices[_+S]+o}rangeFullyUploaded(e,t){for(let n of this.pendingRanges)if(n.start<=t&&n.end>=e)return!1;return!0}zeroAndFreeSlot(e,t){let n=e*Tr,r=t*Tr;for(let s=0;s<r;s++)this.indices[n+s]=0;this.markDirty(e,e+t-1),this.insertFreeSlot({start:e,count:t})}finalizePendingReplace(e){let t=this.pendingReplace.get(e);t&&(this.zeroAndFreeSlot(t.oldStart,t.oldCount),this.pendingReplace.delete(e),this.shrinkHighWatermark(),this.syncDefaultDrawGroups(),this.layoutVersion++,this.uploadEpoch++)}finalizePendingMove(){let e=this.pendingMove;if(!e)return;let{oldStart:t,count:n}=e;this.zeroAndFreeSlot(t,n),this.shrinkHighWatermark(),this.syncDefaultDrawGroups(),this.pendingMove=null,this.layoutVersion++,this.uploadEpoch++}growCapacity(e){this.pendingMove&&this.finalizePendingMove();for(let y of[...this.pendingReplace.keys()])this.finalizePendingReplace(y);let t=this.capacityQuads;for(;t<e;)t+=this.growthIncrementQuads;let n=this.capacityQuads*Ci,r=t*Ci,s=new Float32Array(r*Cn),a=new Float32Array(r*Cn),o=new Float32Array(r*Ir),l=new Float32Array(r*Ir),c=new Float32Array(r*Us),u=new Float32Array(r*Cn),d=new Uint32Array(t*Tr);s.set(this.positions),a.set(this.colors),o.set(this.skyLights),l.set(this.blockLights),c.set(this.uvs),u.set(this.aOrigin),d.set(this.indices),this.positions=s,this.colors=a,this.skyLights=o,this.blockLights=l,this.uvs=c,this.aOrigin=u,this.indices=d,this.capacityQuads=t;let f=this.mesh.geometry,v=(y,_,x)=>{f.getAttribute(x)&&f.deleteAttribute(x);let S=new Mt(y,_);S.setUsage(So),f.setAttribute(x,S)};v(this.positions,Cn,"position"),v(this.colors,Cn,"color"),v(this.skyLights,Ir,"a_skyLight"),v(this.blockLights,Ir,"a_blockLight"),v(this.uvs,Us,"uv"),v(this.aOrigin,Cn,"a_origin"),f.index&&f.setIndex(null);let b=new Mt(this.indices,1);b.setUsage(So),f.setIndex(b),this.pendingRanges.length=0}};function BYe(i){if(i.length<2)return;let e=0;for(;e<i.length-1;){let t=i[e],n=i[e+1];t.start+t.count===n.start?(t.count=n.start+n.count-t.start,i.splice(e+1,1)):e++}}function s4e(i,e,t=!0,n,r=[]){if(i.length===0||e===0)return[];let s=0;for(let l of i)s+=l.count;let a;if(t&&s>=e*RP)a=[{start:0,count:e}];else{a=i.map(c=>({start:c.start,count:c.count})),a.sort((c,u)=>c.start-u.start);let l=a.map(c=>({...c}));return BYe(a),a=l9(a,r),CP(a,l,"globalBlockBuffer"),a}return l9(a,r)}Kc();function o4e(){return{firsts:new Int32Array(c0),counts:new Int32Array(c0),instanceCounts:new Int32Array(c0),baseInstances:new Int32Array(c0)}}function l4e(i){let e=i.getExtension("WEBGL_multi_draw_instanced_base_vertex_base_instance");if(e)return{tier:"A",ext:e};let t=i.getExtension("WEBGL_draw_instanced_base_vertex_base_instance");return t?{tier:"B",ext:t}:{tier:"C",ext:null}}var a4e=!1;function c4e(i,e){a4e||!e||(a4e=!0,console.info("[globalBlockBuffer] cube multi_draw tier",i))}function u4e(i,e,t,n,r){let s=t.length;if(s===0)return;let a=i.TRIANGLES;if(e.tier==="A"&&e.ext){let o=e.ext;for(let l=0;l<s;l++){let c=t[l];n.firsts[l]=0,n.counts[l]=l0,n.instanceCounts[l]=c.count,n.baseInstances[l]=c.start}o.multiDrawArraysInstancedBaseInstanceWEBGL(a,n.firsts,0,n.counts,0,n.instanceCounts,0,n.baseInstances,0,s);return}if(e.tier==="B"&&e.ext){let o=e.ext;for(let l=0;l<s;l++){let c=t[l];o.drawArraysInstancedBaseInstanceWEBGL(a,0,l0,c.count,c.start)}return}r?.(i,t)}Kc();z5();var DYe=512e3,OYe=1e6,d4e=15e3,NYe=.25,dg=F_e(),f4e=16,c9=class{mesh;capacityFaces;w0;w1;w2;w3;sectionSlots=new Map;freeList=[];highWatermark=0;pendingRanges=[];pendingMove=null;pendingReplace=new Map;uploadEpoch=0;visibleSpans=[];_drawScratch=o4e();multiDrawCaps=null;tierCVao=null;tierCAttrs=null;tierCGl=null;debugOverlay=!1;layoutVersion=0;constructor(e,t){this.capacityFaces=DYe,this.w0=new Uint32Array(this.capacityFaces),this.w1=new Uint32Array(this.capacityFaces),this.w2=new Uint32Array(this.capacityFaces),this.w3=new Uint32Array(this.capacityFaces),this.w2.fill(dg);let n=new Sa,r=new Float32Array(l0*3);n.setAttribute("position",new Mt(r,3));let s=a=>{let o=new Ar(a,1);return o.setUsage(So),o};n.setAttribute("a_w0",s(this.w0)),n.setAttribute("a_w1",s(this.w1)),n.setAttribute("a_w2",s(this.w2)),n.setAttribute("a_w3",s(this.w3)),n.instanceCount=0,this.mesh=new Ke(n,e),this.mesh.name="globalShaderCubes",this.mesh.frustumCulled=!1,this.mesh.matrixAutoUpdate=!1,this.mesh.matrix.identity(),this.mesh.position.set(0,0,0),t.add(this.mesh),this.mesh.onAfterRender=(a,o,l,c,u)=>{if(this.visibleSpans.length===0)return;let d=u,f=a.getContext();this.multiDrawCaps||(this.multiDrawCaps=l4e(f),c4e(this.multiDrawCaps.tier,this.debugOverlay)),u4e(f,this.multiDrawCaps,this.visibleSpans,this._drawScratch,this.multiDrawCaps.tier==="C"?(v,g)=>this.drawTierCSpans(v,g,a,d):void 0)}}setDebugOverlay(e){this.debugOverlay=e}suppressThreeDraw(){let e=this.mesh.geometry;e.setDrawRange(0,l0),e.instanceCount=0}setVisibleSpans(e){this.visibleSpans=e}getVisibleSpans(){return this.visibleSpans}forEachSectionSlot(e){for(let[t,n]of this.sectionSlots)e(t,n)}getSectionDrawStart(e){let t=this.sectionSlots.get(e);if(!t)return;if(this.pendingMove?.key===e)return this.pendingMove.oldStart;let n=this.pendingReplace.get(e);if(n)return n.oldStart;if(this.rangeFullyUploaded(t.start,t.start+t.count-1))return t.start}getSectionDrawCount(e){let t=this.sectionSlots.get(e);if(!t)return;if(this.pendingMove?.key===e)return this.pendingMove.count;let n=this.pendingReplace.get(e);if(n)return n.oldCount;if(this.rangeFullyUploaded(t.start,t.start+t.count-1))return t.count}getUploadEpoch(){return this.uploadEpoch}hasPendingReplace(){return this.pendingReplace.size>0}canUseFullDrawShortcut(){return this.pendingRanges.length===0&&this.interiorFreeFaces()===0&&this.pendingMove===null&&this.pendingReplace.size===0}isRangeFullyUploaded(e,t){return this.rangeFullyUploaded(e,t)}getPendingDirtyRanges(){return this.pendingRanges}getHighWatermark(){return this.highWatermark}getCapacityFaces(){return this.capacityFaces}getSectionCount(){return this.sectionSlots.size}getMemoryBytes(){return this.capacityFaces*f4e}getUsedMemoryBytes(){return this.highWatermark*f4e}hasPendingUploads(){return this.pendingRanges.length>0}getPendingMove(){return this.pendingMove}addSection(e,t,n){if(n<=0){this.removeSection(e);return}let r=this.sectionSlots.has(e),s;if(r){let l=this.sectionSlots.get(e),c=this.pendingReplace.get(e),u=this.pendingMove?.key===e?this.pendingMove:void 0;c?(this.zeroAndFreeSlot(l.start,l.count),s={start:c.oldStart,count:c.oldCount},this.pendingReplace.delete(e)):u?(this.zeroAndFreeSlot(l.start,l.count),s={start:u.oldStart,count:u.count},this.pendingMove=null):s=l}n>this.capacityFaces&&this.growCapacity(n);let a=this.takeFreeSlot(n);a||(this.highWatermark+n>this.capacityFaces&&this.growCapacity(this.highWatermark+n),a={start:this.highWatermark,count:n},this.highWatermark+=n);let o=4;for(let l=0;l<n;l++){let c=a.start+l,u=l*o;this.w0[c]=t[u],this.w1[c]=t[u+1],this.w2[c]=t[u+2],this.w3[c]=t[u+3]}this.sectionSlots.set(e,a),r&&s&&this.pendingReplace.set(e,{oldStart:s.start,oldCount:s.count}),this.markDirty(a.start,a.start+n-1),this.mesh.geometry.instanceCount=this.highWatermark,this.layoutVersion++}getLayoutVersion(){return this.layoutVersion}hasSection(e){return this.sectionSlots.has(e)}getSectionSlot(e){return this.sectionSlots.get(e)}getW0(){return this.w0}takeSectionData(e){let t=this.sectionSlots.get(e);if(!t)return;let n=4,r=new Uint32Array(t.count*n);for(let s=0;s<t.count;s++){let a=t.start+s,o=s*n;r[o]=this.w0[a],r[o+1]=this.w1[a],r[o+2]=this.w2[a],r[o+3]=this.w3[a]}return this.removeSection(e),{words:r,count:t.count}}removeSection(e){let t=this.sectionSlots.get(e);if(t){if(this.pendingReplace.has(e)){let n=this.pendingReplace.get(e);this.zeroAndFreeSlot(n.oldStart,n.oldCount),this.pendingReplace.delete(e)}if(this.pendingMove?.key===e){let{oldStart:n,count:r}=this.pendingMove;this.zeroAndFreeSlot(n,r),this.pendingMove=null}for(let n=t.start;n<t.start+t.count;n++)this.w0[n]=0,this.w1[n]=0,this.w2[n]=dg,this.w3[n]=0;this.markDirty(t.start,t.start+t.count-1),this.sectionSlots.delete(e),this.insertFreeSlot(t),this.shrinkHighWatermark(),this.mesh.geometry.instanceCount=this.highWatermark,this.layoutVersion++}}compactStep(){if(this.pendingMove){let{newStart:o,count:l}=this.pendingMove;this.rangeFullyUploaded(o,o+l-1)&&this.finalizePendingMove();return}for(let o of[...this.pendingReplace.keys()]){let l=this.sectionSlots.get(o);l&&this.rangeFullyUploaded(l.start,l.start+l.count-1)&&this.finalizePendingReplace(o)}if(this.highWatermark===0||this.interiorFreeFaces()/this.highWatermark<=NYe)return;let t=this.findMovableSection(d4e);if(!t)return;let n=this.findLowestInteriorHole(t.start,t.count);if(!n)return;let r=this.reserveFreeSlotAt(n.index,t.count),s=t.start,a=r.start;this.copySectionRange(s,a,t.count),this.sectionSlots.set(t.key,{start:a,count:t.count}),this.markDirty(a,a+t.count-1),this.pendingMove={key:t.key,oldStart:s,newStart:a,count:t.count},this.layoutVersion++}uploadDirtyRange(){let e=this.pendingRanges[0];if(!e)return;let t=e.start,n=Math.min(e.end-e.start+1,d4e),r=this.mesh.geometry;for(let s of["a_w0","a_w1","a_w2","a_w3"]){let a=r.getAttribute(s);a.clearUpdateRanges(),a.addUpdateRange(t,n),a.needsUpdate=!0}t+n>e.end?this.pendingRanges.shift():e.start=t+n,this.uploadEpoch++}setCameraOrigin(e,t,n,r){let{originDelta:s,cameraOriginFrac:a}=$d(e,t,n,r),o=Kb(e),l=this.mesh.material.uniforms.u_originDelta;l?.value?.set&&l.value.set(s.x,s.y,s.z);let c=this.mesh.material.uniforms.u_cameraOriginFrac;c?.value?.set&&c.value.set(a.x,a.y,a.z);let u=this.mesh.material.uniforms.u_sectionOriginRel;u?.value?.set&&u.value.set(o.x,o.y,o.z)}reset(){this.sectionSlots.clear(),this.freeList.length=0,this.highWatermark=0,this.pendingRanges.length=0,this.pendingMove=null,this.pendingReplace.clear(),this.uploadEpoch=0,this.visibleSpans=[],this.w0.fill(0),this.w1.fill(0),this.w2.fill(dg),this.w3.fill(0),this.mesh.geometry.instanceCount=0,this.invalidateTierCVao()}dispose(){this.invalidateTierCVao(),this.mesh.parent?.remove(this.mesh),this.mesh.geometry.dispose(),this.reset()}invalidateTierCVao(){this.tierCVao&&this.tierCGl&&this.tierCGl.deleteVertexArray(this.tierCVao),this.tierCVao=null,this.tierCAttrs=null}drawTierCSpans(e,t,n,r){if(this.ensureTierCVao(e,n,r),!this.tierCVao||!this.tierCAttrs)return;let s=this.tierCAttrs;e.bindVertexArray(this.tierCVao);for(let a of t){let o=a.start*4,l=c=>{e.bindBuffer(e.ARRAY_BUFFER,c.buffer),e.vertexAttribIPointer(c.loc,1,e.UNSIGNED_INT,4,o)};l(s.w0),l(s.w1),l(s.w2),l(s.w3),e.drawArraysInstanced(e.TRIANGLES,0,l0,a.count)}e.bindVertexArray(null)}ensureTierCVao(e,t,n){this.tierCGl=e;let a=t.properties.get(n).currentProgram.program,o=e.getAttribLocation(a,"a_w0"),l=e.getAttribLocation(a,"a_w1"),c=e.getAttribLocation(a,"a_w2"),u=e.getAttribLocation(a,"a_w3"),d=w=>w<0?null:e.getVertexAttrib(w,e.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING),f=d(o);if(this.tierCVao&&this.tierCAttrs&&f&&this.tierCAttrs.w0.buffer!==f&&this.invalidateTierCVao(),this.tierCVao)return;let v=d(o),g=d(l),b=d(c),y=d(u);if(!v||!g||!b||!y)return;let _=e.createVertexArray();if(!_)return;e.bindVertexArray(_);let x=(w,S)=>{e.enableVertexAttribArray(w),e.bindBuffer(e.ARRAY_BUFFER,S),e.vertexAttribIPointer(w,1,e.UNSIGNED_INT,4,0),e.vertexAttribDivisor(w,1)};x(o,v),x(l,g),x(c,b),x(u,y),e.bindVertexArray(null),this.tierCVao=_,this.tierCAttrs={w0:{loc:o,buffer:v},w1:{loc:l,buffer:g},w2:{loc:c,buffer:b},w3:{loc:u,buffer:y}}}markDirty(e,t){this.pendingRanges.push({start:e,end:t}),this.pendingRanges.sort((n,r)=>n.start-r.start),this.mergePendingRanges()}mergePendingRanges(){if(this.pendingRanges.length<2)return;let e=[],t=this.pendingRanges[0];for(let n=1;n<this.pendingRanges.length;n++){let r=this.pendingRanges[n];r.start<=t.end+1?t={start:t.start,end:Math.max(t.end,r.end)}:(e.push(t),t=r)}e.push(t),this.pendingRanges=e}takeFreeSlot(e){for(let t=0;t<this.freeList.length;t++){let n=this.freeList[t];if(n.count>=e){if(this.freeList.splice(t,1),n.count===e)return n;let r={start:n.start,count:e};return this.insertFreeSlot({start:n.start+e,count:n.count-e}),r}}}insertFreeSlot(e){this.freeList.push(e),this.freeList.sort((t,n)=>t.start-n.start),this.mergeFreeList()}mergeFreeList(){if(this.freeList.length<2)return;let e=[],t=this.freeList[0];for(let n=1;n<this.freeList.length;n++){let r=this.freeList[n];t.start+t.count===r.start?t={start:t.start,count:t.count+r.count}:(e.push(t),t=r)}e.push(t),this.freeList=e}interiorFreeFaces(){let e=0;for(let t of this.freeList)t.start<this.highWatermark&&(e+=t.count);return e}findMovableSection(e){let t=[];for(let[s,a]of this.sectionSlots)t.push({key:s,start:a.start,count:a.count});if(t.length===0)return;t.sort((s,a)=>a.start!==s.start?a.start-s.start:a.start+a.count-(s.start+s.count));let n=t[0];if(n.count<=e&&this.findLowestInteriorHole(n.start,n.count))return n;let r=t.filter(s=>s.count<=e).sort((s,a)=>a.count-s.count);for(let s of r)if(this.findLowestInteriorHole(s.start,s.count))return s}findLowestInteriorHole(e,t){for(let n=0;n<this.freeList.length;n++){let r=this.freeList[n];if(r.start<e&&r.count>=t)return{start:r.start,count:r.count,index:n}}}reserveFreeSlotAt(e,t){let n=this.freeList[e];if(this.freeList.splice(e,1),n.count===t)return{start:n.start,count:t};let r={start:n.start,count:t};return this.insertFreeSlot({start:n.start+t,count:n.count-t}),r}copySectionRange(e,t,n){this.w0.copyWithin(t,e,e+n),this.w1.copyWithin(t,e,e+n),this.w2.copyWithin(t,e,e+n),this.w3.copyWithin(t,e,e+n)}rangeFullyUploaded(e,t){for(let n of this.pendingRanges)if(n.start<=t&&n.end>=e)return!1;return!0}zeroAndFreeSlot(e,t){for(let n=e;n<e+t;n++)this.w0[n]=0,this.w1[n]=0,this.w2[n]=dg,this.w3[n]=0;this.markDirty(e,e+t-1),this.insertFreeSlot({start:e,count:t})}finalizePendingReplace(e){let t=this.pendingReplace.get(e);t&&(this.zeroAndFreeSlot(t.oldStart,t.oldCount),this.pendingReplace.delete(e),this.shrinkHighWatermark(),this.mesh.geometry.instanceCount=this.highWatermark,this.layoutVersion++,this.uploadEpoch++)}finalizePendingMove(){let e=this.pendingMove;if(!e)return;let{oldStart:t,count:n}=e;this.zeroAndFreeSlot(t,n),this.shrinkHighWatermark(),this.mesh.geometry.instanceCount=this.highWatermark,this.pendingMove=null,this.layoutVersion++,this.uploadEpoch++}shrinkHighWatermark(){for(;this.highWatermark>0;){let e=this.highWatermark-1,t=this.freeList.find(r=>r.start<=e&&r.start+r.count>e);if(!t||t.start+t.count!==this.highWatermark)break;this.highWatermark=t.start;let n=this.freeList.indexOf(t);this.freeList.splice(n,1)}}growCapacity(e){this.pendingMove&&this.finalizePendingMove();for(let c of[...this.pendingReplace.keys()])this.finalizePendingReplace(c);console.warn("[globalBlockBuffer] growing faces",this.capacityFaces,"->","(need",e,")");let t=this.capacityFaces;for(;t<e;)t+=OYe;console.warn("[globalBlockBuffer] growing faces",this.capacityFaces,"->",t);let n=new Uint32Array(t),r=new Uint32Array(t),s=new Uint32Array(t),a=new Uint32Array(t);n.set(this.w0),r.set(this.w1),s.set(this.w2),a.set(this.w3),s.fill(dg,this.w0.length),this.w0=n,this.w1=r,this.w2=s,this.w3=a,this.capacityFaces=t;let o=this.mesh.geometry,l=(c,u)=>{let d=o.getAttribute(u);d&&(o.deleteAttribute(u),"dispose"in d&&typeof d.dispose=="function"&&d.dispose());let f=new Ar(c,1);f.setUsage(So),o.setAttribute(u,f)};l(this.w0,"a_w0"),l(this.w1,"a_w1"),l(this.w2,"a_w2"),l(this.w3,"a_w3"),this.pendingRanges.length=0,this.invalidateTierCVao()}};h();p();m();z5();Kc();function h4e(i,e,t,n,r){if(e<=0)return;let s=t-8,a=n-8,o=r-8,l=t9,c=16,u=16,d=16,f=-1,v=-1,g=-1;for(let A=0;A<e;A++){let T=i[A*l],P=T&(1<<Xd.LX_BITS)-1,I=T>>Xd.LY_SHIFT&(1<<Xd.LY_BITS)-1,k=T>>Xd.LZ_SHIFT&(1<<Xd.LZ_BITS)-1;P<c&&(c=P),I<u&&(u=I),k<d&&(d=k),P>f&&(f=P),I>v&&(v=I),k>g&&(g=k)}if(f<0)return;let b=s+c,y=a+u,_=o+d,x=s+f+1,w=a+v+1,S=o+g+1;return{minX:b,minY:y,minZ:_,maxX:x,maxY:w,maxZ:S,cx:(b+x)*.5,cy:(y+w)*.5,cz:(_+S)*.5}}function UYe(i,e,t,n,r,s,a,o,l){return i>=n&&i<=a&&e>=r&&e<=o&&t>=s&&t<=l}function m4e(i,e,t,n,r,s,a,o,l,c,u,d,f){if(UYe(i,e,t,a,o,l,c,u,d))return;let v=0,g=f;if(Math.abs(n)<1e-8){if(i<a||i>c)return}else{let b=1/n,y=(a-i)*b,_=(c-i)*b;if(y>_){let x=y;y=_,_=x}if(v=Math.max(v,y),g=Math.min(g,_),v>g)return}if(Math.abs(r)<1e-8){if(e<o||e>u)return}else{let b=1/r,y=(o-e)*b,_=(u-e)*b;if(y>_){let x=y;y=_,_=x}if(v=Math.max(v,y),g=Math.min(g,_),v>g)return}if(Math.abs(s)<1e-8){if(t<l||t>d)return}else{let b=1/s,y=(l-t)*b,_=(d-t)*b;if(y>_){let x=y;y=_,_=x}if(v=Math.max(v,y),g=Math.min(g,_),v>g)return}return v<=g&&v>=0?v:void 0}function p4e(i,e,t,n,r,s,a,o,l,c,u,d,f){let v=f;if(Math.abs(n)>=1e-8){let g=n>0?(c-i)/n:(a-i)/n;g>1e-6&&(v=Math.min(v,g))}else if(i<a||i>c)return;if(Math.abs(r)>=1e-8){let g=r>0?(u-e)/r:(o-e)/r;g>1e-6&&(v=Math.min(v,g))}else if(e<o||e>u)return;if(Math.abs(s)>=1e-8){let g=s>0?(d-t)/s:(l-t)/s;g>1e-6&&(v=Math.min(v,g))}else if(t<l||t>d)return;return v<=f?v:void 0}h();p();m();Lt();h();p();m();$b();var u9=class{entries=new Set;skyLevel=1;lightmapParams={...Ri};register(e){this.entries.add(e),this.applyBrightness(e)}unregister(e){for(let t of this.entries)if(t.material===e){this.entries.delete(t);break}}setSkyLevel(e){this.skyLevel=e,this.refreshAll()}setLightmapParams(e){this.lightmapParams={...this.lightmapParams,...e},this.refreshAll()}getSkyLevel(){return this.skyLevel}refreshAll(){for(let e of this.entries)this.applyBrightness(e)}applyBrightness(e){let t=yP(e.blockLightNorm,e.skyLightNorm,this.skyLevel,this.lightmapParams);e.material.color.setScalar(t)}};function v4e(i,e,t,n,r=Ri){let s=yP(e,t,n,r);return i.color.setScalar(s),s}var g4e=20,_4e=40,FYe={white_banner:15,orange_banner:14,magenta_banner:13,light_blue_banner:12,yellow_banner:11,lime_banner:10,pink_banner:9,gray_banner:8,light_gray_banner:7,cyan_banner:6,purple_banner:5,blue_banner:4,brown_banner:3,green_banner:2,red_banner:1,black_banner:0},y4e={0:"#1d1d21",1:"#b02e26",2:"#5e7c16",3:"#835432",4:"#3c44aa",5:"#8932b8",6:"#169c9c",7:"#9d9d97",8:"#474f52",9:"#f38baa",10:"#80c71f",11:"#fed83d",12:"#3ab3da",13:"#c74ebd",14:"#f9801d",15:"#f9fffe"};function VYe(i){let e=i.replace("_wall_banner","_banner");return FYe[e]??15}var zYe=(i,e,t,n,r,s,a)=>{switch(i.fillStyle=t,e){case"bs":i.fillRect(n,r,s,a);break;case"ls":i.fillRect(n,r,s/3,a);break;case"rs":i.fillRect(n+s*2/3,r,s/3,a);break;case"ts":i.fillRect(n,r,s,a/3);break;case"ms":i.fillRect(n,r+a/3,s,a/3);break;case"drs":i.fillRect(n,r,s/2,a/2);break;case"dls":i.fillRect(n+s/2,r,s/2,a/2);break;case"ss":for(let o=0;o<s;o+=2)i.fillRect(n+o,r,1,a);break;case"cr":i.fillRect(n,r+a/3,s,a/3),i.fillRect(n+s/3,r,s/3,a);break;case"sc":i.fillRect(n,r+a/2-1,s,2),i.fillRect(n+s/2-1,r,2,a);break;default:i.fillRect(n,r,s,a)}};function HYe(i,e){if(!e||e.length===0)return`banner_${i}_empty`;let t=e.map(n=>`${n.Pattern??"bs"}_${n.Color??0}`).join(",");return`banner_${i}_${t}`}var qYe=(i,e,t=(n,r)=>yi(n,r))=>{let r=t(g4e*1,_4e*1),s=r.getContext("2d");if(!s){console.warn("Failed to get 2d context for banner rendering");return}if(s.imageSmoothingEnabled=!1,e?.Patterns&&e.Patterns.length>0)for(let a of e.Patterns){let o=a.Color??0,l=a.Pattern??"bs",c=y4e[o]||y4e[0];zYe(s,l,c,0,0,g4e*1,_4e*1)}return r},d9=new Map;function b4e(i,e,t){let n=VYe(e),r=HYe(n,t?.Patterns),s=d9.get(r);if(s)return s.refCount++,s.texture;let a=qYe(n,t);if(!a)return;let o=new sn(a);return o.magFilter=ct,o.minFilter=ct,o.needsUpdate=!0,d9.set(r,{texture:o,refCount:1}),o}function x4e(i){for(let[e,t]of d9.entries())if(t.texture===i){t.refCount--,t.refCount<=0&&(t.texture.dispose(),d9.delete(e));return}}function w4e(i,e,t,n,r=0,s=1,a=1){let u,d,f;t?(u=(-14.6+13.4)/2/16-.5,d=1-14.75/16-.5,f=1/2):(u=(1.4+29.4)/2/16,d=1-7.25/16-.5,f=0);let v=new _t({map:n,transparent:!0});v4e(v,r,s,a);let g=new Ke(new zn(.85,1.75),v);g.renderOrder=999;let b=.5/16,y=.25/16;t?g.position.set(0,u,d+y+.004):g.position.set(0,u,d+b/2+.004);let _=new bt;return _.rotation.set(0,-Ot.degToRad(e*(t?90:45/2)),0),_.add(g),_.bannerTexture=n,_.bannerMaterial=v,_.position.set(i.x+.5,i.y+f,i.z+.5),_}h();p();m();Lt();var S4e=Yr(V8(),1);var H5=new Map;function GYe(i,e,t){let n,r;return i&&"front_text"in i?(n=i.front_text?.messages??[],r=i.front_text?.color||"black"):(n=[i?.Text1,i?.Text2,i?.Text3,i?.Text4],r=i?.Color||"black"),`${e?1:0}|${t?1:0}|${r}|${n.join("\0")}`}function E4e(i,e,t,n=!1){let r=GYe(e,t,n),s=H5.get(r);if(s)return s.refCount++,s.texture;let a=(0,S4e.default)(i.version),o=k6e(e,t,a);if(!o)return;let l=new sn(o);return l.magFilter=ct,l.minFilter=ct,l.needsUpdate=!0,H5.set(r,{texture:l,refCount:1}),l}function M4e(i){for(let[e,t]of H5.entries())if(t.texture===i){t.refCount--,t.refCount<=0&&(t.texture.dispose(),H5.delete(e));return}}function A4e(){for(let[,i]of H5)i.texture.dispose();H5.clear()}var ro=class ro{constructor(e,t,n,r,s=3){this.worldRenderer=e;this.scene=t;this.material=n;this.worldHeight=r;this.updateViewDistance(s),this.signHeadsRenderer=new PP(e),this.initializePool()}renderOrigin={x:0,y:0,z:0};meshPool=[];activeSections=new Map;sectionObjects={};waitingChunksToDisplay={};pendingNearReveal=new Map;nearRevealTimers=new Map;nearRevealGraceTimers=new Map;poolSize;maxPoolSize;minPoolSize;signHeadsRenderer;blockEntityLightRegistry=new u9;chunkBoxMaterial=new _t({color:0,transparent:!0,opacity:0});cubeShaderMaterial=null;legacyShaderMaterial=null;globalLegacyShaderMaterial=null;globalLegacyBlendShaderMaterial=null;_legacyCullFrustum=new va;_legacyCullProjScreen=new Et;_legacyCullBox=new kn;_legacyCullBoxMin=new X;_legacyCullBoxMax=new X;_visibleSectionSpans=[];legacyCullSections=new Map;_lastCullFingerprint="";lastBufferStateKey="";cullDirty=!0;_lastCullCamPos=new X;_lastCullCamQuat=new qt;_cullViewQuat=new qt;_cullCamInitialized=!1;globalBlockBuffer=null;globalLegacyBuffer=null;globalLegacyBlendBuffer=null;shaderSectionRaycastBoxes=new Map;hits=0;misses=0;bypassPooling=!1;renderTimes=[];maxRenderTimeSamples=30;_performanceOverrideDistance;lastPerformanceCheck=0;performanceCheckInterval=2e3;get performanceOverrideDistance(){return this._performanceOverrideDistance??0}set performanceOverrideDistance(e){this._performanceOverrideDistance=e,this.updateSectionsVisibility()}initializePool(){for(let e=0;e<this.poolSize;e++){let t=new dt,n=new Ke(t,this.getLegacyShaderMaterial());n.visible=!1,n.matrixAutoUpdate=!1,n.name="pooled-section-mesh";let r={mesh:n,inUse:!1,lastUsedTime:0};this.meshPool.push(r)}}sectionHasRenderableContent(e){return e.positions.length>0||(e.blend?.positions.length??0)>0?!0:this.isShaderCubesGpuEnabled()?(e.shaderCubes?.count??0)>0:!1}isShaderCubesGpuEnabled(){return this.worldRenderer.shaderCubeBlocksEnabled()}syncCubeShaderUniforms(){if(!this.isShaderCubesGpuEnabled())return;let e=this.cubeShaderMaterial??this.getCubeShaderMaterial();if(!e)return;let t=this.material.map??null;e.uniforms.u_atlas.value=t;let n=n9();if(!n)return;let{tintPalette:r}=n;r.isReady()||r.createTexture(),e.uniforms.u_tintPalette.value=r.getTexture(),e.uniforms.u_debugMode.value=this.worldRenderer.worldRendererConfig.shaderCubeDebugMode??0,e.needsUpdate=!0}syncLegacyShaderUniforms(){let e=this.material.map??null;this.legacyShaderMaterial&&(this.legacyShaderMaterial.uniforms.u_atlas.value=e,this.legacyShaderMaterial.needsUpdate=!0),this.globalLegacyShaderMaterial&&(this.globalLegacyShaderMaterial.uniforms.u_atlas.value=e,this.globalLegacyShaderMaterial.needsUpdate=!0),this.globalLegacyBlendShaderMaterial&&(this.globalLegacyBlendShaderMaterial.uniforms.u_atlas.value=e,this.globalLegacyBlendShaderMaterial.needsUpdate=!0)}setSkyLevel(e){let t=this.cubeShaderMaterial??(this.isShaderCubesGpuEnabled()?this.getCubeShaderMaterial():null);t&&Jb(t,e),this.legacyShaderMaterial&&s9(this.legacyShaderMaterial,e),this.globalLegacyShaderMaterial&&s9(this.globalLegacyShaderMaterial,e),this.globalLegacyBlendShaderMaterial&&s9(this.globalLegacyBlendShaderMaterial,e),this.blockEntityLightRegistry.setSkyLevel(e)}setShadingTheme(e,t){let n=this.cubeShaderMaterial??(this.isShaderCubesGpuEnabled()?this.getCubeShaderMaterial():null);n&&bP(n,e,t)}setBlockLightmapParams(e){let t=this.cubeShaderMaterial??(this.isShaderCubesGpuEnabled()?this.getCubeShaderMaterial():null);t&&B_e(t,e),this.legacyShaderMaterial&&a9(this.legacyShaderMaterial,e),this.globalLegacyShaderMaterial&&a9(this.globalLegacyShaderMaterial,e),this.globalLegacyBlendShaderMaterial&&a9(this.globalLegacyBlendShaderMaterial,e),this.blockEntityLightRegistry.setLightmapParams(e)}getLegacyShaderMaterial(){return this.legacyShaderMaterial||(this.legacyShaderMaterial=$_e(),this.syncLegacyShaderUniforms()),this.legacyShaderMaterial}getGlobalLegacyShaderMaterial(){return this.globalLegacyShaderMaterial||(this.globalLegacyShaderMaterial=Y_e(),this.syncLegacyShaderUniforms()),this.globalLegacyShaderMaterial}getGlobalLegacyBuffer(){return this.globalLegacyBuffer||(this.globalLegacyBuffer=new ug(this.getGlobalLegacyShaderMaterial(),this.scene),this.globalLegacyBuffer.setRenderOrigin(this.renderOrigin)),this.globalLegacyBuffer}getGlobalLegacyBlendShaderMaterial(){return this.globalLegacyBlendShaderMaterial||(this.globalLegacyBlendShaderMaterial=J_e(),this.syncLegacyShaderUniforms()),this.globalLegacyBlendShaderMaterial}getGlobalLegacyBlendBuffer(){return this.globalLegacyBlendBuffer||(this.globalLegacyBlendBuffer=new ug(this.getGlobalLegacyBlendShaderMaterial(),this.scene,{name:"globalLegacyBlend",initialCapacityQuads:32e3,growthIncrementQuads:32e3}),this.globalLegacyBlendBuffer.setRenderOrigin(this.renderOrigin)),this.globalLegacyBlendBuffer}getRenderOrigin(){return this.renderOrigin}maybeRebase(e){let t=this.renderOrigin;if(Math.abs(e.x-t.x)<=ro.REBASE_THRESHOLD&&Math.abs(e.y-t.y)<=ro.REBASE_THRESHOLD&&Math.abs(e.z-t.z)<=ro.REBASE_THRESHOLD)return;let n={x:Math.round(e.x/16)*16,y:Math.round(e.y/16)*16,z:Math.round(e.z/16)*16},r={x:n.x-t.x,y:n.y-t.y,z:n.z-t.z};this.globalLegacyBuffer?.rebase(r),this.globalLegacyBlendBuffer?.rebase(r);for(let s of this.activeSections.values()){let a=s.sectionKey;if(!a)continue;let o=this.sectionObjects[a];o&&IP(s.mesh,o.worldX??0,o.worldY??0,o.worldZ??0,n)}this.renderOrigin=n,this.globalLegacyBuffer?.setRenderOrigin(n),this.globalLegacyBlendBuffer?.setRenderOrigin(n)}sectionUsesPooledLegacyMesh(e){return this.activeSections.has(e)}registerLegacyCullSection(e,t,n,r){this.legacyCullSections.set(e,{worldX:t,worldY:n,worldZ:r})}maybeUnregisterLegacyCullSection(e){let t=this.globalLegacyBuffer?.hasSection(e)??!1,n=this.globalLegacyBlendBuffer?.hasSection(e)??!1;!t&&!n&&this.legacyCullSections.delete(e)}updatePooledLegacyCullState(e,t,n){for(let r of this.activeSections.values()){let s=r.sectionKey;if(!s)continue;let a=this.sectionObjects[s];a&&K_e(r.mesh,a.worldX??0,a.worldY??0,a.worldZ??0,e,t,n,this._legacyCullFrustum,this._legacyCullBox,this._legacyCullBoxMin,this._legacyCullBoxMax)}}updateSectionCullAndSort(e,t,n,r){this._legacyCullProjScreen.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),this._legacyCullFrustum.setFromProjectionMatrix(this._legacyCullProjScreen);let s=this._visibleSectionSpans;s.length=0;for(let[b]of this.legacyCullSections){let y=this.sectionObjects[b];if(!y?.visible||y.worldX===void 0)continue;let{visible:_,distSq:x}=o9(y.worldX,y.worldY??0,y.worldZ??0,t,n,r,this._legacyCullFrustum,this._legacyCullBox,this._legacyCullBoxMin,this._legacyCullBoxMax);_&&s.push({key:b,distSq:x})}let a=this.globalLegacyBuffer,o=this.globalLegacyBlendBuffer,l=this.globalBlockBuffer,c=[];for(let b of s)a?.hasSection(b.key)&&c.push(b.key);c.sort();let u=s.filter(b=>o?.hasSection(b.key));u.sort((b,y)=>y.distSq-b.distSq);let d=u.map(b=>b.key),f=[],v=[];l&&l.forEachSectionSlot((b,y)=>{if(!this.sectionObjects[b]?.visible)return;let x=this.shaderSectionRaycastBoxes.get(b);if(!x)return;let{visible:w}=o9(x.sectionCenterX,x.sectionCenterY,x.sectionCenterZ,t,n,r,this._legacyCullFrustum,this._legacyCullBox,this._legacyCullBoxMin,this._legacyCullBoxMax);if(!w)return;f.push(b);let S=l.getSectionDrawStart(b),A=l.getSectionDrawCount(b);S!==void 0&&A!==void 0&&v.push({start:S,count:A})}),f.sort();let g=[c.join(","),d.join(","),f.join(","),a?.getLayoutVersion()??0,o?.getLayoutVersion()??0,l?.getLayoutVersion()??0,a?.getUploadEpoch()??0,o?.getUploadEpoch()??0,l?.getUploadEpoch()??0].join("|");if(g===this._lastCullFingerprint&&!this.hasPendingBufferWork()){this.updatePooledLegacyCullState(t,n,r);return}if(this._lastCullFingerprint=g,a?.updateDrawSpans(s,"opaque"),o?.updateDrawSpans(s,"sortedBlend"),l){let b=s4e(v,l.getHighWatermark(),l.canUseFullDrawShortcut(),(y,_)=>l.isRangeFullyUploaded(y,_),l.getPendingDirtyRanges());l.setVisibleSpans(b)}this.lastBufferStateKey=this.bufferStateKey(),this.updatePooledLegacyCullState(t,n,r)}bufferStateKey(){let e=this.globalBlockBuffer,t=this.globalLegacyBuffer,n=this.globalLegacyBlendBuffer;return[t?.getLayoutVersion()??0,t?.getUploadEpoch()??0,n?.getLayoutVersion()??0,n?.getUploadEpoch()??0,e?.getLayoutVersion()??0,e?.getUploadEpoch()??0].join("|")}markCullDirtyIfBufferStateChanged(){this.bufferStateKey()!==this.lastBufferStateKey&&this.markCullDirty()}markCullDirty(){this.cullDirty=!0}hasPendingBufferWork(){return[this.globalLegacyBuffer,this.globalLegacyBlendBuffer,this.globalBlockBuffer].some(t=>t!=null&&(t.hasPendingUploads()||t.hasPendingReplace()||t.getPendingMove()!=null))}updateCullDirtyFromCamera(e,t,n,r){if(e.getWorldQuaternion(this._cullViewQuat),!this._cullCamInitialized){this._lastCullCamPos.set(t,n,r),this._lastCullCamQuat.copy(this._cullViewQuat),this._cullCamInitialized=!0,this.cullDirty=!0;return}let s=this._lastCullCamPos.x!==t||this._lastCullCamPos.y!==n||this._lastCullCamPos.z!==r,a=this._lastCullCamQuat.x!==this._cullViewQuat.x||this._lastCullCamQuat.y!==this._cullViewQuat.y||this._lastCullCamQuat.z!==this._cullViewQuat.z||this._lastCullCamQuat.w!==this._cullViewQuat.w;(s||a)&&(this._lastCullCamPos.set(t,n,r),this._lastCullCamQuat.copy(this._cullViewQuat),this.markCullDirty())}clearCullDirty(){this.cullDirty=!1}setLegacyCameraOrigin(e,t,n){let r=this.renderOrigin;i9(this.getLegacyShaderMaterial(),r,e,t,n),i9(this.getGlobalLegacyShaderMaterial(),r,e,t,n),i9(this.getGlobalLegacyBlendShaderMaterial(),r,e,t,n),this.globalLegacyBuffer?.setCameraOrigin(e,t,n),this.globalLegacyBlendBuffer?.setCameraOrigin(e,t,n);let s=this.cubeShaderMaterial;if(s){let{originDelta:a,cameraOriginFrac:o}=$d(r,e,t,n),l=Kb(r),c=s.uniforms.u_originDelta;c?.value?.set&&c.value.set(a.x,a.y,a.z);let u=s.uniforms.u_cameraOriginFrac;u?.value?.set&&u.value.set(o.x,o.y,o.z);let d=s.uniforms.u_sectionOriginRel;d?.value?.set&&d.value.set(l.x,l.y,l.z)}}getCubeShaderMaterial(){if(!this.isShaderCubesGpuEnabled())return null;if(!this.cubeShaderMaterial){this.cubeShaderMaterial=Yb(),this.syncCubeShaderUniforms();let e=this.worldRenderer.worldRendererConfig;bP(this.cubeShaderMaterial,e.shadingTheme,e.cardinalLight)}return this.cubeShaderMaterial}getGlobalBlockBuffer(){let e=this.getCubeShaderMaterial();return e?(this.globalBlockBuffer||(this.globalBlockBuffer=new c9(e,this.scene)),this.globalBlockBuffer):null}shouldDeferLegacyOpaqueToPerSection(e){return this.shouldDeferShaderToPerSection(e)}shouldDeferShaderToPerSection(e){return this.worldRenderer.getModule("futuristicReveal")?.shouldDeferSectionGeometry?.(e)===!0}migrateDeferredShaderToGlobal(e){let t=this.sectionObjects[e];if(!t?.deferredShaderCubes)return;let{words:n,count:r}=t.deferredShaderCubes,s=t.worldX,a=t.worldY,o=t.worldZ;s!==void 0&&a!==void 0&&o!==void 0&&this.registerShaderSectionRaycastBox(e,n,r,s,a,o),this.getGlobalBlockBuffer()?.addSection(e,n,r),this.markCullDirty();let c=t.mesh===t.shaderMesh;t.shaderMesh&&(SP(t.shaderMesh),t.remove(t.shaderMesh),t.shaderMesh=void 0),delete t.deferredShaderCubes,c&&(t.mesh=void 0)}migrateDeferredLegacyToGlobal(e){let t=this.sectionObjects[e];if(t){if(t.deferredLegacyOpaque){let{positions:n,colors:r,skyLights:s,blockLights:a,uvs:o,indices:l}=t.deferredLegacyOpaque,c=t.worldX,u=t.worldY,d=t.worldZ;c!==void 0&&u!==void 0&&d!==void 0&&this.getGlobalLegacyBuffer().addSection(e,{positions:n,colors:r,skyLights:s,blockLights:a,uvs:o,indices:l},c,u,d)&&this.registerLegacyCullSection(e,c,u,d),delete t.deferredLegacyOpaque}if(t.deferredLegacyBlend){let{positions:n,colors:r,skyLights:s,blockLights:a,uvs:o,indices:l}=t.deferredLegacyBlend,c=t.worldX,u=t.worldY,d=t.worldZ;c!==void 0&&u!==void 0&&d!==void 0&&this.getGlobalLegacyBlendBuffer().addSection(e,{positions:n,colors:r,skyLights:s,blockLights:a,uvs:o,indices:l},c,u,d)&&this.registerLegacyCullSection(e,c,u,d),delete t.deferredLegacyBlend,t.hasBlendMesh=!1}if(!t.hasBlendMesh){let n=t.mesh===this.activeSections.get(e)?.mesh;this.releasePooledMesh(e),n&&(t.mesh=t.shaderMesh??void 0)}this.markCullDirty()}}registerShaderSectionRaycastBox(e,t,n,r,s,a){let o=h4e(t,n,r,s,a);o?this.shaderSectionRaycastBoxes.set(e,{box:o,sectionCenterX:r,sectionCenterY:s,sectionCenterZ:a}):this.shaderSectionRaycastBoxes.delete(e)}unregisterShaderSectionRaycastBox(e){this.shaderSectionRaycastBoxes.delete(e)}uploadLegacyPooledMesh(e,t,n,r,s){let{mesh:a}=e,o=t;return this.updateGeometryAttribute(a.geometry,"position",o.positions,3),this.updateGeometryAttribute(a.geometry,"normal",o.normals,3),this.updateGeometryAttribute(a.geometry,"color",o.colors,3),this.updateGeometryAttribute(a.geometry,"a_skyLight",o.skyLights,1),this.updateGeometryAttribute(a.geometry,"a_blockLight",o.blockLights,1),this.updateGeometryAttribute(a.geometry,"uv",o.uvs,2),a.geometry.index=new Mt(o.indices,1),a.geometry.boundingBox=new kn(new X(-8,-8,-8),new X(8,8,8)),a.geometry.boundingSphere=new Tn(new X(0,0,0),Math.sqrt(3*8**2)),IP(a,n,r,s,this.renderOrigin),a.visible=!1,a.name="mesh",e.lastUsedTime=performance.now(),a}acquirePooledSectionMesh(e){let t=this.activeSections.get(e);if(!t){if(t=this.acquireMesh(),!t)return console.warn(`ChunkMeshManager: No available mesh in pool for section ${e}`),null;this.activeSections.set(e,t),t.sectionKey=e}return t}updateSection(e,t){let n=t.positions.length>0,r=(t.blend?.positions.length??0)>0,s=n||r,a=t.shaderCubes,o=this.isShaderCubesGpuEnabled()&&(a?.count??0)>0,l=n&&this.shouldDeferLegacyOpaqueToPerSection(e),c=r&&this.shouldDeferLegacyOpaqueToPerSection(e),u=o&&this.shouldDeferShaderToPerSection(e),d=n&&!l,f=r&&!c,v=o&&!!a&&!u;if(!s&&!o)return this.releaseSection(e),null;let g=this.sectionObjects[e],b=g!=null;g&&this.cleanupSection(e,{forRemesh:!0}),b&&(v||this.globalBlockBuffer?.removeSection(e),d||this.globalLegacyBuffer?.removeSection(e),f||this.globalLegacyBlendBuffer?.removeSection(e),o&&a||this.unregisterShaderSectionRaycastBox(e),!d&&!f&&this.maybeUnregisterLegacyCullSection(e)),r||this.releasePooledMesh(e);let y,_,x,w=!1;if(n){let B={positions:t.positions,colors:t.colors,skyLights:t.skyLights,blockLights:t.blockLights,uvs:t.uvs,indices:t.indices};if(l){if(_={positions:new Float32Array(B.positions),colors:new Float32Array(B.colors),skyLights:new Float32Array(B.skyLights),blockLights:new Float32Array(B.blockLights),uvs:new Float32Array(B.uvs),indices:B.indices instanceof Uint32Array?new Uint32Array(B.indices):new Uint16Array(B.indices)},!r){let U=this.acquirePooledSectionMesh(e);if(!U)return null;y=this.uploadLegacyPooledMesh(U,t,t.sx,t.sy,t.sz)}}else if(this.getGlobalLegacyBuffer().addSection(e,B,t.sx,t.sy,t.sz))this.registerLegacyCullSection(e,t.sx,t.sy,t.sz);else{let O=this.acquirePooledSectionMesh(e);if(!O)return null;y=this.uploadLegacyPooledMesh(O,t,t.sx,t.sy,t.sz)}}if(r&&t.blend){let B={positions:t.blend.positions,colors:t.blend.colors,skyLights:t.blend.skyLights,blockLights:t.blend.blockLights,uvs:t.blend.uvs,indices:t.blend.indices};if(c){x={positions:new Float32Array(B.positions),colors:new Float32Array(B.colors),skyLights:new Float32Array(B.skyLights),blockLights:new Float32Array(B.blockLights),uvs:new Float32Array(B.uvs),indices:B.indices instanceof Uint32Array?new Uint32Array(B.indices):new Uint16Array(B.indices)};let U=this.acquirePooledSectionMesh(e);if(!U)return null;let O=this.uploadLegacyPooledMesh(U,t.blend,t.sx,t.sy,t.sz);y=y??O,w=!0}else if(this.getGlobalLegacyBlendBuffer().addSection(e,B,t.sx,t.sy,t.sz))this.registerLegacyCullSection(e,t.sx,t.sy,t.sz);else{console.warn(`ChunkMeshManager: blend invariant violation for section ${e}, using pooled mesh fallback`);let O=this.acquirePooledSectionMesh(e);if(!O)return null;let V=this.uploadLegacyPooledMesh(O,t.blend,t.sx,t.sy,t.sz);y=y??V,w=!0}}let S=o?this.getCubeShaderMaterial():null,A;o&&a&&(u&&S?(A=r9(a,S),A.visible=!0):this.getGlobalBlockBuffer()?.addSection(e,a.words,a.count)),g=new bt,y&&(g.add(y),g.mesh=y),A&&(g.add(A),g.shaderMesh=A,a&&(g.deferredShaderCubes={words:a.words,count:a.count}),g.mesh||(g.mesh=A)),_&&(g.deferredLegacyOpaque=_),x&&(g.deferredLegacyBlend=x),o&&a&&this.registerShaderSectionRaycastBox(e,a.words,a.count,t.sx,t.sy,t.sz);let T=0;n&&(T+=t.positions.length/3/4),r&&t.blend&&(T+=t.blend.positions.length/3/4),o&&a&&(T+=a.count),g.tilesCount=T,g.hasBlendMesh=w,g.blocksCount=t.blocksCount,g.worldX=t.sx,g.worldY=t.sy,g.worldZ=t.sz,g.sectionKey=e,g.name="chunk";try{if(Object.keys(t.signs).length>0){let B=new bt;B.name="signs";for(let[U,{isWall:O,isHanging:V,rotation:F}]of Object.entries(t.signs)){let J=this.worldRenderer.blockEntities[U];if(!J)continue;let[$,ne,se]=U.split(","),j=this.signHeadsRenderer.renderSign(new kt(+$,+ne,+se),F,O,V,f9.simplify(J));j&&B.add(j)}g.add(B),g.signsContainer=B}if(Object.keys(t.heads).length>0){let B=new bt;B.name="heads";for(let[U,{isWall:O,rotation:V}]of Object.entries(t.heads)){let F=this.worldRenderer.blockEntities[U];if(!F)continue;let[J,$,ne]=U.split(","),se=this.signHeadsRenderer.renderHead(new kt(+J,+$,+ne),V,O,f9.simplify(F));se&&B.add(se)}g.add(B),g.headsContainer=B}if(Object.keys(t.banners).length>0){let B=new bt;B.name="banners",g.bannersContainer=B,g.add(B);for(let[U,O]of Object.entries(t.banners)){let{isWall:V,rotation:F,blockName:J,blockLightNorm:$=0,skyLightNorm:ne=1}=O,se=this.worldRenderer.blockEntities[U];if(!se)continue;let[j,q,z]=U.split(","),K=b4e(this.worldRenderer,J,f9.simplify(se));if(!K)continue;let re=this.blockEntityLightRegistry.getSkyLevel(),Z=w4e(new kt(+j,+q,+z),F,V,K,$,ne,re);Z.bannerMaterial&&this.blockEntityLightRegistry.register({material:Z.bannerMaterial,blockLightNorm:$,skyLightNorm:ne});let{x:Y,y:Q,z:ue}=Z.position;this.worldRenderer.sceneOrigin.track(Z),Z.position.set(Y,Q,ue),B.add(Z)}}}catch(B){console.error("ChunkMeshManager: Error adding signs, heads, or banners to section",B)}this.sectionObjects[e]=g,this.scene.add(g),g.matrixAutoUpdate=!1,this.worldRenderer.displayOptions?.inWorldRenderingConfig?.showChunkBorders&&this.updateBoxHelper(e,!0);let P=e.split(","),I=`${P[0]},${P[2]}`,k=!!this.worldRenderer.displayOptions?.inWorldRenderingConfig?._renderByChunks,L=!!this.worldRenderer.worldRendererConfig?.wasmMesher;if((k||L)&&!this.worldRenderer.finishedChunks[I]){g.visible=!1,g._waitingForChunkDisplay=!0;let B=this.waitingChunksToDisplay[I]??(this.waitingChunksToDisplay[I]=[]);B.includes(e)||B.push(e)}return this.markCullDirty(),g}finishChunkDisplay(e){if(!this.waitingChunksToDisplay[e]){this.tryRevealPending();return}if(this.isWasmGateActive()&&this.isBlockedByNearer(e,0)){this.pendingNearReveal.set(e,Date.now()),this.armNearRevealTimer(e),this.armExpectedGraceTimer(e),this.tryRevealPending();return}this.flushChunkDisplay(e),this.tryRevealPending()}flushChunkDisplay(e){let t=this.waitingChunksToDisplay[e];if(this.pendingNearReveal.delete(e),this.clearNearRevealTimer(e),this.clearExpectedGraceTimer(e),!!t){for(let n of t){let r=this.sectionObjects[n];r&&(r._waitingForChunkDisplay=!1,r.visible=!0)}delete this.waitingChunksToDisplay[e],this.markCullDirty()}}tryRevealPending(){if(this.pendingNearReveal.size===0)return;let e=Date.now();for(let[t,n]of[...this.pendingNearReveal])this.isBlockedByNearer(t,e-n)||this.flushChunkDisplay(t)}onChunkRemovedFromGate(e){this.pendingNearReveal.delete(e),this.clearNearRevealTimer(e),this.clearExpectedGraceTimer(e),delete this.waitingChunksToDisplay[e],this.tryRevealPending()}isWasmGateActive(){return!!this.worldRenderer.worldRendererConfig?.wasmMesher}isBlockedByNearer(e,t){let n=this.worldRenderer.viewerChunkPosition;if(!n)return!1;let r=e.split(",");if(r.length!==2)return!1;let s=Number(r[0]),a=Number(r[1]),o=Math.floor(n.x/16),l=Math.floor(n.z/16),c=(s>>4)-o,u=(a>>4)-l,d=c*c+u*u;if(d===0)return!1;let f=this.worldRenderer.finishedChunks,v=this.worldRenderer.loadedChunks,g=this.worldRenderer.viewDistance;if(t<ro.EXPECTED_NEAR_GRACE_MS&&g>0){let y=g*g,_=Math.min(g,Math.ceil(Math.sqrt(Math.max(0,d-1))));for(let x=-_;x<=_;x++)for(let w=-_;w<=_;w++){let S=x*x+w*w;if(S>=d||S>y)continue;let A=o+x<<4,T=l+w<<4,P=`${A},${T}`;if(P!==e&&v[P]&&!f[P])return!0}return!1}for(let y in v){if(y===e||f[y])continue;let _=y.split(",");if(_.length!==2)continue;let x=(Number(_[0])>>4)-o,w=(Number(_[1])>>4)-l;if(x*x+w*w<d)return!0}return!1}armNearRevealTimer(e){if(this.nearRevealTimers.has(e))return;let t=setTimeout(()=>{this.nearRevealTimers.delete(e),this.pendingNearReveal.has(e)&&(console.warn(`[chunk-reveal] safety timeout for ${e} \u2014 a nearer pending column never finished, force-revealing`),this.flushChunkDisplay(e),this.tryRevealPending())},ro.NEAR_REVEAL_TIMEOUT_MS);this.nearRevealTimers.set(e,t)}clearNearRevealTimer(e){let t=this.nearRevealTimers.get(e);t&&(clearTimeout(t),this.nearRevealTimers.delete(e))}armExpectedGraceTimer(e){if(this.nearRevealGraceTimers.has(e))return;let t=setTimeout(()=>{this.nearRevealGraceTimers.delete(e),this.pendingNearReveal.has(e)&&this.tryRevealPending()},ro.EXPECTED_NEAR_GRACE_MS+50);this.nearRevealGraceTimers.set(e,t)}clearExpectedGraceTimer(e){let t=this.nearRevealGraceTimers.get(e);t&&(clearTimeout(t),this.nearRevealGraceTimers.delete(e))}cleanupSection(e,t){let n=this.sectionObjects[e];if(n){if(n._waitingForChunkDisplay){let r=e.split(","),s=`${r[0]},${r[2]}`,a=this.waitingChunksToDisplay[s];if(a){let o=a.indexOf(e);o!==-1&&a.splice(o,1),a.length===0&&delete this.waitingChunksToDisplay[s]}}if(n.bannersContainer){for(let r of n.bannersContainer.children){let s=r;s.bannerMaterial&&this.blockEntityLightRegistry.unregister(s.bannerMaterial),s.bannerTexture&&x4e(s.bannerTexture)}this.disposeContainer(n.bannersContainer)}if(t?.forRemesh||(this.globalBlockBuffer?.removeSection(e),this.globalLegacyBuffer?.removeSection(e),this.globalLegacyBlendBuffer?.removeSection(e),this.maybeUnregisterLegacyCullSection(e),this.unregisterShaderSectionRaycastBox(e)),this.markCullDirty(),delete n.deferredLegacyOpaque,delete n.deferredLegacyBlend,n.shaderMesh&&(SP(n.shaderMesh),n.shaderMesh=void 0),delete n.deferredShaderCubes,n.signsContainer){for(let r of n.signsContainer.children){let s=r;s.signTexture&&M4e(s.signTexture)}this.disposeContainer(n.signsContainer,!1)}if(n.headsContainer&&this.disposeContainer(n.headsContainer),this.worldRenderer.sceneOrigin.removeAndUntrackAll(n),this.scene.remove(n),n.boxHelper){this.worldRenderer.sceneOrigin.removeAndUntrack(n.boxHelper),this.scene.remove(n.boxHelper),n.boxHelper.geometry.dispose();let r=n.boxHelper.material;if(Array.isArray(r))for(let s of r)s.dispose();else r.dispose();n.boxHelper=void 0}delete this.sectionObjects[e],t?.forRemesh||this.worldRenderer.getModule("futuristicReveal")?.onSectionRemoved?.(e)}}releasePooledMesh(e){let t=this.activeSections.get(e);t&&(t.mesh.visible=!1,t.inUse=!1,t.sectionKey=void 0,t.lastUsedTime=0,this.clearGeometry(t.mesh.geometry),this.activeSections.delete(e),this.cleanupExcessMeshes())}releaseSection(e){this.cleanupSection(e);let t=this.activeSections.get(e);return t?(t.mesh.visible=!1,t.inUse=!1,t.sectionKey=void 0,t.lastUsedTime=0,this.clearGeometry(t.mesh.geometry),this.activeSections.delete(e),this.cleanupExcessMeshes(),!0):!1}getSectionObject(e){return this.sectionObjects[e]}updateBoxHelper(e,t,n=this.chunkBoxMaterial){let r=this.sectionObjects[e];if(r)if(t){if(!r.boxHelper){let s=new Ke(new Sn(16,16,16),n),a=new Ea(s,16776960);a.name="helper";let o=r.worldX??0,l=r.worldY??0,c=r.worldZ??0;this.worldRenderer.sceneOrigin.track(a,{updateMatrix:!0}),a.position.set(o,l,c),a.updateMatrix(),this.scene.add(a),r.boxHelper=a}r.boxHelper.visible=!0}else r.boxHelper&&(r.boxHelper.visible=!1)}updateAllBoxHelpers(e){for(let t of Object.keys(this.sectionObjects))this.updateBoxHelper(t,e)}getSectionMesh(e){return this.activeSections.get(e)?.mesh}hasSection(e){return this.activeSections.has(e)}updateViewDistance(e){let t=(e*2+1)**2,n=this.worldHeight/16,r=5;if(this.minPoolSize=Math.floor(t*r),this.maxPoolSize=Math.floor(t*n)+1,this.poolSize??=this.minPoolSize,this.minPoolSize>this.poolSize){let s=Math.min(this.minPoolSize,this.maxPoolSize);this.expandPool(s)}console.log(`ChunkMeshManager: Updated view max distance to ${e}, pool: ${this.poolSize}/${this.maxPoolSize}, optimal: ${this.minPoolSize}`)}getGlobalBufferStats(){let e=n=>n?{used:n.getHighWatermark(),capacity:n.getCapacityQuads(),sections:n.getSectionCount(),usedBytes:n.getUsedMemoryBytes(),capacityBytes:n.getMemoryBytes()}:null,t=this.globalBlockBuffer;return{shaderFaces:t?{used:t.getHighWatermark(),capacity:t.getCapacityFaces(),sections:t.getSectionCount(),usedBytes:t.getUsedMemoryBytes(),capacityBytes:t.getMemoryBytes()}:null,legacyOpaque:e(this.globalLegacyBuffer),legacyBlend:e(this.globalLegacyBlendBuffer)}}getStats(){let e=this.meshPool.filter(r=>!r.inUse).length,t=this.hits+this.misses>0?(this.hits/(this.hits+this.misses)*100).toFixed(1):"0",n=this.getEstimatedMemoryUsage();return{poolSize:this.poolSize,activeCount:this.activeSections.size,freeCount:e,hitRate:`${t}%`,hits:this.hits,misses:this.misses,memoryUsage:n}}getTotalTiles(){return Object.values(this.sectionObjects).reduce((e,t)=>e+(t.tilesCount||0),0)}getTotalBlocks(){return Object.values(this.sectionObjects).reduce((e,t)=>e+(t.blocksCount||0),0)}getEstimatedMemoryUsage(){let e=0,t=0,n=0,r=0,s=0,a=0,o=0,l=this.globalBlockBuffer?.mesh.geometry;if(l)for(let f of["a_w0","a_w1","a_w2","a_w3"]){let v=l.getAttribute(f);if(v){let g=v.array.byteLength;o+=g,e+=g}}let c=this.globalLegacyBuffer?.getMemoryBytes()??0,u=this.globalLegacyBlendBuffer?.getMemoryBytes()??0;e+=c+u,t+=c+u;for(let f of Object.values(this.sectionObjects)){let v=f.shaderMesh?.geometry;if(v)for(let g of["a_w0","a_w1","a_w2","a_w3"]){let b=v.getAttribute(g);if(b){let y=b.array.byteLength;o+=y,e+=y}}}for(let f of this.meshPool)if(f.inUse&&f.mesh.geometry){let{geometry:v}=f.mesh,g=v.getAttribute("position");if(g){let x=g.array.byteLength;t+=x,e+=x}let b=v.getAttribute("normal");if(b){let x=b.array.byteLength;n+=x,e+=x}let y=v.getAttribute("color");if(y){let x=y.array.byteLength;r+=x,e+=x}let _=v.getAttribute("uv");if(_){let x=_.array.byteLength;s+=x,e+=x}if(v.index){let x=v.index.array.byteLength;a+=x,e+=x}}return{total:`${(e/(1024*1024)).toFixed(2)} MB`,breakdown:{position:`${(t/(1024*1024)).toFixed(2)} MB`,normal:`${(n/(1024*1024)).toFixed(2)} MB`,color:`${(r/(1024*1024)).toFixed(2)} MB`,uv:`${(s/(1024*1024)).toFixed(2)} MB`,index:`${(a/(1024*1024)).toFixed(2)} MB`,shaderInstances:`${(o/(1024*1024)).toFixed(2)} MB`}}}dispose(){let e=[...this.activeSections.keys()];for(let t of e)this.releaseSection(t);this.signHeadsRenderer.dispose();for(let t of this.meshPool)t.mesh.geometry.dispose();this.meshPool.length=0,this.activeSections.clear(),this.chunkBoxMaterial.dispose(),this.shaderSectionRaycastBoxes.clear(),this.lastBufferStateKey="",this.globalBlockBuffer?.dispose(),this.globalBlockBuffer=null,this.globalLegacyBuffer?.dispose(),this.globalLegacyBuffer=null,this.globalLegacyBlendBuffer?.dispose(),this.globalLegacyBlendBuffer=null,this.cubeShaderMaterial?.dispose(),this.cubeShaderMaterial=null,this.legacyShaderMaterial?.dispose(),this.legacyShaderMaterial=null,this.globalLegacyShaderMaterial?.dispose(),this.globalLegacyShaderMaterial=null,this.globalLegacyBlendShaderMaterial?.dispose(),this.globalLegacyBlendShaderMaterial=null,this.pendingNearReveal.clear();for(let t of this.nearRevealTimers.values())clearTimeout(t);this.nearRevealTimers.clear();for(let t of this.nearRevealGraceTimers.values())clearTimeout(t);this.nearRevealGraceTimers.clear()}acquireMesh(){if(this.bypassPooling){let t={mesh:new Ke(new dt,this.getLegacyShaderMaterial()),inUse:!0,lastUsedTime:performance.now()};return this.meshPool.push(t),this.poolSize++,t}for(let t of this.meshPool)if(!t.inUse)return t.inUse=!0,t.lastUsedTime=performance.now(),this.hits++,t;this.misses++;let e=Math.min(this.poolSize+16,this.maxPoolSize);e<=this.meshPool.length&&(e=this.meshPool.length+8,this.maxPoolSize=e,console.warn(`ChunkMeshManager: Pool exhausted (${this.poolSize}/${this.maxPoolSize}). Emergency expansion to ${e}`)),this.expandPool(e);for(let t=this.meshPool.length-1;t>=0;t--){let n=this.meshPool[t];if(!n.inUse)return n.inUse=!0,n.lastUsedTime=performance.now(),n}throw new Error("ChunkMeshManager: Failed to acquire mesh after pool expansion")}expandPool(e){let t=this.meshPool.length;this.poolSize=e;for(let n=t;n<e;n++){let r=new dt,s=new Ke(r,this.getLegacyShaderMaterial());s.visible=!1,s.matrixAutoUpdate=!1,s.name="pooled-section-mesh";let a={mesh:s,inUse:!1,lastUsedTime:0};this.meshPool.push(a)}}updateGeometryAttribute(e,t,n,r){let s=e.getAttribute(t);s&&s.count===n.length/r?(s.array.set(n),s.needsUpdate=!0):e.setAttribute(t,new Mt(n,r))}clearGeometry(e){let t=["position","normal","color","a_skyLight","a_blockLight","uv"];for(let n of t)e.hasAttribute(n)&&e.deleteAttribute(n);e.index&&e.setIndex(null),e.boundingBox=null,e.boundingSphere=null}cleanupExcessMeshes(){if(this.poolSize>this.maxPoolSize){let e=this.meshPool.filter(t=>!t.inUse).length;if(e>0){let t=Math.min(this.poolSize-this.maxPoolSize,e);for(let n=0;n<t;n++){let r=this.meshPool.findIndex(s=>!s.inUse);r!==-1&&(this.meshPool[r].mesh.geometry.dispose(),this.meshPool.splice(r,1),this.poolSize--)}}}}disposeContainer(e,t=!0){dr(e,t)}recordRenderTime(e){this.renderTimes.push(e),this.renderTimes.length>this.maxRenderTimeSamples&&this.renderTimes.shift();let t=performance.now();t-this.lastPerformanceCheck>this.performanceCheckInterval&&(this.checkPerformance(),this.lastPerformanceCheck=t)}getEffectiveRenderDistance(){return this.performanceOverrideDistance||this.worldRenderer.viewDistance}resetPerformanceOverride(){this.performanceOverrideDistance=void 0,this.renderTimes.length=0,console.log("ChunkMeshManager: Performance override reset")}getAverageRenderTime(){return this.renderTimes.length===0?0:this.renderTimes.reduce((e,t)=>e+t,0)/this.renderTimes.length}checkPerformance(){if(this.renderTimes.length<this.maxRenderTimeSamples)return;let e=this.getAverageRenderTime(),t=16.67,n=t*1.5;if(e>n){let r=this.worldRenderer.viewDistance,s=Math.max(1,Math.floor(r*.8));(!this.performanceOverrideDistance||s<this.performanceOverrideDistance)&&(this.performanceOverrideDistance=s,console.warn(`ChunkMeshManager: Performance degraded (${e.toFixed(2)}ms avg). Reducing effective render distance to ${s}`))}else if(this.performanceOverrideDistance&&e<t*1.1){let r=this.worldRenderer.viewDistance,s=Math.min(r,this.performanceOverrideDistance+1);s!==this.performanceOverrideDistance&&(this.performanceOverrideDistance=s>=r?void 0:s,console.log(`ChunkMeshManager: Performance improved. Restoring render distance to ${s}`))}}updateSectionsVisibility(){let e=this.worldRenderer.cameraSectionPos;for(let[t,n]of Object.entries(this.sectionObjects)){if(n._waitingForChunkDisplay){n.visible=!1;continue}if(!this.performanceOverrideDistance){n.visible=!0;continue}let[r,s,a]=t.split(",").map(Number),o={x:r/16,y:s/16,z:a/16},l=o.x-e.x,c=o.z-e.z,u=Math.floor(Math.hypot(l,c));n.visible=u<=this.performanceOverrideDistance}}};Wn(ro,"REBASE_THRESHOLD",65536),Wn(ro,"NEAR_REVEAL_TIMEOUT_MS",5e3),Wn(ro,"EXPECTED_NEAR_GRACE_MS",1500);var fg=ro,PP=class{constructor(e){this.worldRendererThree=e}dispose(){A4e()}renderHead(e,t,n,r){let s;if(r.SkullOwner?s=r.SkullOwner.Properties?.textures?.[0]?.Value:s=r.profile?.properties?.find(a=>a.name==="textures")?.value,!!s)try{let o=JSON.parse(Buffer.from(s,"base64").toString()).textures?.SKIN?.url,{skinTexturesProxy:l}=this.worldRendererThree.worldRendererConfig;l&&(o=o?.replace("http://textures.minecraft.net/",l).replace("https://textures.minecraft.net/",l));let c=$c(this.worldRendererThree,o,Yc.head),u=new bt;return n&&c.position.set(0,.3125,.3125),c.position.y-=23/16,u.add(c),this.worldRendererThree.sceneOrigin.track(u),u.position.set(e.x+.5,e.y+.045,e.z+.5),u.rotation.set(0,-Ot.degToRad(t*(n?90:45/2)),0),u.scale.set(.8,.8,.8),u}catch(a){console.error("Error decoding player texture:",a)}}renderSign(e,t,n,r,s){let a=E4e(this.worldRendererThree,s,r);if(!a)return;let o=new Ke(new zn(1,1),new _t({map:a,transparent:!0}));o.renderOrder=999;let l=7/16,c=r?1.3:1;o.scale.set(1*c,l*c,1*c);let u=(r?2:1.5)/16,d=.25/16;n&&!r?o.position.set(0,0,-.5+u+d+1e-4):o.position.set(0,0,u/2+1e-4);let f=new bt;f.rotation.set(0,-Ot.degToRad(t*(n?90:45/2)),0),f.add(o),f.signTexture=a;let v=(r?10:8)/16,g=(r?0:n?4.333:9.333)/16,b=v/2+g;return this.worldRendererThree.sceneOrigin.track(f),f.position.set(e.x+.5,e.y+b,e.z+.5),f}};h();p();m();var h9=(i,e)=>e===0?1/0:e<0?h9(-i,-e):(1-(i-Math.floor(i)))/e,WYe=(i,e,t,n,r,s,a,o,l,c,u,d)=>{let f=a-u,v=o-u,g=l-u,b=a+1+u,y=o+1+u,_=l+1+u,x=m4e(i,e,t,n,r,s,f,v,g,b,y,_,c);if(x===void 0&&(x=p4e(i,e,t,n,r,s,f,v,g,b,y,_,c)),x!==void 0)return Math.max(d,x)};function k4e(i,e,t,n,r,s,a,o,l,c){if(a<=0)return;let u=Math.floor(i),d=Math.floor(e),f=Math.floor(t),v=n>0?1:n<0?-1:0,g=r>0?1:r<0?-1:0,b=s>0?1:s<0?-1:0,y=v!==0?Math.abs(1/n):1/0,_=g!==0?Math.abs(1/r):1/0,x=b!==0?Math.abs(1/s):1/0,w=v!==0?h9(i,n):1/0,S=g!==0?h9(e,r):1/0,A=b!==0?h9(t,s):1/0,T=(k,L,B)=>{if(!c(k,L,B))return;let U=WYe(i,e,t,n,r,s,k,L,B,a,o,l);if(!(U===void 0||U>a))return{distance:U,blockX:k,blockY:L,blockZ:B}},P=T(u,d,f);if(P)return P;let I=0;for(;I<=a&&(w<S?w<A?(u+=v,I=w,w+=y):(f+=b,I=A,A+=x):S<A?(d+=g,I=S,S+=_):(f+=b,I=A,A+=x),!(I>a));)if(P=T(u,d,f),P)return P}h();p();m();h();p();m();Lt();var m9={},T4e=!1;function jYe(){if(T4e)return;let i=globalThis.loadedData?.tints;if(i){for(let e of Object.keys(i))m9[e]=XYe(i[e]);T4e=!0}}function XYe(i){let e={},t=I4e(i.default??16777215);if(i.data)for(let n of i.data){let r=I4e(n.color);for(let s of n.keys)e[s]=r}return new Proxy(e,{get(n,r){return n[r]??t}})}function I4e(i){return[(i>>16&255)/255,(i>>8&255)/255,(i&255)/255]}function R4e(i,e){return jYe(),i==="grass_block"?[1,1,1]:i==="redstone_wire"?[1,1,1]:i==="birch_leaves"||i==="spruce_leaves"||i==="lily_pad"?m9.constant?.[i]??[1,1,1]:i.includes("leaves")||i==="vine"?m9.foliage?.[e]??[1,1,1]:["short_grass","tall_grass","fern","large_fern","sugar_cane","grass"].includes(i)?m9.grass?.[e]??[1,1,1]:[1,1,1]}var $Ye=512,LP=1/20,BP=class{constructor(e){this.worldRenderer=e}particles=[];sharedMaterial;enabled=!1;tickAccumulator=0;nextParticleIndex=0;enable(){this.enabled||(this.enabled=!0,this.ensureMaterial())}disable(){this.enabled&&(this.enabled=!1)}dispose(){for(let e of this.particles)e.active&&this.worldRenderer.sceneOrigin.removeAndUntrack(e.mesh),e.mesh.geometry.dispose();this.particles=[],this.sharedMaterial?.dispose(),this.sharedMaterial=void 0,this.nextParticleIndex=0}render=e=>{if(!this.enabled)return;for(this.tickAccumulator+=e;this.tickAccumulator>=LP;)this.tickAccumulator-=LP,this.tickPhysics();let t=this.tickAccumulator/LP;this.updateVisuals(t)};spawnBlockBreakParticles(e,t,n,r,s,a="plains"){if(!this.enabled)return;let o=this.resolveBlockTexture(r);if(!o)return;let l=R4e(r,a);for(let c=0;c<4;c++)for(let u=0;u<4;u++)for(let d=0;d<4;d++){let f=e+(c+.5)/4,v=t+(u+.5)/4,g=n+(d+.5)/4,b=f-e-.5,y=v-t-.5,_=g-n-.5;b+=(Math.random()*2-1)*.4,y+=(Math.random()*2-1)*.4,_+=(Math.random()*2-1)*.4;let x=(Math.random()+Math.random()+1)*.15,w=Math.sqrt(b*b+y*y+_*_),S=b/w*x*.4,A=y/w*x*.4+.1,T=_/w*x*.4,P=Math.floor(4/(Math.random()*.9+.1));this.createParticle(f,v,g,S,A,T,P,o,s,e,n,1,l)}}tickPhysics(){for(let e of this.particles){if(!e.active)continue;if(e.prevX=e.x,e.prevY=e.y,e.prevZ=e.z,e.age++,e.age>=e.maxAge){this.deactivateParticle(e);continue}e.yd-=.04,e.x+=e.xd,e.y+=e.yd,e.z+=e.zd;let t=this.getFloorY(e);e.y<=t?(e.y=t,e.yd=0,e.onGround=!0):e.onGround=!1,e.xd*=.98,e.yd*=.98,e.zd*=.98,e.onGround&&(e.xd*=.7,e.zd*=.7)}}updateVisuals(e){let t=this.worldRenderer.camera.position;for(let n of this.particles){if(!n.active)continue;let r=n.prevX+(n.x-n.prevX)*e,s=n.prevY+(n.y-n.prevY)*e,a=n.prevZ+(n.z-n.prevZ)*e;n.mesh.position.set(r,s,a),n.mesh.lookAt(t.x,t.y,t.z)}}spawnCrackParticle(e,t,n,r,s,a,o="plains"){if(!this.enabled)return;let l=this.resolveBlockTexture(s);if(!l)return;let c=R4e(s,o),u=e+Math.random()*.8+.1,d=t+Math.random()*.8+.1,f=n+Math.random()*.8+.1;switch(r){case 0:d=t-.1;break;case 1:d=t+1+.1;break;case 2:f=n-.1;break;case 3:f=n+1+.1;break;case 4:u=e-.1;break;case 5:u=e+1+.1;break}let v=(Math.random()*2-1)*.4*.2,g=(Math.random()*2-1)*.4*.2+.1*.2,b=(Math.random()*2-1)*.4*.2,y=Math.floor(4/(Math.random()*.9+.1));this.createParticle(u,d,f,v,g,b,y,l,a,e,n,.6,c)}createParticle(e,t,n,r,s,a,o,l,c,u,d,f=1,v=[1,1,1]){this.ensureMaterial();let g=this.findInactiveParticle();g||(this.particles.length<$Ye?g=this.allocateParticle():g=this.recycleOldest());let b=Math.floor(Math.random()*4),y=Math.floor(Math.random()*4),_=l.u+b/4*l.su,x=l.v+y/4*l.sv,w=l.su/4,S=l.sv/4;this.setGeometryUVs(g.mesh.geometry,_,x,w,S),g.active=!0,g.x=e,g.y=t,g.z=n,g.prevX=e,g.prevY=t,g.prevZ=n,g.xd=r,g.yd=s,g.zd=a,g.age=0,g.maxAge=o,g.onGround=!1,g.floorMap=c,g.blockX=Math.floor(u),g.blockZ=Math.floor(d);let A=.1*(.5+Math.random()*.5)*2*f;g.mesh.scale.set(A,A,A),g.mesh.position.set(e,t,n),g.mesh.visible=!0;let T=.6*v[0],P=.6*v[1],I=.6*v[2],k=new Float32Array([T,P,I,T,P,I,T,P,I,T,P,I]),L=g.mesh.geometry.getAttribute("color");L?(L.set(k),L.needsUpdate=!0):g.mesh.geometry.setAttribute("color",new Je(k,3)),this.worldRenderer.sceneOrigin.addAndTrack(g.mesh)}allocateParticle(){let e=new zn(1,1),t=new Ke(e,this.sharedMaterial);t.visible=!1;let n={mesh:t,active:!1,x:0,y:0,z:0,prevX:0,prevY:0,prevZ:0,xd:0,yd:0,zd:0,age:0,maxAge:0,onGround:!1,floorMap:[],blockX:0,blockZ:0};return this.particles.push(n),n}findInactiveParticle(){for(let e=0;e<this.particles.length;e++){let t=(this.nextParticleIndex+e)%this.particles.length;if(!this.particles[t].active)return this.nextParticleIndex=(t+1)%this.particles.length,this.particles[t]}}recycleOldest(){let e=this.particles[0];for(let t of this.particles)t.age>e.age&&(e=t);return this.deactivateParticle(e),e}deactivateParticle(e){e.active&&(e.active=!1,e.mesh.visible=!1,this.worldRenderer.sceneOrigin.removeAndUntrack(e.mesh))}getFloorY(e){let t=Math.floor(e.x)-e.blockX,n=Math.floor(e.z)-e.blockZ;return t=Math.max(-2,Math.min(2,t)),n=Math.max(-2,Math.min(2,n)),e.floorMap[(n+2)*5+(t+2)]}resolveBlockTexture(e){let t=this.worldRenderer.resourcesManager.currentResources;if(!t)return null;let n=t.blocksAtlasJson,r=n.textures;if(r[e])return this.extractUV(r[e],n);for(let s of["_side","_top","_front","_0",""]){let a=e+s;if(r[a])return this.extractUV(r[a],n)}for(let s of Object.keys(r))if(s.startsWith(e))return this.extractUV(r[s],n);return null}extractUV(e,t){return{u:e.u,v:e.v,su:e.su??t.suSv,sv:e.sv??t.suSv}}setGeometryUVs(e,t,n,r,s){let a=e.getAttribute("uv");a.setXY(0,t,n),a.setXY(1,t+r,n),a.setXY(2,t,n+s),a.setXY(3,t+r,n+s),a.needsUpdate=!0}ensureMaterial(){if(this.sharedMaterial)return;let e=this.worldRenderer.material.map;e&&(this.sharedMaterial=new _t({map:e,vertexColors:!0,transparent:!0,alphaTest:.1}))}},C4e={id:"blockBreakParticles",controller:BP,enabledDefault:!0,cannotBeDisabled:!0,requiresHeightmap:!1};h();p();m();var DP=class{constructor(e){this.worldRenderer=e}enabled=!1;lastBobWalkDist=0;lastBobTickTime=0;enable(){this.enabled=!0}disable(){this.enabled=!1,this.worldRenderer.cameraShake.setCameraBobInput(null);let{perspective:e}=this.worldRenderer.playerStateReactive;e==="first_person"&&this.worldRenderer.camera.position.set(0,0,0)}render=()=>{if(!this.enabled)return;let e=this.worldRenderer.displayOptions.inWorldRenderingConfig,{perspective:t}=this.worldRenderer.playerStateReactive;if(e.viewBobbing&&t==="first_person"&&!this.worldRenderer.playerStateUtils.isSpectator()){this.worldRenderer.playerStateReactive.walkDist!==this.lastBobWalkDist&&(this.lastBobTickTime=performance.now(),this.lastBobWalkDist=this.worldRenderer.playerStateReactive.walkDist);let r=Math.min((performance.now()-this.lastBobTickTime)/50,1);this.worldRenderer.cameraShake.setCameraBobInput({walkDist:this.worldRenderer.playerStateReactive.walkDist,prevWalkDist:this.worldRenderer.playerStateReactive.prevWalkDist,bob:this.worldRenderer.playerStateReactive.bob,prevBob:this.worldRenderer.playerStateReactive.prevBob,partialTick:r})}else this.worldRenderer.cameraShake.setCameraBobInput(null)};dispose(){this.disable()}},P4e={id:"cameraBobbing",controller:DP,enabledDefault:!0,cannotBeDisabled:!0};h();p();m();Lt();var OP=2e3,L4e=32,B4e=32,p9=12,D4e=24,v9=1.2,YYe=-5,NP=class{constructor(e){this.worldRenderer=e;this.configUnsubs.push(this.worldRenderer.onReactiveConfigUpdated("rainColor",()=>this.syncRainAppearance()),this.worldRenderer.onReactiveConfigUpdated("rainOpacity",()=>this.syncRainAppearance()))}instancedMesh;geometry;material;particles=[];enabled=!1;dummy=new Et;tempPosition=new X;tempQuaternion=new qt;tempScale=new X;configUnsubs=[];enable(){this.enabled||(this.enabled=!0,this.instancedMesh?(this.instancedMesh.visible=!0,this.syncRainAppearance()):this.createRain())}disable(){this.enabled&&(this.enabled=!1,this.instancedMesh&&(this.instancedMesh.visible=!1))}autoEnableCheck(){return this.worldRenderer.worldRendererConfig.isRaining===!0}render=e=>{if(!this.enabled||!this.instancedMesh||!this.material)return;let t=this.worldRenderer.getCameraPosition();this.instancedMesh.position.set(0,0,0);let n=this.worldRenderer.reactiveState.world.heightmaps,{dummy:r,tempPosition:s,tempQuaternion:a,tempScale:o}=this,l=NaN,c=NaN,u;for(let d=0;d<OP;d++){let f=this.particles[d];this.instancedMesh.getMatrixAt(d,r),r.decompose(s,a,o),s.addScaledVector(f.velocity,e);let v=s.y,g=Math.sqrt(s.x*s.x+s.z*s.z),b=t.x+s.x,y=t.y+s.y,_=t.z+s.z,x=Math.floor(b/16),w=Math.floor(_/16);(x!==l||w!==c)&&(u=n[`${x},${w}`],l=x,c=w);let S=(Math.floor(b)%16+16)%16,A=(Math.floor(_)%16+16)%16,T=u?.[A*16+S];if(g>L4e||T!==void 0&&T!==-32768&&y<=T+1+f.despawnOffset||v<YYe){this.respawnParticle(s);let I=p9+Math.random()*(D4e-p9);f.velocity.set((Math.random()-.5)*v9,-I,(Math.random()-.5)*v9),f.despawnOffset=Math.random()*.5}r.compose(s,a,o),this.instancedMesh.setMatrixAt(d,r)}this.instancedMesh.instanceMatrix.needsUpdate=!0};dispose(){for(let e of this.configUnsubs)e();this.configUnsubs.length=0,this.instancedMesh&&this.worldRenderer.scene.remove(this.instancedMesh),this.geometry?.dispose(),this.material?.dispose(),this.instancedMesh=void 0,this.geometry=void 0,this.material=void 0,this.particles=[]}syncRainAppearance(){if(!this.material)return;let{rainColor:e,rainOpacity:t}=this.worldRenderer.worldRendererConfig;this.material.color.set(e),this.material.opacity=Math.max(0,Math.min(1,t)),this.material.needsUpdate=!0}createRain(){let{rainColor:e,rainOpacity:t}=this.worldRenderer.worldRendererConfig;this.geometry=new Sn(.03,.3,.03),this.material=new _t({color:e,transparent:!0,opacity:Math.max(0,Math.min(1,t)),depthWrite:!0,fog:!1}),this.instancedMesh=new cl(this.geometry,this.material,OP),this.instancedMesh.name="rain-particles",this.instancedMesh.frustumCulled=!1;let n=new Et,r=new X;for(let s=0;s<OP;s++){this.respawnParticle(r),r.y=Math.random()*B4e,n.setPosition(r),this.instancedMesh.setMatrixAt(s,n);let a=p9+Math.random()*(D4e-p9);this.particles.push({velocity:new X((Math.random()-.5)*v9,-a,(Math.random()-.5)*v9),age:0,despawnOffset:Math.random()*.5})}this.instancedMesh.instanceMatrix.needsUpdate=!0,this.worldRenderer.scene.add(this.instancedMesh)}respawnParticle(e){let t=Math.random()*Math.PI*2,n=Math.random()*L4e;e.set(Math.cos(t)*n,B4e,Math.sin(t)*n)}},O4e={id:"rain",controller:NP,enabledDefault:!1,requiresHeightmap:!0};h();p();m();Lt();var N4e=new We(13/255,234/255,238/255),JYe=9,KYe=12e3,ZYe=1500,QYe=1e4,eJe=350,tJe=650,U4e=120,F4e=280,UP=class{constructor(e){this.worldRenderer=e;e.worldRendererConfig.futuristicReveal!==!0&&(this.enabled=!1)}enabled=!0;sections=new Map;completed=new Set;globalWaveStarted=!1;globalWaveStartMs=0;finishedChunkCount=0;firstQueuedMs=null;pulseTime=0;wireframeMaterial=new Pn({color:N4e,transparent:!0,opacity:1,blending:es,depthWrite:!1});wireframeGlowMaterial=new Pn({color:N4e,transparent:!0,opacity:.55,blending:es,depthWrite:!1});autoEnableCheck(){return this.worldRenderer.worldRendererConfig.futuristicReveal===!0}enable(){this.autoEnableCheck()&&this.setEnabled(!0)}disable(){this.setEnabled(!1)}dispose(){this.reset(),this.wireframeMaterial.dispose(),this.wireframeGlowMaterial.dispose()}shouldDeferSectionGeometry(e){return this.enabled&&!this.completed.has(e)}onSectionMeshed(e,t,n){let r=n.children.find(s=>s.name==="mesh");r instanceof Ke&&this.onSectionMeshedMesh(e,t,r)}onChunkFinished(){this.enabled&&(this.finishedChunkCount++,this.tryStartGlobalWave(performance.now()))}onSectionRemoved(e){this.cancelSection(e,!0),this.completed.delete(e)}onWorldSwitched(){this.reset()}tick(e,t=performance.now()){if(!this.enabled||(this.tryStartGlobalWave(t),!this.globalWaveStarted&&this.firstQueuedMs!==null&&this.sections.size>0&&t-this.firstQueuedMs>=KYe&&this.startGlobalWave(t),this.sections.size===0))return;this.pulseTime+=e*.001;let n=[];for(let r of this.sections.values()){if(t-r.phaseStartMs>QYe){n.push(r);continue}if(r.phase==="queued"){this.globalWaveStarted&&t>=r.revealAtMs&&this.beginWireframe(r,t);continue}let s=t-r.phaseStartMs;if(r.phase==="wireframe"){this.animateWireframe(r,s),s>=r.wireframeMs&&this.beginFade(r,t);continue}if(r.phase==="fade"){let a=Math.min(1,s/r.fadeMs);this.animateFade(r,a),a>=1&&n.push(r)}}for(let r of n)this.finishSection(r)}setEnabled(e){e!==this.enabled&&(this.enabled=e,e||this.forceFinishAll())}onSectionMeshedMesh(e,t,n){if(!this.enabled||!t.positions?.length||this.completed.has(e))return;let r=this.sections.get(e);if(r){r.mesh=n,r.geometry=t,(r.phase==="wireframe"||r.phase==="fade")&&this.finishSection(r);return}let s=performance.now();this.firstQueuedMs===null&&(this.firstQueuedMs=s);let a=this.globalWaveStarted;this.sections.set(e,{key:e,geometry:t,phase:"queued",phaseStartMs:s,revealAtMs:this.globalWaveStarted?s:0,wireframeMs:a?U4e:eJe,fadeMs:a?F4e:tJe,wireframeGroup:null,mesh:n,savedMaterial:null,pulseOffset:Math.random()*Math.PI*2}),n.visible=!1,this.setShaderMeshesVisible(e,!1),this.tryStartGlobalWave(s)}reset(){this.forceFinishAll(),this.sections.clear(),this.completed.clear(),this.globalWaveStarted=!1,this.globalWaveStartMs=0,this.finishedChunkCount=0,this.firstQueuedMs=null,this.pulseTime=0}forceFinishAll(){for(let e of[...this.sections.values()])this.finishSection(e);this.sections.clear(),this.unhideAllSectionMeshes()}tryStartGlobalWave(e){if(!this.globalWaveStarted&&this.sections.size!==0){if(this.finishedChunkCount>=JYe){this.startGlobalWave(e);return}this.worldRenderer.allChunksFinished&&this.startGlobalWave(e)}}startGlobalWave(e){if(this.globalWaveStarted)return;this.globalWaveStarted=!0,this.globalWaveStartMs=e;let t=this.worldRenderer.getCameraPosition(),n=1,r=new Map;for(let[s,a]of this.sections){if(a.phase!=="queued")continue;let{sx:o,sy:l,sz:c}=a.geometry,u=Math.hypot(o-t.x,l-t.y,c-t.z);r.set(s,u),n=Math.max(n,u)}for(let[,s]of this.sections){if(s.phase!=="queued")continue;let a=r.get(s.key)??0;s.revealAtMs=e+a/n*ZYe,s.wireframeMs=U4e,s.fadeMs=F4e}}beginWireframe(e,t){let n=e.mesh??this.getSectionMesh(e.key);if(e.mesh=n,!n){this.sections.delete(e.key);return}let r=this.createWireframeGeometry(e.geometry),s=new Kn(r,this.wireframeMaterial.clone());this.worldRenderer.sceneOrigin.track(s),s.position.set(e.geometry.sx,e.geometry.sy,e.geometry.sz),s.name="scifi-wireframe",s.renderOrder=1e3;let a=new Kn(r.clone(),this.wireframeGlowMaterial.clone());this.worldRenderer.sceneOrigin.track(a),a.position.copy(s.position),a.scale.setScalar(1.02),a.name="scifi-glow",a.renderOrder=999;let o=new bt;o.name="scifi-reveal-group",o.add(s,a),this.worldRenderer.realScene.add(o),n.visible=!1,this.setShaderMeshesVisible(e.key,!1),e.wireframeGroup=o,e.phase="wireframe",e.phaseStartMs=t}beginFade(e,t){let n=e.mesh??this.getSectionMesh(e.key);if(e.mesh=n,n){n.visible=!0;let r=n.material;if(!Array.isArray(r)&&r&&typeof r.clone=="function"){e.savedMaterial=r;let s=r.clone();s.transparent=!0,s.opacity=0,s.needsUpdate=!0,n.material=s}}this.setShaderMeshesVisible(e.key,!0),e.phase="fade",e.phaseStartMs=t}animateWireframe(e,t){if(!e.wireframeGroup)return;let n=e.wireframeGroup.children[0],r=e.wireframeGroup.children[1],s=.6+.4*Math.sin(this.pulseTime*4+e.pulseOffset);if(n?.material){let a=n.material;a.opacity=s;let o=.85+.15*Math.sin(this.pulseTime*6+t*.002);a.color.setRGB(13/255*o,234/255*o,238/255*o)}r?.material&&(r.material.opacity=s*.4)}animateFade(e,t){let n=1-(1-t)**3;if(e.wireframeGroup){let s=e.wireframeGroup.children[0],a=e.wireframeGroup.children[1];s?.material&&(s.material.opacity=1-n),a?.material&&(a.material.opacity=(1-n)*.55)}let r=e.mesh;r&&e.savedMaterial&&!Array.isArray(r.material)&&(r.material.opacity=n),this.setShaderMeshesVisible(e.key,n>.001)}finishSection(e){let t=e.mesh??this.getSectionMesh(e.key);if(t){if(e.savedMaterial){let r=t.material;t.material=e.savedMaterial,r.dispose(),e.savedMaterial=null}t.visible=!0}this.setShaderMeshesVisible(e.key,!0);let{chunkMeshManager:n}=this.worldRenderer;n.migrateDeferredShaderToGlobal(e.key),n.migrateDeferredLegacyToGlobal(e.key),e.wireframeGroup&&(this.disposeWireframeGroup(e.wireframeGroup),e.wireframeGroup=null),this.sections.delete(e.key),this.completed.add(e.key)}cancelSection(e,t){let n=this.sections.get(e);if(n){if(n.wireframeGroup&&this.disposeWireframeGroup(n.wireframeGroup),t){let r=n.mesh??this.getSectionMesh(e);if(r){if(n.savedMaterial){let s=r.material;r.material=n.savedMaterial,s.dispose()}r.visible=!0}this.setShaderMeshesVisible(e,!0)}this.sections.delete(e)}}getSectionMesh(e){let t=this.worldRenderer.chunkMeshManager.sectionObjects[e];if(!t)return null;let n=t.children.find(r=>r.name==="mesh");return n instanceof Ke?n:null}getShaderMesh(e){let t=this.worldRenderer.chunkMeshManager.sectionObjects[e];if(!t)return null;let n=t.children.find(r=>r.name==="shaderMesh");return n instanceof Ke?n:null}setShaderMeshesVisible(e,t){let n=this.getShaderMesh(e);n&&(n.visible=t)}unhideAllSectionMeshes(){for(let e of Object.values(this.worldRenderer.chunkMeshManager.sectionObjects))e&&e.traverse(t=>{t instanceof Ke&&(t.name==="mesh"||t.name==="shaderMesh")&&(t.visible=!0)})}disposeWireframeGroup(e){this.worldRenderer.sceneOrigin.removeAndUntrackAll(e),this.worldRenderer.realScene.remove(e),e.traverse(t=>{let n=t;n.geometry?.dispose();let r=n.material;Array.isArray(r)?r.forEach(s=>s.dispose()):r?.dispose()}),e.clear()}createWireframeGeometry(e){let t=e.positions,n=e.indices,r=[],s=new Set;for(let o=0;o<n.length;o+=3){let l=n[o],c=n[o+1],u=n[o+2];this.addEdge(t,l,c,r,s),this.addEdge(t,c,u,r,s),this.addEdge(t,u,l,r,s)}let a=new dt;return a.setAttribute("position",new Je(r,3)),a}addEdge(e,t,n,r,s){let a=Math.min(t,n),o=Math.max(t,n),l=`${a}-${o}`;s.has(l)||(s.add(l),r.push(e[t*3],e[t*3+1],e[t*3+2],e[n*3],e[n*3+1],e[n*3+2]))}},V4e={id:"futuristicReveal",controller:UP,enabledDefault:!0};h();p();m();Lt();var nJe=parseInt(Ma.replaceAll(/\D+/g,""),10),FP=class extends Xn{constructor(){super({uniforms:{time:{value:0}},vertexShader:`
|
|
29562
29562
|
uniform float time;
|
|
29563
29563
|
attribute float size;
|
|
29564
29564
|
varying vec3 vColor;
|
|
@@ -29570,17 +29570,13 @@ void main() {
|
|
|
29570
29570
|
gl_Position = projectionMatrix * mvPosition;
|
|
29571
29571
|
}`,fragmentShader:`
|
|
29572
29572
|
uniform sampler2D pointTexture;
|
|
29573
|
-
uniform float fade;
|
|
29574
29573
|
varying vec3 vColor;
|
|
29575
29574
|
void main() {
|
|
29576
|
-
|
|
29577
|
-
// the only way to dim stars \u2014 scene fog never reaches this shader. Driven by the
|
|
29578
|
-
// rain state so stars disappear in rain like in vanilla.
|
|
29579
|
-
gl_FragColor = vec4(vColor * fade, 1.0);
|
|
29575
|
+
gl_FragColor = vec4(vColor, 1.0);
|
|
29580
29576
|
|
|
29581
29577
|
#include <tonemapping_fragment>
|
|
29582
29578
|
#include <${nJe>=154?"colorspace_fragment":"encodings_fragment"}>
|
|
29583
|
-
}`})}},VP=class{constructor(e){this.worldRenderer=e}points;timer=new Hs;enabled=!1;currentTime;fade=1;enable(){this.enabled||(this.enabled=!0,this.updateVisibility())}disable(){this.enabled&&(this.enabled=!1,this.removeStars())}toggle(){return this.enabled?this.disable():this.enable(),this.enabled}enablementCheck=()=>this.currentTime?this.currentTime>13500&&this.currentTime<23e3:!1;render=e=>{if(!this.points)return;this.points.position.set(0,0,0);let t=this.points.material;this.timer.update(performance.now()),t.uniforms.time.value=this.timer.getElapsed()*.2;let n=this.worldRenderer.worldRendererConfig.isRaining?0:1,r=Math.min(1,e*2);this.fade+=(n-this.fade)*r,t.uniforms.fade.value=this.fade};updateTimeOfDay(e){this.currentTime=e,this.enabled&&this.updateVisibility()}updateVisibility(){if(!this.enabled)return;let e=this.enablementCheck?.()??!1;e&&!this.points?this.createStars():!e&&this.points&&this.removeStars()}createStars(){if(this.points)return;let e=80,t=50,n=7e3,r=7,s=10,a=new dt,o=b=>new X().setFromSpherical(new Jf(b,Math.acos(1-Math.random()*2),Math.random()*2*Math.PI)),l=[],c=[],u=Array.from({length:n},()=>(.5+.5*Math.random())*r),d=new We,f=e+t,v=t/n;for(let b=0;b<n;b++)f-=v*Math.random(),l.push(...o(f).toArray()),d.setHSL(b/n,s,.9),c.push(d.r,d.g,d.b);a.setAttribute("position",new Je(l,3)),a.setAttribute("color",new Je(c,3)),a.setAttribute("size",new Je(u,1));let g=new FP;g.blending=es,g.depthTest=!0,g.depthWrite=!1,g.transparent=!0,this.points=new gr(a,g),this.points.renderOrder=-1,this.worldRenderer.scene.add(this.points)}dispose(){this.removeStars()}removeStars(){this.points&&(this.points.geometry.dispose(),this.points.material.dispose(),this.worldRenderer.scene.remove(this.points),this.points=void 0)}},z4e={id:"starfield",controller:VP,enabledDefault:!0,cannotBeDisabled:!0};var H4e={starfield:z4e,futuristicReveal:V4e,rain:O4e,cameraBobbing:P4e,blockBreakParticles:C4e};h();p();m();h();p();m();var zP=()=>({longRenderTime:!1,constantLongRenderTime:!1,tooManyEntities:!1,tooManyTextures:!1,unknownReason:!1});h();p();m();h();p();m();var hg=class{constructor(e){this.factors=e}renderTimeHistory=[];onFrame(e){this.pushRenderTime(e.totalMs),this.recompute(e)}pushRenderTime(e){this.renderTimeHistory.push(e),this.renderTimeHistory.length>24&&this.renderTimeHistory.shift()}recompute(e){let t=e.fps>0&&e.fps<=45,n=Math.max(0,e.totalMs-e.entitiesMs),r=e.totalMs>=30,s=this.renderTimeHistory.length,a=this.renderTimeHistory.filter(f=>f>=30).length,o=s>=8&&a/s>=.65,l=e.loadedTextureCount>=100,c=t&&e.entitiesMs>=8&&n<=20,d=t&&!(r||o||c||l);this.factors.longRenderTime=r,this.factors.constantLongRenderTime=o,this.factors.tooManyEntities=c,this.factors.tooManyTextures=l,this.factors.unknownReason=d}reset(){this.renderTimeHistory.length=0,this.factors.longRenderTime=!1,this.factors.constantLongRenderTime=!1,this.factors.tooManyEntities=!1,this.factors.tooManyTextures=!1,this.factors.unknownReason=!1}};h();p();m();var lJe=[{key:"longRenderTime",code:"LR"},{key:"constantLongRenderTime",code:"CLR"},{key:"tooManyEntities",code:"ENT"},{key:"tooManyTextures",code:"TEX"},{key:"unknownReason",code:"UNK"}];function qP(i){let e=lJe.filter(({key:t})=>i[t]).map(({code:t})=>t);return e.length>0?e.join("+"):""}var ia=class ia extends Ry{constructor(t,n,r){if(!r.resourcesManager)throw new Error("resourcesManager is required in displayOptions");super(r.resourcesManager,r,n);this.renderer=t;this.initOptions=n;this.displayOptions=r;this.performanceMonitor=new hg(this.reactiveState.world.instabilityFactors),this.renderer=t;let s=ia.getRendererInfo(t)??"...";r.rendererState.renderer=s,this.chunkMeshManager=new fg(this,this.scene,this.material,this.worldSizeParams.worldHeight,this.viewDistance),this.onRenderDistanceChanged=a=>{this.chunkMeshManager.updateViewDistance(a)},typeof window<"u"&&(window.setBlockLightmap=a=>{this.chunkMeshManager.setBlockLightmapParams(a)}),this.syncSkyLevelFromTime(this.timeOfTheDay),this.cursorBlock=new Bb(this),this.holdingBlock=sg(this),this.holdingBlockLeft=sg(this,!0);for(let a of Object.values(H4e))this.registerModule(a);this.skyboxRenderer=new qb(this.realScene,!1,null),this.skyboxRenderer.init(),this.addDebugOverlay(),this.resetScene(),this.init(),this.soundSystem=new Ob(this),this.cameraShake=new Nb(this,this.onRender),this.media=new Ub(this),this.fireworksLegacy=new zb(this),this.waypoints=new Vb(this),this.cinimaticScript=new Hb(this,(a,o,l)=>this.setCinimaticCamera(a,o,l),a=>this.setCinimaticFov(a),()=>({position:new kt(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),yaw:this.cameraShake.getBaseRotation().yaw,pitch:this.cameraShake.getBaseRotation().pitch,fov:this.camera.fov})),this.fireworks=new Gb(this.realScene,this.sceneOrigin),this.renderUpdateEmitter.on("chunkFinished",a=>{this.finishChunk(a)}),this.worldSwitchActions(),this.initializeModules()}outputFormat="threeJs";isShaderCubeBlocksEnabled(){return this.worldRendererConfig.shaderCubeBlocks===!0&&!!this.renderer?.capabilities?.isWebGL2}chunkMeshManager;get sectionObjects(){return this.chunkMeshManager.sectionObjects}cameraSectionPos=new kt(0,0,0);holdingBlock;holdingBlockLeft;scene=new Rr;get realScene(){return this.scene}ambientLight=new wa(13421772,ia.LEGACY_TO_PHYSICAL_LIGHT);directionalLight=new Ss(16777215,.5*ia.LEGACY_TO_PHYSICAL_LIGHT);entities=new Lb(this,globalThis.mcData);performanceMonitor;cameraGroupVr;material=new _t({vertexColors:!0,transparent:!0,alphaTest:.1});itemsTexture;cursorBlock;onRender=[];lastRenderTime=0;lastSciFiTickMs=0;animatedFov=0;lastFovAnimTime=0;cameraShake;cameraContainer;media;get waitingChunksToDisplay(){return this.chunkMeshManager.waitingChunksToDisplay}waypoints;cinimaticScript;camera;renderTimeAvg=0;pendingSectionUpdates=new Map;pendingSectionBufferStartTimes=new Map;get estimatedMemoryUsage(){return this.chunkMeshManager.getEstimatedMemoryUsage().total}modules={};sectionsOffsetsAnimations={};fountains=[];fireworksLegacy;DEBUG_RAYCAST=!1;skyboxRenderer;fireworks;sceneOrigin=new Wb(this.scene);cameraWorldPos={x:0,y:0,z:0};_cameraPositionAccessWarned=!1;_tmpCameraPos=new X;currentPosTween;currentRotTween;_tpDirection=new X;_tpPitchQuat=new qt;_tpYawQuat=new qt;_tpFinalQuat=new qt;_tpScenePos=new X;_tpAxisX=new X(1,0,0);_tpAxisY=new X(0,1,0);_tpChunkWorldPos=new X;get tilesRendered(){return this.chunkMeshManager.getTotalTiles()}get blocksRendered(){return this.chunkMeshManager.getTotalBlocks()}registerModule(t){if(t.id in this.modules){console.warn(`Module ${t.id} is already registered`);return}let n=new t.controller(this),r={manifest:t,controller:n,enabled:!1,toggle:()=>this.toggleModule(t.id)};this.modules[t.id]=r,t.enabledDefault&&this.toggleModule(t.id,!0)}enableModule(t){let n=this.modules[t];if(!n){console.warn(`Module ${t} not found`);return}n.enabled||(n.enabled=!0,n.controller.enable(),n.controller.render&&this.onRender.push(n.controller.render))}disableModule(t){let n=this.modules[t];if(!n){console.warn(`Module ${t} not found`);return}if(n.manifest.cannotBeDisabled){console.warn(`Module ${t} cannot be disabled`);return}if(n.enabled&&(n.enabled=!1,n.controller.disable(),n.controller.render)){let r=this.onRender.indexOf(n.controller.render);r>-1&&this.onRender.splice(r,1)}}toggleModule(t,n){let r=this.modules[t];if(!r)return console.warn(`Module ${t} not found`),!1;let s=n!==void 0?n:!r.enabled;if(s===r.enabled)return r.enabled;if(!s&&r.manifest.cannotBeDisabled)return console.warn(`Module ${t} cannot be disabled`),!0;if(r.enabled=s,s)r.controller.enable(),r.controller.render&&!this.onRender.includes(r.controller.render)&&this.onRender.push(r.controller.render);else if(r.controller.disable(),r.controller.render){let a=this.onRender.indexOf(r.controller.render);a>-1&&this.onRender.splice(a,1)}return s}setRain(t){this.worldRendererConfig.isRaining=t,this.toggleModule("rain",t)}disposeModules(){for(let t of Object.values(this.modules))t.controller.dispose();this.modules={}}initializeModules(){this.updateModulesFromConfig()}getModule(t){return this.modules[t]?.controller}anyModuleRequiresHeightmap(){return Object.values(this.modules).some(t=>t.enabled&&t.manifest.requiresHeightmap)}get cameraObject(){return this.cameraGroupVr??this.cameraContainer}_wrapCameraPositionWithWarning(){let t=this.camera.position,n=this,r=20,s=(l,c,u)=>Math.abs(l)>r||Math.abs(c)>r||Math.abs(u)>r,a=()=>{!n._cameraPositionAccessWarned&&typeof process<"u"},o=new Proxy(t,{set(l,c,u){return(c==="x"||c==="y"||c==="z")&&typeof u=="number"&&Math.abs(u)>r&&a(),l[c]=u,!0},get(l,c,u){let d=l[c];return c==="set"?function(f,v,g){return s(f,v,g)&&a(),l.set(f,v,g)}:c==="setX"||c==="setY"||c==="setZ"?function(f){return Math.abs(f)>r&&a(),l[c](f)}:c==="copy"?function(f){return s(f.x,f.y,f.z)&&a(),l.copy(f)}:typeof d=="function"?d.bind(l):d}});Object.defineProperty(this.camera,"position",{value:o,configurable:!0,enumerable:!0})}worldSwitchActions(){this.onWorldSwitched.push(()=>{this.getModule("futuristicReveal")?.onWorldSwitched?.(),this.protocolCustomBlocks.clear(),this.sectionsOffsetsAnimations={},this.waypoints.clear(),this.cinimaticScript.stopScript(),this.fireworks.clear(),this.syncSkyLevelFromTime(this.timeOfTheDay)})}downloadWorldGeometry(){MP(this,new X(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),this.cameraShake.getBaseRotation(),"world-geometry.json")}updateEntity(t,n=!1){let r={rotation:{head:{x:t.headPitch??t.pitch,y:t.headYaw,z:0}}};n?this.entities.updateEntityPosition(t,!1,r):this.entities.update(t,r)}updatePlayerEntity(t){this.entities.handlePlayerEntity(t)}resetScene(){this.sceneOrigin.update(0,0,0),this.cameraWorldPos.x=0,this.cameraWorldPos.y=0,this.cameraWorldPos.z=0,this.scene.matrixAutoUpdate=!1,this.scene.background=new We(this.initOptions.config.sceneBackground),this.scene.add(this.ambientLight),this.directionalLight.position.set(1,1,.5).normalize(),this.directionalLight.castShadow=!0,this.scene.add(this.directionalLight);let t=this.renderer.getSize(new ze);this.camera=new fn(75,t.x/t.y,.1,1e3),this._wrapCameraPositionWithWarning(),this.cameraContainer=new Ut,this.cameraContainer.add(this.camera),this.scene.add(this.cameraContainer)}watchReactivePlayerState(){super.watchReactivePlayerState(),this.onReactivePlayerStateUpdated("inWater",t=>{this.skyboxRenderer.updateWaterState(t,this.playerStateReactive.waterBreathing)}),this.onReactivePlayerStateUpdated("waterBreathing",t=>{this.skyboxRenderer.updateWaterState(this.playerStateReactive.inWater,t)}),this.onReactivePlayerStateUpdated("ambientLight",t=>{t&&(this.ambientLight.intensity=t*ia.LEGACY_TO_PHYSICAL_LIGHT)}),this.onReactivePlayerStateUpdated("directionalLight",t=>{t&&(this.directionalLight.intensity=t*ia.LEGACY_TO_PHYSICAL_LIGHT)}),this.onReactivePlayerStateUpdated("lookingAtBlock",t=>{this.cursorBlock.setHighlightCursorBlock(t?new kt(t.x,t.y,t.z):null,t?.shapes)}),this.onReactivePlayerStateUpdated("diggingBlock",t=>{this.cursorBlock.updateBreakAnimation(t?{x:t.x,y:t.y,z:t.z}:void 0,t?.stage??null,t?.mergedShape)}),this.onReactivePlayerStateUpdated("perspective",t=>{let n=new kt(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z);this.updateCamera(n,this.cameraShake.getBaseRotation().yaw,this.cameraShake.getBaseRotation().pitch)})}watchReactiveConfig(){super.watchReactiveConfig(),this.onReactiveConfigUpdated("showChunkBorders",r=>{this.updateShowChunksBorder(r)}),this.onReactiveConfigUpdated("defaultSkybox",r=>{this.skyboxRenderer.updateDefaultSkybox(r)}),this.onReactiveConfigUpdated("shaderCubeDebugMode",()=>{this.chunkMeshManager.syncCubeShaderUniforms(),this.chunkMeshManager.syncLegacyShaderUniforms()});let t=()=>{let r=this.worldRendererConfig;this.chunkMeshManager.setShadingTheme(r.shadingTheme,r.cardinalLight)};this.onReactiveConfigUpdated("shadingTheme",t),this.onReactiveConfigUpdated("cardinalLight",t),this.onReactiveConfigUpdated("futuristicReveal",()=>{this.updateModulesFromConfig()});let n=this.displayOptions.inWorldRenderingConfig.handRenderer;this.onReactiveConfigUpdated("handRenderer",r=>{if(r===n)return;n=r;let s=this.holdingBlock.ready,a=this.holdingBlockLeft.ready;this.holdingBlock.dispose(),this.holdingBlockLeft.dispose(),this.holdingBlock=sg(this),this.holdingBlockLeft=sg(this,!0),s&&(this.holdingBlock.ready=!0,this.holdingBlock.updateItem()),a&&(this.holdingBlockLeft.ready=!0,this.holdingBlockLeft.updateItem())}),this.onReactiveConfigUpdated("*",()=>{this.updateModulesFromConfig()}),this.updateModulesFromConfig()}updateModulesFromConfig(){let{moduleStates:t}=this.worldRendererConfig;for(let[n,r]of Object.entries(this.modules)){let s=t[n];if(s==="enabled"){r.enabled||this.toggleModule(n,!0);continue}if(s==="disabled"){r.enabled&&!r.manifest.cannotBeDisabled&&this.toggleModule(n,!1);continue}if(s==="auto"||s===void 0)if(r.controller.autoEnableCheck){let a=r.controller.autoEnableCheck();a&&!r.enabled?this.toggleModule(n,!0):!a&&r.enabled&&!r.manifest.cannotBeDisabled&&this.toggleModule(n,!1)}else{let a=r.manifest.enabledDefault??!1;a&&!r.enabled?this.toggleModule(n,!0):!a&&r.enabled&&!r.manifest.cannotBeDisabled&&this.toggleModule(n,!1)}}}changeHandSwingingState(t,n=!1){let r=n?this.holdingBlockLeft:this.holdingBlock;t?r.startSwing():r.stopSwing()}async updateAssetsData(){let t=this.resourcesManager.currentResources,n=this.material.map,r=this.itemsTexture,s=cc(t.blocksAtlasImage);s.needsUpdate=!0,s.flipY=!1,this.material.map=s,this.chunkMeshManager.syncCubeShaderUniforms(),this.chunkMeshManager.syncLegacyShaderUniforms();let a=cc(t.itemsAtlasImage);a.needsUpdate=!0,a.flipY=!1,this.itemsTexture=a,n&&n.dispose(),r&&r.dispose(),await super.updateAssetsData(),this.onAllTexturesLoaded(),Object.keys(this.loadedChunks).length>0&&(console.log("rerendering chunks because of texture update"),this.rerenderAllChunks())}onAllTexturesLoaded(){this.holdingBlock.ready=!0,this.holdingBlock.updateItem(),this.holdingBlockLeft.ready=!0,this.holdingBlockLeft.updateItem()}changeBackgroundColor(t){this.realScene.background=new We(t[0],t[1],t[2])}changeCardinalLight(t){this.worldRendererConfig.cardinalLight=t}timeUpdated(t){let n=this.getModule("starfield");n?.updateTimeOfDay&&n.updateTimeOfDay(t),this.skyboxRenderer.updateTime(t),this.syncSkyLevelFromTime(t)}syncSkyLevelFromTime(t){let n=Ml(t)/15;this.chunkMeshManager.setSkyLevel(n)}onDayCycleSkyLightChanged(t){}biomeUpdated(t){t?.temperature!==void 0&&this.skyboxRenderer.updateTemperature(t.temperature)}biomeReset(){this.skyboxRenderer.updateTemperature(vP)}getItemRenderData(t,n){return k_e(t,n,this.resourcesManager,this.playerStateReactive)}async demoModel(){let t=cursorBlockRel(0,1,0).position,n=await Pv();Sve(n,t);let r=new Ea(n,16776960);n.add(r),this.realScene.add(n)}demoItem(){let t=cursorBlockRel(0,1,0).position,{mesh:n}=this.entities.getItemMesh({itemId:541},{});n.position.set(t.x+.5,t.y+.5,t.z+.5);let r=new Ea(n,16776960);n.add(r),this.realScene.add(n)}debugOverlayAdded=!1;addDebugOverlay(){if(this.debugOverlayAdded)return;this.debugOverlayAdded=!0;let t=i4("debug-overlay",80,0,void 0,{className:r4});setInterval(()=>{if(t.setVisibility(this.displayAdvancedStats),this.displayAdvancedStats){let n=c=>new Intl.NumberFormat("en-US",{}).format(c),r=c=>new Intl.NumberFormat("en-US",{notation:"compact",maximumFractionDigits:1}).format(c),s="";s+=`TE: ${n(this.renderer.info.memory.textures)} `;let a=this.chunkMeshManager.getGlobalBufferStats();if(a.shaderFaces){let c=a.shaderFaces;s+=`CUBE: ${r(c.used)}/${r(c.capacity)}f `}if(a.legacyOpaque){let c=a.legacyOpaque;s+=`LEG-O: ${r(c.used)}/${r(c.capacity)}q `}if(a.legacyBlend){let c=a.legacyBlend;s+=`LEG-B: ${r(c.used)}/${r(c.capacity)}q `}s+=`MEM: ${this.chunkMeshManager.getEstimatedMemoryUsage().total} `;let o=this.cameraCollisionBlockCache.getAllocatedBytes();o>0&&(s+=`CAM: ${r(o)}b `);let l=qP(this.reactiveState.world.instabilityFactors);l&&(s+=`PF: ${l} `),t.updateText(s),this.backendInfoReport=s}},200)}updatePosDataChunk(t){let n=this.sectionObjects[t];if(!n)return;let[r,s,a]=t.split(",").map(u=>Math.floor(+u/16)),l=500-(Math.abs(r-this.cameraSectionPos.x)+Math.abs(s-this.cameraSectionPos.y)+Math.abs(a-this.cameraSectionPos.z)),c=n.mesh??n.shaderMesh??n.children.find(u=>u.name==="mesh"||u.name==="shaderMesh");c&&(c.renderOrder=l)}cameraSectionPositionUpdate(){for(let t in this.sectionObjects)this.sectionObjects[t]&&this.updatePosDataChunk(t)}getDir(t,n){return t===n?0:t<n?1:-1}finishChunk(t){this.chunkMeshManager.finishChunkDisplay(t),this.getModule("futuristicReveal")?.onChunkFinished?.()}applyPendingSectionUpdates(){if(this.pendingSectionUpdates.size===0)return;let t=performance.now(),n=this.getSectionHeight(),r=[];for(let s of this.pendingSectionUpdates.keys()){let a=this.pendingSectionBufferStartTimes.get(s)??t;if(t-a<ia.MAX_SECTION_UPDATE_BUFFER_MS){let[l,c,u]=s.split(",").map(Number),d=[`${l-16},${c},${u}`,`${l+16},${c},${u}`,`${l},${c-n},${u}`,`${l},${c+n},${u}`,`${l},${c},${u-16}`,`${l},${c},${u+16}`],f=!1;for(let v of d)if(this.sectionsWaiting.has(v)&&!this.pendingSectionUpdates.has(v)&&this.sectionObjects[v]){f=!0;break}if(f)continue}r.push(s)}if(r.length!==0)for(let s of r){let a=this.pendingSectionUpdates.get(s);this.pendingSectionUpdates.delete(s),this.pendingSectionBufferStartTimes.delete(s);let o=a.key.split(","),l=`${o[0]},${o[2]}`;if(!this.loadedChunks[l]||!this.active){this.chunkMeshManager.releaseSection(a.key);continue}if(!this.chunkMeshManager.sectionHasRenderableContent(a.geometry)){this.chunkMeshManager.releaseSection(a.key);continue}let c=this.chunkMeshManager.updateSection(a.key,a.geometry);this.updatePosDataChunk(a.key),c&&this.getModule("futuristicReveal")?.onSectionMeshed?.(a.key,a.geometry,c)}}clearPendingSectionUpdatesForChunk(t,n){for(let r of[...this.pendingSectionUpdates.keys()])r.startsWith(`${t},`)&&r.endsWith(`,${n}`)&&(this.pendingSectionUpdates.delete(r),this.pendingSectionBufferStartTimes.delete(r))}handleWorkerMessage(t){if(t.type==="geometry"){let n=t.key.split(","),r=`${n[0]},${n[2]}`;if(!this.loadedChunks[r]||!this.active){this.pendingSectionUpdates.delete(t.key),this.pendingSectionBufferStartTimes.delete(t.key);return}if(this.sectionObjects[t.key]){this.pendingSectionUpdates.set(t.key,t),this.pendingSectionBufferStartTimes.has(t.key)||this.pendingSectionBufferStartTimes.set(t.key,performance.now());return}if(!this.chunkMeshManager.sectionHasRenderableContent(t.geometry)){this.chunkMeshManager.releaseSection(t.key);return}let s=this.chunkMeshManager.updateSection(t.key,t.geometry);this.updatePosDataChunk(t.key),s&&this.getModule("futuristicReveal")?.onSectionMeshed?.(t.key,t.geometry,s)}}getCameraPosition(t){return(t??this._tmpCameraPos).set(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z)}getSectionCameraPosition(){let t=this.getCameraPosition();return new kt(Math.floor(t.x/16),Math.floor(t.y/16),Math.floor(t.z/16))}updateCameraSectionPos(){let t=this.getSectionCameraPosition();this.cameraSectionPos.equals(t)||(this.cameraSectionPos=t,this.cameraSectionPositionUpdate())}setFirstPersonCamera(t,n,r){let s=this.playerStateReactive.eyeHeight;this.updateCamera(t?.offset(0,s,0)??null,n,r),this.updateCameraSectionPos()}getThirdPersonCamera(t,n,r){t??=new X(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z);let s=this.playerStateReactive.perspective==="third_person_back",a=4,o=this._tpDirection.set(0,0,-1),l=this._tpPitchQuat.setFromAxisAngle(this._tpAxisX,r),c=this._tpYawQuat.setFromAxisAngle(this._tpAxisY,n),u=this._tpFinalQuat.multiplyQuaternions(c,l);o.applyQuaternion(u),s&&o.multiplyScalar(-1),this.DEBUG_RAYCAST&&this.debugRaycast(t,o,a);let d=.25,f=.05,v=.4,g=this.cameraCollisionBlockCache,b=k4e(t.x,t.y,t.z,o.x,o.y,o.z,a,d,f,(_,x,w)=>g.isSolidBlock(_,x,w)),y=a;return b!==void 0&&(y=Math.min(y,b.distance)),y<v&&(y=v),new kt(t.x+o.x*y,t.y+o.y*y,t.z+o.z*y)}debugRaycastHelper;debugHitPoint;debugRaycast(t,n,r){this.debugRaycastHelper&&(this.realScene.remove(this.debugRaycastHelper),this.debugRaycastHelper=void 0),this.debugHitPoint&&(this.realScene.remove(this.debugHitPoint),this.debugHitPoint=void 0);let s=new X(this.sceneOrigin.toSceneX(t.x),this.sceneOrigin.toSceneY(t.y),this.sceneOrigin.toSceneZ(t.z));this.debugRaycastHelper=new F0(n.clone().normalize(),s,r,16711680,r*.1,r*.05),this.realScene.add(this.debugRaycastHelper);let a=new xs(.2,8,8),o=new _t({color:65280});this.debugHitPoint=new Ke(a,o),this.debugHitPoint.position.copy(s).add(n.clone().multiplyScalar(r)),this.realScene.add(this.debugHitPoint)}prevFramePerspective=null;setCinimaticCamera(t,n,r){this.cameraWorldPos.x=t.x,this.cameraWorldPos.y=t.y,this.cameraWorldPos.z=t.z,this.sceneOrigin.update(t.x,t.y,t.z),this.cameraObject.position.set(0,0,0),this.cameraShake.setBaseRotation(r,n),this.updateCameraSectionPos()}setCinimaticFov(t){this.animatedFov=t,this.camera.fov=t,this.camera.updateProjectionMatrix()}updateSmoothFov(){if(this.cinimaticScript.running)return;let t=this.displayOptions.inWorldRenderingConfig.fov,n=this.playerStateReactive.fovMultiplier,r=t*(Number.isFinite(n)?n:1),s=performance.now();if(this.animatedFov===0&&(this.animatedFov=r),Math.abs(this.animatedFov-r)>=.01){let a=s-this.lastFovAnimTime,o=Math.min(a/ia.FOV_TRANSITION_MS,1),l=c=>1-(1-c)**3;this.animatedFov+=(r-this.animatedFov)*l(o),Math.abs(this.animatedFov-r)<.01&&(this.animatedFov=r)}else this.animatedFov=r;this.lastFovAnimTime=s,this.camera.fov!==this.animatedFov&&(this.camera.fov=this.animatedFov,this.camera.updateProjectionMatrix())}updateCamera(t,n,r){if(!this.cinimaticScript.running){if(t){this.renderer.xr.isPresenting&&(t.y-=this.camera.position.y),this.currentPosTween?.stop();let s=this.displayOptions.inWorldRenderingConfig.instantCameraUpdate?0:this.playerStateUtils.isSpectatingEntity()?150:50;this.currentPosTween=new jr(this.cameraWorldPos).to({x:t.x,y:t.y,z:t.z},s).onUpdate(()=>{this.sceneOrigin.update(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),this.cameraObject.position.set(0,0,0)}).start()}if(this.playerStateUtils.isSpectatingEntity()){let s=this.cameraShake.getBaseRotation(),a=0,o=Math.PI/2;s.yaw<o&&n>Math.PI+o?a=-Math.PI*2:n<o&&s.yaw>Math.PI+o&&(a=Math.PI*2),this.currentRotTween?.stop(),this.currentRotTween=new jr(s).to({pitch:r,yaw:n+a},100).onUpdate(l=>this.cameraShake.setBaseRotation(l.pitch,l.yaw-a)).start()}else{this.currentRotTween?.stop(),this.cameraShake.setBaseRotation(r,n);let{perspective:s}=this.playerStateReactive;if(s==="third_person_back"||s==="third_person_front"){let a=new X(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),o=this.getThirdPersonCamera(a,n,r),l=a.distanceTo(new X(o.x,o.y,o.z)),c=s==="third_person_back"?l:-l;this.camera.position.set(0,0,c),s==="third_person_front"?this.camera.rotation.set(0,Math.PI,0):this.camera.rotation.set(0,0,0)}else this.camera.position.z=0,this.camera.rotation.set(0,0,0),this.debugRaycastHelper&&(this.realScene.remove(this.debugRaycastHelper),this.debugRaycastHelper=void 0),this.debugHitPoint&&(this.realScene.remove(this.debugHitPoint),this.debugHitPoint=void 0)}this.updateCameraSectionPos()}}debugChunksVisibilityOverride(){let{chunksRenderAboveOverride:t,chunksRenderBelowOverride:n,chunksRenderDistanceOverride:r,chunksRenderAboveEnabled:s,chunksRenderBelowEnabled:a,chunksRenderDistanceEnabled:o}=this.reactiveDebugParams,l=this.getSectionHeight(),c=this.cameraSectionPos.y*l;if(this.displayOptions.inWorldRenderingConfig.enableDebugOverlay&&t!==void 0||n!==void 0||r!==void 0)for(let[u,d]of Object.entries(this.sectionObjects)){if(d._waitingForChunkDisplay)continue;let[f,v,g]=u.split(",").map(Number),b=s&&t!==void 0?v<=c+t:a&&n!==void 0?v>=c-n:o&&r!==void 0?Math.abs(v-c)<=r:!0;d.visible=b}else this.chunkMeshManager.updateSectionsVisibility()}render(t=!1){if(this.currentRenderedFrames++,this.reactiveDebugParams.stopRendering)return;this.debugChunksVisibilityOverride();let n=performance.now();this.lastRendered=performance.now();let r=this.lastRenderTime>0?Math.min(Math.max((n-this.lastRenderTime)/1e3,0),.1):1/60;this.lastRenderTime=n,this.cursorBlock.render(),this.updateSectionOffsets();let s=this.getCameraPosition();if(this.skyboxRenderer.update(s,this.viewDistance),this.updateSmoothFov(),t){let w=this.renderer.getSize(new ze);this.camera.aspect=w.width/w.height,this.camera.updateProjectionMatrix()}let a=0;if(!this.reactiveDebugParams.disableEntities){let w=performance.now();this.entities.render(),a=performance.now()-w}let o=this.cameraGroupVr instanceof bt?this.cameraGroupVr.children.find(w=>w instanceof fn):this.camera;this.applyPendingSectionUpdates();let l=performance.now(),c=l-this.lastSciFiTickMs;this.lastSciFiTickMs=l,this.getModule("futuristicReveal")?.tick?.(c,l);let u=this.cameraWorldPos.x,d=this.cameraWorldPos.y,f=this.cameraWorldPos.z;this.chunkMeshManager.maybeRebase({x:u,y:d,z:f});let v=this.chunkMeshManager.getRenderOrigin(),g=this.chunkMeshManager.globalBlockBuffer;g&&(g.setCameraOrigin(v,u,d,f),g.setDebugOverlay(this.displayOptions.inWorldRenderingConfig.enableDebugOverlay),g.compactStep(),g.hasPendingUploads()&&g.uploadDirtyRange(),g.suppressThreeDraw());let b=this.chunkMeshManager.globalLegacyBuffer;b&&(b.setDebugOverlay(this.displayOptions.inWorldRenderingConfig.enableDebugOverlay),b.compactStep(),b.hasPendingUploads()&&b.uploadDirtyRange(),b.suppressThreeDraw());let y=this.chunkMeshManager.globalLegacyBlendBuffer;y&&(y.setDebugOverlay(this.displayOptions.inWorldRenderingConfig.enableDebugOverlay),y.compactStep(),y.hasPendingUploads()&&y.uploadDirtyRange(),y.suppressThreeDraw()),this.chunkMeshManager.markCullDirtyIfBufferStateChanged(),this.chunkMeshManager.setLegacyCameraOrigin(u,d,f),this.chunkMeshManager.updateCullDirtyFromCamera(o,u,d,f),this.chunkMeshManager.cullDirty&&(this.chunkMeshManager.updateSectionCullAndSort(o,this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),this.chunkMeshManager.clearCullDirty()),this.renderer.render(this.scene,o),this.displayOptions.inWorldRenderingConfig.showHand&&this.playerStateReactive.gameMode!=="spectator"&&this.playerStateReactive.perspective==="first_person"&&!this.renderer.xr.isPresenting&&(this.holdingBlock.render(this.camera,this.renderer,this.ambientLight,this.directionalLight),this.holdingBlockLeft.render(this.camera,this.renderer,this.ambientLight,this.directionalLight));for(let w of this.fountains)this.sectionObjects[w.sectionId]&&!this.sectionObjects[w.sectionId].foutain&&(w.createParticles(this.sectionObjects[w.sectionId]),this.sectionObjects[w.sectionId].foutain=!0),w.render();this.waypoints.render(),this.fireworks.update();for(let w of this.onRender)w(r);let x=performance.now()-n;this.worldRendererConfig.autoLowerRenderDistance&&this.chunkMeshManager.recordRenderTime(x),this.renderTimeAvgCount++,this.renderTimeAvg=(this.renderTimeAvg*(this.renderTimeAvgCount-1)+x)/this.renderTimeAvgCount,this.renderTimeMax=Math.max(this.renderTimeMax,x),this.performanceMonitor.onFrame({totalMs:x,entitiesMs:a,loadedTextureCount:this.renderer.info.memory.textures,fps:this.lastFps})}renderHead(t,n,r,s){let a;if(s.SkullOwner?a=s.SkullOwner.Properties?.textures?.[0]?.Value:a=s.profile?.properties?.find(o=>o.name==="textures")?.value,!!a)try{let l=JSON.parse(Buffer.from(a,"base64").toString()).textures?.SKIN?.url,{skinTexturesProxy:c}=this.worldRendererConfig;c&&(l=l?.replace("http://textures.minecraft.net/",c).replace("https://textures.minecraft.net/",c));let u=$c(this,l,Yc.head),d=new bt;return r&&u.position.set(0,.3125,.3125),u.position.y-=23/16,d.add(u),this.sceneOrigin.track(d),d.position.set(t.x+.5,t.y+.045,t.z+.5),d.rotation.set(0,-Ot.degToRad(n*(r?90:45/2)),0),d.scale.set(.8,.8,.8),d}catch(o){console.error("Error decoding player texture:",o)}}lightUpdate(t,n){for(let r=this.worldSizeParams.minY;r<this.worldSizeParams.worldHeight;r+=16)this.setSectionDirty(new kt(t,r,n))}rerenderAllChunks(){for(let t of Object.keys(this.sectionObjects)){let[n,r,s]=t.split(",").map(Number);this.setSectionDirty(new kt(n,r,s))}}updateShowChunksBorder(t){this.chunkMeshManager.updateAllBoxHelpers(t)}resetWorld(){super.resetWorld(),this.pendingSectionUpdates.clear(),this.pendingSectionBufferStartTimes.clear(),this.chunkMeshManager.dispose(),this.chunkMeshManager=new fg(this,this.scene,this.material,this.worldSizeParams.worldHeight,this.viewDistance),this.debugRaycastHelper&&(this.realScene.remove(this.debugRaycastHelper),this.debugRaycastHelper=void 0),this.debugHitPoint&&(this.realScene.remove(this.debugHitPoint),this.debugHitPoint=void 0)}getLoadedChunksRelative(t,n=!1){let[r,s,a]=NE(t);return Object.fromEntries(Object.entries(this.sectionObjects).map(([o,l])=>{let[c,u,d]=o.split(",").map(Number),[f,v,g]=NE({x:c,y:u,z:d});return[n?`${f-r},${v-s},${g-a}`:`${f-r},${g-a}`,l]}))}readdChunks(){for(let t of Object.keys(this.sectionObjects))this.scene.remove(this.sectionObjects[t]);setTimeout(()=>{for(let t of Object.keys(this.sectionObjects))this.scene.add(this.sectionObjects[t])},500)}disableUpdates(t=this.scene.children){for(let n of t)n.matrixWorldNeedsUpdate=!1,this.disableUpdates(n.children??[])}removeColumn(t,n){super.removeColumn(t,n),this.clearPendingSectionUpdatesForChunk(t,n);let r=this.getSectionHeight(),s=this.worldMinYRender;for(let a=s;a<this.worldSizeParams.worldHeight;a+=r){let o=`${t},${a},${n}`;this.chunkMeshManager.sectionObjects[o]&&this.chunkMeshManager.releaseSection(o)}this.chunkMeshManager.onChunkRemovedFromGate(`${t},${n}`)}updateViewerPosition(t){super.updateViewerPosition(t),this.chunkMeshManager.pendingNearReveal.size>0&&this.chunkMeshManager.tryRevealPending()}onViewerChunkPositionChanged(){this.chunkMeshManager.tryRevealPending()}setSectionDirty(...t){super.setSectionDirty(...t)}static getRendererInfo(t){try{let n=t.getContext();return`${n.getParameter(n.getExtension("WEBGL_debug_renderer_info").UNMASKED_RENDERER_WEBGL)}`}catch(n){console.warn("Failed to get renderer info",n)}}worldStop(){this.media.onWorldStop()}destroy(){this.performanceMonitor?.reset(),this.pendingSectionUpdates.clear(),this.pendingSectionBufferStartTimes.clear(),this.chunkMeshManager.dispose(),this.disposeModules(),this.fireworksLegacy.destroy(),super.destroy(),this.skyboxRenderer.dispose(),this.fireworks.dispose()}shouldObjectVisible(t){let r=this.getSectionHeight(),s,a,o,l=this.sceneOrigin.getWorldPosition(t);l?(s=l.x,a=l.y,o=l.z):(s=this.sceneOrigin.toWorldX(t.position.x),a=this.sceneOrigin.toWorldY(t.position.y),o=this.sceneOrigin.toWorldZ(t.position.z));let c=Math.floor(s/16)*16,u=Math.floor(o/16)*16,d=Math.floor(a/r)*r,f=`${c},${u}`,v=`${c},${d},${u}`;return!!this.finishedChunks[f]||!!this.sectionObjects[v]}handleUserClick(t){this.media.handleUserClick(t)}updateSectionOffsets(){let t=performance.now();for(let[n,r]of Object.entries(this.sectionsOffsetsAnimations)){let s=(t-r.time)/1e3;r.time=t,r.currentOffsetX+=r.speedX*s,r.currentOffsetY+=r.speedY*s,r.currentOffsetZ+=r.speedZ*s,r.limitX!==void 0&&(r.speedX>0?r.currentOffsetX=Math.min(r.currentOffsetX,r.limitX):r.currentOffsetX=Math.max(r.currentOffsetX,r.limitX)),r.limitY!==void 0&&(r.speedY>0?r.currentOffsetY=Math.min(r.currentOffsetY,r.limitY):r.currentOffsetY=Math.max(r.currentOffsetY,r.limitY)),r.limitZ!==void 0&&(r.speedZ>0?r.currentOffsetZ=Math.min(r.currentOffsetZ,r.limitZ):r.currentOffsetZ=Math.max(r.currentOffsetZ,r.limitZ));let a=this.sectionObjects[n];a&&(a.position.set(r.currentOffsetX,r.currentOffsetY,r.currentOffsetZ),a.updateMatrix())}}reloadWorld(){this.entities.reloadEntities()}};Wn(ia,"LEGACY_TO_PHYSICAL_LIGHT",Math.PI),Wn(ia,"FOV_TRANSITION_MS",200),Wn(ia,"MAX_SECTION_UPDATE_BUFFER_MS",500);var Yd=ia;h();p();m();h();p();m();var mg="1.21.4";h();p();m();function Jd(i,e){i.aspect=e.width/e.height,i.updateProjectionMatrix()}h();p();m();h();p();m();var u0={mode:"v2",minecraftTextures:!0,v2Scene:"light",v2Camera:"dive",v2BlockGroup:"stainedGlass",v2CameraSpeedPercent:80,v2BlockSpeedPercent:40},GP=i=>i/100,g9={camera:GP(u0.v2CameraSpeedPercent),block:GP(u0.v2BlockSpeedPercent)};function WP(i,e=!1){return i?.mode?i.mode:e?"worldBlocks":u0.mode}h();p();m();Lt();h();p();m();var jP={};function XP(...i){let e=i.filter(n=>n.length>0).join("/"),t=typeof globalThis.location<"u"&&globalThis.location.href?globalThis.location.href:typeof jP<"u"&&jP.url?jP.url:`/${e}`;try{return new URL(e,t).href}catch{return`/${e}`}}var $P=new Date,W4e=$P.getMonth()===11&&$P.getDate()>=24&&$P.getDate()<=26,cJe=["panorama_3.webp","panorama_1.webp","panorama_4.webp","panorama_5.webp","panorama_0.webp","panorama_2.webp"],uJe=200,pg=class{constructor(e){this.documentRenderer=e;this.scene=new Rr,this.scene.background=new We(3294568);let t=new wa(13421772);this.scene.add(t);let n=new Ss(16777215,.5);n.position.set(1,1,.5).normalize(),n.castShadow=!0,this.scene.add(n),this.camera=new fn(85,e.canvas.width/e.canvas.height,.05,1e3),this.camera.position.set(0,0,0),this.camera.rotation.set(0,0,0)}scene;camera;startTimes=new Map;time=0;panoramaGroup=null;async init(){this.buildCubemap()}update(e,t){t&&Jd(this.camera,this.documentRenderer.canvas)}dispose(){this.scene.clear(),this.panoramaGroup=null,this.startTimes.clear()}buildCubemap(){let e=new Sn(1e3,1e3,1e3),t=[];for(let s of cJe)(async()=>{let o=XP("background",W4e?"christmas":"",s),l=await qu(o),c=cc(l);c.matrixAutoUpdate=!1,c.matrix.set(-1,0,1,0,1,0,0,0,1),c.wrapS=jn,c.wrapT=jn,c.minFilter=$t,c.magFilter=$t;let u=new _t({map:c,transparent:!0,side:In,depthWrite:!1,opacity:0});this.startTimes.set(u,Date.now()),t.push(u)})().catch(o=>{console.warn("[ClassicMenuBackground] Failed to load panorama face:",s,o)});let n=new Ke(e,t);n.onBeforeRender=()=>{this.time+=.01,n.rotation.y=Math.PI+this.time*.01,n.rotation.z=Math.sin(-this.time*.001)*.001;for(let s of t){let a=this.startTimes.get(s);if(a){let o=Date.now()-a;s.opacity=Math.min(1,o/uJe)}}};let r=new Ut;if(r.add(n),!W4e)for(let s=0;s<20;s++){let a=new o0("1.16.4","squid").mesh;a.position.set(Math.random()*30-15,Math.random()*20-10,Math.random()*10-17),a.rotation.set(0,Math.PI+Math.random(),-Math.PI/4,"ZYX");let o=Math.random()*.01;a.children[0].onBeforeRender=()=>{a.rotation.y+=o,a.rotation.z=Math.cos(n.rotation.y*3)*Math.PI/4-Math.PI/2},r.add(a)}this.scene.add(r),this.panoramaGroup=r}async debugImageInFrontOfCamera(){let e=await qu(XP("background","panorama_0.webp")),t=cc(e),n=new Ke(new zn(1e3,1e3),new _t({map:t}));n.position.set(0,0,-500),this.scene.add(n)}};h();p();m();Lt();h();p();m();var q5=["galaxy","nether","end","cyber","light"],G5=["cruise","barrel","dive","orbit","snake"],_9={galaxy:"Galaxy",nether:"Nether",end:"The End",cyber:"Cyber",light:"Light Space"},y9={cruise:"Cruise",barrel:"Barrel",dive:"Dive",orbit:"Orbit",snake:"Snake"},W5=["mixed","stainedGlass","wool","construction","glow","world"],b9={mixed:"Mixed",stainedGlass:"Stained glass",wool:"Wool",construction:"Construction",glow:"Glow",world:"World (grass & ores)"};var j4e=.1,Y4e={mixed:["white_wool","cyan_wool","blue_wool","purple_wool","white_stained_glass","cyan_stained_glass","blue_stained_glass","purple_stained_glass","glowstone","sea_lantern","amethyst_block","copper_block","gold_block","diamond_block"],stainedGlass:["white_stained_glass","orange_stained_glass","magenta_stained_glass","light_blue_stained_glass","yellow_stained_glass","lime_stained_glass","pink_stained_glass","gray_stained_glass","light_gray_stained_glass","cyan_stained_glass","purple_stained_glass","blue_stained_glass","brown_stained_glass","green_stained_glass","red_stained_glass","black_stained_glass"],wool:["white_wool","orange_wool","magenta_wool","light_blue_wool","yellow_wool","lime_wool","pink_wool","gray_wool","light_gray_wool","cyan_wool","purple_wool","blue_wool","brown_wool","green_wool","red_wool","black_wool"],construction:["copper_block","exposed_copper","weathered_copper","oxidized_copper","cut_copper","exposed_cut_copper","weathered_cut_copper","oxidized_cut_copper","iron_block","gold_block","diamond_block","emerald_block","netherite_block","lapis_block","redstone_block","coal_block","quartz_block","amethyst_block","bricks","stone_bricks","deepslate_bricks","polished_blackstone"],glow:["glowstone","sea_lantern","shroomlight","ochre_froglight","verdant_froglight","pearlescent_froglight","redstone_lamp","beacon"],world:["grass_block","podzol","mycelium","dirt","coarse_dirt","rooted_dirt","mud","clay","stone","cobblestone","mossy_cobblestone","deepslate","cobbled_deepslate","tuff","calcite","sand","red_sand","gravel","snow_block","coal_ore","deepslate_coal_ore","iron_ore","deepslate_iron_ore","copper_ore","deepslate_copper_ore","gold_ore","deepslate_gold_ore","diamond_ore","deepslate_diamond_ore","emerald_ore","deepslate_emerald_ore","lapis_ore","deepslate_lapis_ore","redstone_ore","deepslate_redstone_ore","nether_gold_ore","ancient_debris","oak_log","birch_log","spruce_log","jungle_log","acacia_log","dark_oak_log","mangrove_log","cherry_log","netherrack","soul_sand","basalt","end_stone"]},X4e={galaxy:{bg:132114,fog:132114,fogD:.011,blocks:[61695,54527,47359,59647,2280703,43263],emit:[13158,8789,6724],nebula:[4403,1114146,4386],galFn:i=>new We(i*.05,i*.2,i),ambient:264216,dir:3368703,pt1:43775,pt2:16729343,name:"GALAXY"},nether:{bg:917760,fog:917760,fogD:.016,blocks:[16720384,16737792,16750848,13373696,16729122,16755200],emit:[2230272,1114112,3346688],nebula:[1704960,851968,1705984],galFn:i=>new We(i,i*.15,0),ambient:1573376,dir:16724736,pt1:16729088,pt2:16755200,name:"NETHER"},end:{bg:0,fog:0,fogD:.009,blocks:[7807658,11158732,5570679,14527231,3342421,12299007],emit:[655381,1572901,327696],nebula:[524312,851989,262158],galFn:i=>new We(i*.4,0,i),ambient:393232,dir:10040319,pt1:11158783,pt2:4456618,name:"THE END"},cyber:{bg:792610,fog:792610,fogD:.008,blocks:[65535,4521932,11206468,6741503,8978278,65450],emit:[666163,668450,665656],nebula:[1192e3,1587240,1323588],galFn:i=>new We(i*.15,i*.85,i*.95),ambient:1716288,dir:6750156,pt1:4521966,pt2:10092356,name:"CYBER",starColor:13431039,starOpacity:.75,galaxyOpacity:.62,nebulaOpacity:.36,edgeLineColor:4521949,blockOpacity:[.38,.54]},light:{bg:8951984,fog:7899296,fogD:.006,gradientBg:{top:14214392,mid:10531016,bottom:6846608,radial:!0},blocks:[15266559,13691135,12114175,10537208,8960240,7383272,10012927,12640511,15792383,7909608,14216447,14739711],emit:[6854864,8958176,11061488,12638456],nebula:[9480392,11059424,12637420,14215416,7901360],galFn:i=>{let e=new We;return i<.4?e.lerpColors(new We(16054527),new We(14215423),i/.4):i<.75?e.lerpColors(new We(14215423),new We(11061488),(i-.4)/.35):e.lerpColors(new We(11061488),new We(9482464),(i-.75)/.25),e},ambient:7899296,dir:13688040,pt1:11061503,pt2:13162751,name:"LIGHT",starColor:15266047,starOpacity:.5,galaxyOpacity:.7,nebulaOpacity:.32,edgeLineColor:10010856,blockOpacity:[.42,.56]}},dJe={cruise:{pos:(i,e,t)=>({x:Math.sin(i*.28)*18+Math.cos(i*.11)*7+e*10,y:Math.sin(i*.19)*6+Math.cos(i*.31)*3+t*6,z:0}),look:(i,e,t)=>({x:Math.sin((i+.18)*.28)*18+e*8,y:Math.sin((i+.18)*.19)*6+t*4,z:-25}),roll:(i,e=0)=>e*.05+Math.sin(i*.22)*.015,spd:.18},barrel:{pos:(i,e,t)=>{let r=i*2.4;return{x:Math.cos(r)*10+e*4,y:Math.sin(r)*10+t*4,z:Math.sin(i*.4)*8}},look:i=>({x:Math.sin(i*.5)*5,y:Math.cos(i*.5)*5,z:-30}),roll:i=>i*2.4+Math.PI*.5,spd:.24},dive:{pos:(i,e,t)=>({x:Math.sin(i*.6)*30+e*8,y:Math.cos(i*.4)*18+t*6,z:Math.sin(i*.3)*12}),look:(i,e,t)=>({x:Math.sin(i*.6+.2)*30+e*6,y:Math.cos(i*.4+.2)*18-8+t*4,z:-35}),roll:(i,e=0)=>e*.08+Math.sin(i*.6)*.12,spd:.3},orbit:{pos:(i,e,t)=>({x:Math.cos(i*.5)*20+e*5,y:Math.sin(i*.25)*10+t*5,z:Math.sin(i*.5)*20}),look:()=>({x:0,y:0,z:-60}),roll:i=>Math.sin(i*.5)*.08,spd:.15},snake:{pos:(i,e,t)=>({x:Math.sin(i*1.1)*22+Math.sin(i*.37)*8+e*10,y:Math.sin(i*.7)*10+e*4+t*8,z:0}),look:(i,e,t)=>{let n=i+.12;return{x:Math.sin(n*1.1)*22+Math.sin(n*.37)*8+e*8,y:Math.sin(n*.7)*10+t*6,z:-22}},roll:(i,e=0)=>e*.1+Math.sin(i*1.1)*.06,spd:.22}},fJe={cruise:1,barrel:1.6,dive:2.2,orbit:.7,snake:1.4},hJe=250,x9=1e4,w9=3e3,j5=i=>i[Math.floor(Math.random()*i.length)],YP=i=>"#"+i.toString(16).padStart(6,"0"),$4e=i=>{if(typeof document>"u")return null;let e=document.createElement("canvas");e.width=4,e.height=512;let t=e.getContext("2d");if(!t)return null;let n=e.width,r=e.height,s=i.radial?t.createRadialGradient(n/2,r*.32,0,n/2,r*.32,r*.85):t.createLinearGradient(0,0,0,r);s.addColorStop(0,YP(i.top)),i.mid!=null&&s.addColorStop(.45,YP(i.mid)),s.addColorStop(1,YP(i.bottom)),t.fillStyle=s,t.fillRect(0,0,n,r);let a=new On(e);return a.needsUpdate=!0,a},X5=class{constructor(e,t={},n){this.documentRenderer=e;this.abortSignal=n;let r=u0;this.curScene=t.initialScene??r.v2Scene,this.curCam=t.initialCamera??r.v2Camera,this.blockGroup=t.initialBlockGroup??r.v2BlockGroup,this.cameraSpeed=t.initialCameraSpeed??g9.camera,this.blockSpeed=t.initialBlockSpeed??g9.block,this.useMinecraftTextures=t.useMinecraftTextures??r.minecraftTextures,this.resourcesManager=t.resourcesManager;let s=X4e[this.curScene];this.scene=new Rr,this.scene.fog=new C0(s.fog,s.fogD),this.applyScenePalette(s),this.camera=new fn(80,this.documentRenderer.canvas.width/this.documentRenderer.canvas.height,.1,700),this.ambient=new wa(s.ambient,2.5),this.scene.add(this.ambient),this.dir=new Ss(s.dir,4),this.dir.position.set(1,1,0),this.scene.add(this.dir),this.pt1=new yo(s.pt1,5,100),this.scene.add(this.pt1),this.pt2=new yo(s.pt2,4,80),this.pt2.position.set(30,20,-30),this.scene.add(this.pt2);for(let f=0;f<hJe;f++)this.spawnBlock(s,!0);if(!this.useMinecraftTextures){let f=s.edgeLineColor??62975;for(let v=0;v<40;v++){let g=new Pn({color:f,transparent:!0,opacity:.25});j5(this.blocks).mesh.add(new Kn(this.eGeo,g))}}this.scene.add(this.bGroup);let a=new dt,o=new Float32Array(5e3*3);for(let f=0;f<5e3*3;f++)o[f]=(Math.random()-.5)*500;a.setAttribute("position",new Mt(o,3)),this.stars=new gr(a,new Jr({color:s.starColor??16777215,size:.3,transparent:!0,opacity:s.starOpacity??.7,sizeAttenuation:!0})),this.scene.add(this.stars),this.galGeo=new dt;let l=new Float32Array(x9*3),c=new Float32Array(x9*3);for(let f=0;f<x9;f++){let v=f%3,g=Math.random(),b=v/3*Math.PI*2+g*Math.PI*5,y=g*90+Math.random()*10,_=(1-g)*18;l[f*3]=Math.cos(b)*y+(Math.random()-.5)*_,l[f*3+1]=(Math.random()-.5)*7,l[f*3+2]=Math.sin(b)*y+(Math.random()-.5)*_-180;let x=.2+g*.8,w=s.galFn(x);c[f*3]=w.r,c[f*3+1]=w.g,c[f*3+2]=w.b}this.galGeo.setAttribute("position",new Mt(l,3)),this.galGeo.setAttribute("color",new Mt(c,3)),this.galaxy=new gr(this.galGeo,new Jr({size:.9,vertexColors:!0,transparent:!0,opacity:s.galaxyOpacity??.55,sizeAttenuation:!0})),this.scene.add(this.galaxy),this.nebGeo=new dt;let u=new Float32Array(w9*3),d=new Float32Array(w9*3);for(let f=0;f<w9;f++){let v=25+Math.random()*110,g=Math.random()*Math.PI*2,b=(Math.random()-.5)*Math.PI*.5;u[f*3]=v*Math.cos(g)*Math.cos(b),u[f*3+1]=v*Math.sin(b)*.6,u[f*3+2]=v*Math.sin(g)*Math.cos(b)-80;let y=new We(j5(s.nebula));d[f*3]=y.r,d[f*3+1]=y.g,d[f*3+2]=y.b}this.nebGeo.setAttribute("position",new Mt(u,3)),this.nebGeo.setAttribute("color",new Mt(d,3)),this.nebula=new gr(this.nebGeo,new Jr({size:3,vertexColors:!0,transparent:!0,opacity:s.nebulaOpacity??.3,sizeAttenuation:!0})),this.scene.add(this.nebula),this.addBackgroundTextPlane(),this.setupMouseTracking()}scene;camera;ambient;dir;pt1;pt2;blocks=[];bGroup=new bt;galaxy;nebula;stars;galGeo;nebGeo;bGeo=new Sn(1,1,1);eGeo=new dl(this.bGeo);curScene;curCam;blockGroup;cameraSpeed;blockSpeed;camT=0;mx=0;my=0;tmx=0;tmy=0;transitioning=!1;useMinecraftTextures=!1;resourcesManager;atlasTexture=null;blockMaterialPool=new Map;gradientSky=null;gradientSkyTexture=null;disposed=!1;animTime=0;texturesApplied=!1;textureLoadInProgress=!1;onAssetsTexturesUpdated;async init(){this.useMinecraftTextures&&this.scheduleMinecraftTextureLoad()}scheduleMinecraftTextureLoad(){!this.useMinecraftTextures||this.disposed||this.texturesApplied||this.textureLoadInProgress||this.tryApplyMinecraftTextures()}attachAssetsListener(){let e=this.resourcesManager;!e||this.onAssetsTexturesUpdated||(this.onAssetsTexturesUpdated=()=>this.scheduleMinecraftTextureLoad(),e.on("assetsTexturesUpdated",this.onAssetsTexturesUpdated))}detachAssetsListener(){let e=this.resourcesManager;!e||!this.onAssetsTexturesUpdated||(e.off("assetsTexturesUpdated",this.onAssetsTexturesUpdated),this.onAssetsTexturesUpdated=void 0)}hasBlockAtlas(e){let t=e.currentResources;return!!(t?.blocksAtlasImage&&t.blocksAtlasJson)}async ensureAtlasReady(e){if(await this.ensureMcDataLoaded(),this.hasBlockAtlas(e))return!0;if(typeof document>"u"&&e!==this.resourcesManager)return!1;e.currentConfig={...e.currentConfig,version:mg,noInventoryGui:!0};try{await e.updateAssetsData?.({})}catch{return!1}return this.hasBlockAtlas(e)}async tryApplyMinecraftTextures(){if(!(this.disposed||!this.useMinecraftTextures||this.texturesApplied)){this.textureLoadInProgress=!0;try{let e=this.resourcesManager??new lc;if(!await this.ensureAtlasReady(e)){this.resourcesManager&&this.attachAssetsListener();return}if(this.disposed)return;this.applyMinecraftTexturesFromAtlas(e),this.texturesApplied=!0,this.detachAssetsListener()}catch(e){console.warn("[V2MenuBackground] Failed to load Minecraft textures, using solid colors:",e),this.useMinecraftTextures=!1,this.detachAssetsListener()}finally{this.textureLoadInProgress=!1}}}applyScenePalette(e){if(this.documentRenderer.renderer.setClearColor(e.bg),e.gradientBg)if(this.scene.background=null,this.gradientSky){if(this.gradientSky.visible=!0,this.gradientSkyTexture&&e.gradientBg){let s=$4e(e.gradientBg);s&&(this.gradientSkyTexture.dispose(),this.gradientSkyTexture=s,this.gradientSky.material.map=s,this.gradientSky.material.needsUpdate=!0)}}else{let s=$4e(e.gradientBg);s?(this.gradientSkyTexture=s,this.gradientSky=new Ke(new zn(900,700),new _t({map:s,depthWrite:!1,side:In})),this.gradientSky.position.set(0,0,-280),this.gradientSky.renderOrder=-1e3,this.scene.add(this.gradientSky)):this.scene.background=new We(e.bg)}else this.scene.background=new We(e.bg),this.gradientSky&&(this.gradientSky.visible=!1);this.scene.fog instanceof C0&&(this.scene.fog.color.set(e.fog),this.scene.fog.density=e.fogD);let t=this.stars?.material;t&&(t.color.set(e.starColor??16777215),t.opacity=e.starOpacity??.7);let n=this.galaxy?.material;n&&(n.opacity=e.galaxyOpacity??.55);let r=this.nebula?.material;r&&(r.opacity=e.nebulaOpacity??.3)}setupMouseTracking(){let e=n=>{let r=typeof window<"u"?window.innerWidth:this.documentRenderer.canvas.width,s=typeof window<"u"?window.innerHeight:this.documentRenderer.canvas.height;this.tmx=(n.clientX/r-.5)*2,this.tmy=-(n.clientY/s-.5)*2};(typeof document<"u"?document:void 0)?.addEventListener("mousemove",e,{signal:this.abortSignal})}addBackgroundTextPlane(){let n=typeof document<"u"?document.createElement("canvas"):null;if(!n)return;n.width=2048,n.height=768;let r=n.getContext("2d");if(!r)return;r.clearRect(0,0,2048,768),r.save(),r.font="bold 560px Orbitron, sans-serif",r.textAlign="center",r.textBaseline="middle",r.shadowColor="rgba(0,200,255,0.35)",r.shadowBlur=80,r.fillStyle="rgba(255,255,255,0.055)",r.fillText("V2",2048*.28,768*.5),r.restore(),r.save(),r.font="bold 148px Orbitron, sans-serif",r.textAlign="center",r.textBaseline="middle",r.shadowColor="rgba(0,200,255,0.2)",r.shadowBlur=40,r.fillStyle="rgba(255,255,255,0.038)",r.fillText("by ZARDOY",2048*.72,768*.52),r.restore();let s=new On(n),a=new Ke(new zn(280,105),new _t({map:s,transparent:!0,opacity:1,depthWrite:!1,side:In,blending:es}));a.position.set(8,4,-320),this.scene.add(a)}spawnBlock(e,t,n){let r=this.createBlockMaterial(e,n),s=new Ke(this.bGeo,r),a=.3+Math.random()*3;s.scale.setScalar(a),s.position.set((Math.random()-.5)*140,(Math.random()-.5)*70,t?-(Math.random()*140):-155-Math.random()*30),s.rotation.set(Math.random()*Math.PI*2,Math.random()*Math.PI*2,Math.random()*Math.PI*2);let o={mesh:s,spd:.04+Math.random()*.12,dx:(Math.random()-.5)*.012,dy:(Math.random()-.5)*.008,rx:(Math.random()-.5)*.012,ry:(Math.random()-.5)*.012,rz:(Math.random()-.5)*.01,minecraftBlockName:n};this.blocks.push(o),this.bGroup.add(s)}createBlockMaterial(e,t){if(this.useMinecraftTextures&&t){let s=this.blockMaterialPool.get(t);if(s)return s.clone()}let[n,r]=e.blockOpacity??[.32,.46];return new _t({color:j5(e.blocks),transparent:!0,opacity:n+Math.random()*(r-n),depthWrite:!1,blending:es})}removeBlockEdgeLines(){for(let e of this.blocks){let t=e.mesh.children.filter(n=>n instanceof Kn);for(let n of t){e.mesh.remove(n),n.geometry?.dispose();let r=n.material;Array.isArray(r)?r.forEach(s=>s.dispose()):r.dispose()}}}async ensureMcDataLoaded(){let e=globalThis._LOAD_MC_DATA;e&&await e()}resolveBlockAtlasUv(e,t,n){let r=s=>{let a=t[s];return a?{u:a.u,v:a.v,su:a.su??n.suSv,sv:a.sv??n.suSv}:null};if(t[e])return r(e);for(let s of["_top","_side","_front","_0"]){let a=r(`${e}${s}`);if(a)return a}for(let s of Object.keys(t))if(s.startsWith(e))return r(s);return null}applyMinecraftTexturesFromAtlas(e){let t=e.currentResources;if(!t?.blocksAtlasImage||!t.blocksAtlasJson)throw new Error("Block atlas not available");let n=t.blocksAtlasJson,r=n.textures;this.atlasTexture=cc(t.blocksAtlasImage),this.atlasTexture.flipY=!1,this.atlasTexture.needsUpdate=!0;for(let s of Y4e[this.blockGroup]){let a=this.resolveBlockAtlasUv(s,r,n);if(!a)continue;let o=this.atlasTexture.clone();o.flipY=!1,o.offset.set(a.u,a.v),o.repeat.set(a.su,a.sv),o.needsUpdate=!0;let l=s.includes("glass"),c=new _t({map:o,side:In,transparent:l,opacity:l?.85:1,alphaTest:l?.08:0,depthWrite:!0,toneMapped:!1});this.blockMaterialPool.set(s,c)}if(this.blockMaterialPool.size===0)throw new Error("No block textures resolved from atlas (check block names vs atlas keys)");this.removeBlockEdgeLines();for(let s of this.blocks){let a=j5([...this.blockMaterialPool.keys()]);s.minecraftBlockName=a,s.mesh.material=this.blockMaterialPool.get(a).clone()}}setScene(e){if(!q5.includes(e)||e===this.curScene||this.transitioning)return;this.transitioning=!0,this.curScene=e;let t=X4e[e];setTimeout(()=>{if(this.disposed)return;this.applyScenePalette(t),this.ambient.color.set(t.ambient),this.dir.color.set(t.dir),this.pt1.color.set(t.pt1),this.pt2.color.set(t.pt2);for(let s of this.blocks)this.useMinecraftTextures&&s.minecraftBlockName||s.mesh.material instanceof _t&&s.mesh.material.color.set(j5(t.blocks));let n=this.nebGeo.attributes.color;for(let s=0;s<w9;s++){let a=new We(j5(t.nebula));n.setXYZ(s,a.r,a.g,a.b)}n.needsUpdate=!0;let r=this.galGeo.attributes.color;for(let s=0;s<x9;s++){let a=.2+Math.random()*.8,o=t.galFn(a);r.setXYZ(s,o.r,o.g,o.b)}r.needsUpdate=!0,this.transitioning=!1},150)}setCamera(e){G5.includes(e)&&(this.curCam=e)}setCameraSpeed(e){this.cameraSpeed=Math.max(0,e)}setBlockSpeed(e){this.blockSpeed=Math.max(0,e)}async setBlockGroup(e){if(W5.includes(e)&&e!==this.blockGroup&&(this.blockGroup=e,!(!this.useMinecraftTextures||this.disposed))){for(let t of this.blockMaterialPool.values())t.map?.dispose(),t.dispose();this.blockMaterialPool.clear(),this.texturesApplied=!1,this.scheduleMinecraftTextureLoad()}}getSceneId(){return this.curScene}getCameraId(){return this.curCam}getBlockGroupId(){return this.blockGroup}update(e,t){t&&Jd(this.camera,this.documentRenderer.canvas);let n=dJe[this.curCam],r=this.cameraSpeed,s=this.blockSpeed;this.camT+=e*n.spd*r,this.mx+=(this.tmx-this.mx)*.05,this.my+=(this.tmy-this.my)*.05;let a=this.mx*j4e,o=this.my*j4e,l=n.pos(this.camT,a,o),c=n.look(this.camT,a,o);this.camera.position.set(l.x,l.y,l.z),this.camera.lookAt(c.x,c.y,c.z),this.camera.rotation.z=n.roll(this.camT,a);let u=fJe[this.curCam]*s;this.animTime+=e*1e3*s;for(let d of this.blocks){if(d.mesh.position.z+=d.spd*u*60*e,d.mesh.position.x+=d.dx*60*e*s,d.mesh.position.y+=d.dy*60*e*s,d.mesh.rotation.x+=d.rx*u,d.mesh.rotation.y+=d.ry*u,d.mesh.rotation.z+=d.rz,!this.useMinecraftTextures&&d.mesh.material instanceof _t){let f=d.mesh.userData.baseOpacity??.38;d.mesh.userData.baseOpacity==null&&(d.mesh.userData.baseOpacity=f);let v=.88+Math.abs(Math.sin(this.animTime*8e-4+d.mesh.position.x*.3))*.12;d.mesh.material.opacity=f*v}d.mesh.position.z>this.camera.position.z+15&&d.mesh.position.set((Math.random()-.5)*140,(Math.random()-.5)*70,this.camera.position.z-155-Math.random()*30)}this.pt1.position.set(Math.sin(this.camT*.8)*25+this.camera.position.x,Math.cos(this.camT*.6)*12+this.camera.position.y,this.camera.position.z-18),this.pt2.position.set(Math.cos(this.camT*.5)*20+this.camera.position.x,Math.sin(this.camT*.9)*15+this.camera.position.y,this.camera.position.z-30),this.galaxy.rotation.y+=e*.006*s,this.nebula.rotation.y-=e*.003*s,this.stars.rotation.y+=e*4e-4*s}dispose(){this.disposed=!0,this.detachAssetsListener(),this.scene.clear(),this.bGeo.dispose(),this.eGeo.dispose(),this.galGeo.dispose(),this.nebGeo.dispose(),this.gradientSkyTexture?.dispose(),this.atlasTexture?.dispose();for(let e of this.blockMaterialPool.values())e.map?.dispose(),e.dispose();this.blockMaterialPool.clear()}};h();p();m();Lt();h();p();m();var r8e=Yr(n8e(),1),i8e=Yr(CI(),1);var s8e=i=>{let e=(0,r8e.default)(i),t=(0,i8e.default)(i),n=new e(i).sync,r=xJe(n);for(let s of r)if(s.startsWith("set")&&s!=="setColumn"){let a=n[s].bind(n);n[s]=(...o)=>{let l=o[0];l.x!==void 0&&!n.getColumnAt(l)&&n.setColumn(Math.floor(l.x/16),Math.floor(l.z/16),new t(void 0)),a(...o)}}return n};function xJe(i){let e=new Set,t=i;do for(let n of Object.getOwnPropertyNames(t))typeof i[n]=="function"&&n!=="constructor"&&e.add(n);while(t=Object.getPrototypeOf(t));return[...e]}h();p();m();var a8e={paused:!1,showChunkBorders:!1,enableDebugOverlay:!1,debugWasmPerf:!1,debugModelVariant:void 0,futuristicReveal:!1,wasmMesher:!0,shaderCubeBlocks:!1,shaderCubeDebugMode:0,mesherWorkers:1,addChunksBatchWaitTime:200,_experimentalSmoothChunkLoading:!0,_renderByChunks:!1,autoLowerRenderDistance:!1,disableMesherConversionCache:!1,dedicatedChangeWorker:!1,shadingTheme:"high-contrast",cardinalLight:"default",dayCycle:!0,smoothLighting:!0,enableLighting:!0,starfield:!0,defaultSkybox:!0,renderEntities:!0,extraBlockRenderers:!0,foreground:!0,fov:75,volume:1,showHand:!1,viewBobbing:!1,handRenderer:"vanilla",renderEars:!0,highlightBlockColor:"blue",fetchPlayerSkins:!0,skinTexturesProxy:void 0,vrSupport:!0,vrPageGameRendering:!0,clipWorldBelowY:void 0,isPlayground:!1,instantCameraUpdate:!1,isRaining:!1,rainColor:"rgb(118, 148, 226)",rainOpacity:.5,moduleStates:{}};var nL=()=>({reactive:_l({world:{chunksLoaded:{},heightmaps:{},allChunksLoaded:!1,mesherWork:!1,instabilityFactors:zP(),intersectMedia:null},renderer:"...",preventEscapeMenu:!1}),nonReactive:{fps:0,worstRenderTime:0,avgRenderTime:0,world:{chunksLoadedCount:0,chunksTotalNumber:0,chunksFullInfo:"-"},renderer:{timeline:{live:[],frozen:[],lastSecond:[]}}}});h();p();m();h();p();m();h();p();m();Ia();var yg=i=>[Math.floor(i.x/16),Math.floor(i.z/16)];var wJe=async(i,e,t,n=1)=>{for(let r=0;r<i.length;r+=n)e&&await new Promise(s=>setTimeout(s,e)),await t(i[r],r)},$5=new WeakMap,bg=class bg extends W0{static restoreTransferred(e,t){let n=new bg;if(!t)return n;let r=$5.get(t);if(r)r.activeWorldView=n;else{let s=({data:a})=>{let l=$5.get(t)?.activeWorldView;!l||a?.class!==bg.restorerName||a.type==="event"&&l.emit(a.eventName,...a.args)};t.addEventListener("message",s),r={activeWorldView:n,handler:s},$5.set(t,r)}return n}static clearWorkerBridgeForTest(e){let t=$5.get(e);t&&(e.removeEventListener("message",t.handler),$5.delete(e))}static getWorkerBridgeListenerCountForTest(e){return $5.has(e)?1:0}};Wn(bg,"restorerName","WorldViewWorker");var Y5=bg,M9=class extends W0{constructor(t,n,r=new kt(0,0,0)){super();this.world=t;this.viewDistance=n;this.lastPos=new kt(0,0,0).update(r)}spiralNumber=0;gotPanicLastTime=!1;panicChunksReload=()=>{};loadedChunks={};inLoading=!1;chunkReceiveTimes=[];lastChunkReceiveTime=0;lastChunkReceiveTimeAvg=0;panicTimeout;lastPos;eventListeners={};debugChunksInfo={};waitingSpiralChunksLoad={};addWaitTime=1;keepChunksDistance=0;isPlayground=!1;allowPositionUpdate=!0;prepareForTransfer(t){if(t){let n=this.emit.bind(this);this.emit=(r,...s)=>{n(r,...s),t.postMessage({class:Y5.restorerName,type:"event",eventName:r,args:e4(s)})}}return{__restorer:Y5.restorerName}}setBlockStateId(t,n){let r=this.world.setBlockStateId(t,n);if(r&&typeof r.then=="function")throw new Error("setBlockStateId returned promise (not supported)");this.emit("blockUpdate",{pos:t,stateId:n})}updateViewDistance(t){this.viewDistance=t,this.emit("renderDistance",t)}async init(t,n){console.log("WorldView init"),this.updateViewDistance(this.viewDistance),this.emit("chunkPosUpdate",{pos:t}),n?.time?.timeOfDay!==void 0&&this.emit("time",n.time.timeOfDay),n?.entity&&this.emit("playerEntity",n.entity),this.emitterGotConnected(n);let[r,s]=yg(t),a=C3(this.viewDistance).map(([o,l])=>new kt((r+o)*16,0,(s+l)*16));this.lastPos.update(t),await this._loadChunks(a,t)}chunkProgress(){if(this.panicTimeout&&clearTimeout(this.panicTimeout),this.chunkReceiveTimes.length>=5){let t=this.chunkReceiveTimes.reduce((r,s)=>r+s,0)/this.chunkReceiveTimes.length;this.lastChunkReceiveTimeAvg=t;let n=t*2+1e3;this.panicTimeout&&clearTimeout(this.panicTimeout),this.panicTimeout=setTimeout(()=>{!this.gotPanicLastTime&&this.inLoading&&(console.warn("Chunk loading seems stuck, triggering panic reload"),this.gotPanicLastTime=!0,this.panicChunksReload())},n)}}async _loadChunks(t,n){this.spiralNumber++;let{spiralNumber:r}=this;for(let a of Object.keys(this.waitingSpiralChunksLoad))this.waitingSpiralChunksLoad[a](!1),delete this.waitingSpiralChunksLoad[a];let s=!0;this.inLoading=!0,await wJe(t,this.addWaitTime,async a=>{!s||this.loadedChunks[`${a.x},${a.z}`]||(this.world.getColumnAt(a)||(s=await new Promise(o=>{this.waitingSpiralChunksLoad[`${a.x},${a.z}`]=o})),s&&(await this.loadChunk(a,void 0,`spiral ${r} from ${n.x},${n.z}`),this.chunkProgress()))}),r===this.spiralNumber&&(this.panicTimeout&&clearTimeout(this.panicTimeout),this.inLoading=!1,this.gotPanicLastTime=!1,this.chunkReceiveTimes=[],this.lastChunkReceiveTime=0)}async loadChunk(t,n=!1,r="spiral"){let[s,a]=yg(this.lastPos),o=Math.abs(s-Math.floor(t.x/16)),l=Math.abs(a-Math.floor(t.z/16));if(o<=this.viewDistance&&l<=this.viewDistance){let c=await this.world.getColumnAt(t.y!==void 0?t:new kt(t.x,0,t.z));if(c){let u=c.toJson(),d={minY:c.minY??0,worldHeight:c.worldHeight??256};this.emit("loadChunk",{x:t.x,z:t.z,chunk:u,blockEntities:c.blockEntities,worldConfig:d,isLightUpdate:n}),this.loadedChunks[`${t.x},${t.z}`]=!0,this.debugChunksInfo[`${t.x},${t.z}`]??={loads:[]},this.debugChunksInfo[`${t.x},${t.z}`].loads.push({dataLength:u.length,reason:r,time:Date.now()})}else this.isPlayground&&this.emit("markAsLoaded",{x:t.x,z:t.z})}}async reloadLoadedChunks(){let t=Object.keys(this.loadedChunks);for(let n of t){let[r,s]=n.split(",").map(Number);await this.loadChunk({x:r,z:s},!1,"mesher-reconfigure")}}unloadAllChunks(){for(let t of Object.keys(this.loadedChunks)){let[n,r]=t.split(",").map(Number);this.unloadChunk({x:n,z:r})}}unloadChunk(t){this.emit("unloadChunk",{x:t.x,z:t.z}),delete this.loadedChunks[`${t.x},${t.z}`],delete this.debugChunksInfo[`${t.x},${t.z}`]}emitterGotConnected(t){typeof globalThis.WorkerGlobalScope<"u"&&globalThis instanceof globalThis.WorkerGlobalScope||!t||this.emit("blockEntities",new Proxy({},{get(r,s,a){if(typeof s!="string")return;let[o,l,c]=s.split(",").map(Number);return t.world.getBlock(new kt(o,l,c))?.entity}}))}lastBiomeId=null;updateBiome(t){try{if(!this.world.getBiome)return;let n=this.world.getBiome(t);n!==this.lastBiomeId&&(this.lastBiomeId=n,this.emit("biomeReset"))}catch(n){console.error("error updating biome",n)}}lastPosCheck=null;async updatePosition(t,n=!1){if(!this.allowPositionUpdate)return;let r=t.floored();if(!n&&this.lastPosCheck&&this.lastPosCheck.equals(r))return;this.lastPosCheck=r,this.updateBiome(t);let[s,a]=yg(this.lastPos),[o,l]=yg(t);if(s!==o||a!==l||n){this.emit("chunkPosUpdate",{pos:t});let c=[],u=n?this.viewDistance:this.viewDistance+this.keepChunksDistance;for(let f of Object.keys(this.loadedChunks)){let[v,g]=f.split(",").map(Number),b=new kt(v,0,g),[y,_]=yg(b),x=Math.abs(o-y),w=Math.abs(l-_);(x>u||w>u)&&c.push(b)}for(let f of c)this.unloadChunk(f);let d=C3(this.viewDistance).map(([f,v])=>{let g=new kt((o+f)*16,0,(l+v)*16);if(!this.loadedChunks[`${g.x},${g.z}`])return g}).filter(f=>!!f);this.lastPos.update(t),this._loadChunks(d,t)}else this.emit("chunkPosUpdate",{pos:t}),this.lastPos.update(t)}};var xg=class{constructor(e,t,n){this.documentRenderer=e;this.options=t;this.abortSignal=n;this._scene=new Rr,this._scene.background=new We(3294568),this._camera=new fn(85,e.canvas.width/e.canvas.height,.05,1e3),this.camera.position.set(0,0,0),this.camera.rotation.set(0,0,0)}_scene;_camera;get scene(){return this._scene}get camera(){return this._camera}worldRenderer;WorldRendererClass=Yd;async init(){let e=mg,t=new lc;if(t.currentConfig={version:e,noInventoryGui:!0},await t.updateAssetsData?.({}),this.abortSignal.aborted)return;console.time("load menu background scene");let n=s8e(e),s=Si()(e),o=globalThis.mcData.blocksArray.filter(v=>{if(!v.name.includes("stained_glass"))return!1;let g=s.fromStateId(v.defaultState,0);if(g.shapes?.length!==1)return!1;let b=g.shapes[0];return b[0]===0&&b[1]===0&&b[2]===0&&b[3]===1&&b[4]===1&&b[5]===1}),l=-15,c=100,u=100;for(let v=-c;v<c;v++)for(let g=-u;g<u;g++){let b=o[Math.floor(Math.random()*o.length)];n.setBlockStateId(new kt(v,g,l),b.defaultState)}this._camera.updateProjectionMatrix(),this._camera.position.set(.5,u/2+.5,.5),this._camera.rotation.set(0,0,0);let d=new kt(...this._camera.position.toArray()),f=new M9(n,2,d);this.abortSignal.aborted||(this.worldRenderer=new this.WorldRendererClass(this.documentRenderer.renderer,this.options,{version:e,worldView:f,inWorldRenderingConfig:a8e,playerStateReactive:Y0e().reactive,rendererState:nL().reactive,nonReactiveState:nL().nonReactive,resourcesManager:t}),this.worldRenderer instanceof Yd&&(this._scene=this.worldRenderer.realScene,this._camera=this.worldRenderer.camera),f.init(d),await this.worldRenderer.waitForChunksToRender(),!this.abortSignal.aborted&&(this.setupMouseParallax(),console.timeEnd("load menu background scene")))}update(e,t){t&&Jd(this.camera,this.documentRenderer.canvas)}dispose(){this.worldRenderer?.destroy(),this.worldRenderer=void 0,this._scene.clear()}setupMouseParallax(){let e=this._camera,t=e.position.x,n=e.position.y,r;document.body.addEventListener("pointermove",s=>{if(s.pointerType!=="mouse")return;let a=.2,o=s.clientX/window.innerWidth-.5,l=-(s.clientY/window.innerHeight-.5);r?.stop(),r=new jr(e.position).to({x:t+o*a,y:n+l*a},0),r.start(),e.updateProjectionMatrix()},{signal:this.abortSignal})}};h();p();m();Lt();var wg=class{constructor(e,t,n={},r=!1){this.documentRenderer=e;this.options=t;this.mode=WP(n,r)}active;abortController=new AbortController;mode;lastFrameTime=0;get v2(){return this.active instanceof X5?this.active:void 0}get scene(){return this.active?.scene}get camera(){return this.active?.camera}async start(e={}){this.active=this.createImplementation(e),await this.active.init(),this.active.scene.background instanceof We&&this.documentRenderer.renderer.setClearColor(this.active.scene.background),this.lastFrameTime=performance.now(),this.documentRenderer.render=(t=!1)=>{let n=performance.now(),r=Math.min((n-this.lastFrameTime)/1e3,.05);this.lastFrameTime=n;let s=this.active;s&&(s.update(r,t),this.documentRenderer.renderer.render(s.scene,s.camera))}}createImplementation(e){switch(this.mode){case"v2":return new X5(this.documentRenderer,{useMinecraftTextures:e.useMinecraftTextures,initialScene:e.v2Scene,initialCamera:e.v2Camera,initialBlockGroup:e.v2BlockGroup,initialCameraSpeed:e.v2CameraSpeed,initialBlockSpeed:e.v2BlockSpeed,resourcesManager:e.resourcesManager},this.abortController.signal);case"worldBlocks":return new xg(this.documentRenderer,this.options,this.abortController.signal);default:return new pg(this.documentRenderer)}}dispose(){this.active?.dispose(),this.active=void 0,this.abortController.abort()}};h();p();m();var Kd=u0,SJe={rendererWorldPerformance:"normal",rendererMeshersCountOverride:null,starfieldRendering:!0,defaultSkybox:!0,menuBackgroundMode:Kd.mode,menuBackgroundMinecraftTextures:Kd.minecraftTextures,menuBackgroundV2Scene:Kd.v2Scene,menuBackgroundV2Camera:Kd.v2Camera,menuBackgroundV2BlockGroup:Kd.v2BlockGroup,menuBackgroundV2CameraSpeed:Kd.v2CameraSpeedPercent,menuBackgroundV2BlockSpeed:Kd.v2BlockSpeedPercent,rendererFuturisticReveal:!1,rendererPerfDebugOverlay:!1,disableBlockEntityTextures:!1,rendererMesher:"wasm",rendererShaderCubeDebugMode:"off",showChunkBorders:!1,renderEntities:!0,renderDebug:"basic",frameLimit:!1,backgroundRendering:"20fps",vanillaLook:!1,smoothLighting:!0,newVersionsLighting:!1,vrSupport:!0,vrPageGameRendering:!1,clipWorldBelowY:void 0,highlightBlockColor:"auto",loadPlayerSkins:!0,renderEars:!0,showHand:!0,viewBobbing:!0,dayCycleAndLighting:!0,keepChunksDistance:1,gpuPreference:"default",fov:75};var EJe={menuBackgroundMode:{possibleValues:[["classic","Classic"],["v2","V2"]],requiresRestart:!0},menuBackgroundMinecraftTextures:{text:"Minecraft block textures",tooltip:"Use block atlas on V2 menu cubes (loads assets on menu)"},menuBackgroundV2Scene:{possibleValues:q5.map(i=>[i,_9[i]])},menuBackgroundV2Camera:{possibleValues:G5.map(i=>[i,y9[i]])},menuBackgroundV2BlockGroup:{possibleValues:W5.map(i=>[i,b9[i]]),text:"Block pool",tooltip:"Block set for textured menu cubes (requires Minecraft textures)"},menuBackgroundV2CameraSpeed:{text:"Camera speed",tooltip:"Orbit / fly-through camera path speed. 0 freezes the path; mouse parallax still works.",min:0,max:200,unit:"%"},menuBackgroundV2BlockSpeed:{text:"Block speed",tooltip:"Floating blocks and sky rotation. Independent of camera path speed.",min:0,max:200,unit:"%"},rendererWorldPerformance:{text:"World performance",tooltip:"Background workers for chunk geometry. Recreates mesher workers and reloads chunks.",requiresChunksReload:!0,possibleValues:[["low-energy","Low Energy"],["normal","Normal"],["maximum","Maximum"]]},starfieldRendering:{text:"Starfield"},defaultSkybox:{text:"Default skybox"},rendererFuturisticReveal:{text:"Futuristic world reveal"},rendererPerfDebugOverlay:{text:"Performance debug overlay"},disableBlockEntityTextures:{text:"Disable block entity textures",tooltip:"Skips signs, banners, heads, maps, etc."},rendererMesher:{possibleValues:[["wasm","WASM"],["legacy-js","Legacy JS"]],text:"Mesher pipeline",tooltip:"Browser technology for processing world geometry before render. WASM is the fastest; if you see a dead tab icon, reloads, or other errors, switch to Legacy JS.",requiresChunksReload:!0},rendererShaderCubeDebugMode:{text:"Shader cube debug",tooltip:"Instanced cube path visualization (requires shader cubes enabled).",possibleValues:[["off","Off"],["holes","Hole test (red)"],["texIndex","Tile index colors"],["faces","Face id colors"],["atlasAlpha","Atlas alpha"]]},showChunkBorders:{text:"Chunk borders"},renderEntities:{text:"Render entities"},renderDebug:{possibleValues:["advanced","basic","none"]},frameLimit:{text:"Frame limit",tooltip:"false = VSync / unlimited when focused"},backgroundRendering:{text:"Background FPS limit",possibleValues:[["full","NO"],["5fps","5 FPS"],["20fps","20 FPS"]]},vanillaLook:{text:"Vanilla shading",tooltip:"On: Minecraft-style face shading. Off: higher-contrast client shading."},smoothLighting:{},newVersionsLighting:{text:"Lighting in newer versions"},vrSupport:{text:"VR support",tooltip:"Shows VR entry; does not force VR on."},vrPageGameRendering:{text:"VR page game rendering"},clipWorldBelowY:{text:"Clip world below Y"},highlightBlockColor:{possibleValues:[["auto","Auto"],["blue","Blue"],["classic","Classic"]]},loadPlayerSkins:{},renderEars:{tooltip:"Deadmau5 ears when the skin texture includes them"},showHand:{},viewBobbing:{},dayCycleAndLighting:{text:"Day cycle"},keepChunksDistance:{text:"Keep chunks distance",tooltip:"Extra distance before unloading chunks",max:5,unit:""},fov:{min:30,max:110,unit:"\xB0",text:"FOV"},gpuPreference:{text:"GPU preference",tooltip:"WebGL power preference. Requires reload / backend restart to apply.",requiresRestart:!0,possibleValues:[["default","Auto"],["high-performance","Dedicated"],["low-power","Low power"]]}};Ht.enabled=!1;globalThis.THREE=Gt;var o8e=i=>({updateMap:i.entities.updateMap.bind(i.entities),updateCustomBlock:i.updateCustomBlock.bind(i),getBlockInfo:i.getBlockInfo.bind(i),playEntityAnimation:i.entities.playAnimation.bind(i.entities),damageEntity:i.entities.handleDamageEvent.bind(i.entities),updatePlayerSkin:i.entities.updatePlayerSkin.bind(i.entities),applyTemporaryPlayerSkinOverride:i.entities.applyTemporaryPlayerSkinOverride.bind(i.entities),changeHandSwingingState:i.changeHandSwingingState.bind(i),getHighestBlocks:i.getHighestBlocks.bind(i),reloadWorld:i.reloadWorld.bind(i),updateEntityModel:i.entities.updateEntityModel.bind(i.entities),playEntityModelAnimation:i.entities.playEntityModelAnimation.bind(i.entities),addMedia:i.media.addMedia.bind(i.media),destroyMedia:i.media.destroyMedia.bind(i.media),setControlMode:i.media.setControlMode.bind(i.media),setVideoPlaying:i.media.setVideoPlaying.bind(i.media),setVideoSeeking:i.media.setVideoSeeking.bind(i.media),setVideoVolume:i.media.setVideoVolume.bind(i.media),setVideoSpeed:i.media.setVideoSpeed.bind(i.media),handleUserClick:i.media.handleUserClick.bind(i.media),addSectionAnimation(e,t){i.sectionsOffsetsAnimations[e]=t},removeSectionAnimation(e){delete i.sectionsOffsetsAnimations[e]},shakeFromDamage:i.cameraShake.shakeFromDamage.bind(i.cameraShake),onPageInteraction:i.media.onPageInteraction.bind(i.media),downloadMesherLog:i.downloadMesherLog.bind(i),explodeFirework:i.fireworksLegacy.explode.bind(i.fireworksLegacy),explodeFireworkFacingCamera:i.fireworksLegacy.explodeFacingCamera.bind(i.fireworksLegacy),addWaypoint:i.waypoints.addWaypoint.bind(i.waypoints),removeWaypoint:i.waypoints.removeWaypoint.bind(i.waypoints),startCinimaticScript:i.cinimaticScript.startScript.bind(i.cinimaticScript),stopCinimaticScript:i.cinimaticScript.stopScript.bind(i.cinimaticScript),launchFirework:i.fireworks.launchFirework.bind(i.fireworks),setSkyboxImage:i.skyboxRenderer.setSkyboxImage.bind(i.skyboxRenderer),setRain:i.setRain.bind(i),spawnBlockBreakParticles(e,t,n,r,s,a){i.getModule("blockBreakParticles")?.spawnBlockBreakParticles(e,t,n,r,s,a)},spawnBlockCrackParticle(e,t,n,r,s,a,o){i.getModule("blockBreakParticles")?.spawnCrackParticle(e,t,n,r,s,a,o)},async loadGeometryExport(e){let{applyWorldGeometryExport:t}=await Promise.resolve().then(()=>(AP(),j_e));return t(i,e)},feedChunkPacket(e){let{kind:t,...n}=e,r={type:t,...n};for(let s of i.workers)s.postMessage(r)},getChunksDebugState(){let e={};for(let t of Object.keys(i.sectionObjects)){let[n,,r]=t.split(",").map(Number);e[`${n},${r}`]=!0}return{loadedSectionsChunks:e,loadedChunks:{...i.loadedChunks},finishedChunks:{...i.finishedChunks}}}}),MJe=[],A9=(i,...e)=>{for(let t of Object.values(globalThis.loadedMods??{}))try{t.threeJsBackendModule?.[i]?.(...e)}catch(n){let r=`[mod three.js] Error calling ${i} on ${t.name}: ${n}`;throw new Error(r)}},l8e=()=>{let i,e=null,t=null,n=null,r=null,s=(u,d)=>{u.hello&&console.log("Thanks for using minecraft-renderer project: one of the most performant Minecraft world renderers for the web!"),Ln?i=u2(u,MJe,globalThis):i=u,e=new Q_(i,d?.canvas),globalThis.renderer=e.renderer,globalThis.documentRenderer=e,globalThis.threeJsBackend=c,A9("default",c)},a=async u=>{if(!e)throw new Error("Document renderer not initialized");n&&(n.destroy(),n=null,r=null,globalThis.world=void 0,globalThis.frameTimingCollector=void 0),t&&(t.dispose(),t=null);let d={...i.config.menuBackground,...u};t=new wg(e,{...i},d,!!process.env.SINGLE_FILE_BUILD_MODE),A9("menuBackgroundCreated",t),await t.start(d),A9("menuBackgroundReady",t)},o=async u=>{if(!e)throw new Error("Document renderer not initialized");t&&(t.dispose(),t=null),n&&(n.destroy(),n=null,r=null,globalThis.world=void 0,globalThis.frameTimingCollector=void 0);let f=Ln?u2(u,[lc,Y5],globalThis):u;e.nonReactiveState=f.nonReactiveState,globalThis.resourcesManager=f.resourcesManager,n=new Yd(e.renderer,i,f),await n.worldReadyPromise,r=f.inWorldRenderingConfig.enableDebugOverlay?new n4(f.nonReactiveState):null,globalThis.frameTimingCollector=r;let v=e.render;e.render=function(g){v.call(this,g),r?.markFrameStart(),f.inWorldRenderingConfig.paused||n?.render(g),r?.markFrameEnd(),r?.markFrameDisplay()},e.inWorldRenderingConfig=f.inWorldRenderingConfig,globalThis.world=n,A9("worldReady",n)},l=()=>{t&&(t.dispose(),t=null),e&&e.dispose(),n&&(n.destroy(),n=null)},c={id:"threejs",displayName:`three.js ${Ma}`,startMenuBackground:a,startWorld:o,disconnect:l,setRendering(u){e.setPaused(!u),n&&(n.renderingActive=u)},getMenuBackground:()=>t??void 0,getDebugOverlay:()=>({get entitiesString(){return n?.entities.getDebugString()},get left(){return{"Geo Memory":n?.chunkMeshManager.getEstimatedMemoryUsage().total??"-"}}}),updateCamera(u,d,f){r?.markCameraUpdate(!u),n?.setFirstPersonCamera(u,d,f)},get soundSystem(){return n?.soundSystem},get backendMethods(){if(n)return o8e(n)}};return{main:{init:s,backend:c},workerProxy(){return SN({init(u,d){s(u,{canvas:d})},updateSizeExternal(u,d,f){e?.updateSizeExternal(u,d,f)},startMenuBackground:a,startWorld:o,disconnect:l,setRendering:c.setRendering,updateCamera(u,d,f){let v=u?new kt(u.x,u.y,u.z):null;r?.markCameraUpdate(!v),c.updateCamera(v,d,f)},async callBackendMethod(u,...d){if(!n)throw new Error("World renderer not initialized");let v=o8e(n)[u];if(!v)throw new Error(`Backend method ${String(u)} is unavailable`);return v(...d)}})}}};globalThis.structuredClone??=i=>JSON.parse(JSON.stringify(i));var c8e=i=>{TB(i);let e=globalThis;e.mcData=i,e.loadedData=i,self.postMessage({type:"mcDataApplied"})};self.addEventListener("message",i=>{let e=i.data;if(e.type==="mcData"){c8e(e.mcData),console.log("data loaded");return}Array.isArray(e)&&e.forEach(t=>{t.type==="mcData"&&c8e(t.mcData)})});var AJe=l8e();AJe.workerProxy();})();
|
|
29579
|
+
}`})}},VP=class{constructor(e){this.worldRenderer=e}points;timer=new Hs;enabled=!1;currentTime;enable(){this.enabled||(this.enabled=!0,this.updateVisibility())}disable(){this.enabled&&(this.enabled=!1,this.removeStars())}toggle(){return this.enabled?this.disable():this.enable(),this.enabled}enablementCheck=()=>this.currentTime?this.currentTime>13500&&this.currentTime<23e3:!1;render=()=>{if(!this.points)return;this.points.position.set(0,0,0);let e=this.points.material;this.timer.update(performance.now()),e.uniforms.time.value=this.timer.getElapsed()*.2};updateTimeOfDay(e){this.currentTime=e,this.enabled&&this.updateVisibility()}updateVisibility(){if(!this.enabled)return;let e=this.enablementCheck?.()??!1;e&&!this.points?this.createStars():!e&&this.points&&this.removeStars()}createStars(){if(this.points)return;let e=80,t=50,n=7e3,r=7,s=10,a=new dt,o=b=>new X().setFromSpherical(new Jf(b,Math.acos(1-Math.random()*2),Math.random()*2*Math.PI)),l=[],c=[],u=Array.from({length:n},()=>(.5+.5*Math.random())*r),d=new We,f=e+t,v=t/n;for(let b=0;b<n;b++)f-=v*Math.random(),l.push(...o(f).toArray()),d.setHSL(b/n,s,.9),c.push(d.r,d.g,d.b);a.setAttribute("position",new Je(l,3)),a.setAttribute("color",new Je(c,3)),a.setAttribute("size",new Je(u,1));let g=new FP;g.blending=es,g.depthTest=!0,g.depthWrite=!1,g.transparent=!0,this.points=new gr(a,g),this.points.renderOrder=-1,this.worldRenderer.scene.add(this.points)}dispose(){this.removeStars()}removeStars(){this.points&&(this.points.geometry.dispose(),this.points.material.dispose(),this.worldRenderer.scene.remove(this.points),this.points=void 0)}},z4e={id:"starfield",controller:VP,enabledDefault:!0,cannotBeDisabled:!0};var H4e={starfield:z4e,futuristicReveal:V4e,rain:O4e,cameraBobbing:P4e,blockBreakParticles:C4e};h();p();m();h();p();m();var zP=()=>({longRenderTime:!1,constantLongRenderTime:!1,tooManyEntities:!1,tooManyTextures:!1,unknownReason:!1});h();p();m();h();p();m();var hg=class{constructor(e){this.factors=e}renderTimeHistory=[];onFrame(e){this.pushRenderTime(e.totalMs),this.recompute(e)}pushRenderTime(e){this.renderTimeHistory.push(e),this.renderTimeHistory.length>24&&this.renderTimeHistory.shift()}recompute(e){let t=e.fps>0&&e.fps<=45,n=Math.max(0,e.totalMs-e.entitiesMs),r=e.totalMs>=30,s=this.renderTimeHistory.length,a=this.renderTimeHistory.filter(f=>f>=30).length,o=s>=8&&a/s>=.65,l=e.loadedTextureCount>=100,c=t&&e.entitiesMs>=8&&n<=20,d=t&&!(r||o||c||l);this.factors.longRenderTime=r,this.factors.constantLongRenderTime=o,this.factors.tooManyEntities=c,this.factors.tooManyTextures=l,this.factors.unknownReason=d}reset(){this.renderTimeHistory.length=0,this.factors.longRenderTime=!1,this.factors.constantLongRenderTime=!1,this.factors.tooManyEntities=!1,this.factors.tooManyTextures=!1,this.factors.unknownReason=!1}};h();p();m();var lJe=[{key:"longRenderTime",code:"LR"},{key:"constantLongRenderTime",code:"CLR"},{key:"tooManyEntities",code:"ENT"},{key:"tooManyTextures",code:"TEX"},{key:"unknownReason",code:"UNK"}];function qP(i){let e=lJe.filter(({key:t})=>i[t]).map(({code:t})=>t);return e.length>0?e.join("+"):""}var ia=class ia extends Ry{constructor(t,n,r){if(!r.resourcesManager)throw new Error("resourcesManager is required in displayOptions");super(r.resourcesManager,r,n);this.renderer=t;this.initOptions=n;this.displayOptions=r;this.performanceMonitor=new hg(this.reactiveState.world.instabilityFactors),this.renderer=t;let s=ia.getRendererInfo(t)??"...";r.rendererState.renderer=s,this.chunkMeshManager=new fg(this,this.scene,this.material,this.worldSizeParams.worldHeight,this.viewDistance),this.onRenderDistanceChanged=a=>{this.chunkMeshManager.updateViewDistance(a)},typeof window<"u"&&(window.setBlockLightmap=a=>{this.chunkMeshManager.setBlockLightmapParams(a)}),this.syncSkyLevelFromTime(this.timeOfTheDay),this.cursorBlock=new Bb(this),this.holdingBlock=sg(this),this.holdingBlockLeft=sg(this,!0);for(let a of Object.values(H4e))this.registerModule(a);this.skyboxRenderer=new qb(this.realScene,!1,null),this.skyboxRenderer.init(),this.addDebugOverlay(),this.resetScene(),this.init(),this.soundSystem=new Ob(this),this.cameraShake=new Nb(this,this.onRender),this.media=new Ub(this),this.fireworksLegacy=new zb(this),this.waypoints=new Vb(this),this.cinimaticScript=new Hb(this,(a,o,l)=>this.setCinimaticCamera(a,o,l),a=>this.setCinimaticFov(a),()=>({position:new kt(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),yaw:this.cameraShake.getBaseRotation().yaw,pitch:this.cameraShake.getBaseRotation().pitch,fov:this.camera.fov})),this.fireworks=new Gb(this.realScene,this.sceneOrigin),this.renderUpdateEmitter.on("chunkFinished",a=>{this.finishChunk(a)}),this.worldSwitchActions(),this.initializeModules()}outputFormat="threeJs";isShaderCubeBlocksEnabled(){return this.worldRendererConfig.shaderCubeBlocks===!0&&!!this.renderer?.capabilities?.isWebGL2}chunkMeshManager;get sectionObjects(){return this.chunkMeshManager.sectionObjects}cameraSectionPos=new kt(0,0,0);holdingBlock;holdingBlockLeft;scene=new Rr;get realScene(){return this.scene}ambientLight=new wa(13421772,ia.LEGACY_TO_PHYSICAL_LIGHT);directionalLight=new Ss(16777215,.5*ia.LEGACY_TO_PHYSICAL_LIGHT);entities=new Lb(this,globalThis.mcData);performanceMonitor;cameraGroupVr;material=new _t({vertexColors:!0,transparent:!0,alphaTest:.1});itemsTexture;cursorBlock;onRender=[];lastRenderTime=0;lastSciFiTickMs=0;animatedFov=0;lastFovAnimTime=0;cameraShake;cameraContainer;media;get waitingChunksToDisplay(){return this.chunkMeshManager.waitingChunksToDisplay}waypoints;cinimaticScript;camera;renderTimeAvg=0;pendingSectionUpdates=new Map;pendingSectionBufferStartTimes=new Map;get estimatedMemoryUsage(){return this.chunkMeshManager.getEstimatedMemoryUsage().total}modules={};sectionsOffsetsAnimations={};fountains=[];fireworksLegacy;DEBUG_RAYCAST=!1;skyboxRenderer;fireworks;sceneOrigin=new Wb(this.scene);cameraWorldPos={x:0,y:0,z:0};_cameraPositionAccessWarned=!1;_tmpCameraPos=new X;currentPosTween;currentRotTween;_tpDirection=new X;_tpPitchQuat=new qt;_tpYawQuat=new qt;_tpFinalQuat=new qt;_tpScenePos=new X;_tpAxisX=new X(1,0,0);_tpAxisY=new X(0,1,0);_tpChunkWorldPos=new X;get tilesRendered(){return this.chunkMeshManager.getTotalTiles()}get blocksRendered(){return this.chunkMeshManager.getTotalBlocks()}registerModule(t){if(t.id in this.modules){console.warn(`Module ${t.id} is already registered`);return}let n=new t.controller(this),r={manifest:t,controller:n,enabled:!1,toggle:()=>this.toggleModule(t.id)};this.modules[t.id]=r,t.enabledDefault&&this.toggleModule(t.id,!0)}enableModule(t){let n=this.modules[t];if(!n){console.warn(`Module ${t} not found`);return}n.enabled||(n.enabled=!0,n.controller.enable(),n.controller.render&&this.onRender.push(n.controller.render))}disableModule(t){let n=this.modules[t];if(!n){console.warn(`Module ${t} not found`);return}if(n.manifest.cannotBeDisabled){console.warn(`Module ${t} cannot be disabled`);return}if(n.enabled&&(n.enabled=!1,n.controller.disable(),n.controller.render)){let r=this.onRender.indexOf(n.controller.render);r>-1&&this.onRender.splice(r,1)}}toggleModule(t,n){let r=this.modules[t];if(!r)return console.warn(`Module ${t} not found`),!1;let s=n!==void 0?n:!r.enabled;if(s===r.enabled)return r.enabled;if(!s&&r.manifest.cannotBeDisabled)return console.warn(`Module ${t} cannot be disabled`),!0;if(r.enabled=s,s)r.controller.enable(),r.controller.render&&!this.onRender.includes(r.controller.render)&&this.onRender.push(r.controller.render);else if(r.controller.disable(),r.controller.render){let a=this.onRender.indexOf(r.controller.render);a>-1&&this.onRender.splice(a,1)}return s}setRain(t){this.worldRendererConfig.isRaining=t,this.toggleModule("rain",t)}disposeModules(){for(let t of Object.values(this.modules))t.controller.dispose();this.modules={}}initializeModules(){this.updateModulesFromConfig()}getModule(t){return this.modules[t]?.controller}anyModuleRequiresHeightmap(){return Object.values(this.modules).some(t=>t.enabled&&t.manifest.requiresHeightmap)}get cameraObject(){return this.cameraGroupVr??this.cameraContainer}_wrapCameraPositionWithWarning(){let t=this.camera.position,n=this,r=20,s=(l,c,u)=>Math.abs(l)>r||Math.abs(c)>r||Math.abs(u)>r,a=()=>{!n._cameraPositionAccessWarned&&typeof process<"u"},o=new Proxy(t,{set(l,c,u){return(c==="x"||c==="y"||c==="z")&&typeof u=="number"&&Math.abs(u)>r&&a(),l[c]=u,!0},get(l,c,u){let d=l[c];return c==="set"?function(f,v,g){return s(f,v,g)&&a(),l.set(f,v,g)}:c==="setX"||c==="setY"||c==="setZ"?function(f){return Math.abs(f)>r&&a(),l[c](f)}:c==="copy"?function(f){return s(f.x,f.y,f.z)&&a(),l.copy(f)}:typeof d=="function"?d.bind(l):d}});Object.defineProperty(this.camera,"position",{value:o,configurable:!0,enumerable:!0})}worldSwitchActions(){this.onWorldSwitched.push(()=>{this.getModule("futuristicReveal")?.onWorldSwitched?.(),this.protocolCustomBlocks.clear(),this.sectionsOffsetsAnimations={},this.waypoints.clear(),this.cinimaticScript.stopScript(),this.fireworks.clear(),this.syncSkyLevelFromTime(this.timeOfTheDay)})}downloadWorldGeometry(){MP(this,new X(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),this.cameraShake.getBaseRotation(),"world-geometry.json")}updateEntity(t,n=!1){let r={rotation:{head:{x:t.headPitch??t.pitch,y:t.headYaw,z:0}}};n?this.entities.updateEntityPosition(t,!1,r):this.entities.update(t,r)}updatePlayerEntity(t){this.entities.handlePlayerEntity(t)}resetScene(){this.sceneOrigin.update(0,0,0),this.cameraWorldPos.x=0,this.cameraWorldPos.y=0,this.cameraWorldPos.z=0,this.scene.matrixAutoUpdate=!1,this.scene.background=new We(this.initOptions.config.sceneBackground),this.scene.add(this.ambientLight),this.directionalLight.position.set(1,1,.5).normalize(),this.directionalLight.castShadow=!0,this.scene.add(this.directionalLight);let t=this.renderer.getSize(new ze);this.camera=new fn(75,t.x/t.y,.1,1e3),this._wrapCameraPositionWithWarning(),this.cameraContainer=new Ut,this.cameraContainer.add(this.camera),this.scene.add(this.cameraContainer)}watchReactivePlayerState(){super.watchReactivePlayerState(),this.onReactivePlayerStateUpdated("inWater",t=>{this.skyboxRenderer.updateWaterState(t,this.playerStateReactive.waterBreathing)}),this.onReactivePlayerStateUpdated("waterBreathing",t=>{this.skyboxRenderer.updateWaterState(this.playerStateReactive.inWater,t)}),this.onReactivePlayerStateUpdated("ambientLight",t=>{t&&(this.ambientLight.intensity=t*ia.LEGACY_TO_PHYSICAL_LIGHT)}),this.onReactivePlayerStateUpdated("directionalLight",t=>{t&&(this.directionalLight.intensity=t*ia.LEGACY_TO_PHYSICAL_LIGHT)}),this.onReactivePlayerStateUpdated("lookingAtBlock",t=>{this.cursorBlock.setHighlightCursorBlock(t?new kt(t.x,t.y,t.z):null,t?.shapes)}),this.onReactivePlayerStateUpdated("diggingBlock",t=>{this.cursorBlock.updateBreakAnimation(t?{x:t.x,y:t.y,z:t.z}:void 0,t?.stage??null,t?.mergedShape)}),this.onReactivePlayerStateUpdated("perspective",t=>{let n=new kt(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z);this.updateCamera(n,this.cameraShake.getBaseRotation().yaw,this.cameraShake.getBaseRotation().pitch)})}watchReactiveConfig(){super.watchReactiveConfig(),this.onReactiveConfigUpdated("showChunkBorders",r=>{this.updateShowChunksBorder(r)}),this.onReactiveConfigUpdated("defaultSkybox",r=>{this.skyboxRenderer.updateDefaultSkybox(r)}),this.onReactiveConfigUpdated("shaderCubeDebugMode",()=>{this.chunkMeshManager.syncCubeShaderUniforms(),this.chunkMeshManager.syncLegacyShaderUniforms()});let t=()=>{let r=this.worldRendererConfig;this.chunkMeshManager.setShadingTheme(r.shadingTheme,r.cardinalLight)};this.onReactiveConfigUpdated("shadingTheme",t),this.onReactiveConfigUpdated("cardinalLight",t),this.onReactiveConfigUpdated("futuristicReveal",()=>{this.updateModulesFromConfig()});let n=this.displayOptions.inWorldRenderingConfig.handRenderer;this.onReactiveConfigUpdated("handRenderer",r=>{if(r===n)return;n=r;let s=this.holdingBlock.ready,a=this.holdingBlockLeft.ready;this.holdingBlock.dispose(),this.holdingBlockLeft.dispose(),this.holdingBlock=sg(this),this.holdingBlockLeft=sg(this,!0),s&&(this.holdingBlock.ready=!0,this.holdingBlock.updateItem()),a&&(this.holdingBlockLeft.ready=!0,this.holdingBlockLeft.updateItem())}),this.onReactiveConfigUpdated("*",()=>{this.updateModulesFromConfig()}),this.updateModulesFromConfig()}updateModulesFromConfig(){let{moduleStates:t}=this.worldRendererConfig;for(let[n,r]of Object.entries(this.modules)){let s=t[n];if(s==="enabled"){r.enabled||this.toggleModule(n,!0);continue}if(s==="disabled"){r.enabled&&!r.manifest.cannotBeDisabled&&this.toggleModule(n,!1);continue}if(s==="auto"||s===void 0)if(r.controller.autoEnableCheck){let a=r.controller.autoEnableCheck();a&&!r.enabled?this.toggleModule(n,!0):!a&&r.enabled&&!r.manifest.cannotBeDisabled&&this.toggleModule(n,!1)}else{let a=r.manifest.enabledDefault??!1;a&&!r.enabled?this.toggleModule(n,!0):!a&&r.enabled&&!r.manifest.cannotBeDisabled&&this.toggleModule(n,!1)}}}changeHandSwingingState(t,n=!1){let r=n?this.holdingBlockLeft:this.holdingBlock;t?r.startSwing():r.stopSwing()}async updateAssetsData(){let t=this.resourcesManager.currentResources,n=this.material.map,r=this.itemsTexture,s=cc(t.blocksAtlasImage);s.needsUpdate=!0,s.flipY=!1,this.material.map=s,this.chunkMeshManager.syncCubeShaderUniforms(),this.chunkMeshManager.syncLegacyShaderUniforms();let a=cc(t.itemsAtlasImage);a.needsUpdate=!0,a.flipY=!1,this.itemsTexture=a,n&&n.dispose(),r&&r.dispose(),await super.updateAssetsData(),this.onAllTexturesLoaded(),Object.keys(this.loadedChunks).length>0&&(console.log("rerendering chunks because of texture update"),this.rerenderAllChunks())}onAllTexturesLoaded(){this.holdingBlock.ready=!0,this.holdingBlock.updateItem(),this.holdingBlockLeft.ready=!0,this.holdingBlockLeft.updateItem()}changeBackgroundColor(t){this.realScene.background=new We(t[0],t[1],t[2])}changeCardinalLight(t){this.worldRendererConfig.cardinalLight=t}timeUpdated(t){let n=this.getModule("starfield");n?.updateTimeOfDay&&n.updateTimeOfDay(t),this.skyboxRenderer.updateTime(t),this.syncSkyLevelFromTime(t)}syncSkyLevelFromTime(t){let n=Ml(t)/15;this.chunkMeshManager.setSkyLevel(n)}onDayCycleSkyLightChanged(t){}biomeUpdated(t){t?.temperature!==void 0&&this.skyboxRenderer.updateTemperature(t.temperature)}biomeReset(){this.skyboxRenderer.updateTemperature(vP)}getItemRenderData(t,n){return k_e(t,n,this.resourcesManager,this.playerStateReactive)}async demoModel(){let t=cursorBlockRel(0,1,0).position,n=await Pv();Sve(n,t);let r=new Ea(n,16776960);n.add(r),this.realScene.add(n)}demoItem(){let t=cursorBlockRel(0,1,0).position,{mesh:n}=this.entities.getItemMesh({itemId:541},{});n.position.set(t.x+.5,t.y+.5,t.z+.5);let r=new Ea(n,16776960);n.add(r),this.realScene.add(n)}debugOverlayAdded=!1;addDebugOverlay(){if(this.debugOverlayAdded)return;this.debugOverlayAdded=!0;let t=i4("debug-overlay",80,0,void 0,{className:r4});setInterval(()=>{if(t.setVisibility(this.displayAdvancedStats),this.displayAdvancedStats){let n=c=>new Intl.NumberFormat("en-US",{}).format(c),r=c=>new Intl.NumberFormat("en-US",{notation:"compact",maximumFractionDigits:1}).format(c),s="";s+=`TE: ${n(this.renderer.info.memory.textures)} `;let a=this.chunkMeshManager.getGlobalBufferStats();if(a.shaderFaces){let c=a.shaderFaces;s+=`CUBE: ${r(c.used)}/${r(c.capacity)}f `}if(a.legacyOpaque){let c=a.legacyOpaque;s+=`LEG-O: ${r(c.used)}/${r(c.capacity)}q `}if(a.legacyBlend){let c=a.legacyBlend;s+=`LEG-B: ${r(c.used)}/${r(c.capacity)}q `}s+=`MEM: ${this.chunkMeshManager.getEstimatedMemoryUsage().total} `;let o=this.cameraCollisionBlockCache.getAllocatedBytes();o>0&&(s+=`CAM: ${r(o)}b `);let l=qP(this.reactiveState.world.instabilityFactors);l&&(s+=`PF: ${l} `),t.updateText(s),this.backendInfoReport=s}},200)}updatePosDataChunk(t){let n=this.sectionObjects[t];if(!n)return;let[r,s,a]=t.split(",").map(u=>Math.floor(+u/16)),l=500-(Math.abs(r-this.cameraSectionPos.x)+Math.abs(s-this.cameraSectionPos.y)+Math.abs(a-this.cameraSectionPos.z)),c=n.mesh??n.shaderMesh??n.children.find(u=>u.name==="mesh"||u.name==="shaderMesh");c&&(c.renderOrder=l)}cameraSectionPositionUpdate(){for(let t in this.sectionObjects)this.sectionObjects[t]&&this.updatePosDataChunk(t)}getDir(t,n){return t===n?0:t<n?1:-1}finishChunk(t){this.chunkMeshManager.finishChunkDisplay(t),this.getModule("futuristicReveal")?.onChunkFinished?.()}applyPendingSectionUpdates(){if(this.pendingSectionUpdates.size===0)return;let t=performance.now(),n=this.getSectionHeight(),r=[];for(let s of this.pendingSectionUpdates.keys()){let a=this.pendingSectionBufferStartTimes.get(s)??t;if(t-a<ia.MAX_SECTION_UPDATE_BUFFER_MS){let[l,c,u]=s.split(",").map(Number),d=[`${l-16},${c},${u}`,`${l+16},${c},${u}`,`${l},${c-n},${u}`,`${l},${c+n},${u}`,`${l},${c},${u-16}`,`${l},${c},${u+16}`],f=!1;for(let v of d)if(this.sectionsWaiting.has(v)&&!this.pendingSectionUpdates.has(v)&&this.sectionObjects[v]){f=!0;break}if(f)continue}r.push(s)}if(r.length!==0)for(let s of r){let a=this.pendingSectionUpdates.get(s);this.pendingSectionUpdates.delete(s),this.pendingSectionBufferStartTimes.delete(s);let o=a.key.split(","),l=`${o[0]},${o[2]}`;if(!this.loadedChunks[l]||!this.active){this.chunkMeshManager.releaseSection(a.key);continue}if(!this.chunkMeshManager.sectionHasRenderableContent(a.geometry)){this.chunkMeshManager.releaseSection(a.key);continue}let c=this.chunkMeshManager.updateSection(a.key,a.geometry);this.updatePosDataChunk(a.key),c&&this.getModule("futuristicReveal")?.onSectionMeshed?.(a.key,a.geometry,c)}}clearPendingSectionUpdatesForChunk(t,n){for(let r of[...this.pendingSectionUpdates.keys()])r.startsWith(`${t},`)&&r.endsWith(`,${n}`)&&(this.pendingSectionUpdates.delete(r),this.pendingSectionBufferStartTimes.delete(r))}handleWorkerMessage(t){if(t.type==="geometry"){let n=t.key.split(","),r=`${n[0]},${n[2]}`;if(!this.loadedChunks[r]||!this.active){this.pendingSectionUpdates.delete(t.key),this.pendingSectionBufferStartTimes.delete(t.key);return}if(this.sectionObjects[t.key]){this.pendingSectionUpdates.set(t.key,t),this.pendingSectionBufferStartTimes.has(t.key)||this.pendingSectionBufferStartTimes.set(t.key,performance.now());return}if(!this.chunkMeshManager.sectionHasRenderableContent(t.geometry)){this.chunkMeshManager.releaseSection(t.key);return}let s=this.chunkMeshManager.updateSection(t.key,t.geometry);this.updatePosDataChunk(t.key),s&&this.getModule("futuristicReveal")?.onSectionMeshed?.(t.key,t.geometry,s)}}getCameraPosition(t){return(t??this._tmpCameraPos).set(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z)}getSectionCameraPosition(){let t=this.getCameraPosition();return new kt(Math.floor(t.x/16),Math.floor(t.y/16),Math.floor(t.z/16))}updateCameraSectionPos(){let t=this.getSectionCameraPosition();this.cameraSectionPos.equals(t)||(this.cameraSectionPos=t,this.cameraSectionPositionUpdate())}setFirstPersonCamera(t,n,r){let s=this.playerStateReactive.eyeHeight;this.updateCamera(t?.offset(0,s,0)??null,n,r),this.updateCameraSectionPos()}getThirdPersonCamera(t,n,r){t??=new X(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z);let s=this.playerStateReactive.perspective==="third_person_back",a=4,o=this._tpDirection.set(0,0,-1),l=this._tpPitchQuat.setFromAxisAngle(this._tpAxisX,r),c=this._tpYawQuat.setFromAxisAngle(this._tpAxisY,n),u=this._tpFinalQuat.multiplyQuaternions(c,l);o.applyQuaternion(u),s&&o.multiplyScalar(-1),this.DEBUG_RAYCAST&&this.debugRaycast(t,o,a);let d=.25,f=.05,v=.4,g=this.cameraCollisionBlockCache,b=k4e(t.x,t.y,t.z,o.x,o.y,o.z,a,d,f,(_,x,w)=>g.isSolidBlock(_,x,w)),y=a;return b!==void 0&&(y=Math.min(y,b.distance)),y<v&&(y=v),new kt(t.x+o.x*y,t.y+o.y*y,t.z+o.z*y)}debugRaycastHelper;debugHitPoint;debugRaycast(t,n,r){this.debugRaycastHelper&&(this.realScene.remove(this.debugRaycastHelper),this.debugRaycastHelper=void 0),this.debugHitPoint&&(this.realScene.remove(this.debugHitPoint),this.debugHitPoint=void 0);let s=new X(this.sceneOrigin.toSceneX(t.x),this.sceneOrigin.toSceneY(t.y),this.sceneOrigin.toSceneZ(t.z));this.debugRaycastHelper=new F0(n.clone().normalize(),s,r,16711680,r*.1,r*.05),this.realScene.add(this.debugRaycastHelper);let a=new xs(.2,8,8),o=new _t({color:65280});this.debugHitPoint=new Ke(a,o),this.debugHitPoint.position.copy(s).add(n.clone().multiplyScalar(r)),this.realScene.add(this.debugHitPoint)}prevFramePerspective=null;setCinimaticCamera(t,n,r){this.cameraWorldPos.x=t.x,this.cameraWorldPos.y=t.y,this.cameraWorldPos.z=t.z,this.sceneOrigin.update(t.x,t.y,t.z),this.cameraObject.position.set(0,0,0),this.cameraShake.setBaseRotation(r,n),this.updateCameraSectionPos()}setCinimaticFov(t){this.animatedFov=t,this.camera.fov=t,this.camera.updateProjectionMatrix()}updateSmoothFov(){if(this.cinimaticScript.running)return;let t=this.displayOptions.inWorldRenderingConfig.fov,n=this.playerStateReactive.fovMultiplier,r=t*(Number.isFinite(n)?n:1),s=performance.now();if(this.animatedFov===0&&(this.animatedFov=r),Math.abs(this.animatedFov-r)>=.01){let a=s-this.lastFovAnimTime,o=Math.min(a/ia.FOV_TRANSITION_MS,1),l=c=>1-(1-c)**3;this.animatedFov+=(r-this.animatedFov)*l(o),Math.abs(this.animatedFov-r)<.01&&(this.animatedFov=r)}else this.animatedFov=r;this.lastFovAnimTime=s,this.camera.fov!==this.animatedFov&&(this.camera.fov=this.animatedFov,this.camera.updateProjectionMatrix())}updateCamera(t,n,r){if(!this.cinimaticScript.running){if(t){this.renderer.xr.isPresenting&&(t.y-=this.camera.position.y),this.currentPosTween?.stop();let s=this.displayOptions.inWorldRenderingConfig.instantCameraUpdate?0:this.playerStateUtils.isSpectatingEntity()?150:50;this.currentPosTween=new jr(this.cameraWorldPos).to({x:t.x,y:t.y,z:t.z},s).onUpdate(()=>{this.sceneOrigin.update(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),this.cameraObject.position.set(0,0,0)}).start()}if(this.playerStateUtils.isSpectatingEntity()){let s=this.cameraShake.getBaseRotation(),a=0,o=Math.PI/2;s.yaw<o&&n>Math.PI+o?a=-Math.PI*2:n<o&&s.yaw>Math.PI+o&&(a=Math.PI*2),this.currentRotTween?.stop(),this.currentRotTween=new jr(s).to({pitch:r,yaw:n+a},100).onUpdate(l=>this.cameraShake.setBaseRotation(l.pitch,l.yaw-a)).start()}else{this.currentRotTween?.stop(),this.cameraShake.setBaseRotation(r,n);let{perspective:s}=this.playerStateReactive;if(s==="third_person_back"||s==="third_person_front"){let a=new X(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),o=this.getThirdPersonCamera(a,n,r),l=a.distanceTo(new X(o.x,o.y,o.z)),c=s==="third_person_back"?l:-l;this.camera.position.set(0,0,c),s==="third_person_front"?this.camera.rotation.set(0,Math.PI,0):this.camera.rotation.set(0,0,0)}else this.camera.position.z=0,this.camera.rotation.set(0,0,0),this.debugRaycastHelper&&(this.realScene.remove(this.debugRaycastHelper),this.debugRaycastHelper=void 0),this.debugHitPoint&&(this.realScene.remove(this.debugHitPoint),this.debugHitPoint=void 0)}this.updateCameraSectionPos()}}debugChunksVisibilityOverride(){let{chunksRenderAboveOverride:t,chunksRenderBelowOverride:n,chunksRenderDistanceOverride:r,chunksRenderAboveEnabled:s,chunksRenderBelowEnabled:a,chunksRenderDistanceEnabled:o}=this.reactiveDebugParams,l=this.getSectionHeight(),c=this.cameraSectionPos.y*l;if(this.displayOptions.inWorldRenderingConfig.enableDebugOverlay&&t!==void 0||n!==void 0||r!==void 0)for(let[u,d]of Object.entries(this.sectionObjects)){if(d._waitingForChunkDisplay)continue;let[f,v,g]=u.split(",").map(Number),b=s&&t!==void 0?v<=c+t:a&&n!==void 0?v>=c-n:o&&r!==void 0?Math.abs(v-c)<=r:!0;d.visible=b}else this.chunkMeshManager.updateSectionsVisibility()}render(t=!1){if(this.currentRenderedFrames++,this.reactiveDebugParams.stopRendering)return;this.debugChunksVisibilityOverride();let n=performance.now();this.lastRendered=performance.now();let r=this.lastRenderTime>0?Math.min(Math.max((n-this.lastRenderTime)/1e3,0),.1):1/60;this.lastRenderTime=n,this.cursorBlock.render(),this.updateSectionOffsets();let s=this.getCameraPosition();if(this.skyboxRenderer.update(s,this.viewDistance),this.updateSmoothFov(),t){let w=this.renderer.getSize(new ze);this.camera.aspect=w.width/w.height,this.camera.updateProjectionMatrix()}let a=0;if(!this.reactiveDebugParams.disableEntities){let w=performance.now();this.entities.render(),a=performance.now()-w}let o=this.cameraGroupVr instanceof bt?this.cameraGroupVr.children.find(w=>w instanceof fn):this.camera;this.applyPendingSectionUpdates();let l=performance.now(),c=l-this.lastSciFiTickMs;this.lastSciFiTickMs=l,this.getModule("futuristicReveal")?.tick?.(c,l);let u=this.cameraWorldPos.x,d=this.cameraWorldPos.y,f=this.cameraWorldPos.z;this.chunkMeshManager.maybeRebase({x:u,y:d,z:f});let v=this.chunkMeshManager.getRenderOrigin(),g=this.chunkMeshManager.globalBlockBuffer;g&&(g.setCameraOrigin(v,u,d,f),g.setDebugOverlay(this.displayOptions.inWorldRenderingConfig.enableDebugOverlay),g.compactStep(),g.hasPendingUploads()&&g.uploadDirtyRange(),g.suppressThreeDraw());let b=this.chunkMeshManager.globalLegacyBuffer;b&&(b.setDebugOverlay(this.displayOptions.inWorldRenderingConfig.enableDebugOverlay),b.compactStep(),b.hasPendingUploads()&&b.uploadDirtyRange(),b.suppressThreeDraw());let y=this.chunkMeshManager.globalLegacyBlendBuffer;y&&(y.setDebugOverlay(this.displayOptions.inWorldRenderingConfig.enableDebugOverlay),y.compactStep(),y.hasPendingUploads()&&y.uploadDirtyRange(),y.suppressThreeDraw()),this.chunkMeshManager.markCullDirtyIfBufferStateChanged(),this.chunkMeshManager.setLegacyCameraOrigin(u,d,f),this.chunkMeshManager.updateCullDirtyFromCamera(o,u,d,f),this.chunkMeshManager.cullDirty&&(this.chunkMeshManager.updateSectionCullAndSort(o,this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),this.chunkMeshManager.clearCullDirty()),this.renderer.render(this.scene,o),this.displayOptions.inWorldRenderingConfig.showHand&&this.playerStateReactive.gameMode!=="spectator"&&this.playerStateReactive.perspective==="first_person"&&!this.renderer.xr.isPresenting&&(this.holdingBlock.render(this.camera,this.renderer,this.ambientLight,this.directionalLight),this.holdingBlockLeft.render(this.camera,this.renderer,this.ambientLight,this.directionalLight));for(let w of this.fountains)this.sectionObjects[w.sectionId]&&!this.sectionObjects[w.sectionId].foutain&&(w.createParticles(this.sectionObjects[w.sectionId]),this.sectionObjects[w.sectionId].foutain=!0),w.render();this.waypoints.render(),this.fireworks.update();for(let w of this.onRender)w(r);let x=performance.now()-n;this.worldRendererConfig.autoLowerRenderDistance&&this.chunkMeshManager.recordRenderTime(x),this.renderTimeAvgCount++,this.renderTimeAvg=(this.renderTimeAvg*(this.renderTimeAvgCount-1)+x)/this.renderTimeAvgCount,this.renderTimeMax=Math.max(this.renderTimeMax,x),this.performanceMonitor.onFrame({totalMs:x,entitiesMs:a,loadedTextureCount:this.renderer.info.memory.textures,fps:this.lastFps})}renderHead(t,n,r,s){let a;if(s.SkullOwner?a=s.SkullOwner.Properties?.textures?.[0]?.Value:a=s.profile?.properties?.find(o=>o.name==="textures")?.value,!!a)try{let l=JSON.parse(Buffer.from(a,"base64").toString()).textures?.SKIN?.url,{skinTexturesProxy:c}=this.worldRendererConfig;c&&(l=l?.replace("http://textures.minecraft.net/",c).replace("https://textures.minecraft.net/",c));let u=$c(this,l,Yc.head),d=new bt;return r&&u.position.set(0,.3125,.3125),u.position.y-=23/16,d.add(u),this.sceneOrigin.track(d),d.position.set(t.x+.5,t.y+.045,t.z+.5),d.rotation.set(0,-Ot.degToRad(n*(r?90:45/2)),0),d.scale.set(.8,.8,.8),d}catch(o){console.error("Error decoding player texture:",o)}}lightUpdate(t,n){for(let r=this.worldSizeParams.minY;r<this.worldSizeParams.worldHeight;r+=16)this.setSectionDirty(new kt(t,r,n))}rerenderAllChunks(){for(let t of Object.keys(this.sectionObjects)){let[n,r,s]=t.split(",").map(Number);this.setSectionDirty(new kt(n,r,s))}}updateShowChunksBorder(t){this.chunkMeshManager.updateAllBoxHelpers(t)}resetWorld(){super.resetWorld(),this.pendingSectionUpdates.clear(),this.pendingSectionBufferStartTimes.clear(),this.chunkMeshManager.dispose(),this.chunkMeshManager=new fg(this,this.scene,this.material,this.worldSizeParams.worldHeight,this.viewDistance),this.debugRaycastHelper&&(this.realScene.remove(this.debugRaycastHelper),this.debugRaycastHelper=void 0),this.debugHitPoint&&(this.realScene.remove(this.debugHitPoint),this.debugHitPoint=void 0)}getLoadedChunksRelative(t,n=!1){let[r,s,a]=NE(t);return Object.fromEntries(Object.entries(this.sectionObjects).map(([o,l])=>{let[c,u,d]=o.split(",").map(Number),[f,v,g]=NE({x:c,y:u,z:d});return[n?`${f-r},${v-s},${g-a}`:`${f-r},${g-a}`,l]}))}readdChunks(){for(let t of Object.keys(this.sectionObjects))this.scene.remove(this.sectionObjects[t]);setTimeout(()=>{for(let t of Object.keys(this.sectionObjects))this.scene.add(this.sectionObjects[t])},500)}disableUpdates(t=this.scene.children){for(let n of t)n.matrixWorldNeedsUpdate=!1,this.disableUpdates(n.children??[])}removeColumn(t,n){super.removeColumn(t,n),this.clearPendingSectionUpdatesForChunk(t,n);let r=this.getSectionHeight(),s=this.worldMinYRender;for(let a=s;a<this.worldSizeParams.worldHeight;a+=r){let o=`${t},${a},${n}`;this.chunkMeshManager.sectionObjects[o]&&this.chunkMeshManager.releaseSection(o)}this.chunkMeshManager.onChunkRemovedFromGate(`${t},${n}`)}updateViewerPosition(t){super.updateViewerPosition(t),this.chunkMeshManager.pendingNearReveal.size>0&&this.chunkMeshManager.tryRevealPending()}onViewerChunkPositionChanged(){this.chunkMeshManager.tryRevealPending()}setSectionDirty(...t){super.setSectionDirty(...t)}static getRendererInfo(t){try{let n=t.getContext();return`${n.getParameter(n.getExtension("WEBGL_debug_renderer_info").UNMASKED_RENDERER_WEBGL)}`}catch(n){console.warn("Failed to get renderer info",n)}}worldStop(){this.media.onWorldStop()}destroy(){this.performanceMonitor?.reset(),this.pendingSectionUpdates.clear(),this.pendingSectionBufferStartTimes.clear(),this.chunkMeshManager.dispose(),this.disposeModules(),this.fireworksLegacy.destroy(),super.destroy(),this.skyboxRenderer.dispose(),this.fireworks.dispose()}shouldObjectVisible(t){let r=this.getSectionHeight(),s,a,o,l=this.sceneOrigin.getWorldPosition(t);l?(s=l.x,a=l.y,o=l.z):(s=this.sceneOrigin.toWorldX(t.position.x),a=this.sceneOrigin.toWorldY(t.position.y),o=this.sceneOrigin.toWorldZ(t.position.z));let c=Math.floor(s/16)*16,u=Math.floor(o/16)*16,d=Math.floor(a/r)*r,f=`${c},${u}`,v=`${c},${d},${u}`;return!!this.finishedChunks[f]||!!this.sectionObjects[v]}handleUserClick(t){this.media.handleUserClick(t)}updateSectionOffsets(){let t=performance.now();for(let[n,r]of Object.entries(this.sectionsOffsetsAnimations)){let s=(t-r.time)/1e3;r.time=t,r.currentOffsetX+=r.speedX*s,r.currentOffsetY+=r.speedY*s,r.currentOffsetZ+=r.speedZ*s,r.limitX!==void 0&&(r.speedX>0?r.currentOffsetX=Math.min(r.currentOffsetX,r.limitX):r.currentOffsetX=Math.max(r.currentOffsetX,r.limitX)),r.limitY!==void 0&&(r.speedY>0?r.currentOffsetY=Math.min(r.currentOffsetY,r.limitY):r.currentOffsetY=Math.max(r.currentOffsetY,r.limitY)),r.limitZ!==void 0&&(r.speedZ>0?r.currentOffsetZ=Math.min(r.currentOffsetZ,r.limitZ):r.currentOffsetZ=Math.max(r.currentOffsetZ,r.limitZ));let a=this.sectionObjects[n];a&&(a.position.set(r.currentOffsetX,r.currentOffsetY,r.currentOffsetZ),a.updateMatrix())}}reloadWorld(){this.entities.reloadEntities()}};Wn(ia,"LEGACY_TO_PHYSICAL_LIGHT",Math.PI),Wn(ia,"FOV_TRANSITION_MS",200),Wn(ia,"MAX_SECTION_UPDATE_BUFFER_MS",500);var Yd=ia;h();p();m();h();p();m();var mg="1.21.4";h();p();m();function Jd(i,e){i.aspect=e.width/e.height,i.updateProjectionMatrix()}h();p();m();h();p();m();var u0={mode:"v2",minecraftTextures:!0,v2Scene:"light",v2Camera:"dive",v2BlockGroup:"stainedGlass",v2CameraSpeedPercent:80,v2BlockSpeedPercent:40},GP=i=>i/100,g9={camera:GP(u0.v2CameraSpeedPercent),block:GP(u0.v2BlockSpeedPercent)};function WP(i,e=!1){return i?.mode?i.mode:e?"worldBlocks":u0.mode}h();p();m();Lt();h();p();m();var jP={};function XP(...i){let e=i.filter(n=>n.length>0).join("/"),t=typeof globalThis.location<"u"&&globalThis.location.href?globalThis.location.href:typeof jP<"u"&&jP.url?jP.url:`/${e}`;try{return new URL(e,t).href}catch{return`/${e}`}}var $P=new Date,W4e=$P.getMonth()===11&&$P.getDate()>=24&&$P.getDate()<=26,cJe=["panorama_3.webp","panorama_1.webp","panorama_4.webp","panorama_5.webp","panorama_0.webp","panorama_2.webp"],uJe=200,pg=class{constructor(e){this.documentRenderer=e;this.scene=new Rr,this.scene.background=new We(3294568);let t=new wa(13421772);this.scene.add(t);let n=new Ss(16777215,.5);n.position.set(1,1,.5).normalize(),n.castShadow=!0,this.scene.add(n),this.camera=new fn(85,e.canvas.width/e.canvas.height,.05,1e3),this.camera.position.set(0,0,0),this.camera.rotation.set(0,0,0)}scene;camera;startTimes=new Map;time=0;panoramaGroup=null;async init(){this.buildCubemap()}update(e,t){t&&Jd(this.camera,this.documentRenderer.canvas)}dispose(){this.scene.clear(),this.panoramaGroup=null,this.startTimes.clear()}buildCubemap(){let e=new Sn(1e3,1e3,1e3),t=[];for(let s of cJe)(async()=>{let o=XP("background",W4e?"christmas":"",s),l=await qu(o),c=cc(l);c.matrixAutoUpdate=!1,c.matrix.set(-1,0,1,0,1,0,0,0,1),c.wrapS=jn,c.wrapT=jn,c.minFilter=$t,c.magFilter=$t;let u=new _t({map:c,transparent:!0,side:In,depthWrite:!1,opacity:0});this.startTimes.set(u,Date.now()),t.push(u)})().catch(o=>{console.warn("[ClassicMenuBackground] Failed to load panorama face:",s,o)});let n=new Ke(e,t);n.onBeforeRender=()=>{this.time+=.01,n.rotation.y=Math.PI+this.time*.01,n.rotation.z=Math.sin(-this.time*.001)*.001;for(let s of t){let a=this.startTimes.get(s);if(a){let o=Date.now()-a;s.opacity=Math.min(1,o/uJe)}}};let r=new Ut;if(r.add(n),!W4e)for(let s=0;s<20;s++){let a=new o0("1.16.4","squid").mesh;a.position.set(Math.random()*30-15,Math.random()*20-10,Math.random()*10-17),a.rotation.set(0,Math.PI+Math.random(),-Math.PI/4,"ZYX");let o=Math.random()*.01;a.children[0].onBeforeRender=()=>{a.rotation.y+=o,a.rotation.z=Math.cos(n.rotation.y*3)*Math.PI/4-Math.PI/2},r.add(a)}this.scene.add(r),this.panoramaGroup=r}async debugImageInFrontOfCamera(){let e=await qu(XP("background","panorama_0.webp")),t=cc(e),n=new Ke(new zn(1e3,1e3),new _t({map:t}));n.position.set(0,0,-500),this.scene.add(n)}};h();p();m();Lt();h();p();m();var q5=["galaxy","nether","end","cyber","light"],G5=["cruise","barrel","dive","orbit","snake"],_9={galaxy:"Galaxy",nether:"Nether",end:"The End",cyber:"Cyber",light:"Light Space"},y9={cruise:"Cruise",barrel:"Barrel",dive:"Dive",orbit:"Orbit",snake:"Snake"},W5=["mixed","stainedGlass","wool","construction","glow","world"],b9={mixed:"Mixed",stainedGlass:"Stained glass",wool:"Wool",construction:"Construction",glow:"Glow",world:"World (grass & ores)"};var j4e=.1,Y4e={mixed:["white_wool","cyan_wool","blue_wool","purple_wool","white_stained_glass","cyan_stained_glass","blue_stained_glass","purple_stained_glass","glowstone","sea_lantern","amethyst_block","copper_block","gold_block","diamond_block"],stainedGlass:["white_stained_glass","orange_stained_glass","magenta_stained_glass","light_blue_stained_glass","yellow_stained_glass","lime_stained_glass","pink_stained_glass","gray_stained_glass","light_gray_stained_glass","cyan_stained_glass","purple_stained_glass","blue_stained_glass","brown_stained_glass","green_stained_glass","red_stained_glass","black_stained_glass"],wool:["white_wool","orange_wool","magenta_wool","light_blue_wool","yellow_wool","lime_wool","pink_wool","gray_wool","light_gray_wool","cyan_wool","purple_wool","blue_wool","brown_wool","green_wool","red_wool","black_wool"],construction:["copper_block","exposed_copper","weathered_copper","oxidized_copper","cut_copper","exposed_cut_copper","weathered_cut_copper","oxidized_cut_copper","iron_block","gold_block","diamond_block","emerald_block","netherite_block","lapis_block","redstone_block","coal_block","quartz_block","amethyst_block","bricks","stone_bricks","deepslate_bricks","polished_blackstone"],glow:["glowstone","sea_lantern","shroomlight","ochre_froglight","verdant_froglight","pearlescent_froglight","redstone_lamp","beacon"],world:["grass_block","podzol","mycelium","dirt","coarse_dirt","rooted_dirt","mud","clay","stone","cobblestone","mossy_cobblestone","deepslate","cobbled_deepslate","tuff","calcite","sand","red_sand","gravel","snow_block","coal_ore","deepslate_coal_ore","iron_ore","deepslate_iron_ore","copper_ore","deepslate_copper_ore","gold_ore","deepslate_gold_ore","diamond_ore","deepslate_diamond_ore","emerald_ore","deepslate_emerald_ore","lapis_ore","deepslate_lapis_ore","redstone_ore","deepslate_redstone_ore","nether_gold_ore","ancient_debris","oak_log","birch_log","spruce_log","jungle_log","acacia_log","dark_oak_log","mangrove_log","cherry_log","netherrack","soul_sand","basalt","end_stone"]},X4e={galaxy:{bg:132114,fog:132114,fogD:.011,blocks:[61695,54527,47359,59647,2280703,43263],emit:[13158,8789,6724],nebula:[4403,1114146,4386],galFn:i=>new We(i*.05,i*.2,i),ambient:264216,dir:3368703,pt1:43775,pt2:16729343,name:"GALAXY"},nether:{bg:917760,fog:917760,fogD:.016,blocks:[16720384,16737792,16750848,13373696,16729122,16755200],emit:[2230272,1114112,3346688],nebula:[1704960,851968,1705984],galFn:i=>new We(i,i*.15,0),ambient:1573376,dir:16724736,pt1:16729088,pt2:16755200,name:"NETHER"},end:{bg:0,fog:0,fogD:.009,blocks:[7807658,11158732,5570679,14527231,3342421,12299007],emit:[655381,1572901,327696],nebula:[524312,851989,262158],galFn:i=>new We(i*.4,0,i),ambient:393232,dir:10040319,pt1:11158783,pt2:4456618,name:"THE END"},cyber:{bg:792610,fog:792610,fogD:.008,blocks:[65535,4521932,11206468,6741503,8978278,65450],emit:[666163,668450,665656],nebula:[1192e3,1587240,1323588],galFn:i=>new We(i*.15,i*.85,i*.95),ambient:1716288,dir:6750156,pt1:4521966,pt2:10092356,name:"CYBER",starColor:13431039,starOpacity:.75,galaxyOpacity:.62,nebulaOpacity:.36,edgeLineColor:4521949,blockOpacity:[.38,.54]},light:{bg:8951984,fog:7899296,fogD:.006,gradientBg:{top:14214392,mid:10531016,bottom:6846608,radial:!0},blocks:[15266559,13691135,12114175,10537208,8960240,7383272,10012927,12640511,15792383,7909608,14216447,14739711],emit:[6854864,8958176,11061488,12638456],nebula:[9480392,11059424,12637420,14215416,7901360],galFn:i=>{let e=new We;return i<.4?e.lerpColors(new We(16054527),new We(14215423),i/.4):i<.75?e.lerpColors(new We(14215423),new We(11061488),(i-.4)/.35):e.lerpColors(new We(11061488),new We(9482464),(i-.75)/.25),e},ambient:7899296,dir:13688040,pt1:11061503,pt2:13162751,name:"LIGHT",starColor:15266047,starOpacity:.5,galaxyOpacity:.7,nebulaOpacity:.32,edgeLineColor:10010856,blockOpacity:[.42,.56]}},dJe={cruise:{pos:(i,e,t)=>({x:Math.sin(i*.28)*18+Math.cos(i*.11)*7+e*10,y:Math.sin(i*.19)*6+Math.cos(i*.31)*3+t*6,z:0}),look:(i,e,t)=>({x:Math.sin((i+.18)*.28)*18+e*8,y:Math.sin((i+.18)*.19)*6+t*4,z:-25}),roll:(i,e=0)=>e*.05+Math.sin(i*.22)*.015,spd:.18},barrel:{pos:(i,e,t)=>{let r=i*2.4;return{x:Math.cos(r)*10+e*4,y:Math.sin(r)*10+t*4,z:Math.sin(i*.4)*8}},look:i=>({x:Math.sin(i*.5)*5,y:Math.cos(i*.5)*5,z:-30}),roll:i=>i*2.4+Math.PI*.5,spd:.24},dive:{pos:(i,e,t)=>({x:Math.sin(i*.6)*30+e*8,y:Math.cos(i*.4)*18+t*6,z:Math.sin(i*.3)*12}),look:(i,e,t)=>({x:Math.sin(i*.6+.2)*30+e*6,y:Math.cos(i*.4+.2)*18-8+t*4,z:-35}),roll:(i,e=0)=>e*.08+Math.sin(i*.6)*.12,spd:.3},orbit:{pos:(i,e,t)=>({x:Math.cos(i*.5)*20+e*5,y:Math.sin(i*.25)*10+t*5,z:Math.sin(i*.5)*20}),look:()=>({x:0,y:0,z:-60}),roll:i=>Math.sin(i*.5)*.08,spd:.15},snake:{pos:(i,e,t)=>({x:Math.sin(i*1.1)*22+Math.sin(i*.37)*8+e*10,y:Math.sin(i*.7)*10+e*4+t*8,z:0}),look:(i,e,t)=>{let n=i+.12;return{x:Math.sin(n*1.1)*22+Math.sin(n*.37)*8+e*8,y:Math.sin(n*.7)*10+t*6,z:-22}},roll:(i,e=0)=>e*.1+Math.sin(i*1.1)*.06,spd:.22}},fJe={cruise:1,barrel:1.6,dive:2.2,orbit:.7,snake:1.4},hJe=250,x9=1e4,w9=3e3,j5=i=>i[Math.floor(Math.random()*i.length)],YP=i=>"#"+i.toString(16).padStart(6,"0"),$4e=i=>{if(typeof document>"u")return null;let e=document.createElement("canvas");e.width=4,e.height=512;let t=e.getContext("2d");if(!t)return null;let n=e.width,r=e.height,s=i.radial?t.createRadialGradient(n/2,r*.32,0,n/2,r*.32,r*.85):t.createLinearGradient(0,0,0,r);s.addColorStop(0,YP(i.top)),i.mid!=null&&s.addColorStop(.45,YP(i.mid)),s.addColorStop(1,YP(i.bottom)),t.fillStyle=s,t.fillRect(0,0,n,r);let a=new On(e);return a.needsUpdate=!0,a},X5=class{constructor(e,t={},n){this.documentRenderer=e;this.abortSignal=n;let r=u0;this.curScene=t.initialScene??r.v2Scene,this.curCam=t.initialCamera??r.v2Camera,this.blockGroup=t.initialBlockGroup??r.v2BlockGroup,this.cameraSpeed=t.initialCameraSpeed??g9.camera,this.blockSpeed=t.initialBlockSpeed??g9.block,this.useMinecraftTextures=t.useMinecraftTextures??r.minecraftTextures,this.resourcesManager=t.resourcesManager;let s=X4e[this.curScene];this.scene=new Rr,this.scene.fog=new C0(s.fog,s.fogD),this.applyScenePalette(s),this.camera=new fn(80,this.documentRenderer.canvas.width/this.documentRenderer.canvas.height,.1,700),this.ambient=new wa(s.ambient,2.5),this.scene.add(this.ambient),this.dir=new Ss(s.dir,4),this.dir.position.set(1,1,0),this.scene.add(this.dir),this.pt1=new yo(s.pt1,5,100),this.scene.add(this.pt1),this.pt2=new yo(s.pt2,4,80),this.pt2.position.set(30,20,-30),this.scene.add(this.pt2);for(let f=0;f<hJe;f++)this.spawnBlock(s,!0);if(!this.useMinecraftTextures){let f=s.edgeLineColor??62975;for(let v=0;v<40;v++){let g=new Pn({color:f,transparent:!0,opacity:.25});j5(this.blocks).mesh.add(new Kn(this.eGeo,g))}}this.scene.add(this.bGroup);let a=new dt,o=new Float32Array(5e3*3);for(let f=0;f<5e3*3;f++)o[f]=(Math.random()-.5)*500;a.setAttribute("position",new Mt(o,3)),this.stars=new gr(a,new Jr({color:s.starColor??16777215,size:.3,transparent:!0,opacity:s.starOpacity??.7,sizeAttenuation:!0})),this.scene.add(this.stars),this.galGeo=new dt;let l=new Float32Array(x9*3),c=new Float32Array(x9*3);for(let f=0;f<x9;f++){let v=f%3,g=Math.random(),b=v/3*Math.PI*2+g*Math.PI*5,y=g*90+Math.random()*10,_=(1-g)*18;l[f*3]=Math.cos(b)*y+(Math.random()-.5)*_,l[f*3+1]=(Math.random()-.5)*7,l[f*3+2]=Math.sin(b)*y+(Math.random()-.5)*_-180;let x=.2+g*.8,w=s.galFn(x);c[f*3]=w.r,c[f*3+1]=w.g,c[f*3+2]=w.b}this.galGeo.setAttribute("position",new Mt(l,3)),this.galGeo.setAttribute("color",new Mt(c,3)),this.galaxy=new gr(this.galGeo,new Jr({size:.9,vertexColors:!0,transparent:!0,opacity:s.galaxyOpacity??.55,sizeAttenuation:!0})),this.scene.add(this.galaxy),this.nebGeo=new dt;let u=new Float32Array(w9*3),d=new Float32Array(w9*3);for(let f=0;f<w9;f++){let v=25+Math.random()*110,g=Math.random()*Math.PI*2,b=(Math.random()-.5)*Math.PI*.5;u[f*3]=v*Math.cos(g)*Math.cos(b),u[f*3+1]=v*Math.sin(b)*.6,u[f*3+2]=v*Math.sin(g)*Math.cos(b)-80;let y=new We(j5(s.nebula));d[f*3]=y.r,d[f*3+1]=y.g,d[f*3+2]=y.b}this.nebGeo.setAttribute("position",new Mt(u,3)),this.nebGeo.setAttribute("color",new Mt(d,3)),this.nebula=new gr(this.nebGeo,new Jr({size:3,vertexColors:!0,transparent:!0,opacity:s.nebulaOpacity??.3,sizeAttenuation:!0})),this.scene.add(this.nebula),this.addBackgroundTextPlane(),this.setupMouseTracking()}scene;camera;ambient;dir;pt1;pt2;blocks=[];bGroup=new bt;galaxy;nebula;stars;galGeo;nebGeo;bGeo=new Sn(1,1,1);eGeo=new dl(this.bGeo);curScene;curCam;blockGroup;cameraSpeed;blockSpeed;camT=0;mx=0;my=0;tmx=0;tmy=0;transitioning=!1;useMinecraftTextures=!1;resourcesManager;atlasTexture=null;blockMaterialPool=new Map;gradientSky=null;gradientSkyTexture=null;disposed=!1;animTime=0;texturesApplied=!1;textureLoadInProgress=!1;onAssetsTexturesUpdated;async init(){this.useMinecraftTextures&&this.scheduleMinecraftTextureLoad()}scheduleMinecraftTextureLoad(){!this.useMinecraftTextures||this.disposed||this.texturesApplied||this.textureLoadInProgress||this.tryApplyMinecraftTextures()}attachAssetsListener(){let e=this.resourcesManager;!e||this.onAssetsTexturesUpdated||(this.onAssetsTexturesUpdated=()=>this.scheduleMinecraftTextureLoad(),e.on("assetsTexturesUpdated",this.onAssetsTexturesUpdated))}detachAssetsListener(){let e=this.resourcesManager;!e||!this.onAssetsTexturesUpdated||(e.off("assetsTexturesUpdated",this.onAssetsTexturesUpdated),this.onAssetsTexturesUpdated=void 0)}hasBlockAtlas(e){let t=e.currentResources;return!!(t?.blocksAtlasImage&&t.blocksAtlasJson)}async ensureAtlasReady(e){if(await this.ensureMcDataLoaded(),this.hasBlockAtlas(e))return!0;if(typeof document>"u"&&e!==this.resourcesManager)return!1;e.currentConfig={...e.currentConfig,version:mg,noInventoryGui:!0};try{await e.updateAssetsData?.({})}catch{return!1}return this.hasBlockAtlas(e)}async tryApplyMinecraftTextures(){if(!(this.disposed||!this.useMinecraftTextures||this.texturesApplied)){this.textureLoadInProgress=!0;try{let e=this.resourcesManager??new lc;if(!await this.ensureAtlasReady(e)){this.resourcesManager&&this.attachAssetsListener();return}if(this.disposed)return;this.applyMinecraftTexturesFromAtlas(e),this.texturesApplied=!0,this.detachAssetsListener()}catch(e){console.warn("[V2MenuBackground] Failed to load Minecraft textures, using solid colors:",e),this.useMinecraftTextures=!1,this.detachAssetsListener()}finally{this.textureLoadInProgress=!1}}}applyScenePalette(e){if(this.documentRenderer.renderer.setClearColor(e.bg),e.gradientBg)if(this.scene.background=null,this.gradientSky){if(this.gradientSky.visible=!0,this.gradientSkyTexture&&e.gradientBg){let s=$4e(e.gradientBg);s&&(this.gradientSkyTexture.dispose(),this.gradientSkyTexture=s,this.gradientSky.material.map=s,this.gradientSky.material.needsUpdate=!0)}}else{let s=$4e(e.gradientBg);s?(this.gradientSkyTexture=s,this.gradientSky=new Ke(new zn(900,700),new _t({map:s,depthWrite:!1,side:In})),this.gradientSky.position.set(0,0,-280),this.gradientSky.renderOrder=-1e3,this.scene.add(this.gradientSky)):this.scene.background=new We(e.bg)}else this.scene.background=new We(e.bg),this.gradientSky&&(this.gradientSky.visible=!1);this.scene.fog instanceof C0&&(this.scene.fog.color.set(e.fog),this.scene.fog.density=e.fogD);let t=this.stars?.material;t&&(t.color.set(e.starColor??16777215),t.opacity=e.starOpacity??.7);let n=this.galaxy?.material;n&&(n.opacity=e.galaxyOpacity??.55);let r=this.nebula?.material;r&&(r.opacity=e.nebulaOpacity??.3)}setupMouseTracking(){let e=n=>{let r=typeof window<"u"?window.innerWidth:this.documentRenderer.canvas.width,s=typeof window<"u"?window.innerHeight:this.documentRenderer.canvas.height;this.tmx=(n.clientX/r-.5)*2,this.tmy=-(n.clientY/s-.5)*2};(typeof document<"u"?document:void 0)?.addEventListener("mousemove",e,{signal:this.abortSignal})}addBackgroundTextPlane(){let n=typeof document<"u"?document.createElement("canvas"):null;if(!n)return;n.width=2048,n.height=768;let r=n.getContext("2d");if(!r)return;r.clearRect(0,0,2048,768),r.save(),r.font="bold 560px Orbitron, sans-serif",r.textAlign="center",r.textBaseline="middle",r.shadowColor="rgba(0,200,255,0.35)",r.shadowBlur=80,r.fillStyle="rgba(255,255,255,0.055)",r.fillText("V2",2048*.28,768*.5),r.restore(),r.save(),r.font="bold 148px Orbitron, sans-serif",r.textAlign="center",r.textBaseline="middle",r.shadowColor="rgba(0,200,255,0.2)",r.shadowBlur=40,r.fillStyle="rgba(255,255,255,0.038)",r.fillText("by ZARDOY",2048*.72,768*.52),r.restore();let s=new On(n),a=new Ke(new zn(280,105),new _t({map:s,transparent:!0,opacity:1,depthWrite:!1,side:In,blending:es}));a.position.set(8,4,-320),this.scene.add(a)}spawnBlock(e,t,n){let r=this.createBlockMaterial(e,n),s=new Ke(this.bGeo,r),a=.3+Math.random()*3;s.scale.setScalar(a),s.position.set((Math.random()-.5)*140,(Math.random()-.5)*70,t?-(Math.random()*140):-155-Math.random()*30),s.rotation.set(Math.random()*Math.PI*2,Math.random()*Math.PI*2,Math.random()*Math.PI*2);let o={mesh:s,spd:.04+Math.random()*.12,dx:(Math.random()-.5)*.012,dy:(Math.random()-.5)*.008,rx:(Math.random()-.5)*.012,ry:(Math.random()-.5)*.012,rz:(Math.random()-.5)*.01,minecraftBlockName:n};this.blocks.push(o),this.bGroup.add(s)}createBlockMaterial(e,t){if(this.useMinecraftTextures&&t){let s=this.blockMaterialPool.get(t);if(s)return s.clone()}let[n,r]=e.blockOpacity??[.32,.46];return new _t({color:j5(e.blocks),transparent:!0,opacity:n+Math.random()*(r-n),depthWrite:!1,blending:es})}removeBlockEdgeLines(){for(let e of this.blocks){let t=e.mesh.children.filter(n=>n instanceof Kn);for(let n of t){e.mesh.remove(n),n.geometry?.dispose();let r=n.material;Array.isArray(r)?r.forEach(s=>s.dispose()):r.dispose()}}}async ensureMcDataLoaded(){let e=globalThis._LOAD_MC_DATA;e&&await e()}resolveBlockAtlasUv(e,t,n){let r=s=>{let a=t[s];return a?{u:a.u,v:a.v,su:a.su??n.suSv,sv:a.sv??n.suSv}:null};if(t[e])return r(e);for(let s of["_top","_side","_front","_0"]){let a=r(`${e}${s}`);if(a)return a}for(let s of Object.keys(t))if(s.startsWith(e))return r(s);return null}applyMinecraftTexturesFromAtlas(e){let t=e.currentResources;if(!t?.blocksAtlasImage||!t.blocksAtlasJson)throw new Error("Block atlas not available");let n=t.blocksAtlasJson,r=n.textures;this.atlasTexture=cc(t.blocksAtlasImage),this.atlasTexture.flipY=!1,this.atlasTexture.needsUpdate=!0;for(let s of Y4e[this.blockGroup]){let a=this.resolveBlockAtlasUv(s,r,n);if(!a)continue;let o=this.atlasTexture.clone();o.flipY=!1,o.offset.set(a.u,a.v),o.repeat.set(a.su,a.sv),o.needsUpdate=!0;let l=s.includes("glass"),c=new _t({map:o,side:In,transparent:l,opacity:l?.85:1,alphaTest:l?.08:0,depthWrite:!0,toneMapped:!1});this.blockMaterialPool.set(s,c)}if(this.blockMaterialPool.size===0)throw new Error("No block textures resolved from atlas (check block names vs atlas keys)");this.removeBlockEdgeLines();for(let s of this.blocks){let a=j5([...this.blockMaterialPool.keys()]);s.minecraftBlockName=a,s.mesh.material=this.blockMaterialPool.get(a).clone()}}setScene(e){if(!q5.includes(e)||e===this.curScene||this.transitioning)return;this.transitioning=!0,this.curScene=e;let t=X4e[e];setTimeout(()=>{if(this.disposed)return;this.applyScenePalette(t),this.ambient.color.set(t.ambient),this.dir.color.set(t.dir),this.pt1.color.set(t.pt1),this.pt2.color.set(t.pt2);for(let s of this.blocks)this.useMinecraftTextures&&s.minecraftBlockName||s.mesh.material instanceof _t&&s.mesh.material.color.set(j5(t.blocks));let n=this.nebGeo.attributes.color;for(let s=0;s<w9;s++){let a=new We(j5(t.nebula));n.setXYZ(s,a.r,a.g,a.b)}n.needsUpdate=!0;let r=this.galGeo.attributes.color;for(let s=0;s<x9;s++){let a=.2+Math.random()*.8,o=t.galFn(a);r.setXYZ(s,o.r,o.g,o.b)}r.needsUpdate=!0,this.transitioning=!1},150)}setCamera(e){G5.includes(e)&&(this.curCam=e)}setCameraSpeed(e){this.cameraSpeed=Math.max(0,e)}setBlockSpeed(e){this.blockSpeed=Math.max(0,e)}async setBlockGroup(e){if(W5.includes(e)&&e!==this.blockGroup&&(this.blockGroup=e,!(!this.useMinecraftTextures||this.disposed))){for(let t of this.blockMaterialPool.values())t.map?.dispose(),t.dispose();this.blockMaterialPool.clear(),this.texturesApplied=!1,this.scheduleMinecraftTextureLoad()}}getSceneId(){return this.curScene}getCameraId(){return this.curCam}getBlockGroupId(){return this.blockGroup}update(e,t){t&&Jd(this.camera,this.documentRenderer.canvas);let n=dJe[this.curCam],r=this.cameraSpeed,s=this.blockSpeed;this.camT+=e*n.spd*r,this.mx+=(this.tmx-this.mx)*.05,this.my+=(this.tmy-this.my)*.05;let a=this.mx*j4e,o=this.my*j4e,l=n.pos(this.camT,a,o),c=n.look(this.camT,a,o);this.camera.position.set(l.x,l.y,l.z),this.camera.lookAt(c.x,c.y,c.z),this.camera.rotation.z=n.roll(this.camT,a);let u=fJe[this.curCam]*s;this.animTime+=e*1e3*s;for(let d of this.blocks){if(d.mesh.position.z+=d.spd*u*60*e,d.mesh.position.x+=d.dx*60*e*s,d.mesh.position.y+=d.dy*60*e*s,d.mesh.rotation.x+=d.rx*u,d.mesh.rotation.y+=d.ry*u,d.mesh.rotation.z+=d.rz,!this.useMinecraftTextures&&d.mesh.material instanceof _t){let f=d.mesh.userData.baseOpacity??.38;d.mesh.userData.baseOpacity==null&&(d.mesh.userData.baseOpacity=f);let v=.88+Math.abs(Math.sin(this.animTime*8e-4+d.mesh.position.x*.3))*.12;d.mesh.material.opacity=f*v}d.mesh.position.z>this.camera.position.z+15&&d.mesh.position.set((Math.random()-.5)*140,(Math.random()-.5)*70,this.camera.position.z-155-Math.random()*30)}this.pt1.position.set(Math.sin(this.camT*.8)*25+this.camera.position.x,Math.cos(this.camT*.6)*12+this.camera.position.y,this.camera.position.z-18),this.pt2.position.set(Math.cos(this.camT*.5)*20+this.camera.position.x,Math.sin(this.camT*.9)*15+this.camera.position.y,this.camera.position.z-30),this.galaxy.rotation.y+=e*.006*s,this.nebula.rotation.y-=e*.003*s,this.stars.rotation.y+=e*4e-4*s}dispose(){this.disposed=!0,this.detachAssetsListener(),this.scene.clear(),this.bGeo.dispose(),this.eGeo.dispose(),this.galGeo.dispose(),this.nebGeo.dispose(),this.gradientSkyTexture?.dispose(),this.atlasTexture?.dispose();for(let e of this.blockMaterialPool.values())e.map?.dispose(),e.dispose();this.blockMaterialPool.clear()}};h();p();m();Lt();h();p();m();var r8e=Yr(n8e(),1),i8e=Yr(CI(),1);var s8e=i=>{let e=(0,r8e.default)(i),t=(0,i8e.default)(i),n=new e(i).sync,r=xJe(n);for(let s of r)if(s.startsWith("set")&&s!=="setColumn"){let a=n[s].bind(n);n[s]=(...o)=>{let l=o[0];l.x!==void 0&&!n.getColumnAt(l)&&n.setColumn(Math.floor(l.x/16),Math.floor(l.z/16),new t(void 0)),a(...o)}}return n};function xJe(i){let e=new Set,t=i;do for(let n of Object.getOwnPropertyNames(t))typeof i[n]=="function"&&n!=="constructor"&&e.add(n);while(t=Object.getPrototypeOf(t));return[...e]}h();p();m();var a8e={paused:!1,showChunkBorders:!1,enableDebugOverlay:!1,debugWasmPerf:!1,debugModelVariant:void 0,futuristicReveal:!1,wasmMesher:!0,shaderCubeBlocks:!1,shaderCubeDebugMode:0,mesherWorkers:1,addChunksBatchWaitTime:200,_experimentalSmoothChunkLoading:!0,_renderByChunks:!1,autoLowerRenderDistance:!1,disableMesherConversionCache:!1,dedicatedChangeWorker:!1,shadingTheme:"high-contrast",cardinalLight:"default",dayCycle:!0,smoothLighting:!0,enableLighting:!0,starfield:!0,defaultSkybox:!0,renderEntities:!0,extraBlockRenderers:!0,foreground:!0,fov:75,volume:1,showHand:!1,viewBobbing:!1,handRenderer:"vanilla",renderEars:!0,highlightBlockColor:"blue",fetchPlayerSkins:!0,skinTexturesProxy:void 0,vrSupport:!0,vrPageGameRendering:!0,clipWorldBelowY:void 0,isPlayground:!1,instantCameraUpdate:!1,isRaining:!1,rainColor:"rgb(118, 148, 226)",rainOpacity:.5,moduleStates:{}};var nL=()=>({reactive:_l({world:{chunksLoaded:{},heightmaps:{},allChunksLoaded:!1,mesherWork:!1,instabilityFactors:zP(),intersectMedia:null},renderer:"...",preventEscapeMenu:!1}),nonReactive:{fps:0,worstRenderTime:0,avgRenderTime:0,world:{chunksLoadedCount:0,chunksTotalNumber:0,chunksFullInfo:"-"},renderer:{timeline:{live:[],frozen:[],lastSecond:[]}}}});h();p();m();h();p();m();h();p();m();Ia();var yg=i=>[Math.floor(i.x/16),Math.floor(i.z/16)];var wJe=async(i,e,t,n=1)=>{for(let r=0;r<i.length;r+=n)e&&await new Promise(s=>setTimeout(s,e)),await t(i[r],r)},$5=new WeakMap,bg=class bg extends W0{static restoreTransferred(e,t){let n=new bg;if(!t)return n;let r=$5.get(t);if(r)r.activeWorldView=n;else{let s=({data:a})=>{let l=$5.get(t)?.activeWorldView;!l||a?.class!==bg.restorerName||a.type==="event"&&l.emit(a.eventName,...a.args)};t.addEventListener("message",s),r={activeWorldView:n,handler:s},$5.set(t,r)}return n}static clearWorkerBridgeForTest(e){let t=$5.get(e);t&&(e.removeEventListener("message",t.handler),$5.delete(e))}static getWorkerBridgeListenerCountForTest(e){return $5.has(e)?1:0}};Wn(bg,"restorerName","WorldViewWorker");var Y5=bg,M9=class extends W0{constructor(t,n,r=new kt(0,0,0)){super();this.world=t;this.viewDistance=n;this.lastPos=new kt(0,0,0).update(r)}spiralNumber=0;gotPanicLastTime=!1;panicChunksReload=()=>{};loadedChunks={};inLoading=!1;chunkReceiveTimes=[];lastChunkReceiveTime=0;lastChunkReceiveTimeAvg=0;panicTimeout;lastPos;eventListeners={};debugChunksInfo={};waitingSpiralChunksLoad={};addWaitTime=1;keepChunksDistance=0;isPlayground=!1;allowPositionUpdate=!0;prepareForTransfer(t){if(t){let n=this.emit.bind(this);this.emit=(r,...s)=>{n(r,...s),t.postMessage({class:Y5.restorerName,type:"event",eventName:r,args:e4(s)})}}return{__restorer:Y5.restorerName}}setBlockStateId(t,n){let r=this.world.setBlockStateId(t,n);if(r&&typeof r.then=="function")throw new Error("setBlockStateId returned promise (not supported)");this.emit("blockUpdate",{pos:t,stateId:n})}updateViewDistance(t){this.viewDistance=t,this.emit("renderDistance",t)}async init(t,n){console.log("WorldView init"),this.updateViewDistance(this.viewDistance),this.emit("chunkPosUpdate",{pos:t}),n?.time?.timeOfDay!==void 0&&this.emit("time",n.time.timeOfDay),n?.entity&&this.emit("playerEntity",n.entity),this.emitterGotConnected(n);let[r,s]=yg(t),a=C3(this.viewDistance).map(([o,l])=>new kt((r+o)*16,0,(s+l)*16));this.lastPos.update(t),await this._loadChunks(a,t)}chunkProgress(){if(this.panicTimeout&&clearTimeout(this.panicTimeout),this.chunkReceiveTimes.length>=5){let t=this.chunkReceiveTimes.reduce((r,s)=>r+s,0)/this.chunkReceiveTimes.length;this.lastChunkReceiveTimeAvg=t;let n=t*2+1e3;this.panicTimeout&&clearTimeout(this.panicTimeout),this.panicTimeout=setTimeout(()=>{!this.gotPanicLastTime&&this.inLoading&&(console.warn("Chunk loading seems stuck, triggering panic reload"),this.gotPanicLastTime=!0,this.panicChunksReload())},n)}}async _loadChunks(t,n){this.spiralNumber++;let{spiralNumber:r}=this;for(let a of Object.keys(this.waitingSpiralChunksLoad))this.waitingSpiralChunksLoad[a](!1),delete this.waitingSpiralChunksLoad[a];let s=!0;this.inLoading=!0,await wJe(t,this.addWaitTime,async a=>{!s||this.loadedChunks[`${a.x},${a.z}`]||(this.world.getColumnAt(a)||(s=await new Promise(o=>{this.waitingSpiralChunksLoad[`${a.x},${a.z}`]=o})),s&&(await this.loadChunk(a,void 0,`spiral ${r} from ${n.x},${n.z}`),this.chunkProgress()))}),r===this.spiralNumber&&(this.panicTimeout&&clearTimeout(this.panicTimeout),this.inLoading=!1,this.gotPanicLastTime=!1,this.chunkReceiveTimes=[],this.lastChunkReceiveTime=0)}async loadChunk(t,n=!1,r="spiral"){let[s,a]=yg(this.lastPos),o=Math.abs(s-Math.floor(t.x/16)),l=Math.abs(a-Math.floor(t.z/16));if(o<=this.viewDistance&&l<=this.viewDistance){let c=await this.world.getColumnAt(t.y!==void 0?t:new kt(t.x,0,t.z));if(c){let u=c.toJson(),d={minY:c.minY??0,worldHeight:c.worldHeight??256};this.emit("loadChunk",{x:t.x,z:t.z,chunk:u,blockEntities:c.blockEntities,worldConfig:d,isLightUpdate:n}),this.loadedChunks[`${t.x},${t.z}`]=!0,this.debugChunksInfo[`${t.x},${t.z}`]??={loads:[]},this.debugChunksInfo[`${t.x},${t.z}`].loads.push({dataLength:u.length,reason:r,time:Date.now()})}else this.isPlayground&&this.emit("markAsLoaded",{x:t.x,z:t.z})}}async reloadLoadedChunks(){let t=Object.keys(this.loadedChunks);for(let n of t){let[r,s]=n.split(",").map(Number);await this.loadChunk({x:r,z:s},!1,"mesher-reconfigure")}}unloadAllChunks(){for(let t of Object.keys(this.loadedChunks)){let[n,r]=t.split(",").map(Number);this.unloadChunk({x:n,z:r})}}unloadChunk(t){this.emit("unloadChunk",{x:t.x,z:t.z}),delete this.loadedChunks[`${t.x},${t.z}`],delete this.debugChunksInfo[`${t.x},${t.z}`]}emitterGotConnected(t){typeof globalThis.WorkerGlobalScope<"u"&&globalThis instanceof globalThis.WorkerGlobalScope||!t||this.emit("blockEntities",new Proxy({},{get(r,s,a){if(typeof s!="string")return;let[o,l,c]=s.split(",").map(Number);return t.world.getBlock(new kt(o,l,c))?.entity}}))}lastBiomeId=null;updateBiome(t){try{if(!this.world.getBiome)return;let n=this.world.getBiome(t);n!==this.lastBiomeId&&(this.lastBiomeId=n,this.emit("biomeReset"))}catch(n){console.error("error updating biome",n)}}lastPosCheck=null;async updatePosition(t,n=!1){if(!this.allowPositionUpdate)return;let r=t.floored();if(!n&&this.lastPosCheck&&this.lastPosCheck.equals(r))return;this.lastPosCheck=r,this.updateBiome(t);let[s,a]=yg(this.lastPos),[o,l]=yg(t);if(s!==o||a!==l||n){this.emit("chunkPosUpdate",{pos:t});let c=[],u=n?this.viewDistance:this.viewDistance+this.keepChunksDistance;for(let f of Object.keys(this.loadedChunks)){let[v,g]=f.split(",").map(Number),b=new kt(v,0,g),[y,_]=yg(b),x=Math.abs(o-y),w=Math.abs(l-_);(x>u||w>u)&&c.push(b)}for(let f of c)this.unloadChunk(f);let d=C3(this.viewDistance).map(([f,v])=>{let g=new kt((o+f)*16,0,(l+v)*16);if(!this.loadedChunks[`${g.x},${g.z}`])return g}).filter(f=>!!f);this.lastPos.update(t),this._loadChunks(d,t)}else this.emit("chunkPosUpdate",{pos:t}),this.lastPos.update(t)}};var xg=class{constructor(e,t,n){this.documentRenderer=e;this.options=t;this.abortSignal=n;this._scene=new Rr,this._scene.background=new We(3294568),this._camera=new fn(85,e.canvas.width/e.canvas.height,.05,1e3),this.camera.position.set(0,0,0),this.camera.rotation.set(0,0,0)}_scene;_camera;get scene(){return this._scene}get camera(){return this._camera}worldRenderer;WorldRendererClass=Yd;async init(){let e=mg,t=new lc;if(t.currentConfig={version:e,noInventoryGui:!0},await t.updateAssetsData?.({}),this.abortSignal.aborted)return;console.time("load menu background scene");let n=s8e(e),s=Si()(e),o=globalThis.mcData.blocksArray.filter(v=>{if(!v.name.includes("stained_glass"))return!1;let g=s.fromStateId(v.defaultState,0);if(g.shapes?.length!==1)return!1;let b=g.shapes[0];return b[0]===0&&b[1]===0&&b[2]===0&&b[3]===1&&b[4]===1&&b[5]===1}),l=-15,c=100,u=100;for(let v=-c;v<c;v++)for(let g=-u;g<u;g++){let b=o[Math.floor(Math.random()*o.length)];n.setBlockStateId(new kt(v,g,l),b.defaultState)}this._camera.updateProjectionMatrix(),this._camera.position.set(.5,u/2+.5,.5),this._camera.rotation.set(0,0,0);let d=new kt(...this._camera.position.toArray()),f=new M9(n,2,d);this.abortSignal.aborted||(this.worldRenderer=new this.WorldRendererClass(this.documentRenderer.renderer,this.options,{version:e,worldView:f,inWorldRenderingConfig:a8e,playerStateReactive:Y0e().reactive,rendererState:nL().reactive,nonReactiveState:nL().nonReactive,resourcesManager:t}),this.worldRenderer instanceof Yd&&(this._scene=this.worldRenderer.realScene,this._camera=this.worldRenderer.camera),f.init(d),await this.worldRenderer.waitForChunksToRender(),!this.abortSignal.aborted&&(this.setupMouseParallax(),console.timeEnd("load menu background scene")))}update(e,t){t&&Jd(this.camera,this.documentRenderer.canvas)}dispose(){this.worldRenderer?.destroy(),this.worldRenderer=void 0,this._scene.clear()}setupMouseParallax(){let e=this._camera,t=e.position.x,n=e.position.y,r;document.body.addEventListener("pointermove",s=>{if(s.pointerType!=="mouse")return;let a=.2,o=s.clientX/window.innerWidth-.5,l=-(s.clientY/window.innerHeight-.5);r?.stop(),r=new jr(e.position).to({x:t+o*a,y:n+l*a},0),r.start(),e.updateProjectionMatrix()},{signal:this.abortSignal})}};h();p();m();Lt();var wg=class{constructor(e,t,n={},r=!1){this.documentRenderer=e;this.options=t;this.mode=WP(n,r)}active;abortController=new AbortController;mode;lastFrameTime=0;get v2(){return this.active instanceof X5?this.active:void 0}get scene(){return this.active?.scene}get camera(){return this.active?.camera}async start(e={}){this.active=this.createImplementation(e),await this.active.init(),this.active.scene.background instanceof We&&this.documentRenderer.renderer.setClearColor(this.active.scene.background),this.lastFrameTime=performance.now(),this.documentRenderer.render=(t=!1)=>{let n=performance.now(),r=Math.min((n-this.lastFrameTime)/1e3,.05);this.lastFrameTime=n;let s=this.active;s&&(s.update(r,t),this.documentRenderer.renderer.render(s.scene,s.camera))}}createImplementation(e){switch(this.mode){case"v2":return new X5(this.documentRenderer,{useMinecraftTextures:e.useMinecraftTextures,initialScene:e.v2Scene,initialCamera:e.v2Camera,initialBlockGroup:e.v2BlockGroup,initialCameraSpeed:e.v2CameraSpeed,initialBlockSpeed:e.v2BlockSpeed,resourcesManager:e.resourcesManager},this.abortController.signal);case"worldBlocks":return new xg(this.documentRenderer,this.options,this.abortController.signal);default:return new pg(this.documentRenderer)}}dispose(){this.active?.dispose(),this.active=void 0,this.abortController.abort()}};h();p();m();var Kd=u0,SJe={rendererWorldPerformance:"normal",rendererMeshersCountOverride:null,starfieldRendering:!0,defaultSkybox:!0,menuBackgroundMode:Kd.mode,menuBackgroundMinecraftTextures:Kd.minecraftTextures,menuBackgroundV2Scene:Kd.v2Scene,menuBackgroundV2Camera:Kd.v2Camera,menuBackgroundV2BlockGroup:Kd.v2BlockGroup,menuBackgroundV2CameraSpeed:Kd.v2CameraSpeedPercent,menuBackgroundV2BlockSpeed:Kd.v2BlockSpeedPercent,rendererFuturisticReveal:!1,rendererPerfDebugOverlay:!1,disableBlockEntityTextures:!1,rendererMesher:"wasm",rendererShaderCubeDebugMode:"off",showChunkBorders:!1,renderEntities:!0,renderDebug:"basic",frameLimit:!1,backgroundRendering:"20fps",vanillaLook:!1,smoothLighting:!0,newVersionsLighting:!1,vrSupport:!0,vrPageGameRendering:!1,clipWorldBelowY:void 0,highlightBlockColor:"auto",loadPlayerSkins:!0,renderEars:!0,showHand:!0,viewBobbing:!0,dayCycleAndLighting:!0,keepChunksDistance:1,gpuPreference:"default",fov:75};var EJe={menuBackgroundMode:{possibleValues:[["classic","Classic"],["v2","V2"]],requiresRestart:!0},menuBackgroundMinecraftTextures:{text:"Minecraft block textures",tooltip:"Use block atlas on V2 menu cubes (loads assets on menu)"},menuBackgroundV2Scene:{possibleValues:q5.map(i=>[i,_9[i]])},menuBackgroundV2Camera:{possibleValues:G5.map(i=>[i,y9[i]])},menuBackgroundV2BlockGroup:{possibleValues:W5.map(i=>[i,b9[i]]),text:"Block pool",tooltip:"Block set for textured menu cubes (requires Minecraft textures)"},menuBackgroundV2CameraSpeed:{text:"Camera speed",tooltip:"Orbit / fly-through camera path speed. 0 freezes the path; mouse parallax still works.",min:0,max:200,unit:"%"},menuBackgroundV2BlockSpeed:{text:"Block speed",tooltip:"Floating blocks and sky rotation. Independent of camera path speed.",min:0,max:200,unit:"%"},rendererWorldPerformance:{text:"World performance",tooltip:"Background workers for chunk geometry. Recreates mesher workers and reloads chunks.",requiresChunksReload:!0,possibleValues:[["low-energy","Low Energy"],["normal","Normal"],["maximum","Maximum"]]},starfieldRendering:{text:"Starfield"},defaultSkybox:{text:"Default skybox"},rendererFuturisticReveal:{text:"Futuristic world reveal"},rendererPerfDebugOverlay:{text:"Performance debug overlay"},disableBlockEntityTextures:{text:"Disable block entity textures",tooltip:"Skips signs, banners, heads, maps, etc."},rendererMesher:{possibleValues:[["wasm","WASM"],["legacy-js","Legacy JS"]],text:"Mesher pipeline",tooltip:"Browser technology for processing world geometry before render. WASM is the fastest; if you see a dead tab icon, reloads, or other errors, switch to Legacy JS.",requiresChunksReload:!0},rendererShaderCubeDebugMode:{text:"Shader cube debug",tooltip:"Instanced cube path visualization (requires shader cubes enabled).",possibleValues:[["off","Off"],["holes","Hole test (red)"],["texIndex","Tile index colors"],["faces","Face id colors"],["atlasAlpha","Atlas alpha"]]},showChunkBorders:{text:"Chunk borders"},renderEntities:{text:"Render entities"},renderDebug:{possibleValues:["advanced","basic","none"]},frameLimit:{text:"Frame limit",tooltip:"false = VSync / unlimited when focused"},backgroundRendering:{text:"Background FPS limit",possibleValues:[["full","NO"],["5fps","5 FPS"],["20fps","20 FPS"]]},vanillaLook:{text:"Vanilla shading",tooltip:"On: Minecraft-style face shading. Off: higher-contrast client shading."},smoothLighting:{},newVersionsLighting:{text:"Lighting in newer versions"},vrSupport:{text:"VR support",tooltip:"Shows VR entry; does not force VR on."},vrPageGameRendering:{text:"VR page game rendering"},clipWorldBelowY:{text:"Clip world below Y"},highlightBlockColor:{possibleValues:[["auto","Auto"],["blue","Blue"],["classic","Classic"]]},loadPlayerSkins:{},renderEars:{tooltip:"Deadmau5 ears when the skin texture includes them"},showHand:{},viewBobbing:{},dayCycleAndLighting:{text:"Day cycle"},keepChunksDistance:{text:"Keep chunks distance",tooltip:"Extra distance before unloading chunks",max:5,unit:""},fov:{min:30,max:110,unit:"\xB0",text:"FOV"},gpuPreference:{text:"GPU preference",tooltip:"WebGL power preference. Requires reload / backend restart to apply.",requiresRestart:!0,possibleValues:[["default","Auto"],["high-performance","Dedicated"],["low-power","Low power"]]}};Ht.enabled=!1;globalThis.THREE=Gt;var o8e=i=>({updateMap:i.entities.updateMap.bind(i.entities),updateCustomBlock:i.updateCustomBlock.bind(i),getBlockInfo:i.getBlockInfo.bind(i),playEntityAnimation:i.entities.playAnimation.bind(i.entities),damageEntity:i.entities.handleDamageEvent.bind(i.entities),updatePlayerSkin:i.entities.updatePlayerSkin.bind(i.entities),applyTemporaryPlayerSkinOverride:i.entities.applyTemporaryPlayerSkinOverride.bind(i.entities),changeHandSwingingState:i.changeHandSwingingState.bind(i),getHighestBlocks:i.getHighestBlocks.bind(i),reloadWorld:i.reloadWorld.bind(i),updateEntityModel:i.entities.updateEntityModel.bind(i.entities),playEntityModelAnimation:i.entities.playEntityModelAnimation.bind(i.entities),addMedia:i.media.addMedia.bind(i.media),destroyMedia:i.media.destroyMedia.bind(i.media),setControlMode:i.media.setControlMode.bind(i.media),setVideoPlaying:i.media.setVideoPlaying.bind(i.media),setVideoSeeking:i.media.setVideoSeeking.bind(i.media),setVideoVolume:i.media.setVideoVolume.bind(i.media),setVideoSpeed:i.media.setVideoSpeed.bind(i.media),handleUserClick:i.media.handleUserClick.bind(i.media),addSectionAnimation(e,t){i.sectionsOffsetsAnimations[e]=t},removeSectionAnimation(e){delete i.sectionsOffsetsAnimations[e]},shakeFromDamage:i.cameraShake.shakeFromDamage.bind(i.cameraShake),onPageInteraction:i.media.onPageInteraction.bind(i.media),downloadMesherLog:i.downloadMesherLog.bind(i),explodeFirework:i.fireworksLegacy.explode.bind(i.fireworksLegacy),explodeFireworkFacingCamera:i.fireworksLegacy.explodeFacingCamera.bind(i.fireworksLegacy),addWaypoint:i.waypoints.addWaypoint.bind(i.waypoints),removeWaypoint:i.waypoints.removeWaypoint.bind(i.waypoints),startCinimaticScript:i.cinimaticScript.startScript.bind(i.cinimaticScript),stopCinimaticScript:i.cinimaticScript.stopScript.bind(i.cinimaticScript),launchFirework:i.fireworks.launchFirework.bind(i.fireworks),setSkyboxImage:i.skyboxRenderer.setSkyboxImage.bind(i.skyboxRenderer),setRain:i.setRain.bind(i),spawnBlockBreakParticles(e,t,n,r,s,a){i.getModule("blockBreakParticles")?.spawnBlockBreakParticles(e,t,n,r,s,a)},spawnBlockCrackParticle(e,t,n,r,s,a,o){i.getModule("blockBreakParticles")?.spawnCrackParticle(e,t,n,r,s,a,o)},async loadGeometryExport(e){let{applyWorldGeometryExport:t}=await Promise.resolve().then(()=>(AP(),j_e));return t(i,e)},feedChunkPacket(e){let{kind:t,...n}=e,r={type:t,...n};for(let s of i.workers)s.postMessage(r)},getChunksDebugState(){let e={};for(let t of Object.keys(i.sectionObjects)){let[n,,r]=t.split(",").map(Number);e[`${n},${r}`]=!0}return{loadedSectionsChunks:e,loadedChunks:{...i.loadedChunks},finishedChunks:{...i.finishedChunks}}}}),MJe=[],A9=(i,...e)=>{for(let t of Object.values(globalThis.loadedMods??{}))try{t.threeJsBackendModule?.[i]?.(...e)}catch(n){let r=`[mod three.js] Error calling ${i} on ${t.name}: ${n}`;throw new Error(r)}},l8e=()=>{let i,e=null,t=null,n=null,r=null,s=(u,d)=>{u.hello&&console.log("Thanks for using minecraft-renderer project: one of the most performant Minecraft world renderers for the web!"),Ln?i=u2(u,MJe,globalThis):i=u,e=new Q_(i,d?.canvas),globalThis.renderer=e.renderer,globalThis.documentRenderer=e,globalThis.threeJsBackend=c,A9("default",c)},a=async u=>{if(!e)throw new Error("Document renderer not initialized");n&&(n.destroy(),n=null,r=null,globalThis.world=void 0,globalThis.frameTimingCollector=void 0),t&&(t.dispose(),t=null);let d={...i.config.menuBackground,...u};t=new wg(e,{...i},d,!!process.env.SINGLE_FILE_BUILD_MODE),A9("menuBackgroundCreated",t),await t.start(d),A9("menuBackgroundReady",t)},o=async u=>{if(!e)throw new Error("Document renderer not initialized");t&&(t.dispose(),t=null),n&&(n.destroy(),n=null,r=null,globalThis.world=void 0,globalThis.frameTimingCollector=void 0);let f=Ln?u2(u,[lc,Y5],globalThis):u;e.nonReactiveState=f.nonReactiveState,globalThis.resourcesManager=f.resourcesManager,n=new Yd(e.renderer,i,f),await n.worldReadyPromise,r=f.inWorldRenderingConfig.enableDebugOverlay?new n4(f.nonReactiveState):null,globalThis.frameTimingCollector=r;let v=e.render;e.render=function(g){v.call(this,g),r?.markFrameStart(),f.inWorldRenderingConfig.paused||n?.render(g),r?.markFrameEnd(),r?.markFrameDisplay()},e.inWorldRenderingConfig=f.inWorldRenderingConfig,globalThis.world=n,A9("worldReady",n)},l=()=>{t&&(t.dispose(),t=null),e&&e.dispose(),n&&(n.destroy(),n=null)},c={id:"threejs",displayName:`three.js ${Ma}`,startMenuBackground:a,startWorld:o,disconnect:l,setRendering(u){e.setPaused(!u),n&&(n.renderingActive=u)},getMenuBackground:()=>t??void 0,getDebugOverlay:()=>({get entitiesString(){return n?.entities.getDebugString()},get left(){return{"Geo Memory":n?.chunkMeshManager.getEstimatedMemoryUsage().total??"-"}}}),updateCamera(u,d,f){r?.markCameraUpdate(!u),n?.setFirstPersonCamera(u,d,f)},get soundSystem(){return n?.soundSystem},get backendMethods(){if(n)return o8e(n)}};return{main:{init:s,backend:c},workerProxy(){return SN({init(u,d){s(u,{canvas:d})},updateSizeExternal(u,d,f){e?.updateSizeExternal(u,d,f)},startMenuBackground:a,startWorld:o,disconnect:l,setRendering:c.setRendering,updateCamera(u,d,f){let v=u?new kt(u.x,u.y,u.z):null;r?.markCameraUpdate(!v),c.updateCamera(v,d,f)},async callBackendMethod(u,...d){if(!n)throw new Error("World renderer not initialized");let v=o8e(n)[u];if(!v)throw new Error(`Backend method ${String(u)} is unavailable`);return v(...d)}})}}};globalThis.structuredClone??=i=>JSON.parse(JSON.stringify(i));var c8e=i=>{TB(i);let e=globalThis;e.mcData=i,e.loadedData=i,self.postMessage({type:"mcDataApplied"})};self.addEventListener("message",i=>{let e=i.data;if(e.type==="mcData"){c8e(e.mcData),console.log("data loaded");return}Array.isArray(e)&&e.forEach(t=>{t.type==="mcData"&&c8e(t.mcData)})});var AJe=l8e();AJe.workerProxy();})();
|
|
29584
29580
|
/*! Bundled license information:
|
|
29585
29581
|
|
|
29586
29582
|
@jspm/core/nodelibs/browser/chunk-DtuTasat.js:
|