minecraft-renderer 0.1.68 → 0.1.70
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/minecraft-renderer.js +2 -2
- package/dist/minecraft-renderer.js.meta.json +1 -1
- package/dist/threeWorker.js +1 -1
- package/package.json +1 -1
- package/src/graphicsBackend/rendererDefaultOptions.ts +1 -1
- package/src/three/graphicsBackendOffThread.ts +2 -1
- package/src/three/graphicsBackendSingleThread.ts +1 -1
- package/src/three/menuBackground/v2.ts +12 -6
|
@@ -283,7 +283,7 @@ void main() {
|
|
|
283
283
|
applyFog();
|
|
284
284
|
writeLogDepth();
|
|
285
285
|
}
|
|
286
|
-
`;X1=6,c0={LX_BITS:4,LY_BITS:4,LZ_BITS:4,FACE_BITS:3,TINT_BITS:8,AO_BITS_PER_CORNER:2,NUM_CORNERS:4,LX_SHIFT:0,LY_SHIFT:4,LZ_SHIFT:8,FACE_SHIFT:12,TINT_SHIFT:15,AO_SHIFT:23,TRANSPARENT_SHIFT:31},ra={TEX_INDEX_BITS:12,DIAGONAL_FLAG_SHIFT:12,SECTION_Y_SHIFT:13,SECTION_Y_BITS:5,EMPTY_SHIFT:18,SECTION_X_HI_SHIFT:19,SECTION_Z_HI_SHIFT:25,SECTION_HI_BITS:6,SPARE_BITS:1},Cv={SECTION_BITS:22,SECTION_MASK:(1<<22)-1,LO_BITS:16,HI_BITS:6,SECTION_BIAS:2097152}});var $1,ia=Xe(()=>{"use strict";E();x();k();R();$1=class{constructor(e){d(this,"atlasWidth");d(this,"atlasHeight");d(this,"tileSize");d(this,"tilesPerRow");d(this,"maxTiles");d(this,"valid");this.atlasWidth=e.width,this.atlasHeight=e.height,this.tileSize=e.tileSize,this.tilesPerRow=Math.floor(this.atlasWidth/this.tileSize),this.maxTiles=this.tilesPerRow*Math.floor(this.atlasHeight/this.tileSize),this.valid=this.atlasWidth===1024&&this.atlasHeight===1024&&this.tileSize===16&&this.maxTiles<=4096}isValid(){return this.valid}getTilesPerRow(){return this.tilesPerRow}tileIndexFromPixelCoords(e,t){if(!this.valid)return-1;let r=Math.floor(e/this.tileSize),i=Math.floor(t/this.tileSize);if(r<0||r>=this.tilesPerRow||i<0)return-1;let s=i*this.tilesPerRow+r;return s>=this.maxTiles?-1:s}tileIndexFromTextureEntry(e){return!this.valid||e.su!==this.tileSize||e.sv!==this.tileSize?-1:this.tileIndexFromPixelCoords(e.u,e.v)}tileIndexFromTextureName(e,t){if(!this.valid)return-1;let r=t.textures[e];if(!r&&e.includes(":")&&(r=t.textures[e.split(":")[1]]),!r&&e.includes("/")&&(r=t.textures[e.split("/")[1]]),r||(r=t.textures[`block/${e}`]),!r){let i=e.replace(/^block\//,"");r=t.textures[i]}return r?this.tileIndexFromTextureEntry(r):-1}}});import*as d0 from"three";var er,na=Xe(()=>{"use strict";E();x();k();R();er=class n{constructor(){d(this,"entries",[{r:1,g:1,b:1}]);d(this,"colorToIndex",new Map);d(this,"categoryBiomeToIndex",new Map);d(this,"texture",null);d(this,"ready",!1)}packColor(e,t,r){let i=Math.round(e*255),s=Math.round(t*255),o=Math.round(r*255);return i<<16|s<<8|o}add(e,t,r,i,s){let o=this.packColor(e,t,r),a=`${i}:${s}`,v=this.categoryBiomeToIndex.get(a);if(v!==void 0)return v;let l=this.colorToIndex.get(o);if(l!==void 0)return this.categoryBiomeToIndex.set(a,l),l;let c=this.entries.length;return this.entries.push({r:e,g:t,b:r}),this.colorToIndex.set(o,c),this.categoryBiomeToIndex.set(a,c),c}getTintIndex(e,t,r,i){return e===void 0?0:e===0?t==="redstone_wire"?this.categoryBiomeToIndex.get(`redstone:${r.power}`)??this.categoryBiomeToIndex.get("redstone:0")??0:t==="birch_leaves"||t==="spruce_leaves"||t==="lily_pad"?this.categoryBiomeToIndex.get(`constant:${t}`)??this.categoryBiomeToIndex.get("constant:default")??0:t.includes("leaves")||t==="vine"?this.categoryBiomeToIndex.get(`foliage:${i}`)??this.categoryBiomeToIndex.get("foliage:plains")??0:this.categoryBiomeToIndex.get(`grass:${i}`)??this.categoryBiomeToIndex.get("grass:plains")??0:0}getEntry(e){return this.entries[e]??this.entries[0]}get size(){return this.entries.length}buildTextureData(){let e=new Float32Array(1024);for(let t=0;t<this.entries.length&&t<256;t++){let r=this.entries[t];e[t*4]=r.r,e[t*4+1]=r.g,e[t*4+2]=r.b,e[t*4+3]=1}return e}createTexture(){this.texture&&(this.texture.dispose(),this.texture=null,this.ready=!1);let e=this.buildTextureData(),t=new d0.DataTexture(e,256,1,d0.RGBAFormat,d0.FloatType);return t.minFilter=d0.NearestFilter,t.magFilter=d0.NearestFilter,t.wrapS=d0.ClampToEdgeWrapping,t.wrapT=d0.ClampToEdgeWrapping,t.needsUpdate=!0,this.texture=t,this.ready=!0,t}getTexture(){return this.texture}isReady(){return this.ready}static fromTintsData(e){let t=new n;function r(i){let s=(i>>16&255)/255,o=(i>>8&255)/255,a=(i&255)/255;return[s,o,a]}if(e.grass){let i=r(e.grass.default);for(let{keys:s,color:o}of e.grass.data??[]){let a=r(o);for(let v of s)t.add(a[0],a[1],a[2],"grass",v)}t.add(i[0],i[1],i[2],"grass","plains")}if(e.foliage){let i=r(e.foliage.default);for(let{keys:s,color:o}of e.foliage.data??[]){let a=r(o);for(let v of s)t.add(a[0],a[1],a[2],"foliage",v)}t.add(i[0],i[1],i[2],"foliage","plains")}if(e.redstone){let i=r(e.redstone.default);for(let{keys:s,color:o}of e.redstone.data??[]){let a=r(o);for(let v of s)t.add(a[0],a[1],a[2],"redstone",v)}t.add(i[0],i[1],i[2],"redstone","0")}if(e.constant){let i=r(e.constant.default);for(let{keys:s,color:o}of e.constant.data??[]){let a=r(o);for(let v of s)t.add(a[0],a[1],a[2],"constant",v)}t.add(i[0],i[1],i[2],"constant","default")}return t}}});import sa from"mc-assets/dist/blocksAtlases.json";function Bv(){let n=globalThis.loadedData?.tints;return n||(oa||(oa=!0),null)}function rr(){let n=Bv();if(!n)return null;if(tr||(tr=er.fromTintsData(n),tr.createTexture()),!Vi){let e=sa.latest??sa;Vi=new $1({width:e.width,height:e.height,tileSize:e.tileSize??16,suSv:e.suSv??16,textures:e.textures??{}})}return{tintPalette:tr,textureIndexMapping:Vi}}function aa(){return 1<<ra.EMPTY_SHIFT>>>0}var Jt,tr,Vi,oa,Zt=Xe(()=>{"use strict";E();x();k();R();gt();ia();na();Jt=4,tr=null,Vi=null,oa=!1});import*as Ce from"three";function Pv(n,e){let t=new Ce.InstancedBufferGeometry,r=new Float32Array(X1*3);t.setAttribute("position",new Ce.BufferAttribute(r,3));let i=new Uint32Array(e),s=new Uint32Array(e),o=new Uint32Array(e),a=new Uint32Array(e),v=Jt;for(let l=0;l<e;l++)i[l]=n[l*v],s[l]=n[l*v+1],o[l]=n[l*v+2],a[l]=n[l*v+3];return t.setAttribute("a_w0",new Ce.InstancedBufferAttribute(i,1)),t.setAttribute("a_w1",new Ce.InstancedBufferAttribute(s,1)),t.setAttribute("a_w2",new Ce.InstancedBufferAttribute(o,1)),t.setAttribute("a_w3",new Ce.InstancedBufferAttribute(a,1)),t.instanceCount=e,t.boundingBox=new Ce.Box3(new Ce.Vector3(-8,-8,-8),new Ce.Vector3(8,8,8)),t.boundingSphere=new Ce.Sphere(new Ce.Vector3(0,0,0),Math.sqrt(3*8**2)),t}function Iv(n){n.raycast=(e,t)=>{let{geometry:r}=n;if(!r.boundingBox||(va.copy(r.boundingBox).applyMatrix4(n.matrixWorld),!e.ray.intersectBox(va,ji)))return;let i=e.ray.origin.distanceTo(ji);t.push({distance:i,point:ji.clone(),object:n})}}function ir(n,e){let t=Pv(n.words,n.count),r=new Ce.Mesh(t,e);return r.name="shaderMesh",r.matrixAutoUpdate=!1,r.frustumCulled=!1,Iv(r),r}function Yi(n){n.geometry.dispose()}var va,ji,Qi=Xe(()=>{"use strict";E();x();k();R();gt();Zt();va=new Ce.Box3,ji=new Ce.Vector3});var ha={};q5(ha,{applyWorldGeometryExport:()=>Dv,createMeshesFromExport:()=>ua,downloadWorldGeometry:()=>Ki,exportWorldGeometry:()=>ca,loadTextureFromDataUrl:()=>fa,loadWorldGeometryFromUrl:()=>Hv});import*as Be from"three";function ca(n,e,t,r=!1){let i=[];for(let[o,a]of Object.entries(n.sectionObjects)){let v=a.children.find(A=>A.name==="mesh");if(!v?.geometry)continue;let{geometry:l}=v,c=l.getAttribute("position"),u=l.getAttribute("normal"),h=l.getAttribute("color"),p=l.getAttribute("uv"),g=l.index;if(!c||!g)continue;let y=n.sceneOrigin.getWorldPosition(v);i.push({key:o,position:{x:y?.x??n.sceneOrigin.toWorldX(v.position.x),y:y?.y??n.sceneOrigin.toWorldY(v.position.y),z:y?.z??n.sceneOrigin.toWorldZ(v.position.z)},geometry:{positions:[...c.array],normals:u?[...u.array]:[],colors:h?[...h.array]:[],uvs:p?[...p.array]:[],indices:[...g.array]}})}let s={version:n.version??"unknown",exportedAt:new Date().toISOString(),camera:{position:e,rotation:t},sections:i};if(r&&n.material.map){let o=document.createElement("canvas"),a=n.material.map,{image:v}=a;v&&(o.width=v.width,o.height=v.height,o.getContext("2d").drawImage(v,0,0),s.textureAtlasDataUrl=o.toDataURL("image/png"))}return s}function Ki(n,e,t,r="world-geometry.json",i=!1){let s=ca(n,e,t,i),o=JSON.stringify(s),a=new Blob([o],{type:"application/json"}),v=URL.createObjectURL(a),l=document.createElement("a");l.href=v,l.download=r,l.click(),URL.revokeObjectURL(v)}async function Hv(n){let e=await fetch(n);if(!e.ok)throw new Error(`Failed to fetch world geometry: ${e.statusText}`);return e.json()}function da(n){let e=n.map??n.map;if(!e)return null;let t=q1();t.uniforms.u_atlas.value=e;let r=rr();if(!r)return null;let{tintPalette:i}=r;return i.isReady()||i.createTexture(),t.uniforms.u_tintPalette.value=i.getTexture(),t}function ua(n,e,t){let r=[],i=t??da(e);for(let s of n.sections){let o=new Be.Group;if(o.name="chunk",s.geometry.positions.length>0&&s.geometry.indices.length>0){let l=new Be.BufferGeometry;l.setAttribute("position",new Be.Float32BufferAttribute(s.geometry.positions,3)),s.geometry.normals.length&&l.setAttribute("normal",new Be.Float32BufferAttribute(s.geometry.normals,3)),s.geometry.colors.length&&l.setAttribute("color",new Be.Float32BufferAttribute(s.geometry.colors,3)),s.geometry.uvs.length&&l.setAttribute("uv",new Be.Float32BufferAttribute(s.geometry.uvs,2));let u=Math.max(...s.geometry.indices)>65535?Uint32Array:Uint16Array;l.setIndex(new Be.BufferAttribute(new u(s.geometry.indices),1));let h=new Be.Mesh(l,e);h.position.set(s.position.x,s.position.y,s.position.z),h.name="mesh",o.add(h)}let v=s.shaderCubes;if(v&&v.count>0&&i){let l=ir(v,i);l.position.set(s.position.x,s.position.y,s.position.z),o.add(l)}o.children.length>0&&r.push(o)}return r}async function fa(n){return new Promise((e,t)=>{let r=new Image;r.onload=()=>{let i=new Be.Texture(r);i.magFilter=Be.NearestFilter,i.minFilter=Be.NearestFilter,i.needsUpdate=!0,i.flipY=!1,e(i)},r.onerror=t,r.src=n})}async function Dv(n,e){let{scene:t,renderUpdateEmitter:r,material:i}=n,s=t.getObjectByName(la);s&&(t.remove(s),Ov(s));let o=!!e.textureAtlasDataUrl,a;if(o&&e.textureAtlasDataUrl){let u=await fa(e.textureAtlasDataUrl);a=new Be.MeshLambertMaterial({map:u,vertexColors:!0,transparent:!0,alphaTest:.1}),a.name="geometry-export-material"}else a=i;let v=e.sections.some(u=>(u.shaderCubes?.count??0)>0)?da(a):null,l=ua(e,a,v),c=new Be.Group;c.name=la,o&&(c.userData.geometryExportMaterial=a);for(let u of l)c.add(u);return t.add(c),r.emit("update"),l.length}var la,Ov,Ji=Xe(()=>{"use strict";E();x();k();R();Zt();gt();Qi();la="geometry-export-root";Ov=n=>{n.traverse(t=>{t.isMesh&&t.geometry?.dispose()});let e=n.userData?.geometryExportMaterial;e&&(e.map?.dispose?.(),e.dispose?.())}});E();x();k();R();E();x();k();R();E();x();k();R();E();x();k();R();import{proxy as z2}from"valtio";E();x();k();R();E();x();k();R();var _r=()=>({longRenderTime:!1,constantLongRenderTime:!1,tooManyEntities:!1,tooManyTextures:!1,unknownReason:!1});E();x();k();R();var r1=30;var wr=45,Ar=100;E();x();k();R();var l5=class{constructor(e){this.factors=e;d(this,"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,r=Math.max(0,e.totalMs-e.entitiesMs),i=e.totalMs>=30,s=this.renderTimeHistory.length,o=this.renderTimeHistory.filter(h=>h>=30).length,a=s>=8&&o/s>=.65,v=e.loadedTextureCount>=100,l=t&&e.entitiesMs>=8&&r<=20,u=t&&!(i||a||l||v);this.factors.longRenderTime=i,this.factors.constantLongRenderTime=a,this.factors.tooManyEntities=l,this.factors.tooManyTextures=v,this.factors.unknownReason=u}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}};E();x();k();R();var v6=[{key:"longRenderTime",code:"LR"},{key:"constantLongRenderTime",code:"CLR"},{key:"tooManyEntities",code:"ENT"},{key:"tooManyTextures",code:"TEX"},{key:"unknownReason",code:"UNK"}];function Er(n){let e=v6.filter(({key:t})=>n[t]).map(({code:t})=>t);return e.length>0?e.join("+"):""}var c5={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,moduleStates:{}},L2={fpsLimit:void 0,sceneBackground:"lightblue",timeoutRendering:!1},El=(n={})=>z2({...c5,...n}),J0=()=>({reactive:z2({world:{chunksLoaded:{},heightmaps:{},allChunksLoaded:!1,mesherWork:!1,instabilityFactors:_r(),intersectMedia:null},renderer:"...",preventEscapeMenu:!1}),nonReactive:{fps:0,worstRenderTime:0,avgRenderTime:0,world:{chunksLoadedCount:0,chunksTotalNumber:0,chunksFullInfo:"-"},renderer:{timeline:{live:[],frozen:[],lastSecond:[]}}}});E();x();k();R();import{proxy as l6}from"valtio";var xr=()=>l6({playerSkin:void 0,inWater:!1,waterBreathing:!1,backgroundColor:[0,0,0],ambientLight:0,directionalLight:0,eyeHeight:0,gameMode:void 0,lookingAtBlock:void 0,diggingBlock:void 0,movementState:"NOT_MOVING",onGround:!0,sneaking:!1,flying:!1,sprinting:!1,walkDist:0,prevWalkDist:0,bob:0,prevBob:0,itemUsageTicks:0,username:"",onlineMode:!1,cardinalLight:"default",lightingDisabled:!1,shouldHideHand:!1,heldItemMain:void 0,heldItemOff:void 0,perspective:"first_person",onFire:!1,fovMultiplier:1,cameraSpectatingEntity:void 0,team:void 0}),U2=n=>({isSpectator(){return n.gameMode==="spectator"},isSpectatingEntity(){return n.cameraSpectatingEntity!==void 0&&n.gameMode==="spectator"},isThirdPerson(){return this.isSpectatingEntity()?!1:n.perspective==="third_person_back"||n.perspective==="third_person_front"}}),G2=()=>({reactive:xr()});E();x();k();R();import{Vec3 as A6}from"vec3";import{proxy as is}from"valtio";E();x();k();R();E();x();k();R();E();x();k();R();E();x();k();R();var i1={},N2=!1;function c6(){if(N2)return i1;N2=!0;var n=typeof Reflect=="object"?Reflect:null,e=n&&typeof n.apply=="function"?n.apply:function(M,I,B){return Function.prototype.apply.call(M,I,B)},t;n&&typeof n.ownKeys=="function"?t=n.ownKeys:Object.getOwnPropertySymbols?t=function(M){return Object.getOwnPropertyNames(M).concat(Object.getOwnPropertySymbols(M))}:t=function(M){return Object.getOwnPropertyNames(M)};function r(C){}var i=Number.isNaN||function(M){return M!==M};function s(){s.init.call(this)}i1=s,i1.once=b,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var o=10;function a(C){if(typeof C!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof C)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(C){if(typeof C!="number"||C<0||i(C))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+C+".");o=C}}),s.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(M){if(typeof M!="number"||M<0||i(M))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+M+".");return this._maxListeners=M,this};function v(C){return C._maxListeners===void 0?s.defaultMaxListeners:C._maxListeners}s.prototype.getMaxListeners=function(){return v(this)},s.prototype.emit=function(M){for(var I=[],B=1;B<arguments.length;B++)I.push(arguments[B]);var H=M==="error",G=this._events;if(G!==void 0)H=H&&G.error===void 0;else if(!H)return!1;if(H){var O;if(I.length>0&&(O=I[0]),O instanceof Error)throw O;var j=new Error("Unhandled error."+(O?" ("+O.message+")":""));throw j.context=O,j}var J=G[M];if(J===void 0)return!1;if(typeof J=="function")e(J,this,I);else for(var Z=J.length,$=g(J,Z),B=0;B<Z;++B)e($[B],this,I);return!0};function l(C,M,I,B){var H,G,O;if(a(I),G=C._events,G===void 0?(G=C._events=Object.create(null),C._eventsCount=0):(G.newListener!==void 0&&(C.emit("newListener",M,I.listener?I.listener:I),G=C._events),O=G[M]),O===void 0)O=G[M]=I,++C._eventsCount;else if(typeof O=="function"?O=G[M]=B?[I,O]:[O,I]:B?O.unshift(I):O.push(I),H=v(C),H>0&&O.length>H&&!O.warned){O.warned=!0;var j=new Error("Possible EventEmitter memory leak detected. "+O.length+" "+String(M)+" listeners added. Use emitter.setMaxListeners() to increase limit");j.name="MaxListenersExceededWarning",j.emitter=C,j.type=M,j.count=O.length}return C}s.prototype.addListener=function(M,I){return l(this,M,I,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(M,I){return l(this,M,I,!0)};function c(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function u(C,M,I){var B={fired:!1,wrapFn:void 0,target:C,type:M,listener:I},H=c.bind(B);return H.listener=I,B.wrapFn=H,H}s.prototype.once=function(M,I){return a(I),this.on(M,u(this,M,I)),this},s.prototype.prependOnceListener=function(M,I){return a(I),this.prependListener(M,u(this,M,I)),this},s.prototype.removeListener=function(M,I){var B,H,G,O,j;if(a(I),H=this._events,H===void 0)return this;if(B=H[M],B===void 0)return this;if(B===I||B.listener===I)--this._eventsCount===0?this._events=Object.create(null):(delete H[M],H.removeListener&&this.emit("removeListener",M,B.listener||I));else if(typeof B!="function"){for(G=-1,O=B.length-1;O>=0;O--)if(B[O]===I||B[O].listener===I){j=B[O].listener,G=O;break}if(G<0)return this;G===0?B.shift():y(B,G),B.length===1&&(H[M]=B[0]),H.removeListener!==void 0&&this.emit("removeListener",M,j||I)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(M){var I,B,H;if(B=this._events,B===void 0)return this;if(B.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):B[M]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete B[M]),this;if(arguments.length===0){var G=Object.keys(B),O;for(H=0;H<G.length;++H)O=G[H],O!=="removeListener"&&this.removeAllListeners(O);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(I=B[M],typeof I=="function")this.removeListener(M,I);else if(I!==void 0)for(H=I.length-1;H>=0;H--)this.removeListener(M,I[H]);return this};function h(C,M,I){var B=C._events;if(B===void 0)return[];var H=B[M];return H===void 0?[]:typeof H=="function"?I?[H.listener||H]:[H]:I?A(H):g(H,H.length)}s.prototype.listeners=function(M){return h(this,M,!0)},s.prototype.rawListeners=function(M){return h(this,M,!1)},s.listenerCount=function(C,M){return typeof C.listenerCount=="function"?C.listenerCount(M):p.call(C,M)},s.prototype.listenerCount=p;function p(C){var M=this._events;if(M!==void 0){var I=M[C];if(typeof I=="function")return 1;if(I!==void 0)return I.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function g(C,M){for(var I=new Array(M),B=0;B<M;++B)I[B]=C[B];return I}function y(C,M){for(;M+1<C.length;M++)C[M]=C[M+1];C.pop()}function A(C){for(var M=new Array(C.length),I=0;I<M.length;++I)M[I]=C[I].listener||C[I];return M}function b(C,M){return new Promise(function(I,B){function H(O){C.removeListener(M,G),B(O)}function G(){typeof C.removeListener=="function"&&C.removeListener("error",H),I([].slice.call(arguments))}S(C,M,G,{once:!0}),M!=="error"&&w(C,H,{once:!0})})}function w(C,M,I){typeof C.on=="function"&&S(C,"error",M,I)}function S(C,M,I,B){if(typeof C.on=="function")B.once?C.once(M,I):C.on(M,I);else if(typeof C.addEventListener=="function")C.addEventListener(M,function H(G){B.once&&C.removeEventListener(M,H),I(G)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof C)}return i1}var n1=c6();n1.once;n1.once=function(n,e){return new Promise((t,r)=>{function i(...o){s!==void 0&&n.removeListener("error",s),t(o)}let s;e!=="error"&&(s=o=>{n.removeListener(name,i),r(o)},n.once("error",s)),n.once(e,i)})};n1.on=function(n,e){let t=[],r=[],i=null,s=!1,o={async next(){let l=t.shift();if(l)return createIterResult(l,!1);if(i){let c=Promise.reject(i);return i=null,c}return s?createIterResult(void 0,!0):new Promise((c,u)=>r.push({resolve:c,reject:u}))},async return(){n.removeListener(e,a),n.removeListener("error",v),s=!0;for(let l of r)l.resolve(createIterResult(void 0,!0));return createIterResult(void 0,!0)},throw(l){i=l,n.removeListener(e,a),n.removeListener("error",v)},[Symbol.asyncIterator](){return this}};return n.on(e,a),n.on("error",v),o;function a(...l){let c=r.shift();c?c.resolve(createIterResult(l,!1)):t.push(l)}function v(l){s=!0;let c=r.shift();c?c.reject(l):i=l,o.return()}};var{EventEmitter:Z0,defaultMaxListeners:Ll,init:Ul,listenerCount:Gl,on:Nl,once:Wl}=n1;import{Vec3 as q0}from"vec3";E();x();k();R();function d5(n){let e=n*2+1;if(e<=0)return[];let t=[],r=0,i=0,s=0,o=-1;for(let a=0;a<e*e;a++){if(Math.abs(r)<=e/2&&Math.abs(i)<=e/2&&t.push([r,i]),r===i||r<0&&r===-i||r>0&&r===1-i){let v=s;s=-o,o=v}r+=s,i+=o}return t}E();x();k();R();function Rr(n,e=0){if(e>16)return;if(n==null)return n;let t=typeof n;if(t==="function"||t==="symbol")return;if(t==="bigint")return n.toString();if(t!=="object"||n instanceof ArrayBuffer)return n;if(ArrayBuffer.isView(n)){let s=n;return s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength)}if(n instanceof Date)return n.toISOString();if(Array.isArray(n))return n.map(s=>Rr(s,e+1)).filter(s=>s!==void 0);let r=n;if(typeof r.x=="number"&&typeof r.y=="number"&&typeof r.z=="number"&&!("w"in r))return{x:r.x,y:r.y,z:r.z};let i={};for(let s of Object.keys(r)){if(s==="_client"||s==="_events"||s==="_eventsCount")continue;let o=Rr(r[s],e+1);o!==void 0&&(i[s]=o)}return i}function s1(n){return n.map(e=>Rr(e))}var Mt=n=>[Math.floor(n.x/16),Math.floor(n.z/16)],d6=n=>[Math.floor(n.x/16),Math.floor(n.y/16),Math.floor(n.z/16)],W2=async(n,e,t,r=1)=>{for(let i=0;i<n.length;i+=r)e&&await new Promise(s=>setTimeout(s,e)),await t(n[i],i)},Tt=new WeakMap,u5=class u5 extends Z0{static restoreTransferred(e,t){let r=new u5;if(!t)return r;let i=Tt.get(t);if(i)i.activeWorldView=r;else{let s=({data:o})=>{let v=Tt.get(t)?.activeWorldView;!v||o?.class!==u5.restorerName||o.type==="event"&&v.emit(o.eventName,...o.args)};t.addEventListener("message",s),i={activeWorldView:r,handler:s},Tt.set(t,i)}return r}static clearWorkerBridgeForTest(e){let t=Tt.get(e);t&&(e.removeEventListener("message",t.handler),Tt.delete(e))}static getWorkerBridgeListenerCountForTest(e){return Tt.has(e)?1:0}};d(u5,"restorerName","WorldViewWorker");var X0=u5,$0=class extends Z0{constructor(t,r,i=new q0(0,0,0)){super();this.world=t;this.viewDistance=r;d(this,"spiralNumber",0);d(this,"gotPanicLastTime",!1);d(this,"panicChunksReload",()=>{});d(this,"loadedChunks",{});d(this,"inLoading",!1);d(this,"chunkReceiveTimes",[]);d(this,"lastChunkReceiveTime",0);d(this,"lastChunkReceiveTimeAvg",0);d(this,"panicTimeout");d(this,"lastPos");d(this,"eventListeners",{});d(this,"debugChunksInfo",{});d(this,"waitingSpiralChunksLoad",{});d(this,"addWaitTime",1);d(this,"keepChunksDistance",0);d(this,"isPlayground",!1);d(this,"allowPositionUpdate",!0);d(this,"lastBiomeId",null);d(this,"lastPosCheck",null);this.lastPos=new q0(0,0,0).update(i)}prepareForTransfer(t){if(t){let r=this.emit.bind(this);this.emit=(i,...s)=>{r(i,...s),t.postMessage({class:X0.restorerName,type:"event",eventName:i,args:s1(s)})}}return{__restorer:X0.restorerName}}setBlockStateId(t,r){let i=this.world.setBlockStateId(t,r);if(i&&typeof i.then=="function")throw new Error("setBlockStateId returned promise (not supported)");this.emit("blockUpdate",{pos:t,stateId:r})}updateViewDistance(t){this.viewDistance=t,this.emit("renderDistance",t)}async init(t,r){this.updateViewDistance(this.viewDistance),this.emit("chunkPosUpdate",{pos:t}),r?.time?.timeOfDay!==void 0&&this.emit("time",r.time.timeOfDay),r?.entity&&this.emit("playerEntity",r.entity),this.emitterGotConnected(r);let[i,s]=Mt(t),o=d5(this.viewDistance).map(([a,v])=>new q0((i+a)*16,0,(s+v)*16));this.lastPos.update(t),await this._loadChunks(o,t)}chunkProgress(){if(this.panicTimeout&&clearTimeout(this.panicTimeout),this.chunkReceiveTimes.length>=5){let t=this.chunkReceiveTimes.reduce((i,s)=>i+s,0)/this.chunkReceiveTimes.length;this.lastChunkReceiveTimeAvg=t;let r=t*2+1e3;this.panicTimeout&&clearTimeout(this.panicTimeout),this.panicTimeout=setTimeout(()=>{!this.gotPanicLastTime&&this.inLoading&&(this.gotPanicLastTime=!0,this.panicChunksReload())},r)}}async _loadChunks(t,r){this.spiralNumber++;let{spiralNumber:i}=this;for(let o of Object.keys(this.waitingSpiralChunksLoad))this.waitingSpiralChunksLoad[o](!1),delete this.waitingSpiralChunksLoad[o];let s=!0;this.inLoading=!0,await W2(t,this.addWaitTime,async o=>{!s||this.loadedChunks[`${o.x},${o.z}`]||(this.world.getColumnAt(o)||(s=await new Promise(a=>{this.waitingSpiralChunksLoad[`${o.x},${o.z}`]=a})),s&&(await this.loadChunk(o,void 0,`spiral ${i} from ${r.x},${r.z}`),this.chunkProgress()))}),i===this.spiralNumber&&(this.panicTimeout&&clearTimeout(this.panicTimeout),this.inLoading=!1,this.gotPanicLastTime=!1,this.chunkReceiveTimes=[],this.lastChunkReceiveTime=0)}async loadChunk(t,r=!1,i="spiral"){var l,c;let[s,o]=Mt(this.lastPos),a=Math.abs(s-Math.floor(t.x/16)),v=Math.abs(o-Math.floor(t.z/16));if(a<=this.viewDistance&&v<=this.viewDistance){let u=await this.world.getColumnAt(t.y!==void 0?t:new q0(t.x,0,t.z));if(u){let h=u.toJson(),p={minY:u.minY??0,worldHeight:u.worldHeight??256};this.emit("loadChunk",{x:t.x,z:t.z,chunk:h,blockEntities:u.blockEntities,worldConfig:p,isLightUpdate:r}),this.loadedChunks[`${t.x},${t.z}`]=!0,(l=this.debugChunksInfo)[c=`${t.x},${t.z}`]??(l[c]={loads:[]}),this.debugChunksInfo[`${t.x},${t.z}`].loads.push({dataLength:h.length,reason:i,time:Date.now()})}else this.isPlayground&&this.emit("markAsLoaded",{x:t.x,z:t.z})}}unloadAllChunks(){for(let t of Object.keys(this.loadedChunks)){let[r,i]=t.split(",").map(Number);this.unloadChunk({x:r,z:i})}}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(i,s,o){if(typeof s!="string")return;let[a,v,l]=s.split(",").map(Number);return t.world.getBlock(new q0(a,v,l))?.entity}}))}updateBiome(t){try{if(!this.world.getBiome)return;let r=this.world.getBiome(t);r!==this.lastBiomeId&&(this.lastBiomeId=r,this.emit("biomeReset"))}catch{}}async updatePosition(t,r=!1){if(!this.allowPositionUpdate)return;let i=t.floored();if(!r&&this.lastPosCheck&&this.lastPosCheck.equals(i))return;this.lastPosCheck=i,this.updateBiome(t);let[s,o]=Mt(this.lastPos),[a,v]=Mt(t);if(s!==a||o!==v||r){this.emit("chunkPosUpdate",{pos:t});let l=[],c=r?this.viewDistance:this.viewDistance+this.keepChunksDistance;for(let h of Object.keys(this.loadedChunks)){let[p,g]=h.split(",").map(Number),y=new q0(p,0,g),[A,b]=Mt(y),w=Math.abs(a-A),S=Math.abs(v-b);(w>c||S>c)&&l.push(y)}for(let h of l)this.unloadChunk(h);let u=d5(this.viewDistance).map(([h,p])=>{let g=new q0((a+h)*16,0,(v+p)*16);if(!this.loadedChunks[`${g.x},${g.z}`])return g}).filter(h=>!!h);this.lastPos.update(t),this._loadChunks(u,t)}else this.emit("chunkPosUpdate",{pos:t}),this.lastPos.update(t)}};E();x();k();R();E();x();k();R();import $2 from"minecraft-data";import u6 from"mc-assets/dist/blocksAtlases.json";import f6 from"mc-assets/dist/itemsAtlases.json";import Ir from"mc-assets/dist/itemDefinitions.json";import h6 from"mc-assets/dist/blocksAtlasLatest.png";import m6 from"mc-assets/dist/blocksAtlasLegacy.png";import p6 from"mc-assets/dist/itemsAtlasLatest.png";import g6 from"mc-assets/dist/itemsAtlasLegacy.png";import b6 from"mc-assets/dist/textureReplacements/christmas";import{AtlasParser as et}from"mc-assets/dist/atlasParser";import Z2 from"mc-assets/dist/worldBlockProvider";E();x();k();R();var Cr=a5(V2(),1);import*as v1 from"three";E();x();k();R();E();x();k();R();var o1=class{constructor(e,t,r){this.name=e,this.fg=t,this.bg=r,this.PR=Math.round(window.devicePixelRatio||1),this.WIDTH=90*this.PR,this.HEIGHT=48*this.PR,this.TEXT_X=3*this.PR,this.TEXT_Y=2*this.PR,this.GRAPH_X=3*this.PR,this.GRAPH_Y=15*this.PR,this.GRAPH_WIDTH=84*this.PR,this.GRAPH_HEIGHT=30*this.PR,this.canvas=document.createElement("canvas"),this.canvas.width=90*this.PR,this.canvas.height=48*this.PR,this.canvas.style.width="90px",this.canvas.style.position="absolute",this.canvas.style.height="48px",this.canvas.style.cssText="width:90px;height:48px",this.context=this.canvas.getContext("2d"),this.context&&(this.context.font="bold "+9*this.PR+"px Helvetica,Arial,sans-serif",this.context.textBaseline="top",this.context.fillStyle=this.bg,this.context.fillRect(0,0,this.WIDTH,this.HEIGHT),this.context.fillStyle=this.fg,this.context.fillText(this.name,this.TEXT_X,this.TEXT_Y),this.context.fillRect(this.GRAPH_X,this.GRAPH_Y,this.GRAPH_WIDTH,this.GRAPH_HEIGHT),this.context.fillStyle=this.bg,this.context.globalAlpha=.9,this.context.fillRect(this.GRAPH_X,this.GRAPH_Y,this.GRAPH_WIDTH,this.GRAPH_HEIGHT))}update(e,t,r,i,s=0){let o=1/0,a=0;this.context&&(o=Math.min(o,e),a=Math.max(r,e),i=Math.max(i,t),this.context.fillStyle=this.bg,this.context.globalAlpha=1,this.context.fillRect(0,0,this.WIDTH,this.GRAPH_Y),this.context.fillStyle=this.fg,this.context.fillText(e.toFixed(s)+" "+this.name+" ("+o.toFixed(s)+"-"+parseFloat(a.toFixed(s))+")",this.TEXT_X,this.TEXT_Y),this.context.drawImage(this.canvas,this.GRAPH_X+this.PR,this.GRAPH_Y,this.GRAPH_WIDTH-this.PR,this.GRAPH_HEIGHT,this.GRAPH_X,this.GRAPH_Y,this.GRAPH_WIDTH-this.PR,this.GRAPH_HEIGHT),this.context.fillRect(this.GRAPH_X+this.GRAPH_WIDTH-this.PR,this.GRAPH_Y,this.PR,this.GRAPH_HEIGHT),this.context.fillStyle=this.bg,this.context.globalAlpha=.9,this.context.fillRect(this.GRAPH_X+this.GRAPH_WIDTH-this.PR,this.GRAPH_Y,this.PR,(1-t/i)*this.GRAPH_HEIGHT))}};var j2=class a1{constructor({logsPerSecond:e=20,samplesLog:t=100,samplesGraph:r=10,precision:i=2,minimal:s=!1,horizontal:o=!0,mode:a=0}={}){this.mode=a,this.horizontal=o,this.container=document.createElement("div"),this.container.style.cssText="position:fixed;top:0;left:0;opacity:0.9;z-index:10000;",s&&(this.container.style.cssText+="cursor:pointer"),this.gl=null,this.query=null,this.minimal=s,this.beginTime=(performance||Date).now(),this.prevTime=this.beginTime,this.prevCpuTime=this.beginTime,this.frames=0,this.averageCpu={logs:[],graph:[]},this.averageGpu={logs:[],graph:[]},this.queryCreated=!1,this.fpsPanel=this.addPanel(new a1.Panel("FPS","#0ff","#002"),0),this.msPanel=this.addPanel(new a1.Panel("CPU","#0f0","#020"),1),this.gpuPanel=null,this.samplesLog=t,this.samplesGraph=r,this.precision=i,this.logsPerSecond=e,this.minimal?(this.container.addEventListener("click",v=>{v.preventDefault(),this.showPanel(++this.mode%this.container.children.length)},!1),this.mode=a,this.showPanel(this.mode)):window.addEventListener("resize",()=>{this.resizePanel(this.fpsPanel,0),this.resizePanel(this.msPanel,1),this.gpuPanel&&this.resizePanel(this.gpuPanel,2)})}resizePanel(e,t){e.canvas.style.position="absolute",this.minimal?e.canvas.style.display="none":(e.canvas.style.display="block",this.horizontal?(e.canvas.style.top="0px",e.canvas.style.left=t*e.WIDTH/e.PR+"px"):(e.canvas.style.left="0px",e.canvas.style.top=t*e.HEIGHT/e.PR+"px"))}addPanel(e,t){return e.canvas&&(this.container.appendChild(e.canvas),this.resizePanel(e,t)),e}showPanel(e){for(let t=0;t<this.container.children.length;t++){let r=this.container.children[t];r.style.display=t===e?"block":"none"}this.mode=e}init(e){if(e){if(e instanceof WebGL2RenderingContext)this.gl=e;else if(e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas){if(this.gl=e.getContext("webgl2"),!this.gl)return}else return;this.ext=this.gl.getExtension("EXT_disjoint_timer_query_webgl2"),this.ext&&(this.gpuPanel=this.addPanel(new a1.Panel("GPU","#ff0","#220"),2))}}begin(){if(this.beginProfiling("cpu-started"),!(!this.gl||!this.ext)){if(this.query){let e=this.gl.getQueryParameter(this.query,this.gl.QUERY_RESULT_AVAILABLE);if(this.disjoint=this.gl.getParameter(this.ext.GPU_DISJOINT_EXT),e&&!this.disjoint){this.ns=this.gl.getQueryParameter(this.query,this.gl.QUERY_RESULT);let t=this.ns*1e-6;(e||this.disjoint)&&(this.gl.deleteQuery(this.query),this.query=null),e&&this.addToAverage(t,this.averageGpu)}}this.query||(this.queryCreated=!0,this.query=this.gl.createQuery(),this.query&&this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,this.query))}}end(){this.beginTime=this.endInternal(),this.endProfiling("cpu-started","cpu-finished","cpu-duration",this.averageCpu),!(!this.gl||!this.ext)&&this.queryCreated&&this.gl.getQuery(this.ext.TIME_ELAPSED_EXT,this.gl.CURRENT_QUERY)&&this.gl.endQuery(this.ext.TIME_ELAPSED_EXT)}endInternal(){this.frames++;let e=(performance||Date).now();if(e>=this.prevCpuTime+1e3/this.logsPerSecond&&(this.updatePanel(this.msPanel,this.averageCpu),this.updatePanel(this.gpuPanel,this.averageGpu),this.prevCpuTime=e),e>=this.prevTime+1e3){let t=this.frames*1e3/(e-this.prevTime);this.fpsPanel.update(t,t,100,100,0),this.prevTime=e,this.frames=0}return e}addToAverage(e,t){t.logs.push(e),t.logs.length>this.samplesLog&&t.logs.shift(),t.graph.push(e),t.graph.length>this.samplesGraph&&t.graph.shift()}beginProfiling(e){window.performance&&window.performance.mark(e)}endProfiling(e,t,r,i){if(window.performance&&t){window.performance.mark(t);let s=performance.measure(r,e,t);this.addToAverage(s.duration,i)}}updatePanel(e,t){if(t.logs.length>0){let r=0,i=.01;for(let a=0;a<t.logs.length;a++)r+=t.logs[a],t.logs[a]>i&&(i=t.logs[a]);let s=0,o=.01;for(let a=0;a<t.graph.length;a++)s+=t.graph[a],t.graph[a]>o&&(o=t.graph[a]);e&&e.update(r/Math.min(t.logs.length,this.samplesLog),s/Math.min(t.graph.length,this.samplesGraph),i,o,this.precision)}}};j2.Panel=o1;var Y2=j2;E();x();k();R();var He=Object.freeze({Linear:Object.freeze({None:function(n){return n},In:function(n){return this.None(n)},Out:function(n){return this.None(n)},InOut:function(n){return this.None(n)}}),Quadratic:Object.freeze({In:function(n){return n*n},Out:function(n){return n*(2-n)},InOut:function(n){return(n*=2)<1?.5*n*n:-.5*(--n*(n-2)-1)}}),Cubic:Object.freeze({In:function(n){return n*n*n},Out:function(n){return--n*n*n+1},InOut:function(n){return(n*=2)<1?.5*n*n*n:.5*((n-=2)*n*n+2)}}),Quartic:Object.freeze({In:function(n){return n*n*n*n},Out:function(n){return 1- --n*n*n*n},InOut:function(n){return(n*=2)<1?.5*n*n*n*n:-.5*((n-=2)*n*n*n-2)}}),Quintic:Object.freeze({In:function(n){return n*n*n*n*n},Out:function(n){return--n*n*n*n*n+1},InOut:function(n){return(n*=2)<1?.5*n*n*n*n*n:.5*((n-=2)*n*n*n*n+2)}}),Sinusoidal:Object.freeze({In:function(n){return 1-Math.sin((1-n)*Math.PI/2)},Out:function(n){return Math.sin(n*Math.PI/2)},InOut:function(n){return .5*(1-Math.sin(Math.PI*(.5-n)))}}),Exponential:Object.freeze({In:function(n){return n===0?0:Math.pow(1024,n-1)},Out:function(n){return n===1?1:1-Math.pow(2,-10*n)},InOut:function(n){return n===0?0:n===1?1:(n*=2)<1?.5*Math.pow(1024,n-1):.5*(-Math.pow(2,-10*(n-1))+2)}}),Circular:Object.freeze({In:function(n){return 1-Math.sqrt(1-n*n)},Out:function(n){return Math.sqrt(1- --n*n)},InOut:function(n){return(n*=2)<1?-.5*(Math.sqrt(1-n*n)-1):.5*(Math.sqrt(1-(n-=2)*n)+1)}}),Elastic:Object.freeze({In:function(n){return n===0?0:n===1?1:-Math.pow(2,10*(n-1))*Math.sin((n-1.1)*5*Math.PI)},Out:function(n){return n===0?0:n===1?1:Math.pow(2,-10*n)*Math.sin((n-.1)*5*Math.PI)+1},InOut:function(n){return n===0?0:n===1?1:(n*=2,n<1?-.5*Math.pow(2,10*(n-1))*Math.sin((n-1.1)*5*Math.PI):.5*Math.pow(2,-10*(n-1))*Math.sin((n-1.1)*5*Math.PI)+1)}}),Back:Object.freeze({In:function(n){var e=1.70158;return n===1?1:n*n*((e+1)*n-e)},Out:function(n){var e=1.70158;return n===0?0:--n*n*((e+1)*n+e)+1},InOut:function(n){var e=2.5949095;return(n*=2)<1?.5*(n*n*((e+1)*n-e)):.5*((n-=2)*n*((e+1)*n+e)+2)}}),Bounce:Object.freeze({In:function(n){return 1-He.Bounce.Out(1-n)},Out:function(n){return n<.36363636363636365?7.5625*n*n:n<.7272727272727273?7.5625*(n-=.5454545454545454)*n+.75:n<.9090909090909091?7.5625*(n-=.8181818181818182)*n+.9375:7.5625*(n-=.9545454545454546)*n+.984375},InOut:function(n){return n<.5?He.Bounce.In(n*2)*.5:He.Bounce.Out(n*2-1)*.5+.5}}),generatePow:function(n){return n===void 0&&(n=4),n=n<Number.EPSILON?Number.EPSILON:n,n=n>1e4?1e4:n,{In:function(e){return Math.pow(e,n)},Out:function(e){return 1-Math.pow(1-e,n)},InOut:function(e){return e<.5?Math.pow(e*2,n)/2:(1-Math.pow(2-e*2,n))/2+.5}}}}),f5=function(){return performance.now()},Ct=function(){function n(){this._tweens={},this._tweensAddedDuringUpdate={}}return n.prototype.getAll=function(){var e=this;return Object.keys(this._tweens).map(function(t){return e._tweens[t]})},n.prototype.removeAll=function(){this._tweens={}},n.prototype.add=function(e){this._tweens[e.getId()]=e,this._tweensAddedDuringUpdate[e.getId()]=e},n.prototype.remove=function(e){delete this._tweens[e.getId()],delete this._tweensAddedDuringUpdate[e.getId()]},n.prototype.update=function(e,t){e===void 0&&(e=f5()),t===void 0&&(t=!1);var r=Object.keys(this._tweens);if(r.length===0)return!1;for(;r.length>0;){this._tweensAddedDuringUpdate={};for(var i=0;i<r.length;i++){var s=this._tweens[r[i]],o=!t;s&&s.update(e,o)===!1&&!t&&delete this._tweens[r[i]]}r=Object.keys(this._tweensAddedDuringUpdate)}return!0},n}(),St={Linear:function(n,e){var t=n.length-1,r=t*e,i=Math.floor(r),s=St.Utils.Linear;return e<0?s(n[0],n[1],r):e>1?s(n[t],n[t-1],t-r):s(n[i],n[i+1>t?t:i+1],r-i)},Bezier:function(n,e){for(var t=0,r=n.length-1,i=Math.pow,s=St.Utils.Bernstein,o=0;o<=r;o++)t+=i(1-e,r-o)*i(e,o)*n[o]*s(r,o);return t},CatmullRom:function(n,e){var t=n.length-1,r=t*e,i=Math.floor(r),s=St.Utils.CatmullRom;return n[0]===n[t]?(e<0&&(i=Math.floor(r=t*(1+e))),s(n[(i-1+t)%t],n[i],n[(i+1)%t],n[(i+2)%t],r-i)):e<0?n[0]-(s(n[0],n[0],n[1],n[1],-r)-n[0]):e>1?n[t]-(s(n[t],n[t],n[t-1],n[t-1],r-t)-n[t]):s(n[i?i-1:0],n[i],n[t<i+1?t:i+1],n[t<i+2?t:i+2],r-i)},Utils:{Linear:function(n,e,t){return(e-n)*t+n},Bernstein:function(n,e){var t=St.Utils.Factorial;return t(n)/t(e)/t(n-e)},Factorial:function(){var n=[1];return function(e){var t=1;if(n[e])return n[e];for(var r=e;r>1;r--)t*=r;return n[e]=t,t}}(),CatmullRom:function(n,e,t,r,i){var s=(t-n)*.5,o=(r-e)*.5,a=i*i,v=i*a;return(2*e-2*t+s+o)*v+(-3*e+3*t-2*s-o)*a+s*i+e}}},Q2=function(){function n(){}return n.nextId=function(){return n._nextId++},n._nextId=0,n}(),Mr=new Ct,Oe=function(){function n(e,t){t===void 0&&(t=Mr),this._object=e,this._group=t,this._isPaused=!1,this._pauseStart=0,this._valuesStart={},this._valuesEnd={},this._valuesStartRepeat={},this._duration=1e3,this._isDynamic=!1,this._initialRepeat=0,this._repeat=0,this._yoyo=!1,this._isPlaying=!1,this._reversed=!1,this._delayTime=0,this._startTime=0,this._easingFunction=He.Linear.None,this._interpolationFunction=St.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=Q2.nextId(),this._isChainStopped=!1,this._propertiesAreSetUp=!1,this._goToEnd=!1}return n.prototype.getId=function(){return this._id},n.prototype.isPlaying=function(){return this._isPlaying},n.prototype.isPaused=function(){return this._isPaused},n.prototype.to=function(e,t){if(t===void 0&&(t=1e3),this._isPlaying)throw new Error("Can not call Tween.to() while Tween is already started or paused. Stop the Tween first.");return this._valuesEnd=e,this._propertiesAreSetUp=!1,this._duration=t,this},n.prototype.duration=function(e){return e===void 0&&(e=1e3),this._duration=e,this},n.prototype.dynamic=function(e){return e===void 0&&(e=!1),this._isDynamic=e,this},n.prototype.start=function(e,t){if(e===void 0&&(e=f5()),t===void 0&&(t=!1),this._isPlaying)return this;if(this._group&&this._group.add(this),this._repeat=this._initialRepeat,this._reversed){this._reversed=!1;for(var r in this._valuesStartRepeat)this._swapEndStartRepeatValues(r),this._valuesStart[r]=this._valuesStartRepeat[r]}if(this._isPlaying=!0,this._isPaused=!1,this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._isChainStopped=!1,this._startTime=e,this._startTime+=this._delayTime,!this._propertiesAreSetUp||t){if(this._propertiesAreSetUp=!0,!this._isDynamic){var i={};for(var s in this._valuesEnd)i[s]=this._valuesEnd[s];this._valuesEnd=i}this._setupProperties(this._object,this._valuesStart,this._valuesEnd,this._valuesStartRepeat,t)}return this},n.prototype.startFromCurrentValues=function(e){return this.start(e,!0)},n.prototype._setupProperties=function(e,t,r,i,s){for(var o in r){var a=e[o],v=Array.isArray(a),l=v?"array":typeof a,c=!v&&Array.isArray(r[o]);if(!(l==="undefined"||l==="function")){if(c){var u=r[o];if(u.length===0)continue;for(var h=[a],p=0,g=u.length;p<g;p+=1){var y=this._handleRelativeValue(a,u[p]);if(isNaN(y)){c=!1;break}h.push(y)}c&&(r[o]=h)}if((l==="object"||v)&&a&&!c){t[o]=v?[]:{};var A=a;for(var b in A)t[o][b]=A[b];i[o]=v?[]:{};var u=r[o];if(!this._isDynamic){var w={};for(var b in u)w[b]=u[b];r[o]=u=w}this._setupProperties(A,t[o],u,i[o],s)}else(typeof t[o]>"u"||s)&&(t[o]=a),v||(t[o]*=1),c?i[o]=r[o].slice().reverse():i[o]=t[o]||0}}},n.prototype.stop=function(){return this._isChainStopped||(this._isChainStopped=!0,this.stopChainedTweens()),this._isPlaying?(this._group&&this._group.remove(this),this._isPlaying=!1,this._isPaused=!1,this._onStopCallback&&this._onStopCallback(this._object),this):this},n.prototype.end=function(){return this._goToEnd=!0,this.update(1/0),this},n.prototype.pause=function(e){return e===void 0&&(e=f5()),this._isPaused||!this._isPlaying?this:(this._isPaused=!0,this._pauseStart=e,this._group&&this._group.remove(this),this)},n.prototype.resume=function(e){return e===void 0&&(e=f5()),!this._isPaused||!this._isPlaying?this:(this._isPaused=!1,this._startTime+=e-this._pauseStart,this._pauseStart=0,this._group&&this._group.add(this),this)},n.prototype.stopChainedTweens=function(){for(var e=0,t=this._chainedTweens.length;e<t;e++)this._chainedTweens[e].stop();return this},n.prototype.group=function(e){return e===void 0&&(e=Mr),this._group=e,this},n.prototype.delay=function(e){return e===void 0&&(e=0),this._delayTime=e,this},n.prototype.repeat=function(e){return e===void 0&&(e=0),this._initialRepeat=e,this._repeat=e,this},n.prototype.repeatDelay=function(e){return this._repeatDelayTime=e,this},n.prototype.yoyo=function(e){return e===void 0&&(e=!1),this._yoyo=e,this},n.prototype.easing=function(e){return e===void 0&&(e=He.Linear.None),this._easingFunction=e,this},n.prototype.interpolation=function(e){return e===void 0&&(e=St.Linear),this._interpolationFunction=e,this},n.prototype.chain=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this._chainedTweens=e,this},n.prototype.onStart=function(e){return this._onStartCallback=e,this},n.prototype.onEveryStart=function(e){return this._onEveryStartCallback=e,this},n.prototype.onUpdate=function(e){return this._onUpdateCallback=e,this},n.prototype.onRepeat=function(e){return this._onRepeatCallback=e,this},n.prototype.onComplete=function(e){return this._onCompleteCallback=e,this},n.prototype.onStop=function(e){return this._onStopCallback=e,this},n.prototype.update=function(e,t){if(e===void 0&&(e=f5()),t===void 0&&(t=!0),this._isPaused)return!0;var r,i,s=this._startTime+this._duration;if(!this._goToEnd&&!this._isPlaying){if(e>s)return!1;t&&this.start(e,!0)}if(this._goToEnd=!1,e<this._startTime)return!0;this._onStartCallbackFired===!1&&(this._onStartCallback&&this._onStartCallback(this._object),this._onStartCallbackFired=!0),this._onEveryStartCallbackFired===!1&&(this._onEveryStartCallback&&this._onEveryStartCallback(this._object),this._onEveryStartCallbackFired=!0),i=(e-this._startTime)/this._duration,i=this._duration===0||i>1?1:i;var o=this._easingFunction(i);if(this._updateProperties(this._object,this._valuesStart,this._valuesEnd,o),this._onUpdateCallback&&this._onUpdateCallback(this._object,i),i===1)if(this._repeat>0){isFinite(this._repeat)&&this._repeat--;for(r in this._valuesStartRepeat)!this._yoyo&&typeof this._valuesEnd[r]=="string"&&(this._valuesStartRepeat[r]=this._valuesStartRepeat[r]+parseFloat(this._valuesEnd[r])),this._yoyo&&this._swapEndStartRepeatValues(r),this._valuesStart[r]=this._valuesStartRepeat[r];return this._yoyo&&(this._reversed=!this._reversed),this._repeatDelayTime!==void 0?this._startTime=e+this._repeatDelayTime:this._startTime=e+this._delayTime,this._onRepeatCallback&&this._onRepeatCallback(this._object),this._onEveryStartCallbackFired=!1,!0}else{this._onCompleteCallback&&this._onCompleteCallback(this._object);for(var a=0,v=this._chainedTweens.length;a<v;a++)this._chainedTweens[a].start(this._startTime+this._duration,!1);return this._isPlaying=!1,!1}return!0},n.prototype._updateProperties=function(e,t,r,i){for(var s in r)if(t[s]!==void 0){var o=t[s]||0,a=r[s],v=Array.isArray(e[s]),l=Array.isArray(a),c=!v&&l;c?e[s]=this._interpolationFunction(a,i):typeof a=="object"&&a?this._updateProperties(e[s],o,a,i):(a=this._handleRelativeValue(o,a),typeof a=="number"&&(e[s]=o+(a-o)*i))}},n.prototype._handleRelativeValue=function(e,t){return typeof t!="string"?t:t.charAt(0)==="+"||t.charAt(0)==="-"?e+parseFloat(t):parseFloat(t)},n.prototype._swapEndStartRepeatValues=function(e){var t=this._valuesStartRepeat[e],r=this._valuesEnd[e];typeof r=="string"?this._valuesStartRepeat[e]=this._valuesStartRepeat[e]+parseFloat(r):this._valuesStartRepeat[e]=this._valuesEnd[e],this._valuesEnd[e]=t},n}();var Fc=Q2.nextId,g0=Mr,zc=g0.getAll.bind(g0),Lc=g0.removeAll.bind(g0),Uc=g0.add.bind(g0),Gc=g0.remove.bind(g0),K2=g0.update.bind(g0);E();x();k();R();function Sr(n){if(n==="high-performance")return"high-performance";if(n==="low-power")return"low-power"}var ae=typeof globalThis.WorkerGlobalScope<"u"&&globalThis instanceof globalThis.WorkerGlobalScope,Br=class{constructor(e,t=0){this.canvas=e;d(this,"stats");d(this,"stats2");d(this,"statsGl");d(this,"total",0);d(this,"denseMode");this.stats=new Cr.default,this.stats2=new Cr.default,this.statsGl=new Y2({minimal:!0}),this.stats2.showPanel(2),this.denseMode=typeof D<"u"&&!0||typeof window<"u"&&window.innerHeight<500,this.initStats(),this.setVisibility(t)}addStat(e,t=80){e.style.position="absolute",this.denseMode&&(e.style.height="12px"),e.style.overflow="hidden",e.style.left="",e.style.top="0",e.style.right=`${this.total}px`,e.style.width="80px",e.style.zIndex="1",e.style.opacity="0.8";let r=document.getElementById("corner-indicator-stats"),i=r??document.body;r&&(e.style.position="relative"),i.appendChild(e),this.total+=t}initStats(){let e=this.stats2.dom.children.length===3;this.addStat(this.stats.dom),e&&this.addStat(this.stats2.dom),this.statsGl.init(this.canvas),this.statsGl.container.style.display="flex",this.statsGl.container.style.justifyContent="flex-end";let t=0;for(let r of this.statsGl.container.children){let i=r;t++===0&&(i.style.display="none"),i.style.position=""}}setVisibility(e){e>0?(this.stats.dom.style.display="block",this.stats2.dom.style.display=e>=2?"block":"none",this.statsGl.container.style.display=e>=2?"block":"none"):(this.stats.dom.style.display="none",this.stats2.dom.style.display="none",this.statsGl.container.style.display="none")}markStart(){this.stats.begin(),this.stats2.begin(),this.statsGl.begin()}markEnd(){this.stats.end(),this.stats2.end(),this.statsGl.end()}dispose(){this.stats.dom.remove(),this.stats2.dom.remove(),this.statsGl.container.remove()}},h5=class{constructor(e,t,r){this.initOptions=e;this.externalCanvas=t;d(this,"canvas");d(this,"renderer");d(this,"animationFrameId");d(this,"timeoutId");d(this,"lastRenderTime",0);d(this,"previousCanvasWidth",0);d(this,"previousCanvasHeight",0);d(this,"currentWidth",0);d(this,"currentHeight",0);d(this,"pendingResize",!1);d(this,"renderedFps",0);d(this,"fpsInterval");d(this,"stats");d(this,"paused",!1);d(this,"disconnected",!1);d(this,"preRender",()=>{});d(this,"render",e=>{});d(this,"postRender",()=>{});d(this,"sizeChanged",()=>{});d(this,"droppedFpsPercentage",0);d(this,"config");d(this,"onRender",[]);d(this,"inWorldRenderingConfig");d(this,"nonReactiveState");this.config=e.config,t?this.canvas=t:this.addToPage();try{let s=e.getRendererOptions?.()?.gpuPreference??"default";this.renderer=new v1.WebGLRenderer({canvas:this.canvas,preserveDrawingBuffer:!0,logarithmicDepthBuffer:!0,powerPreference:Sr(s)})}catch(s){throw e.callbacks.displayCriticalError(new Error(`Failed to create WebGL context, not possible to render (restart browser): ${s.message}`)),s}this.renderer.useLegacyLights=!0,this.renderer.outputColorSpace=v1.LinearSRGBColorSpace,t||(this.updatePixelRatio(),this.setupResizeListener()),this.sizeUpdated(),this.previousCanvasWidth=this.canvas.width,this.previousCanvasHeight=this.canvas.height;let i="WebGL2RenderingContext"in globalThis;!t&&i&&!ae&&(this.stats=new Br(this.canvas,this.config.statsVisible)),this.setupFpsTracking(),this.startRenderLoop()}setupResizeListener(){if(typeof window>"u")return;let e,t=()=>{e&&clearTimeout(e),e=setTimeout(()=>{this.pendingResize=!0},16)};window.addEventListener("resize",t,{passive:!0})}updatePixelRatio(){if(typeof window>"u")return;let e=window.devicePixelRatio||1;this.renderer.capabilities.isWebGL2||(e=1),this.renderer.setPixelRatio(e)}sizeUpdated(){this.renderer.setSize(this.currentWidth,this.currentHeight,!1)}addToPage(){this.canvas=J2(),this.updateCanvasSize()}updateSizeExternal(e,t,r){this.currentWidth=e,this.currentHeight=t,this.renderer.setPixelRatio(r),this.sizeUpdated()}updateCanvasSize(){if(this.externalCanvas||typeof document>"u")return;let e=document.body.offsetWidth,t=document.body.offsetHeight;this.currentWidth!==e&&(this.currentWidth=e),this.currentHeight!==t&&(this.currentHeight=t)}setupFpsTracking(){let e=0;this.fpsInterval=setInterval(()=>{e>0&&(this.droppedFpsPercentage=this.renderedFps/e),e=Math.max(this.renderedFps,e),this.nonReactiveState&&(this.nonReactiveState.fps=this.renderedFps),this.renderedFps=0},1e3)}startRenderLoop(){let e=()=>{if(this.disconnected)return;if(this.config.timeoutRendering){let i=1e3/(this.config.fpsLimit?Math.min(this.config.fpsLimit,60):60);this.timeoutId=setTimeout(e,i)}else this.animationFrameId=requestAnimationFrame(e);if(this.paused||this.renderer.xr.isPresenting&&!this.inWorldRenderingConfig?.vrPageGameRendering)return;if(!this.config.timeoutRendering&&this.config.fpsLimit){let r=performance.now(),i=r-this.lastRenderTime,s=1e3/this.config.fpsLimit;if(i<s)return;this.lastRenderTime=r-i%s}let t=!1;this.pendingResize&&(this.updateCanvasSize(),this.pendingResize=!1),(this.previousCanvasWidth!==this.currentWidth||this.previousCanvasHeight!==this.currentHeight)&&(this.previousCanvasWidth=this.currentWidth,this.previousCanvasHeight=this.currentHeight,this.sizeUpdated(),t=!0),this.frameRender(t),this.config.statsVisible!==void 0&&this.stats?.setVisibility(this.config.statsVisible)};e()}frameRender(e){this.preRender(),this.stats?.markStart(),K2(),globalThis.freezeRender||this.render(e);for(let t of this.onRender)t(e);this.renderedFps++,this.stats?.markEnd(),this.postRender()}setPaused(e){this.paused=e}dispose(){this.disconnected=!0,this.animationFrameId&&cancelAnimationFrame(this.animationFrameId),this.timeoutId&&clearTimeout(this.timeoutId),this.canvas instanceof HTMLCanvasElement&&this.canvas.remove(),clearInterval(this.fpsInterval),this.stats?.dispose(),this.renderer.dispose()}};function J2(){let n=document.createElement("canvas");return n.id="viewer-canvas",document.body.appendChild(n),n}var Pr=()=>{let n=J2(),e=n.transferControlToOffscreen(),t=!1,r=(o,a)=>{},i={width:0,height:0},s=()=>{t||((i.width!==window.innerWidth||i.height!==window.innerHeight)&&(r(window.innerWidth,window.innerHeight),i={width:window.innerWidth,height:window.innerHeight}),requestAnimationFrame(s))};return requestAnimationFrame(s),{canvas:e,destroy(){t=!0,n.remove()},onSizeChanged(o){r=o},get size(){return{width:window.innerWidth,height:window.innerHeight}}}};import{ItemsRenderer as q2}from"mc-assets/dist/itemsRenderer";import{getLoadedItemDefinitionsStore as Hr}from"mc-assets/dist/stores";var l1=null;function es(n){return ae?((!l1||typeof l1.get!="function")&&(l1=Hr(Ir)),l1):(ts(n),n.itemsDefinitionsStore)}function ts(n){ae||typeof n.itemsDefinitionsStore?.get=="function"||(n.itemsDefinitionsStore=Hr(n.sourceItemDefinitionsJson??Ir))}var Bt=class{constructor(e){d(this,"sourceItemDefinitionsJson",Ir);d(this,"itemsDefinitionsStore",Hr(this.sourceItemDefinitionsJson));d(this,"allReady",!1);d(this,"itemsAtlasImage");d(this,"blocksAtlasImage");d(this,"blocksAtlasJson");d(this,"itemsAtlasJson");d(this,"customBlockStates");d(this,"customModels");d(this,"customItemModelNames",{});d(this,"customTextures",{});d(this,"guiAtlas",null);d(this,"guiAtlasVersion",0);d(this,"itemsRenderer");d(this,"worldBlockProvider");d(this,"blockstatesModels",null);d(this,"version");d(this,"texturesVersion");d(this,"mcData");if(e){let t={...e};delete t.itemsDefinitionsStore,delete t.sourceItemDefinitionsJson,Object.assign(this,t),ts(this)}if(this.version){let t=globalThis.loadedData??globalThis.mcData;ae&&t?.entitiesByName?this.mcData=t:this.mcData=$2(this.version)}}prepareForTransfer(){let e={};for(let t in this)Object.prototype.hasOwnProperty.call(this,t)&&typeof this[t]!="function"&&(t==="itemsRenderer"||t==="worldBlockProvider"||t==="mcData"||t==="itemsDefinitionsStore"||t==="sourceItemDefinitionsJson"||(e[t]=this[t]));return e.customTextures={},delete e.itemsDefinitionsStore,delete e.sourceItemDefinitionsJson,e}},X2="1.21.4",P0=class P0 extends Z0{constructor(){super(...arguments);d(this,"sourceBlockStatesModels",null);d(this,"sourceBlocksAtlases",u6);d(this,"sourceItemsAtlases",f6);d(this,"currentResources");d(this,"itemsAtlasParser");d(this,"blocksAtlasParser");d(this,"currentConfig");d(this,"abortController",new AbortController);d(this,"_promiseAssetsReadyResolvers",Promise.withResolvers())}rebuildWorkerRenderers(t){if(ae&&!(!t.version||!t.blockstatesModels||!t.blocksAtlasJson)){if(this.blocksAtlasParser=new et({latest:t.blocksAtlasJson},""),t.itemsAtlasJson)this.itemsAtlasParser=new et({latest:t.itemsAtlasJson},"");else if(!this.itemsAtlasParser?.atlas?.latest){if(!this.sourceItemsAtlases||Object.keys(this.sourceItemsAtlases).length===0)return;this.itemsAtlasParser=new et(this.sourceItemsAtlases,"")}t.itemsRenderer=new q2(t.version,t.blockstatesModels,this.itemsAtlasParser,this.blocksAtlasParser),t.worldBlockProvider=Z2(t.blockstatesModels,this.blocksAtlasParser.atlas,X2)}}static restoreTransferred(t,r){let i=new P0,s=o=>{i.currentResources=new Bt(o),i.rebuildWorkerRenderers(i.currentResources)};return s(t.currentResources),r&&r.addEventListener("message",({data:o})=>{o.class===P0.restorerName&&(o.type==="newResources"&&s(o.currentResources),o.type==="event"&&i.emit(o.eventName,...o.args))}),i}enrichTransferSnapshot(t){return t&&(this.itemsAtlasParser?.atlas?.latest&&(t.itemsAtlasJson=this.itemsAtlasParser.atlas.latest),this.blocksAtlasParser?.atlas?.latest&&(t.blocksAtlasJson=this.blocksAtlasParser.atlas.latest),t)}prepareForTransfer(t){if(t){let r=this.emit.bind(this);this.emit=(i,...s)=>{if(r(i,...s),t.postMessage({class:P0.restorerName,type:"event",eventName:i,args:s1(s)}),i==="assetsTexturesUpdated"||i==="assetsInventoryReady"){let o=this.enrichTransferSnapshot(this.currentResources?.prepareForTransfer());t.postMessage({class:P0.restorerName,type:"newResources",currentResources:o})}}}return{__restorer:P0.restorerName,currentResources:this.enrichTransferSnapshot(this.currentResources?.prepareForTransfer())}}get promiseAssetsReady(){return this._promiseAssetsReadyResolvers.promise}async loadSourceData(t=this.currentConfig?.version){if(!t)throw new Error("No version loaded");this.sourceBlockStatesModels??(this.sourceBlockStatesModels=(await import("mc-assets/dist/blockStatesModels.json")).default)}resetResources(){this.currentResources=new Bt}async updateAssetsData(t,r=!1){if(!this.currentConfig)throw new Error("No config loaded");this._promiseAssetsReadyResolvers=Promise.withResolvers();let i=new AbortController;if(await this.loadSourceData(this.currentConfig.version),i.signal.aborted)return;let s=this.currentResources??new Bt;s.version=this.currentConfig.version,s.texturesVersion=this.currentConfig.texturesVersion??s.version,s.mcData=$2(s.version),s.blockstatesModels={blockstates:{},models:{}},s.blockstatesModels.blockstates.latest={...this.sourceBlockStatesModels.blockstates.latest,...s.customBlockStates},s.blockstatesModels.models.latest={...this.sourceBlockStatesModels.models.latest,...s.customModels},await Promise.all([this.recreateBlockAtlas(s),this.recreateItemsAtlas(s)]),!i.signal.aborted&&(s.version&&s.blockstatesModels&&this.itemsAtlasParser&&this.blocksAtlasParser&&(s.itemsRenderer=new q2(s.version,s.blockstatesModels,this.itemsAtlasParser,this.blocksAtlasParser)),!i.signal.aborted&&(this.currentResources=s,s.allReady=!0,r||this.emit("assetsTexturesUpdated"),this.currentConfig.noInventoryGui?this._promiseAssetsReadyResolvers.resolve():(this.emit("assetsInventoryStarted"),this.generateGuiTextures().then(()=>{i.signal.aborted||(r||this.emit("assetsInventoryReady"),this._promiseAssetsReadyResolvers.resolve())}))))}async recreateBlockAtlas(t=this.currentResources){let r={},i=new Date;(i.getMonth()===11&&i.getDate()>=24||i.getMonth()===0&&i.getDate()<=6)&&Object.assign(r,b6);let s=new et(this.sourceBlocksAtlases,h6,m6),o=Object.keys(t.customTextures.blocks?.textures??{}),{atlas:a,canvas:v}=await s.makeNewAtlas(t.texturesVersion,l=>{if(this.currentConfig.includeOnlyBlocks&&!this.currentConfig.includeOnlyBlocks.includes(l))return!1;let c=t.customTextures.blocks?.textures[l];return r[l]??c},void 0,void 0,o,{needHorizontalIndexes:!!this.currentConfig.includeOnlyBlocks});this.blocksAtlasParser=new et({latest:a},v.toDataURL()),t.blocksAtlasImage=await createImageBitmap(v),t.blocksAtlasJson=this.blocksAtlasParser.atlas.latest,t.worldBlockProvider=Z2(t.blockstatesModels,this.blocksAtlasParser.atlas,X2)}async recreateItemsAtlas(t=this.currentResources){let r=new et(this.sourceItemsAtlases,p6,g6),i=Object.keys(t.customTextures.items?.textures??{}),{atlas:s,canvas:o}=await r.makeNewAtlas(t.texturesVersion,a=>{let v=t.customTextures.items?.textures[a];if(v)return v},t.customTextures.items?.tileSize,void 0,i);this.itemsAtlasParser=new et({latest:s},o.toDataURL()),t.itemsAtlasImage=await createImageBitmap(o),t.itemsAtlasJson=this.itemsAtlasParser.atlas.latest}async generateGuiTextures(){}async downloadDebugAtlas(t=!1){if(!this.currentResources)throw new Error("No resources loaded");let s=await(t?this.itemsAtlasParser:this.blocksAtlasParser).createDebugImage(!0),o=document.createElement("a");o.href=s,o.download=`atlas-debug-${t?"items":"blocks"}.png`,o.click()}destroy(){this.abortController.abort(),this.currentResources=void 0,this.abortController=new AbortController}};d(P0,"restorerName","ResourcesManager");var h0=P0;E();x();k();R();var o0=class extends Error{constructor(t,r){super(t);d(this,"failure");this.name="MesherWorkerPreloadError",this.failure=r}};function y6(n){return!n||typeof n!="object"?!1:n.type==="mc-web-pong"?!0:Array.isArray(n)?n.some(e=>e&&typeof e=="object"&&e.type==="mc-web-pong"):!1}var _6=45e3,w6=1e4;async function rs(n){if(D.env.SINGLE_FILE_BUILD)return;let e=n?.fetchTimeoutMs??_6,t=n?.pingTimeoutMs??w6,r=n?.script??"mesher.js",i=new URL(r,document.baseURI).href,s;try{let u=new AbortController,h=window.setTimeout(()=>u.abort(),e);try{s=await fetch(i,{credentials:"same-origin",cache:"force-cache",signal:u.signal})}finally{clearTimeout(h)}}catch(u){let h=u;throw h?.name==="AbortError"?new o0(`Mesher script fetch timed out after ${e}ms (${i}).`,{phase:"fetch",code:"timeout"}):new o0(`Mesher script fetch failed (network): ${h?.message??u}. URL: ${i}`,{phase:"fetch",code:"network",detail:String(h?.message??u)})}if(!s.ok)throw new o0(`Mesher script HTTP ${s.status} ${s.statusText}: ${i}`,{phase:"fetch",code:"bad-status",status:s.status});let o=s.headers.get("content-type")??"",a=await s.arrayBuffer();if(a.byteLength===0)throw new o0(`Mesher script response was empty: ${i}`,{phase:"fetch",code:"invalid-body",hint:"empty"});let v=Math.min(1024,a.byteLength),l=new TextDecoder().decode(a.slice(0,v)).trimStart();if(l.startsWith("<!DOCTYPE")||l.startsWith("<html")||l.startsWith("<HTML"))throw new o0(`Mesher URL returned HTML (wrong path, redirect, or SPA fallback), not JavaScript: ${i}`,{phase:"fetch",code:"invalid-body",hint:"html"});o.length>0&&/javascript|ecmascript/i.test(o);let c;try{c=new Worker(i)}catch(u){let h=u instanceof Error?u.message:String(u);throw new o0(`Could not construct Worker for mesher (${i}): ${h}`,{phase:"worker",code:"construct-failed",message:h})}await new Promise((u,h)=>{let p=!1,g=window.setTimeout(()=>{p||(p=!0,y(),h(new o0(`Mesher worker did not reply with mc-web-pong within ${t}ms (wrong script, SW stale cache, worker blocked, or COEP/CORP). URL: ${i}`,{phase:"ping",code:"timeout"})))},t),y=()=>{clearTimeout(g);let M=c;c=void 0,M&&(M.removeEventListener("message",w),M.removeEventListener("error",S),M.removeEventListener("messageerror",C),M.terminate())},A=()=>{p||(p=!0,y(),u())},b=M=>{p||(p=!0,y(),h(M))};function w(M){y6(M.data)&&A()}function S(M){b(new o0(`Mesher worker script failed to load or threw during startup: ${M.message||"unknown"} @ ${i}`,{phase:"worker",code:"script-error",message:M.message}))}function C(){b(new o0(`Mesher worker message channel error (structured clone / deserialization). URL: ${i}`,{phase:"ping",code:"messageerror"}))}c.addEventListener("message",w),c.addEventListener("error",S),c.addEventListener("messageerror",C);try{c.postMessage({type:"mc-web-ping",t:performance.now(),workerIndex:0})}catch(M){let I=M instanceof Error?M.message:String(M);b(new o0(`Failed to post mc-web-ping to mesher worker: ${I}`,{phase:"ping",code:"post-failed",detail:I}))}})}var ns=class{constructor(e={},t=new h0){this.resourcesManager=t;d(this,"waitBackendLoadPromises",[]);d(this,"onWorldStart");d(this,"onBeforeWorldStart");d(this,"worldView");d(this,"config");d(this,"menuBackgroundOptions");d(this,"inWorldRenderingConfig");d(this,"backend");d(this,"backendLoader");d(this,"currentState");d(this,"currentDisplay",null);d(this,"playerState",{reactive:xr()});d(this,"rendererState");d(this,"nonReactiveState");d(this,"worldReady");d(this,"resolveWorldReady");d(this,"lastCamUpdate",0);d(this,"getRendererOptions");this.config={...L2,...e.config},this.menuBackgroundOptions={...e.config?.menuBackground,...e.menuBackground},this.inWorldRenderingConfig=is({...c5,...e.rendererConfig});let r=J0();this.rendererState=r.reactive,this.nonReactiveState=r.nonReactive,this.initWorldReadyPromise()}initWorldReadyPromise(){let{promise:e,resolve:t}=Promise.withResolvers();this.worldReady=e,this.resolveWorldReady=t}preloadWorkers(){let e=this.inWorldRenderingConfig.wasmMesher?"mesherWasm.js":"mesher.js";return rs({script:e})}bindRendererOptions(e){this.getRendererOptions=e}async loadBackend(e){this.backend&&this.disconnectBackend(),await Promise.all(this.waitBackendLoadPromises),this.waitBackendLoadPromises=[],this.backendLoader=e;let t={config:this.config,getRendererOptions:this.getRendererOptions,callbacks:{displayCriticalError:i=>{},setRendererSpecificSettings:(i,s)=>{},fireCustomEvent:(i,...s)=>{}},rendererSpecificSettings:{}},r=e(t);if(this.backend=await Promise.resolve(r),this.currentState)if(this.currentState.method==="startMenuBackground")this.startMenuBackground(...this.currentState.args);else{let{method:i,args:s}=this.currentState;this.backend[i](...s)}}async startWorld(e,t,r=this.playerState.reactive,i){if(this.currentDisplay==="world")throw new Error("World already started");this.currentDisplay="world";let s=i??new A6(0,64,0);this.worldView=new $0(e,t,s),this.worldView.isPlayground=this.inWorldRenderingConfig.isPlayground;let o={version:this.resourcesManager?.currentConfig?.version??"1.20.4",worldView:this.worldView,inWorldRenderingConfig:this.inWorldRenderingConfig,playerStateReactive:r,rendererState:this.rendererState,nonReactiveState:this.nonReactiveState,resourcesManager:this.resourcesManager};this.onBeforeWorldStart?.();let a;if(this.backend){let v=this.backend.startWorld(o);v&&typeof v.then=="function"&&(a=v)}return this.currentState={method:"startWorld",args:[o]},await a,this.resolveWorldReady(),this.onWorldStart?.(),!!a}startMenuBackground(e){if(this.currentDisplay==="menu")return;let t={...this.menuBackgroundOptions,...e,resourcesManager:e?.resourcesManager??this.resourcesManager};this.backend&&(this.currentDisplay="menu",this.backend.startMenuBackground(t)),this.currentState={method:"startMenuBackground",args:[t]}}resetBackend(e=!1){this.disconnectBackend(e),this.backendLoader&&this.loadBackend(this.backendLoader)}disconnectBackend(e=!1){e&&(this.currentState=void 0,this.currentDisplay=null,this.worldView=void 0),this.backend&&(this.backend.disconnect(),this.backend=void 0),this.currentDisplay=null,this.initWorldReadyPromise(),this.rendererState=is(J0().reactive),this.nonReactiveState=J0().nonReactive}updateCamera(e,t,r){this.backend?.updateCamera(e,t,r)}setRendering(e){this.backend?.setRendering(e)}async startWithBot(e,t){await this.startWorld(e.world,t),this.worldView&&typeof this.worldView.listenToBot=="function"&&this.worldView.listenToBot(e)}destroyAll(){this.disconnectBackend(!0),this.resourcesManager&&typeof this.resourcesManager.destroy=="function"&&this.resourcesManager.destroy()}get utils(){let e=this.backend;return{async waitingForChunks(){if(!e?.worldState?.allChunksLoaded)return new Promise(t=>{let r=setInterval(()=>{e?.worldState?.allChunksLoaded&&(clearInterval(r),t())},100)})}}}destroy(){this.disconnectBackend(!0)}};E();x();k();R();import{subscribe as I6}from"valtio/vanilla";E();x();k();R();E();x();k();R();var tt=["galaxy","nether","end","cyber","light"],rt=["cruise","barrel","dive","orbit","snake"],m5={galaxy:"Galaxy",nether:"Nether",end:"The End",cyber:"Cyber",light:"Light Space"},p5={cruise:"Cruise",barrel:"Barrel",dive:"Dive",orbit:"Orbit",snake:"Snake"},it=["mixed","stainedGlass","wool","construction","glow","world"],g5={mixed:"Mixed",stainedGlass:"Stained glass",wool:"Wool",construction:"Construction",glow:"Glow",world:"World (grass & ores)"};E();x();k();R();var b0={mode:"v2",minecraftTextures:!0,v2Scene:"light",v2Camera:"dive",v2BlockGroup:"stainedGlass",v2CameraSpeedPercent:80,v2BlockSpeedPercent:40},E0=n=>n/100,b5={camera:E0(b0.v2CameraSpeedPercent),block:E0(b0.v2BlockSpeedPercent)};var E6={off:0,holes:1,texIndex:2,faces:3,atlasAlpha:4};function Or(n){return E6[n]}var nt=b0,ss={rendererWorldPerformance:"normal",rendererMeshersCountOverride:null,starfieldRendering:!0,defaultSkybox:!0,menuBackgroundMode:nt.mode,menuBackgroundMinecraftTextures:nt.minecraftTextures,menuBackgroundV2Scene:nt.v2Scene,menuBackgroundV2Camera:nt.v2Camera,menuBackgroundV2BlockGroup:nt.v2BlockGroup,menuBackgroundV2CameraSpeed:nt.v2CameraSpeedPercent,menuBackgroundV2BlockSpeed:nt.v2BlockSpeedPercent,rendererFuturisticReveal:!1,rendererPerfDebugOverlay:!1,disableBlockEntityTextures:!1,rendererMesher:"wasm",rendererShaderCubeBlocks:!1,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};function x6(n){n.highPerformanceGpu&&(n.gpuPreference="high-performance",delete n.highPerformanceGpu),n.rendererMesher!=="wasm"&&n.rendererMesher!=="legacy-js"&&(typeof n.rendererWasmMesher=="boolean"?n.rendererMesher=n.rendererWasmMesher?"wasm":"legacy-js":typeof n.wasmExperimentalMesher=="boolean"&&(n.rendererMesher=n.wasmExperimentalMesher?"wasm":"legacy-js")),delete n.wasmExperimentalMesher,delete n.rendererWasmMesher,n.menuBackgroundMode==="futuristic"&&(n.menuBackgroundMode="v2");let e=[["menuBackgroundFuturisticScene","menuBackgroundV2Scene"],["menuBackgroundFuturisticCamera","menuBackgroundV2Camera"],["menuBackgroundFuturisticBlockGroup","menuBackgroundV2BlockGroup"],["menuBackgroundFuturisticCameraSpeed","menuBackgroundV2CameraSpeed"],["menuBackgroundFuturisticBlockSpeed","menuBackgroundV2BlockSpeed"]];for(let[t,r]of e)n[t]!==void 0&&n[r]===void 0&&(n[r]=n[t]),delete n[t]}var os={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:tt.map(n=>[n,m5[n]])},menuBackgroundV2Camera:{possibleValues:rt.map(n=>[n,p5[n]])},menuBackgroundV2BlockGroup:{possibleValues:it.map(n=>[n,g5[n]]),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. Reload to apply.",requiresRestart:!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:"WASM is faster. Use JS if WASM is not working. Requires reload.",requiresRestart:!0},rendererShaderCubeBlocks:{text:"Instanced shader cubes",tooltip:"Render full blocks through the global GPU instanced path. Requires WASM mesher and WebGL2.",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"]]}},as=[{title:"World rendering",keys:["rendererWorldPerformance","starfieldRendering","defaultSkybox","disableBlockEntityTextures","showChunkBorders","renderEntities","smoothLighting","vanillaLook","newVersionsLighting","dayCycleAndLighting","loadPlayerSkins","renderEars","showHand","viewBobbing","fov","keepChunksDistance","highlightBlockColor","clipWorldBelowY"]},{title:"Frame pacing",keys:["frameLimit","backgroundRendering","renderDebug","gpuPreference"]},{title:"VR",keys:["vrSupport","vrPageGameRendering"]},{title:"Menu background",keys:["menuBackgroundMode","menuBackgroundMinecraftTextures","menuBackgroundV2Scene","menuBackgroundV2Camera","menuBackgroundV2BlockGroup","menuBackgroundV2CameraSpeed","menuBackgroundV2BlockSpeed"]},{title:"Mesher",keys:["rendererMesher","rendererShaderCubeBlocks"]},{title:"Renderer debug",keys:["rendererFuturisticReveal","rendererPerfDebugOverlay","rendererShaderCubeDebugMode"]}];E();x();k();R();E();x();k();R();E();x();k();R();E();x();k();R();function Dr(n,e,t,r,i){let s=n.getImageData(e,t,r,i);for(let o=0;o<r;o++)for(let a=0;a<i;a++){let v=(o+a*r)*4;if(s.data[v+3]!==255)return!0}return!1}function c1(n){return n/64}function vs(n,e,t){if(t){if(Dr(n,0,0,e,e))return}else if(Dr(n,0,0,e,e/2))return;let r=c1(e),i=(s,o,a,v)=>n.clearRect(s*r,o*r,a*r,v*r);i(40,0,8,8),i(48,0,8,8),i(32,8,8,8),i(40,8,8,8),i(48,8,8,8),i(56,8,8,8),t&&(i(4,32,4,4),i(8,32,4,4),i(0,36,4,12),i(4,36,4,12),i(8,36,4,12),i(12,36,4,12),i(20,32,8,4),i(28,32,8,4),i(16,36,4,12),i(20,36,8,12),i(28,36,4,12),i(32,36,8,12),i(44,32,4,4),i(48,32,4,4),i(40,36,4,12),i(44,36,4,12),i(48,36,4,12),i(52,36,12,12),i(4,48,4,4),i(8,48,4,4),i(0,52,4,12),i(4,52,4,12),i(8,52,4,12),i(12,52,4,12),i(52,48,4,4),i(56,48,4,4),i(48,52,4,12),i(52,52,4,12),i(56,52,4,12),i(60,52,4,12))}function R6(n,e){n.save(),n.scale(-1,1);let t=c1(e),r=(i,s,o,a,v,l)=>n.drawImage(n.canvas,i*t,s*t,o*t,a*t,-v*t,l*t,-o*t,a*t);r(4,16,4,4,20,48),r(8,16,4,4,24,48),r(0,20,4,12,24,52),r(4,20,4,12,20,52),r(8,20,4,12,16,52),r(12,20,4,12,28,52),r(44,16,4,4,36,48),r(48,16,4,4,40,48),r(40,20,4,12,40,52),r(44,20,4,12,36,52),r(48,20,4,12,32,52),r(52,20,4,12,44,52),n.restore()}function Fr(n,e){let t=!1;if(e.width!==e.height)if(e.width===2*e.height)t=!0;else throw new Error(`Bad skin size: ${e.width}x${e.height}`);let r=n.getContext("2d",{willReadFrequently:!0});if(t){let i=e.width;n.width=i,n.height=i,r.clearRect(0,0,i,i),r.drawImage(e,0,0,i,i/2),R6(r,i),vs(r,n.width,!1)}else n.width=e.width,n.height=e.height,r.clearRect(0,0,e.width,e.height),r.drawImage(e,0,0,n.width,n.height),vs(r,n.width,!0)}function k6(n){if(n.width===2*n.height)return n.width/64;if(n.width*17===n.height*22)return n.width/22;if(n.width*11===n.height*23)return n.width/46;throw new Error(`Bad cape size: ${n.width}x${n.height}`)}function zr(n,e){let t=k6(e);n.width=64*t,n.height=32*t;let r=n.getContext("2d",{willReadFrequently:!0});r.clearRect(0,0,n.width,n.height),r.drawImage(e,0,0,e.width,e.height)}function T6(n,e,t,r,i){let s=n.getImageData(e,t,r,i);for(let o=0;o<r;o++)for(let a=0;a<i;a++){let v=(o+a*r)*4;if(!(s.data[v+0]===0&&s.data[v+1]===0&&s.data[v+2]===0&&s.data[v+3]===255))return!1}return!0}function M6(n,e,t,r,i){let s=n.getImageData(e,t,r,i);for(let o=0;o<r;o++)for(let a=0;a<i;a++){let v=(o+a*r)*4;if(!(s.data[v+0]===255&&s.data[v+1]===255&&s.data[v+2]===255&&s.data[v+3]===255))return!1}return!0}function Lr(n){let e=c1(n.width),t=n.getContext("2d",{willReadFrequently:!0}),r=(a,v,l,c)=>Dr(t,a*e,v*e,l*e,c*e),i=(a,v,l,c)=>T6(t,a*e,v*e,l*e,c*e),s=(a,v,l,c)=>M6(t,a*e,v*e,l*e,c*e);return r(50,16,2,4)||r(54,20,2,12)||r(42,48,2,4)||r(46,52,2,12)||i(50,16,2,4)&&i(54,20,2,12)&&i(42,48,2,4)&&i(46,52,2,12)||s(50,16,2,4)&&s(54,20,2,12)&&s(42,48,2,4)&&s(46,52,2,12)?"slim":"default"}function Ur(n,e){if(e.width!==e.height&&e.width!==2*e.height)throw new Error(`Bad skin size: ${e.width}x${e.height}`);let t=c1(e.width),r=14*t,i=7*t;n.width=r,n.height=i;let s=n.getContext("2d",{willReadFrequently:!0});s.clearRect(0,0,r,i),s.drawImage(e,24*t,0,r,i,0,0,r,i)}E();x();k();R();import B6 from"mc-assets/dist/other-textures/latest/entity/player/wide/steve.png";E();x();k();R();import*as m0 from"three";E();x();k();R();var S6=()=>{if(typeof OffscreenCanvas>"u")return!1;try{let n=new OffscreenCanvas(1,1);return(n.getContext("webgl2")||n.getContext("webgl"))!==null}catch{return!1}},C6=S6(),Ve=(n,e)=>{if(C6||typeof document>"u")return new OffscreenCanvas(n,e);let t=document.createElement("canvas");return t.width=n,t.height=e,t};async function st(n){let t=await(await fetch(n)).blob();return createImageBitmap(t)}var Re=(n,e=!1)=>{n instanceof m0.Mesh&&(n.geometry?.dispose?.(),n.material?.dispose?.()),n.children&&n.children.forEach(t=>Re(t,e)),e&&n instanceof m0.Mesh&&n.material?.map?.dispose?.()},Gr={},ls={},y5=n=>{let e=new m0.Texture,t=st(n).then(r=>{let i=new OffscreenCanvas(r.width,r.height);return i.getContext("2d").drawImage(r,0,0),e.source.data=i,e.needsUpdate=!0,e});return{texture:e,promise:t}},Pt=async n=>y5(n).texture,I0=n=>{let e=Ve(n.width,n.height);e.getContext("2d").drawImage(n,0,0);let r=new m0.Texture(e);return r.magFilter=m0.NearestFilter,r.minFilter=m0.NearestFilter,r};function It(n){let{texture:e,promise:t}=y5(n);return e.magFilter=m0.NearestFilter,e.minFilter=m0.NearestFilter,t.catch(r=>{}),e}async function d1(n,e,t){if(!Gr[n]){let{promise:i,resolve:s}=Promise.withResolvers(),o=y5(n);Gr[n]=o.texture,o.promise.then(s),ls[n]=i}e(Gr[n]),ls[n].then(()=>{t?.()})}var $e=B6,af=Pt($e),cs={apiEnabled:!0},u1=n=>{Object.assign(cs,n)};async function H0(n,e){if(!cs.apiEnabled||e==="cape")return;let t=`https://playerdb.co/api/player/minecraft/${n}`,r=await fetch(t);return r.ok?(await r.json()).data.player.skin_texture:void 0}async function y0(n){n.startsWith("data:")||(n=await P6(n.replace("http://","https://")));let e=await st(n),t=Ve(64,64);return Fr(t,e),{canvas:t,image:e}}var P6=async n=>{let t=await(await fetch(n,{})).arrayBuffer();return`data:image/png;base64,${z.from(t).toString("base64")}`};function gf(n){return{mode:n.menuBackgroundMode,useMinecraftTextures:n.menuBackgroundMinecraftTextures,v2Scene:n.menuBackgroundV2Scene,v2Camera:n.menuBackgroundV2Camera,v2BlockGroup:n.menuBackgroundV2BlockGroup,v2CameraSpeed:E0(n.menuBackgroundV2CameraSpeed),v2BlockSpeed:E0(n.menuBackgroundV2BlockSpeed)}}function H6(n,e){let t=n.v2;t&&(t.setScene?.(e.menuBackgroundV2Scene),t.setCamera?.(e.menuBackgroundV2Camera),t.setBlockGroup?.(e.menuBackgroundV2BlockGroup),t.setCameraSpeed?.(E0(e.menuBackgroundV2CameraSpeed)),t.setBlockSpeed?.(E0(e.menuBackgroundV2BlockSpeed)))}function O6(n){return n.rendererMesher!=="legacy-js"}function D6(n,e,t){let r=n.inWorldRenderingConfig,i=e.rendererMeshersCountOverride,s=o=>{r.mesherWorkers=i??o};switch(e.rendererWorldPerformance){case"low-energy":s(1),r.dedicatedChangeWorker=!1;break;case"normal":s(2),r.dedicatedChangeWorker=!t;break;case"maximum":s(Math.max(3,Math.min(navigator.hardwareConcurrency??0,8))),r.dedicatedChangeWorker=!t;break}}function F6(n,e,t){let r=e.backgroundRendering,i=e.frameLimit;t?n.config.fpsLimit=i||void 0:r==="5fps"?n.config.fpsLimit=5:r==="20fps"?n.config.fpsLimit=20:n.config.fpsLimit=void 0}function z6(n,e,t){let{renderDebug:r}=e;r==="none"||t.isCypress?n.config.statsVisible=0:r==="basic"?n.config.statsVisible=1:r==="advanced"&&(n.config.statsVisible=2)}function L6(n,e,t={}){let r=n.inWorldRenderingConfig,i=O6(e);r.showChunkBorders=e.showChunkBorders,r.futuristicReveal=e.rendererFuturisticReveal,D6(n,e,i),r.renderEntities=e.renderEntities,z6(n,e,t),F6(n,e,t.windowFocused!==!1),r.vrSupport=e.vrSupport,r.vrPageGameRendering=e.vrPageGameRendering,r.enableDebugOverlay=e.rendererPerfDebugOverlay,r.clipWorldBelowY=e.clipWorldBelowY,r.extraBlockRenderers=!e.disableBlockEntityTextures,r.fetchPlayerSkins=e.loadPlayerSkins,r.highlightBlockColor=e.highlightBlockColor,r.wasmMesher=i,r.shaderCubeBlocks=e.rendererShaderCubeBlocks&&i,r.disableMesherConversionCache=!!t.isSafari,u1({apiEnabled:e.loadPlayerSkins}),r.smoothLighting=e.smoothLighting,r.shadingTheme=e.vanillaLook?"vanilla":"high-contrast",r.starfield=e.starfieldRendering,r.defaultSkybox=e.defaultSkybox,r.fov=e.fov,r.shaderCubeDebugMode=Or(e.rendererShaderCubeDebugMode)}function bf(n,e,t){e.keepChunksDistance=t.keepChunksDistance;let r=n.inWorldRenderingConfig;r.renderEars=t.renderEars,r.showHand=t.showHand,r.viewBobbing=t.viewBobbing,r.dayCycle=t.dayCycleAndLighting}function yf(n,e,t={}){n.bindRendererOptions(()=>e);let r=t.getWindowFocused?.()??!0,i=()=>{let s=e;if(L6(n,s,{isSafari:t.isSafari,isCypress:t.isCypress,windowFocused:r}),n.currentDisplay==="menu"){let o=n.backend?.getMenuBackground?.();o&&H6(o,s)}};return i(),t.onRegisterFocusHandlers?.({onFocus:()=>{r=!0,i()},onBlur:()=>{r=!1,i()}}),I6(e,i)}function _f(n,e,t){n.inWorldRenderingConfig.enableLighting=!t||e}E();x();k();R();import{proxy as U6}from"valtio";var ds=()=>U6({playerSkin:void 0,inWater:!1,waterBreathing:!1,backgroundColor:[0,0,0],ambientLight:0,directionalLight:0,eyeHeight:0,gameMode:void 0,lookingAtBlock:void 0,diggingBlock:void 0,movementState:"NOT_MOVING",onGround:!0,sneaking:!1,flying:!1,sprinting:!1,walkDist:0,prevWalkDist:0,bob:0,prevBob:0,itemUsageTicks:0,username:"",onlineMode:!1,cardinalLight:"default",lightingDisabled:!1,shouldHideHand:!1,heldItemMain:void 0,heldItemOff:void 0,perspective:"first_person",onFire:!1,fovMultiplier:1,cameraSpectatingEntity:void 0,team:void 0}),G6=n=>({isSpectator(){return n.gameMode==="spectator"},isSpectatingEntity(){return n.cameraSpectatingEntity!==void 0&&n.gameMode==="spectator"},isThirdPerson(){return this.isSpectatingEntity()?!1:n.perspective==="third_person_back"||n.perspective==="third_person_front"}}),N6=()=>({reactive:ds()}),us=(n,e,t)=>({...e,"minecraft:date":new Date});E();x();k();R();E();x();k();R();import*as Q5 from"three";import{Vec3 as u9}from"vec3";E();x();k();R();import{proxy as W6,getVersion as Vr,subscribe as ms}from"valtio";import{Vec3 as jr}from"vec3";function ps(n,e){let t=e??globalThis;return t.addEventListener("message",r=>{let{type:i,args:s,msgId:o}=r.data;if(n[i]){let a=n[i](...s);a instanceof Promise&&a.then(v=>{t.postMessage({type:"result",msgId:o,args:[v]})})}}),null}var gs=(n,e=!0)=>{let t=0;return new Proxy({},{get(r,i){return i==="transfer"?(...s)=>new Proxy({},{get(o,a){return(...v)=>{n.postMessage({type:a,args:v},s)}}}):(...s)=>{let o=t++,a=e?s.filter(v=>v instanceof ArrayBuffer||v instanceof MessagePort||typeof ImageBitmap<"u"&&v instanceof ImageBitmap||typeof OffscreenCanvas<"u"&&v instanceof OffscreenCanvas||typeof ImageData<"u"&&v instanceof ImageData):[];return n.postMessage({type:i,msgId:o,args:s},a),{then(v){let l=({data:c})=>{c.type==="result"&&c.msgId===o&&(v(c.args[0]),n.removeEventListener("message",l))};n.addEventListener("message",l)}}}}})},bs=!1,_5={toWorker:0,fromWorker:0},fs=null,V6=()=>{fs==null&&(typeof window>"u"||(fs=setInterval(()=>{globalThis.debugWorkerSyncStats={..._5},_5.toWorker=0,_5.fromWorker=0},1e3)))},f1=n=>{V6(),n==="toWorker"?_5.toWorker++:_5.fromWorker++};var j6=()=>Math.random().toString(36).slice(2,15)+Math.random().toString(36).slice(2,15),Y6=(n,e,t)=>{if(e.length===0)return;let r=n;for(let i=0;i<e.length-1;i++){let s=e[i];(r[s]==null||typeof r[s]!="object")&&(r[s]={}),r=r[s]}r[e[e.length-1]]=t},Q6=(n,e)=>{if(e.length===0)return;let t=n;for(let r=0;r<e.length-1;r++)if(t=t[e[r]],t==null)return;delete t[e[e.length-1]]},Wr=(n,e)=>{if(n==null||typeof n!="object")return n;if(n instanceof jr)return{x:n.x,y:n.y,z:n.z,__restorer:"Vec3"};if(typeof n.prepareForTransfer=="function")return n.prepareForTransfer(e);if(ArrayBuffer.isView(n))return n;if(Array.isArray(n))return n.map(r=>Wr(r,e));if(Vr(n)!==void 0)return w5(n);let t={};for(let r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=Wr(n[r],e));return t},K6=(n,e)=>{let t=[];for(let r of n){let i=r[0];i==="delete"?t.push({kind:"delete",path:r[1]}):i==="set"&&t.push({kind:"set",path:r[1],value:Wr(r[2],e)})}return t},ys=(n,e,t,r,i)=>{if(e.length===0)return;let s=K6(e,t);if(s.length!==0)try{t.postMessage({type:"sync",syncId:n,ops:s}),r==="toWorker"&&f1("toWorker")}catch{for(let a of s)a.kind==="set"&&ot(a.value)}},_s=(n,e,t,r=!1)=>{for(let i of e)i.kind==="delete"?Q6(n,i.path):Y6(n,i.path,E5(i.value,[],t,!1,!1));r==="fromWorker"&&f1("fromWorker")},ws=(n,e,t,r,i)=>{try{let s=w5(e);t.postMessage({type:"sync",syncId:n,value:s}),r==="toWorker"&&f1("toWorker")}catch{ot(e)}},As=(n,e,t,r=!1)=>{Object.assign(n,E5(e,[],t,!1,!1)),r==="fromWorker"&&f1("fromWorker")},Nr=(n,e,t,r,i)=>{let s=n.__syncFromWorker||e.__syncFromWorker,o=n.__syncToWorker||e.__syncToWorker;if(!o&&!s&&!r)return;let a=j6();if(n.__syncId=a,o||r){r&&o!==!1&&ms(e,l=>{ys(a,l,t,"toWorker",`toWorker:${i}`)});let v=n.__syncToWorkerInterval??e.__syncToWorkerInterval??0;v>0&&!r&&setInterval(()=>{ws(a,e,t,"toWorker",`toWorker:interval:${i}`)},v)}e.__syncFromWorker&&t.addEventListener("message",v=>{v.data.type==="sync"&&v.data.syncId===a&&(v.data.ops?_s(e,v.data.ops,t,"fromWorker"):v.data.value&&As(e,v.data.value,t,"fromWorker"))})},w5=n=>{if(Vr(n)===void 0)return n;if(Array.isArray(n))return n.map(w5);if(typeof n=="object"&&n!==null){let e={};for(let t in n)Object.prototype.hasOwnProperty.call(n,t)&&(e[t]=w5(n[t]));return e}return n},A5=(n,e,t=!0,r=!0,i=!1)=>{var a,v;let s=n,o={};for(let l in n)if(Object.prototype.hasOwnProperty.call(n,l)){if(t&&typeof n[l]=="function")continue;if(n[l]instanceof Date||n[l]instanceof RegExp||n[l]instanceof Map||n[l]instanceof Set||n[l]instanceof WeakMap||n[l]instanceof WeakSet,n[l]instanceof jr){o[l]={x:n[l].x,y:n[l].y,z:n[l].z},o[l].__restorer="Vec3";continue}if(o[l]=n[l],typeof n[l]=="object"&&n[l]!==null){if(n[l].prepareForTransfer){o[l]=n[l].prepareForTransfer(e);continue}let c=Vr(n[l])!==void 0;o[l]=c?w5(n[l]):n[l],n[l].__syncFromWorker&&(o[l].__syncFromWorker=!0),n[l].__syncToWorker&&(o[l].__syncToWorker=!0),n[l].__syncFromWorkerInterval&&(o[l].__syncFromWorkerInterval=n[l].__syncFromWorkerInterval),n[l].__syncToWorkerInterval&&(o[l].__syncToWorkerInterval=n[l].__syncToWorkerInterval);let u=n[l].__syncToWorker!==!1&&!i&&c&&!n[l].__syncFromWorker;if((a=o[l]).__syncToWorker??(a.__syncToWorker=u),c&&((v=o[l]).__valtio??(v.__valtio=!0)),o[l].__syncToWorker&&c){Nr(o[l],s[l],e,!0,l);continue}if(o[l].__syncFromWorker||o[l].__syncToWorker){Nr(o[l],s[l],e,c,l);continue}Nr(o[l],s[l],e,!1,l),o[l]=A5(o[l],e,t,!1,c)}}return o},ot=(n,e=[])=>{for(let t in n)if(Object.prototype.hasOwnProperty.call(n,t)){if(!n[t])continue;typeof n[t]=="object"&&n[t]!==null&&ot(n[t],[...e,t]);try{structuredClone(n[t])}catch{}}},hs=new WeakMap,J6=(n,e,t)=>{if(!n.__syncId)return;let r=n.__syncId,i=hs.get(e);if(i||(i=new Set,hs.set(e,i)),!i.has(r)&&(i.add(r),n.__syncToWorker&&e.addEventListener("message",s=>{s.data.type==="sync"&&s.data.syncId===r&&(s.data.ops?_s(n,s.data.ops,e):s.data.value&&As(n,s.data.value,e))}),n.__syncFromWorker)){n.__valtio&&ms(n,o=>{ys(r,o,e,"fromWorker",`fromWorker:${t}`)});let s=n.__syncFromWorkerInterval??0;s>0&&!n.__valtio&&setInterval(()=>{ws(r,n,e,"fromWorker",`fromWorker:interval:${t}`)},s)}},Z6=[{restorerName:"Vec3",restoreTransferred(n,e){return new jr(n.x,n.y,n.z)}}];var E5=(n,e,t,r=!0,i=!0)=>{let s=[...Z6,...e],o=(a,v)=>{if(a==null||typeof a!="object")return a;if(a.__restorer){let l=s.find(u=>u.restorerName?u.restorerName===a.__restorer:u.name===a.__restorer);if(l)return l.restoreTransferred(a,t);let c=new Error(`Restorer ${a.__restorer} not found`);if(typeof r=="function")r(c);else if(r)throw c;return a}if(Array.isArray(a))return a.map((l,c)=>o(l,`${v}[${c}]`));for(let l in a){if(!Object.prototype.hasOwnProperty.call(a,l))continue;let c=a[l];c!=null&&typeof c=="object"&&(a[l]=o(c,`${v}.${l}`))}return a.__valtio&&(a=W6(a)),i&&J6(a,t,v),a};return o(n,"root")};E();x();k();R();var h1=class{constructor(e){this.nonReactiveState=e;d(this,"events",[]);d(this,"frozenEvents",[]);d(this,"lastSecondEvents",[]);d(this,"currentFrameStartTime",null);d(this,"lastInteractionTime",0);d(this,"lastSecondUpdateTime",0);d(this,"timeWindowMs",5e3);d(this,"lastSecondWindowMs",1e3);d(this,"maxEvents",500);d(this,"lastSecondUpdateInterval",1e3);this.nonReactiveState.renderer||(this.nonReactiveState.renderer={timeline:{live:[],frozen:[],lastSecond:[]}}),this.nonReactiveState.renderer.timeline||(this.nonReactiveState.renderer.timeline={live:[],frozen:[],lastSecond:[]}),setInterval(()=>{this.updateLastSecondTimeline()},this.lastSecondUpdateInterval)}markFrameStart(){this.currentFrameStartTime=performance.now(),this.addEvent({type:"frameStart",timestamp:this.currentFrameStartTime})}markFrameEnd(){if(!this.currentFrameStartTime)return;let e=performance.now(),t=e-this.currentFrameStartTime;this.addEvent({type:"frameEnd",timestamp:e,duration:t}),this.currentFrameStartTime=null}markCameraUpdate(e){if(!e)return;let t=performance.now();this.lastInteractionTime=t,this.addEvent({type:"cameraUpdate",timestamp:t}),this.frozenEvents=[...this.events],this.trimEvents(this.frozenEvents),this.syncFrozenEvents()}markFrameDisplay(){this.addEvent({type:"frameDisplay",timestamp:performance.now()})}addEvent(e){this.events.push(e),this.lastSecondEvents.push(e),this.trimEvents(this.events),this.trimLastSecondEvents(),this.syncLiveEvents()}trimEvents(e){let r=performance.now()-this.timeWindowMs;for(;e.length>0&&e[0].timestamp<r;)e.shift();e.length>this.maxEvents&&e.splice(0,e.length-this.maxEvents)}trimLastSecondEvents(){let t=performance.now()-this.lastSecondWindowMs;for(;this.lastSecondEvents.length>0&&this.lastSecondEvents[0].timestamp<t;)this.lastSecondEvents.shift()}updateLastSecondTimeline(){let e=performance.now();e-this.lastSecondUpdateTime<this.lastSecondUpdateInterval||(this.lastSecondUpdateTime=e,this.trimLastSecondEvents(),this.syncLastSecondEvents())}syncLiveEvents(){this.nonReactiveState.renderer.timeline.live=[...this.events]}syncFrozenEvents(){this.nonReactiveState.renderer.timeline.frozen=[...this.frozenEvents]}syncLastSecondEvents(){this.nonReactiveState.renderer.timeline.lastSecond=[...this.lastSecondEvents]}clear(){this.events=[],this.frozenEvents=[],this.lastSecondEvents=[],this.syncLiveEvents(),this.syncFrozenEvents(),this.syncLastSecondEvents()}};E();x();k();R();import*as Q from"three";import{Vec3 as G0}from"vec3";import i9 from"prismarine-chat";E();x();k();R();var q6=(n,e)=>{try{return JSON.parse(n)}catch{return null}},X6={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"},m1=(n,e,t,r=s=>{},i=(s,o)=>Ve(s,o))=>{let a=[16,9],v=a[0]-a[1],l=v/16,c="front_text"in n?n.front_text.messages:[n.Text1,n.Text2,n.Text3,n.Text4];if(!c.some(g=>g!=="null"))return;let u=i(16*40,v*40),h=u.getContext("2d");r(h);let p=("front_text"in n?n.front_text.color:n.Color)||"black";for(let[g,y]of c.slice(0,4).entries())y!=="null"&&Yr(y,t,u,64,p,64*(g+1)+(e?0:-8));return u},Yr=(n,e,t,r,i,s=0)=>{let o=!1,a=typeof n=="string"&&(n?.startsWith("{")||n?.startsWith('"'))?q6(n??'""',"sign text"):n;if(!a||typeof a!="object"&&typeof a!="string")return;let v=t.getContext("2d");if(!v)throw new Error("Could not get 2d context");v.imageSmoothingEnabled=!1,v.font=`${r}px mojangles`;let l=new e(a),c=[],u=!1,h="",p=s,g=[],y=(S,C)=>{S.text!==null&&S.text!==void 0&&S.text;let M=S.text===null||S.text===void 0?void 0:String(S.text),I={color:S.color??C?.color,underlined:S.underlined??C?.underlined,strikethrough:S.strikethrough??C?.strikethrough,bold:S.bold??C?.bold,italic:S.italic??C?.italic};if(u=u||I.underlined||I.strikethrough||!1,M?.includes(`
|
|
286
|
+
`;X1=6,c0={LX_BITS:4,LY_BITS:4,LZ_BITS:4,FACE_BITS:3,TINT_BITS:8,AO_BITS_PER_CORNER:2,NUM_CORNERS:4,LX_SHIFT:0,LY_SHIFT:4,LZ_SHIFT:8,FACE_SHIFT:12,TINT_SHIFT:15,AO_SHIFT:23,TRANSPARENT_SHIFT:31},ra={TEX_INDEX_BITS:12,DIAGONAL_FLAG_SHIFT:12,SECTION_Y_SHIFT:13,SECTION_Y_BITS:5,EMPTY_SHIFT:18,SECTION_X_HI_SHIFT:19,SECTION_Z_HI_SHIFT:25,SECTION_HI_BITS:6,SPARE_BITS:1},Cv={SECTION_BITS:22,SECTION_MASK:(1<<22)-1,LO_BITS:16,HI_BITS:6,SECTION_BIAS:2097152}});var $1,ia=Xe(()=>{"use strict";E();x();k();R();$1=class{constructor(e){d(this,"atlasWidth");d(this,"atlasHeight");d(this,"tileSize");d(this,"tilesPerRow");d(this,"maxTiles");d(this,"valid");this.atlasWidth=e.width,this.atlasHeight=e.height,this.tileSize=e.tileSize,this.tilesPerRow=Math.floor(this.atlasWidth/this.tileSize),this.maxTiles=this.tilesPerRow*Math.floor(this.atlasHeight/this.tileSize),this.valid=this.atlasWidth===1024&&this.atlasHeight===1024&&this.tileSize===16&&this.maxTiles<=4096}isValid(){return this.valid}getTilesPerRow(){return this.tilesPerRow}tileIndexFromPixelCoords(e,t){if(!this.valid)return-1;let r=Math.floor(e/this.tileSize),i=Math.floor(t/this.tileSize);if(r<0||r>=this.tilesPerRow||i<0)return-1;let s=i*this.tilesPerRow+r;return s>=this.maxTiles?-1:s}tileIndexFromTextureEntry(e){return!this.valid||e.su!==this.tileSize||e.sv!==this.tileSize?-1:this.tileIndexFromPixelCoords(e.u,e.v)}tileIndexFromTextureName(e,t){if(!this.valid)return-1;let r=t.textures[e];if(!r&&e.includes(":")&&(r=t.textures[e.split(":")[1]]),!r&&e.includes("/")&&(r=t.textures[e.split("/")[1]]),r||(r=t.textures[`block/${e}`]),!r){let i=e.replace(/^block\//,"");r=t.textures[i]}return r?this.tileIndexFromTextureEntry(r):-1}}});import*as d0 from"three";var er,na=Xe(()=>{"use strict";E();x();k();R();er=class n{constructor(){d(this,"entries",[{r:1,g:1,b:1}]);d(this,"colorToIndex",new Map);d(this,"categoryBiomeToIndex",new Map);d(this,"texture",null);d(this,"ready",!1)}packColor(e,t,r){let i=Math.round(e*255),s=Math.round(t*255),o=Math.round(r*255);return i<<16|s<<8|o}add(e,t,r,i,s){let o=this.packColor(e,t,r),a=`${i}:${s}`,v=this.categoryBiomeToIndex.get(a);if(v!==void 0)return v;let l=this.colorToIndex.get(o);if(l!==void 0)return this.categoryBiomeToIndex.set(a,l),l;let c=this.entries.length;return this.entries.push({r:e,g:t,b:r}),this.colorToIndex.set(o,c),this.categoryBiomeToIndex.set(a,c),c}getTintIndex(e,t,r,i){return e===void 0?0:e===0?t==="redstone_wire"?this.categoryBiomeToIndex.get(`redstone:${r.power}`)??this.categoryBiomeToIndex.get("redstone:0")??0:t==="birch_leaves"||t==="spruce_leaves"||t==="lily_pad"?this.categoryBiomeToIndex.get(`constant:${t}`)??this.categoryBiomeToIndex.get("constant:default")??0:t.includes("leaves")||t==="vine"?this.categoryBiomeToIndex.get(`foliage:${i}`)??this.categoryBiomeToIndex.get("foliage:plains")??0:this.categoryBiomeToIndex.get(`grass:${i}`)??this.categoryBiomeToIndex.get("grass:plains")??0:0}getEntry(e){return this.entries[e]??this.entries[0]}get size(){return this.entries.length}buildTextureData(){let e=new Float32Array(1024);for(let t=0;t<this.entries.length&&t<256;t++){let r=this.entries[t];e[t*4]=r.r,e[t*4+1]=r.g,e[t*4+2]=r.b,e[t*4+3]=1}return e}createTexture(){this.texture&&(this.texture.dispose(),this.texture=null,this.ready=!1);let e=this.buildTextureData(),t=new d0.DataTexture(e,256,1,d0.RGBAFormat,d0.FloatType);return t.minFilter=d0.NearestFilter,t.magFilter=d0.NearestFilter,t.wrapS=d0.ClampToEdgeWrapping,t.wrapT=d0.ClampToEdgeWrapping,t.needsUpdate=!0,this.texture=t,this.ready=!0,t}getTexture(){return this.texture}isReady(){return this.ready}static fromTintsData(e){let t=new n;function r(i){let s=(i>>16&255)/255,o=(i>>8&255)/255,a=(i&255)/255;return[s,o,a]}if(e.grass){let i=r(e.grass.default);for(let{keys:s,color:o}of e.grass.data??[]){let a=r(o);for(let v of s)t.add(a[0],a[1],a[2],"grass",v)}t.add(i[0],i[1],i[2],"grass","plains")}if(e.foliage){let i=r(e.foliage.default);for(let{keys:s,color:o}of e.foliage.data??[]){let a=r(o);for(let v of s)t.add(a[0],a[1],a[2],"foliage",v)}t.add(i[0],i[1],i[2],"foliage","plains")}if(e.redstone){let i=r(e.redstone.default);for(let{keys:s,color:o}of e.redstone.data??[]){let a=r(o);for(let v of s)t.add(a[0],a[1],a[2],"redstone",v)}t.add(i[0],i[1],i[2],"redstone","0")}if(e.constant){let i=r(e.constant.default);for(let{keys:s,color:o}of e.constant.data??[]){let a=r(o);for(let v of s)t.add(a[0],a[1],a[2],"constant",v)}t.add(i[0],i[1],i[2],"constant","default")}return t}}});import sa from"mc-assets/dist/blocksAtlases.json";function Bv(){let n=globalThis.loadedData?.tints;return n||(oa||(oa=!0),null)}function rr(){let n=Bv();if(!n)return null;if(tr||(tr=er.fromTintsData(n),tr.createTexture()),!Vi){let e=sa.latest??sa;Vi=new $1({width:e.width,height:e.height,tileSize:e.tileSize??16,suSv:e.suSv??16,textures:e.textures??{}})}return{tintPalette:tr,textureIndexMapping:Vi}}function aa(){return 1<<ra.EMPTY_SHIFT>>>0}var Jt,tr,Vi,oa,Zt=Xe(()=>{"use strict";E();x();k();R();gt();ia();na();Jt=4,tr=null,Vi=null,oa=!1});import*as Ce from"three";function Pv(n,e){let t=new Ce.InstancedBufferGeometry,r=new Float32Array(X1*3);t.setAttribute("position",new Ce.BufferAttribute(r,3));let i=new Uint32Array(e),s=new Uint32Array(e),o=new Uint32Array(e),a=new Uint32Array(e),v=Jt;for(let l=0;l<e;l++)i[l]=n[l*v],s[l]=n[l*v+1],o[l]=n[l*v+2],a[l]=n[l*v+3];return t.setAttribute("a_w0",new Ce.InstancedBufferAttribute(i,1)),t.setAttribute("a_w1",new Ce.InstancedBufferAttribute(s,1)),t.setAttribute("a_w2",new Ce.InstancedBufferAttribute(o,1)),t.setAttribute("a_w3",new Ce.InstancedBufferAttribute(a,1)),t.instanceCount=e,t.boundingBox=new Ce.Box3(new Ce.Vector3(-8,-8,-8),new Ce.Vector3(8,8,8)),t.boundingSphere=new Ce.Sphere(new Ce.Vector3(0,0,0),Math.sqrt(3*8**2)),t}function Iv(n){n.raycast=(e,t)=>{let{geometry:r}=n;if(!r.boundingBox||(va.copy(r.boundingBox).applyMatrix4(n.matrixWorld),!e.ray.intersectBox(va,ji)))return;let i=e.ray.origin.distanceTo(ji);t.push({distance:i,point:ji.clone(),object:n})}}function ir(n,e){let t=Pv(n.words,n.count),r=new Ce.Mesh(t,e);return r.name="shaderMesh",r.matrixAutoUpdate=!1,r.frustumCulled=!1,Iv(r),r}function Yi(n){n.geometry.dispose()}var va,ji,Qi=Xe(()=>{"use strict";E();x();k();R();gt();Zt();va=new Ce.Box3,ji=new Ce.Vector3});var ha={};q5(ha,{applyWorldGeometryExport:()=>Dv,createMeshesFromExport:()=>ua,downloadWorldGeometry:()=>Ki,exportWorldGeometry:()=>ca,loadTextureFromDataUrl:()=>fa,loadWorldGeometryFromUrl:()=>Hv});import*as Be from"three";function ca(n,e,t,r=!1){let i=[];for(let[o,a]of Object.entries(n.sectionObjects)){let v=a.children.find(A=>A.name==="mesh");if(!v?.geometry)continue;let{geometry:l}=v,c=l.getAttribute("position"),u=l.getAttribute("normal"),h=l.getAttribute("color"),p=l.getAttribute("uv"),g=l.index;if(!c||!g)continue;let y=n.sceneOrigin.getWorldPosition(v);i.push({key:o,position:{x:y?.x??n.sceneOrigin.toWorldX(v.position.x),y:y?.y??n.sceneOrigin.toWorldY(v.position.y),z:y?.z??n.sceneOrigin.toWorldZ(v.position.z)},geometry:{positions:[...c.array],normals:u?[...u.array]:[],colors:h?[...h.array]:[],uvs:p?[...p.array]:[],indices:[...g.array]}})}let s={version:n.version??"unknown",exportedAt:new Date().toISOString(),camera:{position:e,rotation:t},sections:i};if(r&&n.material.map){let o=document.createElement("canvas"),a=n.material.map,{image:v}=a;v&&(o.width=v.width,o.height=v.height,o.getContext("2d").drawImage(v,0,0),s.textureAtlasDataUrl=o.toDataURL("image/png"))}return s}function Ki(n,e,t,r="world-geometry.json",i=!1){let s=ca(n,e,t,i),o=JSON.stringify(s),a=new Blob([o],{type:"application/json"}),v=URL.createObjectURL(a),l=document.createElement("a");l.href=v,l.download=r,l.click(),URL.revokeObjectURL(v)}async function Hv(n){let e=await fetch(n);if(!e.ok)throw new Error(`Failed to fetch world geometry: ${e.statusText}`);return e.json()}function da(n){let e=n.map??n.map;if(!e)return null;let t=q1();t.uniforms.u_atlas.value=e;let r=rr();if(!r)return null;let{tintPalette:i}=r;return i.isReady()||i.createTexture(),t.uniforms.u_tintPalette.value=i.getTexture(),t}function ua(n,e,t){let r=[],i=t??da(e);for(let s of n.sections){let o=new Be.Group;if(o.name="chunk",s.geometry.positions.length>0&&s.geometry.indices.length>0){let l=new Be.BufferGeometry;l.setAttribute("position",new Be.Float32BufferAttribute(s.geometry.positions,3)),s.geometry.normals.length&&l.setAttribute("normal",new Be.Float32BufferAttribute(s.geometry.normals,3)),s.geometry.colors.length&&l.setAttribute("color",new Be.Float32BufferAttribute(s.geometry.colors,3)),s.geometry.uvs.length&&l.setAttribute("uv",new Be.Float32BufferAttribute(s.geometry.uvs,2));let u=Math.max(...s.geometry.indices)>65535?Uint32Array:Uint16Array;l.setIndex(new Be.BufferAttribute(new u(s.geometry.indices),1));let h=new Be.Mesh(l,e);h.position.set(s.position.x,s.position.y,s.position.z),h.name="mesh",o.add(h)}let v=s.shaderCubes;if(v&&v.count>0&&i){let l=ir(v,i);l.position.set(s.position.x,s.position.y,s.position.z),o.add(l)}o.children.length>0&&r.push(o)}return r}async function fa(n){return new Promise((e,t)=>{let r=new Image;r.onload=()=>{let i=new Be.Texture(r);i.magFilter=Be.NearestFilter,i.minFilter=Be.NearestFilter,i.needsUpdate=!0,i.flipY=!1,e(i)},r.onerror=t,r.src=n})}async function Dv(n,e){let{scene:t,renderUpdateEmitter:r,material:i}=n,s=t.getObjectByName(la);s&&(t.remove(s),Ov(s));let o=!!e.textureAtlasDataUrl,a;if(o&&e.textureAtlasDataUrl){let u=await fa(e.textureAtlasDataUrl);a=new Be.MeshLambertMaterial({map:u,vertexColors:!0,transparent:!0,alphaTest:.1}),a.name="geometry-export-material"}else a=i;let v=e.sections.some(u=>(u.shaderCubes?.count??0)>0)?da(a):null,l=ua(e,a,v),c=new Be.Group;c.name=la,o&&(c.userData.geometryExportMaterial=a);for(let u of l)c.add(u);return t.add(c),r.emit("update"),l.length}var la,Ov,Ji=Xe(()=>{"use strict";E();x();k();R();Zt();gt();Qi();la="geometry-export-root";Ov=n=>{n.traverse(t=>{t.isMesh&&t.geometry?.dispose()});let e=n.userData?.geometryExportMaterial;e&&(e.map?.dispose?.(),e.dispose?.())}});E();x();k();R();E();x();k();R();E();x();k();R();E();x();k();R();import{proxy as z2}from"valtio";E();x();k();R();E();x();k();R();var _r=()=>({longRenderTime:!1,constantLongRenderTime:!1,tooManyEntities:!1,tooManyTextures:!1,unknownReason:!1});E();x();k();R();var r1=30;var wr=45,Ar=100;E();x();k();R();var l5=class{constructor(e){this.factors=e;d(this,"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,r=Math.max(0,e.totalMs-e.entitiesMs),i=e.totalMs>=30,s=this.renderTimeHistory.length,o=this.renderTimeHistory.filter(h=>h>=30).length,a=s>=8&&o/s>=.65,v=e.loadedTextureCount>=100,l=t&&e.entitiesMs>=8&&r<=20,u=t&&!(i||a||l||v);this.factors.longRenderTime=i,this.factors.constantLongRenderTime=a,this.factors.tooManyEntities=l,this.factors.tooManyTextures=v,this.factors.unknownReason=u}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}};E();x();k();R();var v6=[{key:"longRenderTime",code:"LR"},{key:"constantLongRenderTime",code:"CLR"},{key:"tooManyEntities",code:"ENT"},{key:"tooManyTextures",code:"TEX"},{key:"unknownReason",code:"UNK"}];function Er(n){let e=v6.filter(({key:t})=>n[t]).map(({code:t})=>t);return e.length>0?e.join("+"):""}var c5={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,moduleStates:{}},L2={fpsLimit:void 0,sceneBackground:"lightblue",timeoutRendering:!1},El=(n={})=>z2({...c5,...n}),J0=()=>({reactive:z2({world:{chunksLoaded:{},heightmaps:{},allChunksLoaded:!1,mesherWork:!1,instabilityFactors:_r(),intersectMedia:null},renderer:"...",preventEscapeMenu:!1}),nonReactive:{fps:0,worstRenderTime:0,avgRenderTime:0,world:{chunksLoadedCount:0,chunksTotalNumber:0,chunksFullInfo:"-"},renderer:{timeline:{live:[],frozen:[],lastSecond:[]}}}});E();x();k();R();import{proxy as l6}from"valtio";var xr=()=>l6({playerSkin:void 0,inWater:!1,waterBreathing:!1,backgroundColor:[0,0,0],ambientLight:0,directionalLight:0,eyeHeight:0,gameMode:void 0,lookingAtBlock:void 0,diggingBlock:void 0,movementState:"NOT_MOVING",onGround:!0,sneaking:!1,flying:!1,sprinting:!1,walkDist:0,prevWalkDist:0,bob:0,prevBob:0,itemUsageTicks:0,username:"",onlineMode:!1,cardinalLight:"default",lightingDisabled:!1,shouldHideHand:!1,heldItemMain:void 0,heldItemOff:void 0,perspective:"first_person",onFire:!1,fovMultiplier:1,cameraSpectatingEntity:void 0,team:void 0}),U2=n=>({isSpectator(){return n.gameMode==="spectator"},isSpectatingEntity(){return n.cameraSpectatingEntity!==void 0&&n.gameMode==="spectator"},isThirdPerson(){return this.isSpectatingEntity()?!1:n.perspective==="third_person_back"||n.perspective==="third_person_front"}}),G2=()=>({reactive:xr()});E();x();k();R();import{Vec3 as A6}from"vec3";import{proxy as is}from"valtio";E();x();k();R();E();x();k();R();E();x();k();R();E();x();k();R();var i1={},N2=!1;function c6(){if(N2)return i1;N2=!0;var n=typeof Reflect=="object"?Reflect:null,e=n&&typeof n.apply=="function"?n.apply:function(M,I,B){return Function.prototype.apply.call(M,I,B)},t;n&&typeof n.ownKeys=="function"?t=n.ownKeys:Object.getOwnPropertySymbols?t=function(M){return Object.getOwnPropertyNames(M).concat(Object.getOwnPropertySymbols(M))}:t=function(M){return Object.getOwnPropertyNames(M)};function r(C){}var i=Number.isNaN||function(M){return M!==M};function s(){s.init.call(this)}i1=s,i1.once=b,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var o=10;function a(C){if(typeof C!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof C)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(C){if(typeof C!="number"||C<0||i(C))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+C+".");o=C}}),s.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(M){if(typeof M!="number"||M<0||i(M))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+M+".");return this._maxListeners=M,this};function v(C){return C._maxListeners===void 0?s.defaultMaxListeners:C._maxListeners}s.prototype.getMaxListeners=function(){return v(this)},s.prototype.emit=function(M){for(var I=[],B=1;B<arguments.length;B++)I.push(arguments[B]);var H=M==="error",G=this._events;if(G!==void 0)H=H&&G.error===void 0;else if(!H)return!1;if(H){var O;if(I.length>0&&(O=I[0]),O instanceof Error)throw O;var j=new Error("Unhandled error."+(O?" ("+O.message+")":""));throw j.context=O,j}var J=G[M];if(J===void 0)return!1;if(typeof J=="function")e(J,this,I);else for(var Z=J.length,$=g(J,Z),B=0;B<Z;++B)e($[B],this,I);return!0};function l(C,M,I,B){var H,G,O;if(a(I),G=C._events,G===void 0?(G=C._events=Object.create(null),C._eventsCount=0):(G.newListener!==void 0&&(C.emit("newListener",M,I.listener?I.listener:I),G=C._events),O=G[M]),O===void 0)O=G[M]=I,++C._eventsCount;else if(typeof O=="function"?O=G[M]=B?[I,O]:[O,I]:B?O.unshift(I):O.push(I),H=v(C),H>0&&O.length>H&&!O.warned){O.warned=!0;var j=new Error("Possible EventEmitter memory leak detected. "+O.length+" "+String(M)+" listeners added. Use emitter.setMaxListeners() to increase limit");j.name="MaxListenersExceededWarning",j.emitter=C,j.type=M,j.count=O.length}return C}s.prototype.addListener=function(M,I){return l(this,M,I,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(M,I){return l(this,M,I,!0)};function c(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function u(C,M,I){var B={fired:!1,wrapFn:void 0,target:C,type:M,listener:I},H=c.bind(B);return H.listener=I,B.wrapFn=H,H}s.prototype.once=function(M,I){return a(I),this.on(M,u(this,M,I)),this},s.prototype.prependOnceListener=function(M,I){return a(I),this.prependListener(M,u(this,M,I)),this},s.prototype.removeListener=function(M,I){var B,H,G,O,j;if(a(I),H=this._events,H===void 0)return this;if(B=H[M],B===void 0)return this;if(B===I||B.listener===I)--this._eventsCount===0?this._events=Object.create(null):(delete H[M],H.removeListener&&this.emit("removeListener",M,B.listener||I));else if(typeof B!="function"){for(G=-1,O=B.length-1;O>=0;O--)if(B[O]===I||B[O].listener===I){j=B[O].listener,G=O;break}if(G<0)return this;G===0?B.shift():y(B,G),B.length===1&&(H[M]=B[0]),H.removeListener!==void 0&&this.emit("removeListener",M,j||I)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(M){var I,B,H;if(B=this._events,B===void 0)return this;if(B.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):B[M]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete B[M]),this;if(arguments.length===0){var G=Object.keys(B),O;for(H=0;H<G.length;++H)O=G[H],O!=="removeListener"&&this.removeAllListeners(O);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(I=B[M],typeof I=="function")this.removeListener(M,I);else if(I!==void 0)for(H=I.length-1;H>=0;H--)this.removeListener(M,I[H]);return this};function h(C,M,I){var B=C._events;if(B===void 0)return[];var H=B[M];return H===void 0?[]:typeof H=="function"?I?[H.listener||H]:[H]:I?A(H):g(H,H.length)}s.prototype.listeners=function(M){return h(this,M,!0)},s.prototype.rawListeners=function(M){return h(this,M,!1)},s.listenerCount=function(C,M){return typeof C.listenerCount=="function"?C.listenerCount(M):p.call(C,M)},s.prototype.listenerCount=p;function p(C){var M=this._events;if(M!==void 0){var I=M[C];if(typeof I=="function")return 1;if(I!==void 0)return I.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function g(C,M){for(var I=new Array(M),B=0;B<M;++B)I[B]=C[B];return I}function y(C,M){for(;M+1<C.length;M++)C[M]=C[M+1];C.pop()}function A(C){for(var M=new Array(C.length),I=0;I<M.length;++I)M[I]=C[I].listener||C[I];return M}function b(C,M){return new Promise(function(I,B){function H(O){C.removeListener(M,G),B(O)}function G(){typeof C.removeListener=="function"&&C.removeListener("error",H),I([].slice.call(arguments))}S(C,M,G,{once:!0}),M!=="error"&&w(C,H,{once:!0})})}function w(C,M,I){typeof C.on=="function"&&S(C,"error",M,I)}function S(C,M,I,B){if(typeof C.on=="function")B.once?C.once(M,I):C.on(M,I);else if(typeof C.addEventListener=="function")C.addEventListener(M,function H(G){B.once&&C.removeEventListener(M,H),I(G)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof C)}return i1}var n1=c6();n1.once;n1.once=function(n,e){return new Promise((t,r)=>{function i(...o){s!==void 0&&n.removeListener("error",s),t(o)}let s;e!=="error"&&(s=o=>{n.removeListener(name,i),r(o)},n.once("error",s)),n.once(e,i)})};n1.on=function(n,e){let t=[],r=[],i=null,s=!1,o={async next(){let l=t.shift();if(l)return createIterResult(l,!1);if(i){let c=Promise.reject(i);return i=null,c}return s?createIterResult(void 0,!0):new Promise((c,u)=>r.push({resolve:c,reject:u}))},async return(){n.removeListener(e,a),n.removeListener("error",v),s=!0;for(let l of r)l.resolve(createIterResult(void 0,!0));return createIterResult(void 0,!0)},throw(l){i=l,n.removeListener(e,a),n.removeListener("error",v)},[Symbol.asyncIterator](){return this}};return n.on(e,a),n.on("error",v),o;function a(...l){let c=r.shift();c?c.resolve(createIterResult(l,!1)):t.push(l)}function v(l){s=!0;let c=r.shift();c?c.reject(l):i=l,o.return()}};var{EventEmitter:Z0,defaultMaxListeners:Ll,init:Ul,listenerCount:Gl,on:Nl,once:Wl}=n1;import{Vec3 as q0}from"vec3";E();x();k();R();function d5(n){let e=n*2+1;if(e<=0)return[];let t=[],r=0,i=0,s=0,o=-1;for(let a=0;a<e*e;a++){if(Math.abs(r)<=e/2&&Math.abs(i)<=e/2&&t.push([r,i]),r===i||r<0&&r===-i||r>0&&r===1-i){let v=s;s=-o,o=v}r+=s,i+=o}return t}E();x();k();R();function Rr(n,e=0){if(e>16)return;if(n==null)return n;let t=typeof n;if(t==="function"||t==="symbol")return;if(t==="bigint")return n.toString();if(t!=="object"||n instanceof ArrayBuffer)return n;if(ArrayBuffer.isView(n)){let s=n;return s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength)}if(n instanceof Date)return n.toISOString();if(Array.isArray(n))return n.map(s=>Rr(s,e+1)).filter(s=>s!==void 0);let r=n;if(typeof r.x=="number"&&typeof r.y=="number"&&typeof r.z=="number"&&!("w"in r))return{x:r.x,y:r.y,z:r.z};let i={};for(let s of Object.keys(r)){if(s==="_client"||s==="_events"||s==="_eventsCount")continue;let o=Rr(r[s],e+1);o!==void 0&&(i[s]=o)}return i}function s1(n){return n.map(e=>Rr(e))}var Mt=n=>[Math.floor(n.x/16),Math.floor(n.z/16)],d6=n=>[Math.floor(n.x/16),Math.floor(n.y/16),Math.floor(n.z/16)],W2=async(n,e,t,r=1)=>{for(let i=0;i<n.length;i+=r)e&&await new Promise(s=>setTimeout(s,e)),await t(n[i],i)},Tt=new WeakMap,u5=class u5 extends Z0{static restoreTransferred(e,t){let r=new u5;if(!t)return r;let i=Tt.get(t);if(i)i.activeWorldView=r;else{let s=({data:o})=>{let v=Tt.get(t)?.activeWorldView;!v||o?.class!==u5.restorerName||o.type==="event"&&v.emit(o.eventName,...o.args)};t.addEventListener("message",s),i={activeWorldView:r,handler:s},Tt.set(t,i)}return r}static clearWorkerBridgeForTest(e){let t=Tt.get(e);t&&(e.removeEventListener("message",t.handler),Tt.delete(e))}static getWorkerBridgeListenerCountForTest(e){return Tt.has(e)?1:0}};d(u5,"restorerName","WorldViewWorker");var X0=u5,$0=class extends Z0{constructor(t,r,i=new q0(0,0,0)){super();this.world=t;this.viewDistance=r;d(this,"spiralNumber",0);d(this,"gotPanicLastTime",!1);d(this,"panicChunksReload",()=>{});d(this,"loadedChunks",{});d(this,"inLoading",!1);d(this,"chunkReceiveTimes",[]);d(this,"lastChunkReceiveTime",0);d(this,"lastChunkReceiveTimeAvg",0);d(this,"panicTimeout");d(this,"lastPos");d(this,"eventListeners",{});d(this,"debugChunksInfo",{});d(this,"waitingSpiralChunksLoad",{});d(this,"addWaitTime",1);d(this,"keepChunksDistance",0);d(this,"isPlayground",!1);d(this,"allowPositionUpdate",!0);d(this,"lastBiomeId",null);d(this,"lastPosCheck",null);this.lastPos=new q0(0,0,0).update(i)}prepareForTransfer(t){if(t){let r=this.emit.bind(this);this.emit=(i,...s)=>{r(i,...s),t.postMessage({class:X0.restorerName,type:"event",eventName:i,args:s1(s)})}}return{__restorer:X0.restorerName}}setBlockStateId(t,r){let i=this.world.setBlockStateId(t,r);if(i&&typeof i.then=="function")throw new Error("setBlockStateId returned promise (not supported)");this.emit("blockUpdate",{pos:t,stateId:r})}updateViewDistance(t){this.viewDistance=t,this.emit("renderDistance",t)}async init(t,r){this.updateViewDistance(this.viewDistance),this.emit("chunkPosUpdate",{pos:t}),r?.time?.timeOfDay!==void 0&&this.emit("time",r.time.timeOfDay),r?.entity&&this.emit("playerEntity",r.entity),this.emitterGotConnected(r);let[i,s]=Mt(t),o=d5(this.viewDistance).map(([a,v])=>new q0((i+a)*16,0,(s+v)*16));this.lastPos.update(t),await this._loadChunks(o,t)}chunkProgress(){if(this.panicTimeout&&clearTimeout(this.panicTimeout),this.chunkReceiveTimes.length>=5){let t=this.chunkReceiveTimes.reduce((i,s)=>i+s,0)/this.chunkReceiveTimes.length;this.lastChunkReceiveTimeAvg=t;let r=t*2+1e3;this.panicTimeout&&clearTimeout(this.panicTimeout),this.panicTimeout=setTimeout(()=>{!this.gotPanicLastTime&&this.inLoading&&(this.gotPanicLastTime=!0,this.panicChunksReload())},r)}}async _loadChunks(t,r){this.spiralNumber++;let{spiralNumber:i}=this;for(let o of Object.keys(this.waitingSpiralChunksLoad))this.waitingSpiralChunksLoad[o](!1),delete this.waitingSpiralChunksLoad[o];let s=!0;this.inLoading=!0,await W2(t,this.addWaitTime,async o=>{!s||this.loadedChunks[`${o.x},${o.z}`]||(this.world.getColumnAt(o)||(s=await new Promise(a=>{this.waitingSpiralChunksLoad[`${o.x},${o.z}`]=a})),s&&(await this.loadChunk(o,void 0,`spiral ${i} from ${r.x},${r.z}`),this.chunkProgress()))}),i===this.spiralNumber&&(this.panicTimeout&&clearTimeout(this.panicTimeout),this.inLoading=!1,this.gotPanicLastTime=!1,this.chunkReceiveTimes=[],this.lastChunkReceiveTime=0)}async loadChunk(t,r=!1,i="spiral"){var l,c;let[s,o]=Mt(this.lastPos),a=Math.abs(s-Math.floor(t.x/16)),v=Math.abs(o-Math.floor(t.z/16));if(a<=this.viewDistance&&v<=this.viewDistance){let u=await this.world.getColumnAt(t.y!==void 0?t:new q0(t.x,0,t.z));if(u){let h=u.toJson(),p={minY:u.minY??0,worldHeight:u.worldHeight??256};this.emit("loadChunk",{x:t.x,z:t.z,chunk:h,blockEntities:u.blockEntities,worldConfig:p,isLightUpdate:r}),this.loadedChunks[`${t.x},${t.z}`]=!0,(l=this.debugChunksInfo)[c=`${t.x},${t.z}`]??(l[c]={loads:[]}),this.debugChunksInfo[`${t.x},${t.z}`].loads.push({dataLength:h.length,reason:i,time:Date.now()})}else this.isPlayground&&this.emit("markAsLoaded",{x:t.x,z:t.z})}}unloadAllChunks(){for(let t of Object.keys(this.loadedChunks)){let[r,i]=t.split(",").map(Number);this.unloadChunk({x:r,z:i})}}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(i,s,o){if(typeof s!="string")return;let[a,v,l]=s.split(",").map(Number);return t.world.getBlock(new q0(a,v,l))?.entity}}))}updateBiome(t){try{if(!this.world.getBiome)return;let r=this.world.getBiome(t);r!==this.lastBiomeId&&(this.lastBiomeId=r,this.emit("biomeReset"))}catch{}}async updatePosition(t,r=!1){if(!this.allowPositionUpdate)return;let i=t.floored();if(!r&&this.lastPosCheck&&this.lastPosCheck.equals(i))return;this.lastPosCheck=i,this.updateBiome(t);let[s,o]=Mt(this.lastPos),[a,v]=Mt(t);if(s!==a||o!==v||r){this.emit("chunkPosUpdate",{pos:t});let l=[],c=r?this.viewDistance:this.viewDistance+this.keepChunksDistance;for(let h of Object.keys(this.loadedChunks)){let[p,g]=h.split(",").map(Number),y=new q0(p,0,g),[A,b]=Mt(y),w=Math.abs(a-A),S=Math.abs(v-b);(w>c||S>c)&&l.push(y)}for(let h of l)this.unloadChunk(h);let u=d5(this.viewDistance).map(([h,p])=>{let g=new q0((a+h)*16,0,(v+p)*16);if(!this.loadedChunks[`${g.x},${g.z}`])return g}).filter(h=>!!h);this.lastPos.update(t),this._loadChunks(u,t)}else this.emit("chunkPosUpdate",{pos:t}),this.lastPos.update(t)}};E();x();k();R();E();x();k();R();import $2 from"minecraft-data";import u6 from"mc-assets/dist/blocksAtlases.json";import f6 from"mc-assets/dist/itemsAtlases.json";import Ir from"mc-assets/dist/itemDefinitions.json";import h6 from"mc-assets/dist/blocksAtlasLatest.png";import m6 from"mc-assets/dist/blocksAtlasLegacy.png";import p6 from"mc-assets/dist/itemsAtlasLatest.png";import g6 from"mc-assets/dist/itemsAtlasLegacy.png";import b6 from"mc-assets/dist/textureReplacements/christmas";import{AtlasParser as et}from"mc-assets/dist/atlasParser";import Z2 from"mc-assets/dist/worldBlockProvider";E();x();k();R();var Cr=a5(V2(),1);import*as v1 from"three";E();x();k();R();E();x();k();R();var o1=class{constructor(e,t,r){this.name=e,this.fg=t,this.bg=r,this.PR=Math.round(window.devicePixelRatio||1),this.WIDTH=90*this.PR,this.HEIGHT=48*this.PR,this.TEXT_X=3*this.PR,this.TEXT_Y=2*this.PR,this.GRAPH_X=3*this.PR,this.GRAPH_Y=15*this.PR,this.GRAPH_WIDTH=84*this.PR,this.GRAPH_HEIGHT=30*this.PR,this.canvas=document.createElement("canvas"),this.canvas.width=90*this.PR,this.canvas.height=48*this.PR,this.canvas.style.width="90px",this.canvas.style.position="absolute",this.canvas.style.height="48px",this.canvas.style.cssText="width:90px;height:48px",this.context=this.canvas.getContext("2d"),this.context&&(this.context.font="bold "+9*this.PR+"px Helvetica,Arial,sans-serif",this.context.textBaseline="top",this.context.fillStyle=this.bg,this.context.fillRect(0,0,this.WIDTH,this.HEIGHT),this.context.fillStyle=this.fg,this.context.fillText(this.name,this.TEXT_X,this.TEXT_Y),this.context.fillRect(this.GRAPH_X,this.GRAPH_Y,this.GRAPH_WIDTH,this.GRAPH_HEIGHT),this.context.fillStyle=this.bg,this.context.globalAlpha=.9,this.context.fillRect(this.GRAPH_X,this.GRAPH_Y,this.GRAPH_WIDTH,this.GRAPH_HEIGHT))}update(e,t,r,i,s=0){let o=1/0,a=0;this.context&&(o=Math.min(o,e),a=Math.max(r,e),i=Math.max(i,t),this.context.fillStyle=this.bg,this.context.globalAlpha=1,this.context.fillRect(0,0,this.WIDTH,this.GRAPH_Y),this.context.fillStyle=this.fg,this.context.fillText(e.toFixed(s)+" "+this.name+" ("+o.toFixed(s)+"-"+parseFloat(a.toFixed(s))+")",this.TEXT_X,this.TEXT_Y),this.context.drawImage(this.canvas,this.GRAPH_X+this.PR,this.GRAPH_Y,this.GRAPH_WIDTH-this.PR,this.GRAPH_HEIGHT,this.GRAPH_X,this.GRAPH_Y,this.GRAPH_WIDTH-this.PR,this.GRAPH_HEIGHT),this.context.fillRect(this.GRAPH_X+this.GRAPH_WIDTH-this.PR,this.GRAPH_Y,this.PR,this.GRAPH_HEIGHT),this.context.fillStyle=this.bg,this.context.globalAlpha=.9,this.context.fillRect(this.GRAPH_X+this.GRAPH_WIDTH-this.PR,this.GRAPH_Y,this.PR,(1-t/i)*this.GRAPH_HEIGHT))}};var j2=class a1{constructor({logsPerSecond:e=20,samplesLog:t=100,samplesGraph:r=10,precision:i=2,minimal:s=!1,horizontal:o=!0,mode:a=0}={}){this.mode=a,this.horizontal=o,this.container=document.createElement("div"),this.container.style.cssText="position:fixed;top:0;left:0;opacity:0.9;z-index:10000;",s&&(this.container.style.cssText+="cursor:pointer"),this.gl=null,this.query=null,this.minimal=s,this.beginTime=(performance||Date).now(),this.prevTime=this.beginTime,this.prevCpuTime=this.beginTime,this.frames=0,this.averageCpu={logs:[],graph:[]},this.averageGpu={logs:[],graph:[]},this.queryCreated=!1,this.fpsPanel=this.addPanel(new a1.Panel("FPS","#0ff","#002"),0),this.msPanel=this.addPanel(new a1.Panel("CPU","#0f0","#020"),1),this.gpuPanel=null,this.samplesLog=t,this.samplesGraph=r,this.precision=i,this.logsPerSecond=e,this.minimal?(this.container.addEventListener("click",v=>{v.preventDefault(),this.showPanel(++this.mode%this.container.children.length)},!1),this.mode=a,this.showPanel(this.mode)):window.addEventListener("resize",()=>{this.resizePanel(this.fpsPanel,0),this.resizePanel(this.msPanel,1),this.gpuPanel&&this.resizePanel(this.gpuPanel,2)})}resizePanel(e,t){e.canvas.style.position="absolute",this.minimal?e.canvas.style.display="none":(e.canvas.style.display="block",this.horizontal?(e.canvas.style.top="0px",e.canvas.style.left=t*e.WIDTH/e.PR+"px"):(e.canvas.style.left="0px",e.canvas.style.top=t*e.HEIGHT/e.PR+"px"))}addPanel(e,t){return e.canvas&&(this.container.appendChild(e.canvas),this.resizePanel(e,t)),e}showPanel(e){for(let t=0;t<this.container.children.length;t++){let r=this.container.children[t];r.style.display=t===e?"block":"none"}this.mode=e}init(e){if(e){if(e instanceof WebGL2RenderingContext)this.gl=e;else if(e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas){if(this.gl=e.getContext("webgl2"),!this.gl)return}else return;this.ext=this.gl.getExtension("EXT_disjoint_timer_query_webgl2"),this.ext&&(this.gpuPanel=this.addPanel(new a1.Panel("GPU","#ff0","#220"),2))}}begin(){if(this.beginProfiling("cpu-started"),!(!this.gl||!this.ext)){if(this.query){let e=this.gl.getQueryParameter(this.query,this.gl.QUERY_RESULT_AVAILABLE);if(this.disjoint=this.gl.getParameter(this.ext.GPU_DISJOINT_EXT),e&&!this.disjoint){this.ns=this.gl.getQueryParameter(this.query,this.gl.QUERY_RESULT);let t=this.ns*1e-6;(e||this.disjoint)&&(this.gl.deleteQuery(this.query),this.query=null),e&&this.addToAverage(t,this.averageGpu)}}this.query||(this.queryCreated=!0,this.query=this.gl.createQuery(),this.query&&this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,this.query))}}end(){this.beginTime=this.endInternal(),this.endProfiling("cpu-started","cpu-finished","cpu-duration",this.averageCpu),!(!this.gl||!this.ext)&&this.queryCreated&&this.gl.getQuery(this.ext.TIME_ELAPSED_EXT,this.gl.CURRENT_QUERY)&&this.gl.endQuery(this.ext.TIME_ELAPSED_EXT)}endInternal(){this.frames++;let e=(performance||Date).now();if(e>=this.prevCpuTime+1e3/this.logsPerSecond&&(this.updatePanel(this.msPanel,this.averageCpu),this.updatePanel(this.gpuPanel,this.averageGpu),this.prevCpuTime=e),e>=this.prevTime+1e3){let t=this.frames*1e3/(e-this.prevTime);this.fpsPanel.update(t,t,100,100,0),this.prevTime=e,this.frames=0}return e}addToAverage(e,t){t.logs.push(e),t.logs.length>this.samplesLog&&t.logs.shift(),t.graph.push(e),t.graph.length>this.samplesGraph&&t.graph.shift()}beginProfiling(e){window.performance&&window.performance.mark(e)}endProfiling(e,t,r,i){if(window.performance&&t){window.performance.mark(t);let s=performance.measure(r,e,t);this.addToAverage(s.duration,i)}}updatePanel(e,t){if(t.logs.length>0){let r=0,i=.01;for(let a=0;a<t.logs.length;a++)r+=t.logs[a],t.logs[a]>i&&(i=t.logs[a]);let s=0,o=.01;for(let a=0;a<t.graph.length;a++)s+=t.graph[a],t.graph[a]>o&&(o=t.graph[a]);e&&e.update(r/Math.min(t.logs.length,this.samplesLog),s/Math.min(t.graph.length,this.samplesGraph),i,o,this.precision)}}};j2.Panel=o1;var Y2=j2;E();x();k();R();var He=Object.freeze({Linear:Object.freeze({None:function(n){return n},In:function(n){return this.None(n)},Out:function(n){return this.None(n)},InOut:function(n){return this.None(n)}}),Quadratic:Object.freeze({In:function(n){return n*n},Out:function(n){return n*(2-n)},InOut:function(n){return(n*=2)<1?.5*n*n:-.5*(--n*(n-2)-1)}}),Cubic:Object.freeze({In:function(n){return n*n*n},Out:function(n){return--n*n*n+1},InOut:function(n){return(n*=2)<1?.5*n*n*n:.5*((n-=2)*n*n+2)}}),Quartic:Object.freeze({In:function(n){return n*n*n*n},Out:function(n){return 1- --n*n*n*n},InOut:function(n){return(n*=2)<1?.5*n*n*n*n:-.5*((n-=2)*n*n*n-2)}}),Quintic:Object.freeze({In:function(n){return n*n*n*n*n},Out:function(n){return--n*n*n*n*n+1},InOut:function(n){return(n*=2)<1?.5*n*n*n*n*n:.5*((n-=2)*n*n*n*n+2)}}),Sinusoidal:Object.freeze({In:function(n){return 1-Math.sin((1-n)*Math.PI/2)},Out:function(n){return Math.sin(n*Math.PI/2)},InOut:function(n){return .5*(1-Math.sin(Math.PI*(.5-n)))}}),Exponential:Object.freeze({In:function(n){return n===0?0:Math.pow(1024,n-1)},Out:function(n){return n===1?1:1-Math.pow(2,-10*n)},InOut:function(n){return n===0?0:n===1?1:(n*=2)<1?.5*Math.pow(1024,n-1):.5*(-Math.pow(2,-10*(n-1))+2)}}),Circular:Object.freeze({In:function(n){return 1-Math.sqrt(1-n*n)},Out:function(n){return Math.sqrt(1- --n*n)},InOut:function(n){return(n*=2)<1?-.5*(Math.sqrt(1-n*n)-1):.5*(Math.sqrt(1-(n-=2)*n)+1)}}),Elastic:Object.freeze({In:function(n){return n===0?0:n===1?1:-Math.pow(2,10*(n-1))*Math.sin((n-1.1)*5*Math.PI)},Out:function(n){return n===0?0:n===1?1:Math.pow(2,-10*n)*Math.sin((n-.1)*5*Math.PI)+1},InOut:function(n){return n===0?0:n===1?1:(n*=2,n<1?-.5*Math.pow(2,10*(n-1))*Math.sin((n-1.1)*5*Math.PI):.5*Math.pow(2,-10*(n-1))*Math.sin((n-1.1)*5*Math.PI)+1)}}),Back:Object.freeze({In:function(n){var e=1.70158;return n===1?1:n*n*((e+1)*n-e)},Out:function(n){var e=1.70158;return n===0?0:--n*n*((e+1)*n+e)+1},InOut:function(n){var e=2.5949095;return(n*=2)<1?.5*(n*n*((e+1)*n-e)):.5*((n-=2)*n*((e+1)*n+e)+2)}}),Bounce:Object.freeze({In:function(n){return 1-He.Bounce.Out(1-n)},Out:function(n){return n<.36363636363636365?7.5625*n*n:n<.7272727272727273?7.5625*(n-=.5454545454545454)*n+.75:n<.9090909090909091?7.5625*(n-=.8181818181818182)*n+.9375:7.5625*(n-=.9545454545454546)*n+.984375},InOut:function(n){return n<.5?He.Bounce.In(n*2)*.5:He.Bounce.Out(n*2-1)*.5+.5}}),generatePow:function(n){return n===void 0&&(n=4),n=n<Number.EPSILON?Number.EPSILON:n,n=n>1e4?1e4:n,{In:function(e){return Math.pow(e,n)},Out:function(e){return 1-Math.pow(1-e,n)},InOut:function(e){return e<.5?Math.pow(e*2,n)/2:(1-Math.pow(2-e*2,n))/2+.5}}}}),f5=function(){return performance.now()},Ct=function(){function n(){this._tweens={},this._tweensAddedDuringUpdate={}}return n.prototype.getAll=function(){var e=this;return Object.keys(this._tweens).map(function(t){return e._tweens[t]})},n.prototype.removeAll=function(){this._tweens={}},n.prototype.add=function(e){this._tweens[e.getId()]=e,this._tweensAddedDuringUpdate[e.getId()]=e},n.prototype.remove=function(e){delete this._tweens[e.getId()],delete this._tweensAddedDuringUpdate[e.getId()]},n.prototype.update=function(e,t){e===void 0&&(e=f5()),t===void 0&&(t=!1);var r=Object.keys(this._tweens);if(r.length===0)return!1;for(;r.length>0;){this._tweensAddedDuringUpdate={};for(var i=0;i<r.length;i++){var s=this._tweens[r[i]],o=!t;s&&s.update(e,o)===!1&&!t&&delete this._tweens[r[i]]}r=Object.keys(this._tweensAddedDuringUpdate)}return!0},n}(),St={Linear:function(n,e){var t=n.length-1,r=t*e,i=Math.floor(r),s=St.Utils.Linear;return e<0?s(n[0],n[1],r):e>1?s(n[t],n[t-1],t-r):s(n[i],n[i+1>t?t:i+1],r-i)},Bezier:function(n,e){for(var t=0,r=n.length-1,i=Math.pow,s=St.Utils.Bernstein,o=0;o<=r;o++)t+=i(1-e,r-o)*i(e,o)*n[o]*s(r,o);return t},CatmullRom:function(n,e){var t=n.length-1,r=t*e,i=Math.floor(r),s=St.Utils.CatmullRom;return n[0]===n[t]?(e<0&&(i=Math.floor(r=t*(1+e))),s(n[(i-1+t)%t],n[i],n[(i+1)%t],n[(i+2)%t],r-i)):e<0?n[0]-(s(n[0],n[0],n[1],n[1],-r)-n[0]):e>1?n[t]-(s(n[t],n[t],n[t-1],n[t-1],r-t)-n[t]):s(n[i?i-1:0],n[i],n[t<i+1?t:i+1],n[t<i+2?t:i+2],r-i)},Utils:{Linear:function(n,e,t){return(e-n)*t+n},Bernstein:function(n,e){var t=St.Utils.Factorial;return t(n)/t(e)/t(n-e)},Factorial:function(){var n=[1];return function(e){var t=1;if(n[e])return n[e];for(var r=e;r>1;r--)t*=r;return n[e]=t,t}}(),CatmullRom:function(n,e,t,r,i){var s=(t-n)*.5,o=(r-e)*.5,a=i*i,v=i*a;return(2*e-2*t+s+o)*v+(-3*e+3*t-2*s-o)*a+s*i+e}}},Q2=function(){function n(){}return n.nextId=function(){return n._nextId++},n._nextId=0,n}(),Mr=new Ct,Oe=function(){function n(e,t){t===void 0&&(t=Mr),this._object=e,this._group=t,this._isPaused=!1,this._pauseStart=0,this._valuesStart={},this._valuesEnd={},this._valuesStartRepeat={},this._duration=1e3,this._isDynamic=!1,this._initialRepeat=0,this._repeat=0,this._yoyo=!1,this._isPlaying=!1,this._reversed=!1,this._delayTime=0,this._startTime=0,this._easingFunction=He.Linear.None,this._interpolationFunction=St.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=Q2.nextId(),this._isChainStopped=!1,this._propertiesAreSetUp=!1,this._goToEnd=!1}return n.prototype.getId=function(){return this._id},n.prototype.isPlaying=function(){return this._isPlaying},n.prototype.isPaused=function(){return this._isPaused},n.prototype.to=function(e,t){if(t===void 0&&(t=1e3),this._isPlaying)throw new Error("Can not call Tween.to() while Tween is already started or paused. Stop the Tween first.");return this._valuesEnd=e,this._propertiesAreSetUp=!1,this._duration=t,this},n.prototype.duration=function(e){return e===void 0&&(e=1e3),this._duration=e,this},n.prototype.dynamic=function(e){return e===void 0&&(e=!1),this._isDynamic=e,this},n.prototype.start=function(e,t){if(e===void 0&&(e=f5()),t===void 0&&(t=!1),this._isPlaying)return this;if(this._group&&this._group.add(this),this._repeat=this._initialRepeat,this._reversed){this._reversed=!1;for(var r in this._valuesStartRepeat)this._swapEndStartRepeatValues(r),this._valuesStart[r]=this._valuesStartRepeat[r]}if(this._isPlaying=!0,this._isPaused=!1,this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._isChainStopped=!1,this._startTime=e,this._startTime+=this._delayTime,!this._propertiesAreSetUp||t){if(this._propertiesAreSetUp=!0,!this._isDynamic){var i={};for(var s in this._valuesEnd)i[s]=this._valuesEnd[s];this._valuesEnd=i}this._setupProperties(this._object,this._valuesStart,this._valuesEnd,this._valuesStartRepeat,t)}return this},n.prototype.startFromCurrentValues=function(e){return this.start(e,!0)},n.prototype._setupProperties=function(e,t,r,i,s){for(var o in r){var a=e[o],v=Array.isArray(a),l=v?"array":typeof a,c=!v&&Array.isArray(r[o]);if(!(l==="undefined"||l==="function")){if(c){var u=r[o];if(u.length===0)continue;for(var h=[a],p=0,g=u.length;p<g;p+=1){var y=this._handleRelativeValue(a,u[p]);if(isNaN(y)){c=!1;break}h.push(y)}c&&(r[o]=h)}if((l==="object"||v)&&a&&!c){t[o]=v?[]:{};var A=a;for(var b in A)t[o][b]=A[b];i[o]=v?[]:{};var u=r[o];if(!this._isDynamic){var w={};for(var b in u)w[b]=u[b];r[o]=u=w}this._setupProperties(A,t[o],u,i[o],s)}else(typeof t[o]>"u"||s)&&(t[o]=a),v||(t[o]*=1),c?i[o]=r[o].slice().reverse():i[o]=t[o]||0}}},n.prototype.stop=function(){return this._isChainStopped||(this._isChainStopped=!0,this.stopChainedTweens()),this._isPlaying?(this._group&&this._group.remove(this),this._isPlaying=!1,this._isPaused=!1,this._onStopCallback&&this._onStopCallback(this._object),this):this},n.prototype.end=function(){return this._goToEnd=!0,this.update(1/0),this},n.prototype.pause=function(e){return e===void 0&&(e=f5()),this._isPaused||!this._isPlaying?this:(this._isPaused=!0,this._pauseStart=e,this._group&&this._group.remove(this),this)},n.prototype.resume=function(e){return e===void 0&&(e=f5()),!this._isPaused||!this._isPlaying?this:(this._isPaused=!1,this._startTime+=e-this._pauseStart,this._pauseStart=0,this._group&&this._group.add(this),this)},n.prototype.stopChainedTweens=function(){for(var e=0,t=this._chainedTweens.length;e<t;e++)this._chainedTweens[e].stop();return this},n.prototype.group=function(e){return e===void 0&&(e=Mr),this._group=e,this},n.prototype.delay=function(e){return e===void 0&&(e=0),this._delayTime=e,this},n.prototype.repeat=function(e){return e===void 0&&(e=0),this._initialRepeat=e,this._repeat=e,this},n.prototype.repeatDelay=function(e){return this._repeatDelayTime=e,this},n.prototype.yoyo=function(e){return e===void 0&&(e=!1),this._yoyo=e,this},n.prototype.easing=function(e){return e===void 0&&(e=He.Linear.None),this._easingFunction=e,this},n.prototype.interpolation=function(e){return e===void 0&&(e=St.Linear),this._interpolationFunction=e,this},n.prototype.chain=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this._chainedTweens=e,this},n.prototype.onStart=function(e){return this._onStartCallback=e,this},n.prototype.onEveryStart=function(e){return this._onEveryStartCallback=e,this},n.prototype.onUpdate=function(e){return this._onUpdateCallback=e,this},n.prototype.onRepeat=function(e){return this._onRepeatCallback=e,this},n.prototype.onComplete=function(e){return this._onCompleteCallback=e,this},n.prototype.onStop=function(e){return this._onStopCallback=e,this},n.prototype.update=function(e,t){if(e===void 0&&(e=f5()),t===void 0&&(t=!0),this._isPaused)return!0;var r,i,s=this._startTime+this._duration;if(!this._goToEnd&&!this._isPlaying){if(e>s)return!1;t&&this.start(e,!0)}if(this._goToEnd=!1,e<this._startTime)return!0;this._onStartCallbackFired===!1&&(this._onStartCallback&&this._onStartCallback(this._object),this._onStartCallbackFired=!0),this._onEveryStartCallbackFired===!1&&(this._onEveryStartCallback&&this._onEveryStartCallback(this._object),this._onEveryStartCallbackFired=!0),i=(e-this._startTime)/this._duration,i=this._duration===0||i>1?1:i;var o=this._easingFunction(i);if(this._updateProperties(this._object,this._valuesStart,this._valuesEnd,o),this._onUpdateCallback&&this._onUpdateCallback(this._object,i),i===1)if(this._repeat>0){isFinite(this._repeat)&&this._repeat--;for(r in this._valuesStartRepeat)!this._yoyo&&typeof this._valuesEnd[r]=="string"&&(this._valuesStartRepeat[r]=this._valuesStartRepeat[r]+parseFloat(this._valuesEnd[r])),this._yoyo&&this._swapEndStartRepeatValues(r),this._valuesStart[r]=this._valuesStartRepeat[r];return this._yoyo&&(this._reversed=!this._reversed),this._repeatDelayTime!==void 0?this._startTime=e+this._repeatDelayTime:this._startTime=e+this._delayTime,this._onRepeatCallback&&this._onRepeatCallback(this._object),this._onEveryStartCallbackFired=!1,!0}else{this._onCompleteCallback&&this._onCompleteCallback(this._object);for(var a=0,v=this._chainedTweens.length;a<v;a++)this._chainedTweens[a].start(this._startTime+this._duration,!1);return this._isPlaying=!1,!1}return!0},n.prototype._updateProperties=function(e,t,r,i){for(var s in r)if(t[s]!==void 0){var o=t[s]||0,a=r[s],v=Array.isArray(e[s]),l=Array.isArray(a),c=!v&&l;c?e[s]=this._interpolationFunction(a,i):typeof a=="object"&&a?this._updateProperties(e[s],o,a,i):(a=this._handleRelativeValue(o,a),typeof a=="number"&&(e[s]=o+(a-o)*i))}},n.prototype._handleRelativeValue=function(e,t){return typeof t!="string"?t:t.charAt(0)==="+"||t.charAt(0)==="-"?e+parseFloat(t):parseFloat(t)},n.prototype._swapEndStartRepeatValues=function(e){var t=this._valuesStartRepeat[e],r=this._valuesEnd[e];typeof r=="string"?this._valuesStartRepeat[e]=this._valuesStartRepeat[e]+parseFloat(r):this._valuesStartRepeat[e]=this._valuesEnd[e],this._valuesEnd[e]=t},n}();var Fc=Q2.nextId,g0=Mr,zc=g0.getAll.bind(g0),Lc=g0.removeAll.bind(g0),Uc=g0.add.bind(g0),Gc=g0.remove.bind(g0),K2=g0.update.bind(g0);E();x();k();R();function Sr(n){if(n==="high-performance")return"high-performance";if(n==="low-power")return"low-power"}var ae=typeof globalThis.WorkerGlobalScope<"u"&&globalThis instanceof globalThis.WorkerGlobalScope,Br=class{constructor(e,t=0){this.canvas=e;d(this,"stats");d(this,"stats2");d(this,"statsGl");d(this,"total",0);d(this,"denseMode");this.stats=new Cr.default,this.stats2=new Cr.default,this.statsGl=new Y2({minimal:!0}),this.stats2.showPanel(2),this.denseMode=typeof D<"u"&&!0||typeof window<"u"&&window.innerHeight<500,this.initStats(),this.setVisibility(t)}addStat(e,t=80){e.style.position="absolute",this.denseMode&&(e.style.height="12px"),e.style.overflow="hidden",e.style.left="",e.style.top="0",e.style.right=`${this.total}px`,e.style.width="80px",e.style.zIndex="1",e.style.opacity="0.8";let r=document.getElementById("corner-indicator-stats"),i=r??document.body;r&&(e.style.position="relative"),i.appendChild(e),this.total+=t}initStats(){let e=this.stats2.dom.children.length===3;this.addStat(this.stats.dom),e&&this.addStat(this.stats2.dom),this.statsGl.init(this.canvas),this.statsGl.container.style.display="flex",this.statsGl.container.style.justifyContent="flex-end";let t=0;for(let r of this.statsGl.container.children){let i=r;t++===0&&(i.style.display="none"),i.style.position=""}}setVisibility(e){e>0?(this.stats.dom.style.display="block",this.stats2.dom.style.display=e>=2?"block":"none",this.statsGl.container.style.display=e>=2?"block":"none"):(this.stats.dom.style.display="none",this.stats2.dom.style.display="none",this.statsGl.container.style.display="none")}markStart(){this.stats.begin(),this.stats2.begin(),this.statsGl.begin()}markEnd(){this.stats.end(),this.stats2.end(),this.statsGl.end()}dispose(){this.stats.dom.remove(),this.stats2.dom.remove(),this.statsGl.container.remove()}},h5=class{constructor(e,t,r){this.initOptions=e;this.externalCanvas=t;d(this,"canvas");d(this,"renderer");d(this,"animationFrameId");d(this,"timeoutId");d(this,"lastRenderTime",0);d(this,"previousCanvasWidth",0);d(this,"previousCanvasHeight",0);d(this,"currentWidth",0);d(this,"currentHeight",0);d(this,"pendingResize",!1);d(this,"renderedFps",0);d(this,"fpsInterval");d(this,"stats");d(this,"paused",!1);d(this,"disconnected",!1);d(this,"preRender",()=>{});d(this,"render",e=>{});d(this,"postRender",()=>{});d(this,"sizeChanged",()=>{});d(this,"droppedFpsPercentage",0);d(this,"config");d(this,"onRender",[]);d(this,"inWorldRenderingConfig");d(this,"nonReactiveState");this.config=e.config,t?this.canvas=t:this.addToPage();try{let s=e.getRendererOptions?.()?.gpuPreference??"default";this.renderer=new v1.WebGLRenderer({canvas:this.canvas,preserveDrawingBuffer:!0,logarithmicDepthBuffer:!0,powerPreference:Sr(s)})}catch(s){throw e.callbacks.displayCriticalError(new Error(`Failed to create WebGL context, not possible to render (restart browser): ${s.message}`)),s}this.renderer.useLegacyLights=!0,this.renderer.outputColorSpace=v1.LinearSRGBColorSpace,t||(this.updatePixelRatio(),this.setupResizeListener()),this.sizeUpdated(),this.previousCanvasWidth=this.canvas.width,this.previousCanvasHeight=this.canvas.height;let i="WebGL2RenderingContext"in globalThis;!t&&i&&!ae&&(this.stats=new Br(this.canvas,this.config.statsVisible)),this.setupFpsTracking(),this.startRenderLoop()}setupResizeListener(){if(typeof window>"u")return;let e,t=()=>{e&&clearTimeout(e),e=setTimeout(()=>{this.pendingResize=!0},16)};window.addEventListener("resize",t,{passive:!0})}updatePixelRatio(){if(typeof window>"u")return;let e=window.devicePixelRatio||1;this.renderer.capabilities.isWebGL2||(e=1),this.renderer.setPixelRatio(e)}sizeUpdated(){this.renderer.setSize(this.currentWidth,this.currentHeight,!1)}addToPage(){this.canvas=J2(),this.updateCanvasSize()}updateSizeExternal(e,t,r){this.currentWidth=e,this.currentHeight=t,this.renderer.setPixelRatio(r),this.sizeUpdated()}updateCanvasSize(){if(this.externalCanvas||typeof document>"u")return;let e=document.body.offsetWidth,t=document.body.offsetHeight;this.currentWidth!==e&&(this.currentWidth=e),this.currentHeight!==t&&(this.currentHeight=t)}setupFpsTracking(){let e=0;this.fpsInterval=setInterval(()=>{e>0&&(this.droppedFpsPercentage=this.renderedFps/e),e=Math.max(this.renderedFps,e),this.nonReactiveState&&(this.nonReactiveState.fps=this.renderedFps),this.renderedFps=0},1e3)}startRenderLoop(){let e=()=>{if(this.disconnected)return;if(this.config.timeoutRendering){let i=1e3/(this.config.fpsLimit?Math.min(this.config.fpsLimit,60):60);this.timeoutId=setTimeout(e,i)}else this.animationFrameId=requestAnimationFrame(e);if(this.paused||this.renderer.xr.isPresenting&&!this.inWorldRenderingConfig?.vrPageGameRendering)return;if(!this.config.timeoutRendering&&this.config.fpsLimit){let r=performance.now(),i=r-this.lastRenderTime,s=1e3/this.config.fpsLimit;if(i<s)return;this.lastRenderTime=r-i%s}let t=!1;this.pendingResize&&(this.updateCanvasSize(),this.pendingResize=!1),(this.previousCanvasWidth!==this.currentWidth||this.previousCanvasHeight!==this.currentHeight)&&(this.previousCanvasWidth=this.currentWidth,this.previousCanvasHeight=this.currentHeight,this.sizeUpdated(),t=!0),this.frameRender(t),this.config.statsVisible!==void 0&&this.stats?.setVisibility(this.config.statsVisible)};e()}frameRender(e){this.preRender(),this.stats?.markStart(),K2(),globalThis.freezeRender||this.render(e);for(let t of this.onRender)t(e);this.renderedFps++,this.stats?.markEnd(),this.postRender()}setPaused(e){this.paused=e}dispose(){this.disconnected=!0,this.animationFrameId&&cancelAnimationFrame(this.animationFrameId),this.timeoutId&&clearTimeout(this.timeoutId),this.canvas instanceof HTMLCanvasElement&&this.canvas.remove(),clearInterval(this.fpsInterval),this.stats?.dispose(),this.renderer.dispose()}};function J2(){let n=document.createElement("canvas");return n.id="viewer-canvas",document.body.appendChild(n),n}var Pr=()=>{let n=J2(),e=n.transferControlToOffscreen(),t=!1,r=(o,a)=>{},i={width:0,height:0},s=()=>{t||((i.width!==window.innerWidth||i.height!==window.innerHeight)&&(r(window.innerWidth,window.innerHeight),i={width:window.innerWidth,height:window.innerHeight}),requestAnimationFrame(s))};return requestAnimationFrame(s),{canvas:e,destroy(){t=!0,n.remove()},onSizeChanged(o){r=o},get size(){return{width:window.innerWidth,height:window.innerHeight}}}};import{ItemsRenderer as q2}from"mc-assets/dist/itemsRenderer";import{getLoadedItemDefinitionsStore as Hr}from"mc-assets/dist/stores";var l1=null;function es(n){return ae?((!l1||typeof l1.get!="function")&&(l1=Hr(Ir)),l1):(ts(n),n.itemsDefinitionsStore)}function ts(n){ae||typeof n.itemsDefinitionsStore?.get=="function"||(n.itemsDefinitionsStore=Hr(n.sourceItemDefinitionsJson??Ir))}var Bt=class{constructor(e){d(this,"sourceItemDefinitionsJson",Ir);d(this,"itemsDefinitionsStore",Hr(this.sourceItemDefinitionsJson));d(this,"allReady",!1);d(this,"itemsAtlasImage");d(this,"blocksAtlasImage");d(this,"blocksAtlasJson");d(this,"itemsAtlasJson");d(this,"customBlockStates");d(this,"customModels");d(this,"customItemModelNames",{});d(this,"customTextures",{});d(this,"guiAtlas",null);d(this,"guiAtlasVersion",0);d(this,"itemsRenderer");d(this,"worldBlockProvider");d(this,"blockstatesModels",null);d(this,"version");d(this,"texturesVersion");d(this,"mcData");if(e){let t={...e};delete t.itemsDefinitionsStore,delete t.sourceItemDefinitionsJson,Object.assign(this,t),ts(this)}if(this.version){let t=globalThis.loadedData??globalThis.mcData;ae&&t?.entitiesByName?this.mcData=t:this.mcData=$2(this.version)}}prepareForTransfer(){let e={};for(let t in this)Object.prototype.hasOwnProperty.call(this,t)&&typeof this[t]!="function"&&(t==="itemsRenderer"||t==="worldBlockProvider"||t==="mcData"||t==="itemsDefinitionsStore"||t==="sourceItemDefinitionsJson"||(e[t]=this[t]));return e.customTextures={},delete e.itemsDefinitionsStore,delete e.sourceItemDefinitionsJson,e}},X2="1.21.4",P0=class P0 extends Z0{constructor(){super(...arguments);d(this,"sourceBlockStatesModels",null);d(this,"sourceBlocksAtlases",u6);d(this,"sourceItemsAtlases",f6);d(this,"currentResources");d(this,"itemsAtlasParser");d(this,"blocksAtlasParser");d(this,"currentConfig");d(this,"abortController",new AbortController);d(this,"_promiseAssetsReadyResolvers",Promise.withResolvers())}rebuildWorkerRenderers(t){if(ae&&!(!t.version||!t.blockstatesModels||!t.blocksAtlasJson)){if(this.blocksAtlasParser=new et({latest:t.blocksAtlasJson},""),t.itemsAtlasJson)this.itemsAtlasParser=new et({latest:t.itemsAtlasJson},"");else if(!this.itemsAtlasParser?.atlas?.latest){if(!this.sourceItemsAtlases||Object.keys(this.sourceItemsAtlases).length===0)return;this.itemsAtlasParser=new et(this.sourceItemsAtlases,"")}t.itemsRenderer=new q2(t.version,t.blockstatesModels,this.itemsAtlasParser,this.blocksAtlasParser),t.worldBlockProvider=Z2(t.blockstatesModels,this.blocksAtlasParser.atlas,X2)}}static restoreTransferred(t,r){let i=new P0,s=o=>{i.currentResources=new Bt(o),i.rebuildWorkerRenderers(i.currentResources)};return s(t.currentResources),r&&r.addEventListener("message",({data:o})=>{o.class===P0.restorerName&&(o.type==="newResources"&&s(o.currentResources),o.type==="event"&&i.emit(o.eventName,...o.args))}),i}enrichTransferSnapshot(t){return t&&(this.itemsAtlasParser?.atlas?.latest&&(t.itemsAtlasJson=this.itemsAtlasParser.atlas.latest),this.blocksAtlasParser?.atlas?.latest&&(t.blocksAtlasJson=this.blocksAtlasParser.atlas.latest),t)}prepareForTransfer(t){if(t){let r=this.emit.bind(this);this.emit=(i,...s)=>{if(r(i,...s),t.postMessage({class:P0.restorerName,type:"event",eventName:i,args:s1(s)}),i==="assetsTexturesUpdated"||i==="assetsInventoryReady"){let o=this.enrichTransferSnapshot(this.currentResources?.prepareForTransfer());t.postMessage({class:P0.restorerName,type:"newResources",currentResources:o})}}}return{__restorer:P0.restorerName,currentResources:this.enrichTransferSnapshot(this.currentResources?.prepareForTransfer())}}get promiseAssetsReady(){return this._promiseAssetsReadyResolvers.promise}async loadSourceData(t=this.currentConfig?.version){if(!t)throw new Error("No version loaded");this.sourceBlockStatesModels??(this.sourceBlockStatesModels=(await import("mc-assets/dist/blockStatesModels.json")).default)}resetResources(){this.currentResources=new Bt}async updateAssetsData(t,r=!1){if(!this.currentConfig)throw new Error("No config loaded");this._promiseAssetsReadyResolvers=Promise.withResolvers();let i=new AbortController;if(await this.loadSourceData(this.currentConfig.version),i.signal.aborted)return;let s=this.currentResources??new Bt;s.version=this.currentConfig.version,s.texturesVersion=this.currentConfig.texturesVersion??s.version,s.mcData=$2(s.version),s.blockstatesModels={blockstates:{},models:{}},s.blockstatesModels.blockstates.latest={...this.sourceBlockStatesModels.blockstates.latest,...s.customBlockStates},s.blockstatesModels.models.latest={...this.sourceBlockStatesModels.models.latest,...s.customModels},await Promise.all([this.recreateBlockAtlas(s),this.recreateItemsAtlas(s)]),!i.signal.aborted&&(s.version&&s.blockstatesModels&&this.itemsAtlasParser&&this.blocksAtlasParser&&(s.itemsRenderer=new q2(s.version,s.blockstatesModels,this.itemsAtlasParser,this.blocksAtlasParser)),!i.signal.aborted&&(this.currentResources=s,s.allReady=!0,r||this.emit("assetsTexturesUpdated"),this.currentConfig.noInventoryGui?this._promiseAssetsReadyResolvers.resolve():(this.emit("assetsInventoryStarted"),this.generateGuiTextures().then(()=>{i.signal.aborted||(r||this.emit("assetsInventoryReady"),this._promiseAssetsReadyResolvers.resolve())}))))}async recreateBlockAtlas(t=this.currentResources){let r={},i=new Date;(i.getMonth()===11&&i.getDate()>=24||i.getMonth()===0&&i.getDate()<=6)&&Object.assign(r,b6);let s=new et(this.sourceBlocksAtlases,h6,m6),o=Object.keys(t.customTextures.blocks?.textures??{}),{atlas:a,canvas:v}=await s.makeNewAtlas(t.texturesVersion,l=>{if(this.currentConfig.includeOnlyBlocks&&!this.currentConfig.includeOnlyBlocks.includes(l))return!1;let c=t.customTextures.blocks?.textures[l];return r[l]??c},void 0,void 0,o,{needHorizontalIndexes:!!this.currentConfig.includeOnlyBlocks});this.blocksAtlasParser=new et({latest:a},v.toDataURL()),t.blocksAtlasImage=await createImageBitmap(v),t.blocksAtlasJson=this.blocksAtlasParser.atlas.latest,t.worldBlockProvider=Z2(t.blockstatesModels,this.blocksAtlasParser.atlas,X2)}async recreateItemsAtlas(t=this.currentResources){let r=new et(this.sourceItemsAtlases,p6,g6),i=Object.keys(t.customTextures.items?.textures??{}),{atlas:s,canvas:o}=await r.makeNewAtlas(t.texturesVersion,a=>{let v=t.customTextures.items?.textures[a];if(v)return v},t.customTextures.items?.tileSize,void 0,i);this.itemsAtlasParser=new et({latest:s},o.toDataURL()),t.itemsAtlasImage=await createImageBitmap(o),t.itemsAtlasJson=this.itemsAtlasParser.atlas.latest}async generateGuiTextures(){}async downloadDebugAtlas(t=!1){if(!this.currentResources)throw new Error("No resources loaded");let s=await(t?this.itemsAtlasParser:this.blocksAtlasParser).createDebugImage(!0),o=document.createElement("a");o.href=s,o.download=`atlas-debug-${t?"items":"blocks"}.png`,o.click()}destroy(){this.abortController.abort(),this.currentResources=void 0,this.abortController=new AbortController}};d(P0,"restorerName","ResourcesManager");var h0=P0;E();x();k();R();var o0=class extends Error{constructor(t,r){super(t);d(this,"failure");this.name="MesherWorkerPreloadError",this.failure=r}};function y6(n){return!n||typeof n!="object"?!1:n.type==="mc-web-pong"?!0:Array.isArray(n)?n.some(e=>e&&typeof e=="object"&&e.type==="mc-web-pong"):!1}var _6=45e3,w6=1e4;async function rs(n){if(D.env.SINGLE_FILE_BUILD)return;let e=n?.fetchTimeoutMs??_6,t=n?.pingTimeoutMs??w6,r=n?.script??"mesher.js",i=new URL(r,document.baseURI).href,s;try{let u=new AbortController,h=window.setTimeout(()=>u.abort(),e);try{s=await fetch(i,{credentials:"same-origin",cache:"force-cache",signal:u.signal})}finally{clearTimeout(h)}}catch(u){let h=u;throw h?.name==="AbortError"?new o0(`Mesher script fetch timed out after ${e}ms (${i}).`,{phase:"fetch",code:"timeout"}):new o0(`Mesher script fetch failed (network): ${h?.message??u}. URL: ${i}`,{phase:"fetch",code:"network",detail:String(h?.message??u)})}if(!s.ok)throw new o0(`Mesher script HTTP ${s.status} ${s.statusText}: ${i}`,{phase:"fetch",code:"bad-status",status:s.status});let o=s.headers.get("content-type")??"",a=await s.arrayBuffer();if(a.byteLength===0)throw new o0(`Mesher script response was empty: ${i}`,{phase:"fetch",code:"invalid-body",hint:"empty"});let v=Math.min(1024,a.byteLength),l=new TextDecoder().decode(a.slice(0,v)).trimStart();if(l.startsWith("<!DOCTYPE")||l.startsWith("<html")||l.startsWith("<HTML"))throw new o0(`Mesher URL returned HTML (wrong path, redirect, or SPA fallback), not JavaScript: ${i}`,{phase:"fetch",code:"invalid-body",hint:"html"});o.length>0&&/javascript|ecmascript/i.test(o);let c;try{c=new Worker(i)}catch(u){let h=u instanceof Error?u.message:String(u);throw new o0(`Could not construct Worker for mesher (${i}): ${h}`,{phase:"worker",code:"construct-failed",message:h})}await new Promise((u,h)=>{let p=!1,g=window.setTimeout(()=>{p||(p=!0,y(),h(new o0(`Mesher worker did not reply with mc-web-pong within ${t}ms (wrong script, SW stale cache, worker blocked, or COEP/CORP). URL: ${i}`,{phase:"ping",code:"timeout"})))},t),y=()=>{clearTimeout(g);let M=c;c=void 0,M&&(M.removeEventListener("message",w),M.removeEventListener("error",S),M.removeEventListener("messageerror",C),M.terminate())},A=()=>{p||(p=!0,y(),u())},b=M=>{p||(p=!0,y(),h(M))};function w(M){y6(M.data)&&A()}function S(M){b(new o0(`Mesher worker script failed to load or threw during startup: ${M.message||"unknown"} @ ${i}`,{phase:"worker",code:"script-error",message:M.message}))}function C(){b(new o0(`Mesher worker message channel error (structured clone / deserialization). URL: ${i}`,{phase:"ping",code:"messageerror"}))}c.addEventListener("message",w),c.addEventListener("error",S),c.addEventListener("messageerror",C);try{c.postMessage({type:"mc-web-ping",t:performance.now(),workerIndex:0})}catch(M){let I=M instanceof Error?M.message:String(M);b(new o0(`Failed to post mc-web-ping to mesher worker: ${I}`,{phase:"ping",code:"post-failed",detail:I}))}})}var ns=class{constructor(e={},t=new h0){this.resourcesManager=t;d(this,"waitBackendLoadPromises",[]);d(this,"onWorldStart");d(this,"onBeforeWorldStart");d(this,"worldView");d(this,"config");d(this,"menuBackgroundOptions");d(this,"inWorldRenderingConfig");d(this,"backend");d(this,"backendLoader");d(this,"currentState");d(this,"currentDisplay",null);d(this,"playerState",{reactive:xr()});d(this,"rendererState");d(this,"nonReactiveState");d(this,"worldReady");d(this,"resolveWorldReady");d(this,"lastCamUpdate",0);d(this,"getRendererOptions");this.config={...L2,...e.config},this.menuBackgroundOptions={...e.config?.menuBackground,...e.menuBackground},this.inWorldRenderingConfig=is({...c5,...e.rendererConfig});let r=J0();this.rendererState=r.reactive,this.nonReactiveState=r.nonReactive,this.initWorldReadyPromise()}initWorldReadyPromise(){let{promise:e,resolve:t}=Promise.withResolvers();this.worldReady=e,this.resolveWorldReady=t}preloadWorkers(){let e=this.inWorldRenderingConfig.wasmMesher?"mesherWasm.js":"mesher.js";return rs({script:e})}bindRendererOptions(e){this.getRendererOptions=e}async loadBackend(e){this.backend&&this.disconnectBackend(),await Promise.all(this.waitBackendLoadPromises),this.waitBackendLoadPromises=[],this.backendLoader=e;let t={config:this.config,getRendererOptions:this.getRendererOptions,callbacks:{displayCriticalError:i=>{},setRendererSpecificSettings:(i,s)=>{},fireCustomEvent:(i,...s)=>{}},rendererSpecificSettings:{}},r=e(t);if(this.backend=await Promise.resolve(r),this.currentState)if(this.currentState.method==="startMenuBackground")this.startMenuBackground(...this.currentState.args);else{let{method:i,args:s}=this.currentState;this.backend[i](...s)}}async startWorld(e,t,r=this.playerState.reactive,i){if(this.currentDisplay==="world")throw new Error("World already started");this.currentDisplay="world";let s=i??new A6(0,64,0);this.worldView=new $0(e,t,s),this.worldView.isPlayground=this.inWorldRenderingConfig.isPlayground;let o={version:this.resourcesManager?.currentConfig?.version??"1.20.4",worldView:this.worldView,inWorldRenderingConfig:this.inWorldRenderingConfig,playerStateReactive:r,rendererState:this.rendererState,nonReactiveState:this.nonReactiveState,resourcesManager:this.resourcesManager};this.onBeforeWorldStart?.();let a;if(this.backend){let v=this.backend.startWorld(o);v&&typeof v.then=="function"&&(a=v)}return this.currentState={method:"startWorld",args:[o]},await a,this.resolveWorldReady(),this.onWorldStart?.(),!!a}startMenuBackground(e){if(this.currentDisplay==="menu")return;let t={...this.menuBackgroundOptions,...e,resourcesManager:e?.resourcesManager??this.resourcesManager};this.backend&&(this.currentDisplay="menu",this.backend.startMenuBackground(t)),this.currentState={method:"startMenuBackground",args:[t]}}resetBackend(e=!1){this.disconnectBackend(e),this.backendLoader&&this.loadBackend(this.backendLoader)}disconnectBackend(e=!1){e&&(this.currentState=void 0,this.currentDisplay=null,this.worldView=void 0),this.backend&&(this.backend.disconnect(),this.backend=void 0),this.currentDisplay=null,this.initWorldReadyPromise(),this.rendererState=is(J0().reactive),this.nonReactiveState=J0().nonReactive}updateCamera(e,t,r){this.backend?.updateCamera(e,t,r)}setRendering(e){this.backend?.setRendering(e)}async startWithBot(e,t){await this.startWorld(e.world,t),this.worldView&&typeof this.worldView.listenToBot=="function"&&this.worldView.listenToBot(e)}destroyAll(){this.disconnectBackend(!0),this.resourcesManager&&typeof this.resourcesManager.destroy=="function"&&this.resourcesManager.destroy()}get utils(){let e=this.backend;return{async waitingForChunks(){if(!e?.worldState?.allChunksLoaded)return new Promise(t=>{let r=setInterval(()=>{e?.worldState?.allChunksLoaded&&(clearInterval(r),t())},100)})}}}destroy(){this.disconnectBackend(!0)}};E();x();k();R();import{subscribe as I6}from"valtio/vanilla";E();x();k();R();E();x();k();R();var tt=["galaxy","nether","end","cyber","light"],rt=["cruise","barrel","dive","orbit","snake"],m5={galaxy:"Galaxy",nether:"Nether",end:"The End",cyber:"Cyber",light:"Light Space"},p5={cruise:"Cruise",barrel:"Barrel",dive:"Dive",orbit:"Orbit",snake:"Snake"},it=["mixed","stainedGlass","wool","construction","glow","world"],g5={mixed:"Mixed",stainedGlass:"Stained glass",wool:"Wool",construction:"Construction",glow:"Glow",world:"World (grass & ores)"};E();x();k();R();var b0={mode:"v2",minecraftTextures:!0,v2Scene:"light",v2Camera:"dive",v2BlockGroup:"stainedGlass",v2CameraSpeedPercent:80,v2BlockSpeedPercent:40},E0=n=>n/100,b5={camera:E0(b0.v2CameraSpeedPercent),block:E0(b0.v2BlockSpeedPercent)};var E6={off:0,holes:1,texIndex:2,faces:3,atlasAlpha:4};function Or(n){return E6[n]}var nt=b0,ss={rendererWorldPerformance:"normal",rendererMeshersCountOverride:null,starfieldRendering:!0,defaultSkybox:!0,menuBackgroundMode:nt.mode,menuBackgroundMinecraftTextures:nt.minecraftTextures,menuBackgroundV2Scene:nt.v2Scene,menuBackgroundV2Camera:nt.v2Camera,menuBackgroundV2BlockGroup:nt.v2BlockGroup,menuBackgroundV2CameraSpeed:nt.v2CameraSpeedPercent,menuBackgroundV2BlockSpeed:nt.v2BlockSpeedPercent,rendererFuturisticReveal:!1,rendererPerfDebugOverlay:!1,disableBlockEntityTextures:!1,rendererMesher:"wasm",rendererShaderCubeBlocks:!1,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};function x6(n){n.highPerformanceGpu&&(n.gpuPreference="high-performance",delete n.highPerformanceGpu),n.rendererMesher!=="wasm"&&n.rendererMesher!=="legacy-js"&&(typeof n.rendererWasmMesher=="boolean"?n.rendererMesher=n.rendererWasmMesher?"wasm":"legacy-js":typeof n.wasmExperimentalMesher=="boolean"&&(n.rendererMesher=n.wasmExperimentalMesher?"wasm":"legacy-js")),delete n.wasmExperimentalMesher,delete n.rendererWasmMesher,n.menuBackgroundMode==="futuristic"&&(n.menuBackgroundMode="v2");let e=[["menuBackgroundFuturisticScene","menuBackgroundV2Scene"],["menuBackgroundFuturisticCamera","menuBackgroundV2Camera"],["menuBackgroundFuturisticBlockGroup","menuBackgroundV2BlockGroup"],["menuBackgroundFuturisticCameraSpeed","menuBackgroundV2CameraSpeed"],["menuBackgroundFuturisticBlockSpeed","menuBackgroundV2BlockSpeed"]];for(let[t,r]of e)n[t]!==void 0&&n[r]===void 0&&(n[r]=n[t]),delete n[t]}var os={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:tt.map(n=>[n,m5[n]])},menuBackgroundV2Camera:{possibleValues:rt.map(n=>[n,p5[n]])},menuBackgroundV2BlockGroup:{possibleValues:it.map(n=>[n,g5[n]]),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. Reload to apply.",requiresRestart:!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:"WASM is faster. Use JS if WASM is not working. Requires reload.",requiresRestart:!0},rendererShaderCubeBlocks:{text:"(UNSTABLE) Instanced shader cubes",tooltip:"Render full blocks through the global GPU instanced path. Requires WASM mesher and WebGL2.",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"]]}},as=[{title:"World rendering",keys:["rendererWorldPerformance","starfieldRendering","defaultSkybox","disableBlockEntityTextures","showChunkBorders","renderEntities","smoothLighting","vanillaLook","newVersionsLighting","dayCycleAndLighting","loadPlayerSkins","renderEars","showHand","viewBobbing","fov","keepChunksDistance","highlightBlockColor","clipWorldBelowY"]},{title:"Frame pacing",keys:["frameLimit","backgroundRendering","renderDebug","gpuPreference"]},{title:"VR",keys:["vrSupport","vrPageGameRendering"]},{title:"Menu background",keys:["menuBackgroundMode","menuBackgroundMinecraftTextures","menuBackgroundV2Scene","menuBackgroundV2Camera","menuBackgroundV2BlockGroup","menuBackgroundV2CameraSpeed","menuBackgroundV2BlockSpeed"]},{title:"Mesher",keys:["rendererMesher","rendererShaderCubeBlocks"]},{title:"Renderer debug",keys:["rendererFuturisticReveal","rendererPerfDebugOverlay","rendererShaderCubeDebugMode"]}];E();x();k();R();E();x();k();R();E();x();k();R();E();x();k();R();function Dr(n,e,t,r,i){let s=n.getImageData(e,t,r,i);for(let o=0;o<r;o++)for(let a=0;a<i;a++){let v=(o+a*r)*4;if(s.data[v+3]!==255)return!0}return!1}function c1(n){return n/64}function vs(n,e,t){if(t){if(Dr(n,0,0,e,e))return}else if(Dr(n,0,0,e,e/2))return;let r=c1(e),i=(s,o,a,v)=>n.clearRect(s*r,o*r,a*r,v*r);i(40,0,8,8),i(48,0,8,8),i(32,8,8,8),i(40,8,8,8),i(48,8,8,8),i(56,8,8,8),t&&(i(4,32,4,4),i(8,32,4,4),i(0,36,4,12),i(4,36,4,12),i(8,36,4,12),i(12,36,4,12),i(20,32,8,4),i(28,32,8,4),i(16,36,4,12),i(20,36,8,12),i(28,36,4,12),i(32,36,8,12),i(44,32,4,4),i(48,32,4,4),i(40,36,4,12),i(44,36,4,12),i(48,36,4,12),i(52,36,12,12),i(4,48,4,4),i(8,48,4,4),i(0,52,4,12),i(4,52,4,12),i(8,52,4,12),i(12,52,4,12),i(52,48,4,4),i(56,48,4,4),i(48,52,4,12),i(52,52,4,12),i(56,52,4,12),i(60,52,4,12))}function R6(n,e){n.save(),n.scale(-1,1);let t=c1(e),r=(i,s,o,a,v,l)=>n.drawImage(n.canvas,i*t,s*t,o*t,a*t,-v*t,l*t,-o*t,a*t);r(4,16,4,4,20,48),r(8,16,4,4,24,48),r(0,20,4,12,24,52),r(4,20,4,12,20,52),r(8,20,4,12,16,52),r(12,20,4,12,28,52),r(44,16,4,4,36,48),r(48,16,4,4,40,48),r(40,20,4,12,40,52),r(44,20,4,12,36,52),r(48,20,4,12,32,52),r(52,20,4,12,44,52),n.restore()}function Fr(n,e){let t=!1;if(e.width!==e.height)if(e.width===2*e.height)t=!0;else throw new Error(`Bad skin size: ${e.width}x${e.height}`);let r=n.getContext("2d",{willReadFrequently:!0});if(t){let i=e.width;n.width=i,n.height=i,r.clearRect(0,0,i,i),r.drawImage(e,0,0,i,i/2),R6(r,i),vs(r,n.width,!1)}else n.width=e.width,n.height=e.height,r.clearRect(0,0,e.width,e.height),r.drawImage(e,0,0,n.width,n.height),vs(r,n.width,!0)}function k6(n){if(n.width===2*n.height)return n.width/64;if(n.width*17===n.height*22)return n.width/22;if(n.width*11===n.height*23)return n.width/46;throw new Error(`Bad cape size: ${n.width}x${n.height}`)}function zr(n,e){let t=k6(e);n.width=64*t,n.height=32*t;let r=n.getContext("2d",{willReadFrequently:!0});r.clearRect(0,0,n.width,n.height),r.drawImage(e,0,0,e.width,e.height)}function T6(n,e,t,r,i){let s=n.getImageData(e,t,r,i);for(let o=0;o<r;o++)for(let a=0;a<i;a++){let v=(o+a*r)*4;if(!(s.data[v+0]===0&&s.data[v+1]===0&&s.data[v+2]===0&&s.data[v+3]===255))return!1}return!0}function M6(n,e,t,r,i){let s=n.getImageData(e,t,r,i);for(let o=0;o<r;o++)for(let a=0;a<i;a++){let v=(o+a*r)*4;if(!(s.data[v+0]===255&&s.data[v+1]===255&&s.data[v+2]===255&&s.data[v+3]===255))return!1}return!0}function Lr(n){let e=c1(n.width),t=n.getContext("2d",{willReadFrequently:!0}),r=(a,v,l,c)=>Dr(t,a*e,v*e,l*e,c*e),i=(a,v,l,c)=>T6(t,a*e,v*e,l*e,c*e),s=(a,v,l,c)=>M6(t,a*e,v*e,l*e,c*e);return r(50,16,2,4)||r(54,20,2,12)||r(42,48,2,4)||r(46,52,2,12)||i(50,16,2,4)&&i(54,20,2,12)&&i(42,48,2,4)&&i(46,52,2,12)||s(50,16,2,4)&&s(54,20,2,12)&&s(42,48,2,4)&&s(46,52,2,12)?"slim":"default"}function Ur(n,e){if(e.width!==e.height&&e.width!==2*e.height)throw new Error(`Bad skin size: ${e.width}x${e.height}`);let t=c1(e.width),r=14*t,i=7*t;n.width=r,n.height=i;let s=n.getContext("2d",{willReadFrequently:!0});s.clearRect(0,0,r,i),s.drawImage(e,24*t,0,r,i,0,0,r,i)}E();x();k();R();import B6 from"mc-assets/dist/other-textures/latest/entity/player/wide/steve.png";E();x();k();R();import*as m0 from"three";E();x();k();R();var S6=()=>{if(typeof OffscreenCanvas>"u")return!1;try{let n=new OffscreenCanvas(1,1);return(n.getContext("webgl2")||n.getContext("webgl"))!==null}catch{return!1}},C6=S6(),Ve=(n,e)=>{if(C6||typeof document>"u")return new OffscreenCanvas(n,e);let t=document.createElement("canvas");return t.width=n,t.height=e,t};async function st(n){let t=await(await fetch(n)).blob();return createImageBitmap(t)}var Re=(n,e=!1)=>{n instanceof m0.Mesh&&(n.geometry?.dispose?.(),n.material?.dispose?.()),n.children&&n.children.forEach(t=>Re(t,e)),e&&n instanceof m0.Mesh&&n.material?.map?.dispose?.()},Gr={},ls={},y5=n=>{let e=new m0.Texture,t=st(n).then(r=>{let i=new OffscreenCanvas(r.width,r.height);return i.getContext("2d").drawImage(r,0,0),e.source.data=i,e.needsUpdate=!0,e});return{texture:e,promise:t}},Pt=async n=>y5(n).texture,I0=n=>{let e=Ve(n.width,n.height);e.getContext("2d").drawImage(n,0,0);let r=new m0.Texture(e);return r.magFilter=m0.NearestFilter,r.minFilter=m0.NearestFilter,r};function It(n){let{texture:e,promise:t}=y5(n);return e.magFilter=m0.NearestFilter,e.minFilter=m0.NearestFilter,t.catch(r=>{}),e}async function d1(n,e,t){if(!Gr[n]){let{promise:i,resolve:s}=Promise.withResolvers(),o=y5(n);Gr[n]=o.texture,o.promise.then(s),ls[n]=i}e(Gr[n]),ls[n].then(()=>{t?.()})}var $e=B6,af=Pt($e),cs={apiEnabled:!0},u1=n=>{Object.assign(cs,n)};async function H0(n,e){if(!cs.apiEnabled||e==="cape")return;let t=`https://playerdb.co/api/player/minecraft/${n}`,r=await fetch(t);return r.ok?(await r.json()).data.player.skin_texture:void 0}async function y0(n){n.startsWith("data:")||(n=await P6(n.replace("http://","https://")));let e=await st(n),t=Ve(64,64);return Fr(t,e),{canvas:t,image:e}}var P6=async n=>{let t=await(await fetch(n,{})).arrayBuffer();return`data:image/png;base64,${z.from(t).toString("base64")}`};function gf(n){return{mode:n.menuBackgroundMode,useMinecraftTextures:n.menuBackgroundMinecraftTextures,v2Scene:n.menuBackgroundV2Scene,v2Camera:n.menuBackgroundV2Camera,v2BlockGroup:n.menuBackgroundV2BlockGroup,v2CameraSpeed:E0(n.menuBackgroundV2CameraSpeed),v2BlockSpeed:E0(n.menuBackgroundV2BlockSpeed)}}function H6(n,e){let t=n.v2;t&&(t.setScene?.(e.menuBackgroundV2Scene),t.setCamera?.(e.menuBackgroundV2Camera),t.setBlockGroup?.(e.menuBackgroundV2BlockGroup),t.setCameraSpeed?.(E0(e.menuBackgroundV2CameraSpeed)),t.setBlockSpeed?.(E0(e.menuBackgroundV2BlockSpeed)))}function O6(n){return n.rendererMesher!=="legacy-js"}function D6(n,e,t){let r=n.inWorldRenderingConfig,i=e.rendererMeshersCountOverride,s=o=>{r.mesherWorkers=i??o};switch(e.rendererWorldPerformance){case"low-energy":s(1),r.dedicatedChangeWorker=!1;break;case"normal":s(2),r.dedicatedChangeWorker=!t;break;case"maximum":s(Math.max(3,Math.min(navigator.hardwareConcurrency??0,8))),r.dedicatedChangeWorker=!t;break}}function F6(n,e,t){let r=e.backgroundRendering,i=e.frameLimit;t?n.config.fpsLimit=i||void 0:r==="5fps"?n.config.fpsLimit=5:r==="20fps"?n.config.fpsLimit=20:n.config.fpsLimit=void 0}function z6(n,e,t){let{renderDebug:r}=e;r==="none"||t.isCypress?n.config.statsVisible=0:r==="basic"?n.config.statsVisible=1:r==="advanced"&&(n.config.statsVisible=2)}function L6(n,e,t={}){let r=n.inWorldRenderingConfig,i=O6(e);r.showChunkBorders=e.showChunkBorders,r.futuristicReveal=e.rendererFuturisticReveal,D6(n,e,i),r.renderEntities=e.renderEntities,z6(n,e,t),F6(n,e,t.windowFocused!==!1),r.vrSupport=e.vrSupport,r.vrPageGameRendering=e.vrPageGameRendering,r.enableDebugOverlay=e.rendererPerfDebugOverlay,r.clipWorldBelowY=e.clipWorldBelowY,r.extraBlockRenderers=!e.disableBlockEntityTextures,r.fetchPlayerSkins=e.loadPlayerSkins,r.highlightBlockColor=e.highlightBlockColor,r.wasmMesher=i,r.shaderCubeBlocks=e.rendererShaderCubeBlocks&&i,r.disableMesherConversionCache=!!t.isSafari,u1({apiEnabled:e.loadPlayerSkins}),r.smoothLighting=e.smoothLighting,r.shadingTheme=e.vanillaLook?"vanilla":"high-contrast",r.starfield=e.starfieldRendering,r.defaultSkybox=e.defaultSkybox,r.fov=e.fov,r.shaderCubeDebugMode=Or(e.rendererShaderCubeDebugMode)}function bf(n,e,t){e.keepChunksDistance=t.keepChunksDistance;let r=n.inWorldRenderingConfig;r.renderEars=t.renderEars,r.showHand=t.showHand,r.viewBobbing=t.viewBobbing,r.dayCycle=t.dayCycleAndLighting}function yf(n,e,t={}){n.bindRendererOptions(()=>e);let r=t.getWindowFocused?.()??!0,i=()=>{let s=e;if(L6(n,s,{isSafari:t.isSafari,isCypress:t.isCypress,windowFocused:r}),n.currentDisplay==="menu"){let o=n.backend?.getMenuBackground?.();o&&H6(o,s)}};return i(),t.onRegisterFocusHandlers?.({onFocus:()=>{r=!0,i()},onBlur:()=>{r=!1,i()}}),I6(e,i)}function _f(n,e,t){n.inWorldRenderingConfig.enableLighting=!t||e}E();x();k();R();import{proxy as U6}from"valtio";var ds=()=>U6({playerSkin:void 0,inWater:!1,waterBreathing:!1,backgroundColor:[0,0,0],ambientLight:0,directionalLight:0,eyeHeight:0,gameMode:void 0,lookingAtBlock:void 0,diggingBlock:void 0,movementState:"NOT_MOVING",onGround:!0,sneaking:!1,flying:!1,sprinting:!1,walkDist:0,prevWalkDist:0,bob:0,prevBob:0,itemUsageTicks:0,username:"",onlineMode:!1,cardinalLight:"default",lightingDisabled:!1,shouldHideHand:!1,heldItemMain:void 0,heldItemOff:void 0,perspective:"first_person",onFire:!1,fovMultiplier:1,cameraSpectatingEntity:void 0,team:void 0}),G6=n=>({isSpectator(){return n.gameMode==="spectator"},isSpectatingEntity(){return n.cameraSpectatingEntity!==void 0&&n.gameMode==="spectator"},isThirdPerson(){return this.isSpectatingEntity()?!1:n.perspective==="third_person_back"||n.perspective==="third_person_front"}}),N6=()=>({reactive:ds()}),us=(n,e,t)=>({...e,"minecraft:date":new Date});E();x();k();R();E();x();k();R();import*as Q5 from"three";import{Vec3 as u9}from"vec3";E();x();k();R();import{proxy as W6,getVersion as Vr,subscribe as ms}from"valtio";import{Vec3 as jr}from"vec3";function ps(n,e){let t=e??globalThis;return t.addEventListener("message",r=>{let{type:i,args:s,msgId:o}=r.data;if(n[i]){let a=n[i](...s);a instanceof Promise&&a.then(v=>{t.postMessage({type:"result",msgId:o,args:[v]})})}}),null}var gs=(n,e=!0)=>{let t=0;return new Proxy({},{get(r,i){return i==="transfer"?(...s)=>new Proxy({},{get(o,a){return(...v)=>{n.postMessage({type:a,args:v},s)}}}):(...s)=>{let o=t++,a=e?s.filter(v=>v instanceof ArrayBuffer||v instanceof MessagePort||typeof ImageBitmap<"u"&&v instanceof ImageBitmap||typeof OffscreenCanvas<"u"&&v instanceof OffscreenCanvas||typeof ImageData<"u"&&v instanceof ImageData):[];return n.postMessage({type:i,msgId:o,args:s},a),{then(v){let l=({data:c})=>{c.type==="result"&&c.msgId===o&&(v(c.args[0]),n.removeEventListener("message",l))};n.addEventListener("message",l)}}}}})},bs=!1,_5={toWorker:0,fromWorker:0},fs=null,V6=()=>{fs==null&&(typeof window>"u"||(fs=setInterval(()=>{globalThis.debugWorkerSyncStats={..._5},_5.toWorker=0,_5.fromWorker=0},1e3)))},f1=n=>{V6(),n==="toWorker"?_5.toWorker++:_5.fromWorker++};var j6=()=>Math.random().toString(36).slice(2,15)+Math.random().toString(36).slice(2,15),Y6=(n,e,t)=>{if(e.length===0)return;let r=n;for(let i=0;i<e.length-1;i++){let s=e[i];(r[s]==null||typeof r[s]!="object")&&(r[s]={}),r=r[s]}r[e[e.length-1]]=t},Q6=(n,e)=>{if(e.length===0)return;let t=n;for(let r=0;r<e.length-1;r++)if(t=t[e[r]],t==null)return;delete t[e[e.length-1]]},Wr=(n,e)=>{if(n==null||typeof n!="object")return n;if(n instanceof jr)return{x:n.x,y:n.y,z:n.z,__restorer:"Vec3"};if(typeof n.prepareForTransfer=="function")return n.prepareForTransfer(e);if(ArrayBuffer.isView(n))return n;if(Array.isArray(n))return n.map(r=>Wr(r,e));if(Vr(n)!==void 0)return w5(n);let t={};for(let r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=Wr(n[r],e));return t},K6=(n,e)=>{let t=[];for(let r of n){let i=r[0];i==="delete"?t.push({kind:"delete",path:r[1]}):i==="set"&&t.push({kind:"set",path:r[1],value:Wr(r[2],e)})}return t},ys=(n,e,t,r,i)=>{if(e.length===0)return;let s=K6(e,t);if(s.length!==0)try{t.postMessage({type:"sync",syncId:n,ops:s}),r==="toWorker"&&f1("toWorker")}catch{for(let a of s)a.kind==="set"&&ot(a.value)}},_s=(n,e,t,r=!1)=>{for(let i of e)i.kind==="delete"?Q6(n,i.path):Y6(n,i.path,E5(i.value,[],t,!1,!1));r==="fromWorker"&&f1("fromWorker")},ws=(n,e,t,r,i)=>{try{let s=w5(e);t.postMessage({type:"sync",syncId:n,value:s}),r==="toWorker"&&f1("toWorker")}catch{ot(e)}},As=(n,e,t,r=!1)=>{Object.assign(n,E5(e,[],t,!1,!1)),r==="fromWorker"&&f1("fromWorker")},Nr=(n,e,t,r,i)=>{let s=n.__syncFromWorker||e.__syncFromWorker,o=n.__syncToWorker||e.__syncToWorker;if(!o&&!s&&!r)return;let a=j6();if(n.__syncId=a,o||r){r&&o!==!1&&ms(e,l=>{ys(a,l,t,"toWorker",`toWorker:${i}`)});let v=n.__syncToWorkerInterval??e.__syncToWorkerInterval??0;v>0&&!r&&setInterval(()=>{ws(a,e,t,"toWorker",`toWorker:interval:${i}`)},v)}e.__syncFromWorker&&t.addEventListener("message",v=>{v.data.type==="sync"&&v.data.syncId===a&&(v.data.ops?_s(e,v.data.ops,t,"fromWorker"):v.data.value&&As(e,v.data.value,t,"fromWorker"))})},w5=n=>{if(Vr(n)===void 0)return n;if(Array.isArray(n))return n.map(w5);if(typeof n=="object"&&n!==null){let e={};for(let t in n)Object.prototype.hasOwnProperty.call(n,t)&&(e[t]=w5(n[t]));return e}return n},A5=(n,e,t=!0,r=!0,i=!1)=>{var a,v;let s=n,o={};for(let l in n)if(Object.prototype.hasOwnProperty.call(n,l)){if(t&&typeof n[l]=="function")continue;if(n[l]instanceof Date||n[l]instanceof RegExp||n[l]instanceof Map||n[l]instanceof Set||n[l]instanceof WeakMap||n[l]instanceof WeakSet,n[l]instanceof jr){o[l]={x:n[l].x,y:n[l].y,z:n[l].z},o[l].__restorer="Vec3";continue}if(o[l]=n[l],typeof n[l]=="object"&&n[l]!==null){if(n[l].prepareForTransfer){o[l]=n[l].prepareForTransfer(e);continue}let c=Vr(n[l])!==void 0;o[l]=c?w5(n[l]):n[l],n[l].__syncFromWorker&&(o[l].__syncFromWorker=!0),n[l].__syncToWorker&&(o[l].__syncToWorker=!0),n[l].__syncFromWorkerInterval&&(o[l].__syncFromWorkerInterval=n[l].__syncFromWorkerInterval),n[l].__syncToWorkerInterval&&(o[l].__syncToWorkerInterval=n[l].__syncToWorkerInterval);let u=n[l].__syncToWorker!==!1&&!i&&c&&!n[l].__syncFromWorker;if((a=o[l]).__syncToWorker??(a.__syncToWorker=u),c&&((v=o[l]).__valtio??(v.__valtio=!0)),o[l].__syncToWorker&&c){Nr(o[l],s[l],e,!0,l);continue}if(o[l].__syncFromWorker||o[l].__syncToWorker){Nr(o[l],s[l],e,c,l);continue}Nr(o[l],s[l],e,!1,l),o[l]=A5(o[l],e,t,!1,c)}}return o},ot=(n,e=[])=>{for(let t in n)if(Object.prototype.hasOwnProperty.call(n,t)){if(!n[t])continue;typeof n[t]=="object"&&n[t]!==null&&ot(n[t],[...e,t]);try{structuredClone(n[t])}catch{}}},hs=new WeakMap,J6=(n,e,t)=>{if(!n.__syncId)return;let r=n.__syncId,i=hs.get(e);if(i||(i=new Set,hs.set(e,i)),!i.has(r)&&(i.add(r),n.__syncToWorker&&e.addEventListener("message",s=>{s.data.type==="sync"&&s.data.syncId===r&&(s.data.ops?_s(n,s.data.ops,e):s.data.value&&As(n,s.data.value,e))}),n.__syncFromWorker)){n.__valtio&&ms(n,o=>{ys(r,o,e,"fromWorker",`fromWorker:${t}`)});let s=n.__syncFromWorkerInterval??0;s>0&&!n.__valtio&&setInterval(()=>{ws(r,n,e,"fromWorker",`fromWorker:interval:${t}`)},s)}},Z6=[{restorerName:"Vec3",restoreTransferred(n,e){return new jr(n.x,n.y,n.z)}}];var E5=(n,e,t,r=!0,i=!0)=>{let s=[...Z6,...e],o=(a,v)=>{if(a==null||typeof a!="object")return a;if(a.__restorer){let l=s.find(u=>u.restorerName?u.restorerName===a.__restorer:u.name===a.__restorer);if(l)return l.restoreTransferred(a,t);let c=new Error(`Restorer ${a.__restorer} not found`);if(typeof r=="function")r(c);else if(r)throw c;return a}if(Array.isArray(a))return a.map((l,c)=>o(l,`${v}[${c}]`));for(let l in a){if(!Object.prototype.hasOwnProperty.call(a,l))continue;let c=a[l];c!=null&&typeof c=="object"&&(a[l]=o(c,`${v}.${l}`))}return a.__valtio&&(a=W6(a)),i&&J6(a,t,v),a};return o(n,"root")};E();x();k();R();var h1=class{constructor(e){this.nonReactiveState=e;d(this,"events",[]);d(this,"frozenEvents",[]);d(this,"lastSecondEvents",[]);d(this,"currentFrameStartTime",null);d(this,"lastInteractionTime",0);d(this,"lastSecondUpdateTime",0);d(this,"timeWindowMs",5e3);d(this,"lastSecondWindowMs",1e3);d(this,"maxEvents",500);d(this,"lastSecondUpdateInterval",1e3);this.nonReactiveState.renderer||(this.nonReactiveState.renderer={timeline:{live:[],frozen:[],lastSecond:[]}}),this.nonReactiveState.renderer.timeline||(this.nonReactiveState.renderer.timeline={live:[],frozen:[],lastSecond:[]}),setInterval(()=>{this.updateLastSecondTimeline()},this.lastSecondUpdateInterval)}markFrameStart(){this.currentFrameStartTime=performance.now(),this.addEvent({type:"frameStart",timestamp:this.currentFrameStartTime})}markFrameEnd(){if(!this.currentFrameStartTime)return;let e=performance.now(),t=e-this.currentFrameStartTime;this.addEvent({type:"frameEnd",timestamp:e,duration:t}),this.currentFrameStartTime=null}markCameraUpdate(e){if(!e)return;let t=performance.now();this.lastInteractionTime=t,this.addEvent({type:"cameraUpdate",timestamp:t}),this.frozenEvents=[...this.events],this.trimEvents(this.frozenEvents),this.syncFrozenEvents()}markFrameDisplay(){this.addEvent({type:"frameDisplay",timestamp:performance.now()})}addEvent(e){this.events.push(e),this.lastSecondEvents.push(e),this.trimEvents(this.events),this.trimLastSecondEvents(),this.syncLiveEvents()}trimEvents(e){let r=performance.now()-this.timeWindowMs;for(;e.length>0&&e[0].timestamp<r;)e.shift();e.length>this.maxEvents&&e.splice(0,e.length-this.maxEvents)}trimLastSecondEvents(){let t=performance.now()-this.lastSecondWindowMs;for(;this.lastSecondEvents.length>0&&this.lastSecondEvents[0].timestamp<t;)this.lastSecondEvents.shift()}updateLastSecondTimeline(){let e=performance.now();e-this.lastSecondUpdateTime<this.lastSecondUpdateInterval||(this.lastSecondUpdateTime=e,this.trimLastSecondEvents(),this.syncLastSecondEvents())}syncLiveEvents(){this.nonReactiveState.renderer.timeline.live=[...this.events]}syncFrozenEvents(){this.nonReactiveState.renderer.timeline.frozen=[...this.frozenEvents]}syncLastSecondEvents(){this.nonReactiveState.renderer.timeline.lastSecond=[...this.lastSecondEvents]}clear(){this.events=[],this.frozenEvents=[],this.lastSecondEvents=[],this.syncLiveEvents(),this.syncFrozenEvents(),this.syncLastSecondEvents()}};E();x();k();R();import*as Q from"three";import{Vec3 as G0}from"vec3";import i9 from"prismarine-chat";E();x();k();R();var q6=(n,e)=>{try{return JSON.parse(n)}catch{return null}},X6={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"},m1=(n,e,t,r=s=>{},i=(s,o)=>Ve(s,o))=>{let a=[16,9],v=a[0]-a[1],l=v/16,c="front_text"in n?n.front_text.messages:[n.Text1,n.Text2,n.Text3,n.Text4];if(!c.some(g=>g!=="null"))return;let u=i(16*40,v*40),h=u.getContext("2d");r(h);let p=("front_text"in n?n.front_text.color:n.Color)||"black";for(let[g,y]of c.slice(0,4).entries())y!=="null"&&Yr(y,t,u,64,p,64*(g+1)+(e?0:-8));return u},Yr=(n,e,t,r,i,s=0)=>{let o=!1,a=typeof n=="string"&&(n?.startsWith("{")||n?.startsWith('"'))?q6(n??'""',"sign text"):n;if(!a||typeof a!="object"&&typeof a!="string")return;let v=t.getContext("2d");if(!v)throw new Error("Could not get 2d context");v.imageSmoothingEnabled=!1,v.font=`${r}px mojangles`;let l=new e(a),c=[],u=!1,h="",p=s,g=[],y=(S,C)=>{S.text!==null&&S.text!==void 0&&S.text;let M=S.text===null||S.text===void 0?void 0:String(S.text),I={color:S.color??C?.color,underlined:S.underlined??C?.underlined,strikethrough:S.strikethrough??C?.strikethrough,bold:S.bold??C?.bold,italic:S.italic??C?.italic};if(u=u||I.underlined||I.strikethrough||!1,M?.includes(`
|
|
287
287
|
`))for(let B of M.split(`
|
|
288
288
|
`))A(B,I),p+=r,h="";else M&&A(M,I);if(S.extra)for(let B of S.extra)y(B,I)},A=(S,C)=>{o||(o=S.trim()!==""),h+=S,g[p]=v.measureText(h).width;let M=C.color??i;M.startsWith("#")||(M=X6[M.toLowerCase()]||M),c.push({fontStyle:`${C.bold?"bold":""} ${C.italic?"italic":""}`,fillStyle:M,underlineStyle:C.underlined??!1,strikeStyle:C.strikethrough??!1,offset:p,text:S})};if(y(l),!u&&!l.toString().trim())return;let b=0,w=0;for(let{fillStyle:S,fontStyle:C,underlineStyle:M,strikeStyle:I,offset:B,text:H}of c){w!==B&&(b=0),w=B,v.fillStyle=S,v.textRendering="optimizeLegibility",v.font=`${C} ${r}px mojangles`;let G=g[B]??v.measureText(H).width,O=(t.width-G)/2+b;v.fillText(H,O,B),I&&(v.lineWidth=r/8,v.strokeStyle=S,v.beginPath(),v.moveTo(O,B-v.lineWidth*2.5),v.lineTo(O+v.measureText(H).width,B-v.lineWidth*2.5),v.stroke()),M&&(v.lineWidth=r/8,v.strokeStyle=S,v.beginPath(),v.moveTo(O,B+v.lineWidth),v.lineTo(O+v.measureText(H).width,B+v.lineWidth),v.stroke()),b+=v.measureText(H).width}return o};E();x();k();R();function Ht(n){let e=Math.floor(n.x/16),t=Math.floor(n.z/16);return[e,t]}function Qr(n){let e=Math.floor(n.x/16),t=Math.floor(n.y/16),r=Math.floor(n.z/16);return[e,t,r]}E();x();k();R();import{Vec3 as p1}from"vec3";import{subscribeKey as qr}from"valtio/utils";import{proxy as i7,subscribe as n7}from"valtio";E();x();k();R();var at={blocks:"blocksArray",blockCollisionShapes:"blockCollisionShapes",biomes:"biomesArray",tints:"tints"};E();x();k();R();var Es=16;var xs=(n,e)=>e?`${n}:${e}`:String(n);E();x();k();R();var Rs=0,x0={},Kr=40,vt="mc-renderer-debug-overlay",lt=(n,e=80,t=Rs,r=Kr,i)=>{if(ae)return{updateText(){},setVisibility(){}};let s=document.createElement("div");return s.style.position="fixed",s.style.top=`${r??Kr}px`,s.style.right=`${t}px`,s.style.backgroundColor="rgba(0, 0, 0, 0.7)",s.style.color="white",s.style.padding="2px",s.style.fontFamily="monospace",s.style.fontSize="12px",i?.className?s.className=i.className:s.style.zIndex="100",s.style.pointerEvents="none",document.body.appendChild(s),x0[n]=s,r===void 0&&t===Rs&&(Kr+=20),{updateText(o){s.innerText!==o&&(s.innerText=o)},setVisibility(o){s.style.display=o?"block":"none"}}};var Jr=(n,e)=>{ae||!x0[n]||(x0[n].innerText=e)},ks=n=>{if(!ae)for(let e in x0)x0[e].style.display=n?"block":"none"},Ts=()=>{if(!ae)for(let n in x0)$6(n)},$6=n=>{ae||!x0[n]||(x0[n].remove(),delete x0[n])};E();x();k();R();var e7=n=>{let e=n%24e3/24e3-.25;return e<0&&(e+=1),e>1&&(e-=1),e+(1-Math.cos(e*Math.PI))/2},t7=n=>{let e=(n%24e3+24e3)%24e3,t=e7(e),i=Math.cos(t*Math.PI*2)*.5+.5,s=Math.round(4+i*11);return Math.max(4,Math.min(15,s))},Zr=n=>{let e=(n%24e3+24e3)%24e3;if(e>=0&&e<12e3)return 15;if(e>=12e3&&e<13e3){let t=(e-12e3)/1e3;return Math.round(15-t*11)}else{if(e>=13e3&&e<23e3)return 4;{let t=(e-23e3)/1e3;return Math.round(4+t*11)}}},r7=()=>{let n=[{ticks:0,label:"6:00 AM (sunrise)"},{ticks:6e3,label:"12:00 PM (noon)"},{ticks:12e3,label:"6:00 PM (sunset starts)"},{ticks:12500,label:"6:30 PM (sunset mid)"},{ticks:13e3,label:"7:00 PM (night begins)"},{ticks:18e3,label:"12:00 AM (midnight)"},{ticks:19e3,label:"1:00 AM"},{ticks:23e3,label:"5:00 AM (dawn begins)"},{ticks:23500,label:"5:30 AM (dawn mid)"}];for(let{ticks:e,label:t}of n){let r=t7(e),i=Zr(e)}};typeof window<"u"&&(window.debugSkyLight=r7);E();x();k();R();function Ue(n,e,t,r){if(n.on(e,t),r.aborted){n.off(e,t);return}r.addEventListener("abort",()=>{n.off(e,t)},{once:!0})}function Ms(n,e,t,r){if(n.on(e,t),r.aborted){n.off(e,t);return}r.addEventListener("abort",()=>{n.off(e,t)},{once:!0})}function x5(n,e){return(n%e+e)%e}var R0=class R0{constructor(e,t,r){this.resourcesManager=e;this.displayOptions=t;this.initOptions=r;d(this,"worldReadyResolvers",Promise.withResolvers());d(this,"worldReadyPromise",this.worldReadyResolvers.promise);d(this,"timeOfTheDay",0);d(this,"worldSizeParams",{minY:0,worldHeight:256});d(this,"reactiveDebugParams",i7({stopRendering:!1,chunksRenderAboveOverride:void 0,chunksRenderAboveEnabled:!1,chunksRenderBelowOverride:void 0,chunksRenderBelowEnabled:!1,chunksRenderDistanceOverride:void 0,chunksRenderDistanceEnabled:!1,disableEntities:!1}));d(this,"active",!1);d(this,"loadedChunks",{});d(this,"finishedChunks",{});d(this,"finishedSections",{});d(this,"sectionsWaiting",new Map);d(this,"queuedChunks",new Set);d(this,"queuedFunctions",[]);d(this,"renderUpdateEmitter",new Z0);d(this,"customTexturesDataUrl");d(this,"workers",[]);d(this,"viewerChunkPosition");d(this,"lastViewerChunkGridX");d(this,"lastViewerChunkGridZ");d(this,"lastCamUpdate",0);d(this,"droppedFpsPercentage",0);d(this,"initialChunkLoadWasStartedIn");d(this,"initialChunksLoad",!0);d(this,"enableChunksLoadDelay",!1);d(this,"texturesVersion");d(this,"viewDistance",-1);d(this,"onRenderDistanceChanged");d(this,"chunksLength",0);d(this,"allChunksFinished",!1);d(this,"messageQueue",[]);d(this,"isProcessingQueue",!1);d(this,"ONMESSAGE_TIME_LIMIT",30);d(this,"handleResize",()=>{});d(this,"highestBlocksByChunks",new Map);d(this,"blockEntities",{});d(this,"workersProcessAverageTime",0);d(this,"workersProcessAverageTimeCount",0);d(this,"maxWorkersProcessTime",0);d(this,"workersPreAverageTime",0);d(this,"workersWasmAverageTime",0);d(this,"workersPostAverageTime",0);d(this,"workersPhaseSampleCount",0);d(this,"workersPreTargetConvertAverageTime",0);d(this,"workersPreNeighborConvertAverageTime",0);d(this,"workersPreNeighborCountAverage",0);d(this,"workersPreTypedArrayBuildAverageTime",0);d(this,"workersPreOtherAverageTime",0);d(this,"workersPreCacheHitsTotal",0);d(this,"workersPreCacheMissesTotal",0);d(this,"geometryReceiveCount",{});d(this,"allLoadedIn");d(this,"onWorldSwitched",[]);d(this,"renderTimeMax",0);d(this,"renderTimeAvg",0);d(this,"renderTimeAvgCount",0);d(this,"edgeChunks",{});d(this,"lastAddChunk",null);d(this,"neighborChunkUpdates",!0);d(this,"lastChunkDistance",0);d(this,"debugStopGeometryUpdate",!1);d(this,"protocolCustomBlocks",new Map);d(this,"heightmapDebounceTimers",new Map);d(this,"sectionDirtyCount",new Map);d(this,"sectionDirtyTimers",new Map);d(this,"sectionDirtyPendingArgs",new Map);d(this,"blockStateModelInfo",new Map);d(this,"worldBlockProvider");d(this,"soundSystem");d(this,"worldRendererConfig");d(this,"playerStateReactive");d(this,"playerStateUtils");d(this,"reactiveState");d(this,"mesherLogReader");d(this,"forceCallFromMesherReplayer",!1);d(this,"stopMesherMessagesProcessing",!1);d(this,"abortController",new AbortController);d(this,"valtioUnsubs",[]);d(this,"lastRendered",0);d(this,"renderingActive",!0);d(this,"geometryReceiveCountPerSec",0);d(this,"mesherLogger",{contents:[],active:new URL(location.href).searchParams.get("mesherlog")==="true"});d(this,"currentRenderedFrames",0);d(this,"fpsAverage",0);d(this,"lastFps",0);d(this,"fpsWorst");d(this,"fpsSamples",0);d(this,"backendInfoReport","-");d(this,"chunksFullInfo","-");d(this,"workerCustomHandleTime",0);d(this,"queueAwaited",!1);d(this,"toWorkerMessagesQueue",{});this.snapshotInitialValues(),this.worldRendererConfig=t.inWorldRenderingConfig,this.playerStateReactive=t.playerStateReactive,this.playerStateUtils=U2(this.playerStateReactive),this.reactiveState=t.rendererState,this.renderUpdateEmitter.on("update",()=>{let o=Object.keys(this.finishedChunks).length;Jr("loaded-chunks",`${o}/${this.chunksLength} chunks (${this.lastChunkDistance}/${this.viewDistance})`)}),lt("downloaded-chunks",100,140,20,{className:vt}),this.connect(this.displayOptions.worldView);let i=setInterval(()=>{this.geometryReceiveCountPerSec=Object.values(this.geometryReceiveCount).reduce((o,a)=>o+a,0),this.geometryReceiveCount={},ks(this.displayAdvancedStats),this.updateChunksStats()},500),s=setInterval(()=>{this.fpsUpdate()},1e3);this.abortController.signal.addEventListener("abort",()=>{clearInterval(i),clearInterval(s)})}anyModuleRequiresHeightmap(){return!1}isShaderCubeBlocksEnabled(){return this.worldRendererConfig.shaderCubeBlocks===!0}shaderCubeBlocksEnabled(){return this.isShaderCubeBlocksEnabled()}get version(){return this.displayOptions.version}get displayAdvancedStats(){return(this.initOptions.config.statsVisible??0)>1}fpsUpdate(){this.fpsSamples++,this.fpsAverage=(this.fpsAverage*(this.fpsSamples-1)+this.currentRenderedFrames)/this.fpsSamples,this.fpsWorst===void 0?this.fpsWorst=this.currentRenderedFrames:this.fpsWorst=Math.min(this.fpsWorst,this.currentRenderedFrames),this.lastFps=this.currentRenderedFrames,this.displayOptions.nonReactiveState.fps=this.currentRenderedFrames,this.displayOptions.nonReactiveState.worstRenderTime=this.renderTimeMax,this.displayOptions.nonReactiveState.avgRenderTime=this.renderTimeAvg,this.currentRenderedFrames=0}logWorkerWork(e){this.mesherLogger.active&&this.mesherLogger.contents.push(typeof e=="function"?e():e)}async init(){if(this.active)throw new Error("WorldRendererCommon is already initialized");await Promise.all([this.resetWorkers(),(async()=>{this.resourcesManager.currentResources?.allReady&&await this.updateAssetsData()})()]);let e=async()=>{this.active&&await this.updateAssetsData()};Ms(this.resourcesManager,"assetsTexturesUpdated",e,this.abortController.signal),this.watchReactivePlayerState(),this.watchReactiveConfig(),this.worldReadyResolvers.resolve()}snapshotInitialValues(){}wasChunkSentToWorker(e){return this.loadedChunks[e]}async getHighestBlocks(e){return this.highestBlocksByChunks.get(e)}updateCustomBlock(e,t,r){if(this.protocolCustomBlocks.set(e,{...this.protocolCustomBlocks.get(e),[t]:r}),this.logWorkerWork(()=>`-> updateCustomBlock ${e} ${t} ${r} ${this.wasChunkSentToWorker(e)}`),this.wasChunkSentToWorker(e)){let[i,s,o]=t.split(",").map(Number);this.setBlockStateId(new p1(i,s,o),void 0)}}async getBlockInfo(e,t){let i=`${Math.floor(e.x/16)*16},${Math.floor(e.z/16)*16}`,s=this.protocolCustomBlocks.get(i)?.[`${e.x},${e.y},${e.z}`],o=xs(t,s),a=this.blockStateModelInfo.get(o);return{customBlockName:s,modelInfo:a}}initWorkers(e=this.worldRendererConfig.mesherWorkers){for(let t=0;t<e+0;t++){let r=s7(i=>{Array.isArray(i)?this.messageQueue.push(...i):this.messageQueue.push(i),this.processMessageQueue("worker")},this.worldRendererConfig.wasmMesher?"mesherWasm.js":"mesher.js");this.workers.push(r)}}onReactivePlayerStateUpdated(e,t,r=!0){return r&&t(this.playerStateReactive[e]),qr(this.playerStateReactive,e,t)}onReactiveConfigUpdated(e,t){t(this.worldRendererConfig[e]),e==="*"?n7(this.worldRendererConfig,t):qr(this.worldRendererConfig,e,t)}onReactiveDebugUpdated(e,t){t(this.reactiveDebugParams[e]),qr(this.reactiveDebugParams,e,t)}watchReactivePlayerState(){this.valtioUnsubs.push(this.onReactivePlayerStateUpdated("backgroundColor",e=>{this.changeBackgroundColor(e)})),this.valtioUnsubs.push(this.onReactivePlayerStateUpdated("cardinalLight",e=>{this.changeCardinalLight(e)}))}watchReactiveConfig(){this.valtioUnsubs.push(this.onReactiveConfigUpdated("fetchPlayerSkins",e=>{u1({apiEnabled:e})}))}async processMessageQueue(e){if(this.isProcessingQueue||this.messageQueue.length===0)return;if(this.logWorkerWork(`# ${e} processing queue`),this.lastRendered&&performance.now()-this.lastRendered>this.ONMESSAGE_TIME_LIMIT&&this.worldRendererConfig._experimentalSmoothChunkLoading&&this.renderingActive){let i=performance.now();await new Promise(s=>{requestAnimationFrame(s)}),this.logWorkerWork(`# processing got delayed by ${performance.now()-i}ms`)}this.isProcessingQueue=!0;let t=performance.now(),r=0;for(;this.messageQueue.length>0;){let i=this.stopMesherMessagesProcessing;if(!i){let s=this.messageQueue.shift();this.handleMessage(s),r++}if(i||performance.now()-t>this.ONMESSAGE_TIME_LIMIT&&this.renderingActive&&this.worldRendererConfig._experimentalSmoothChunkLoading){if(this.messageQueue.length>0){requestAnimationFrame(async()=>{this.isProcessingQueue=!1,this.processMessageQueue("queue-delay")});return}break}}this.isProcessingQueue=!1}handleMessage(e){var r,i;let t=e;if(this.active){if(this.mesherLogReader?.workerMessageReceived(t.type,t),t.type!=="geometry"||!this.debugStopGeometryUpdate){let s=performance.now();this.handleWorkerMessage(t),this.workerCustomHandleTime+=performance.now()-s}if(t.type==="geometry"){this.logWorkerWork(()=>`-> ${t.workerIndex} geometry ${t.key} ${JSON.stringify({dataSize:JSON.stringify(t).length})}`),(r=this.geometryReceiveCount)[i=t.workerIndex]??(r[i]=0),this.geometryReceiveCount[t.workerIndex]++;let s=t.key.split(",").map(Number);this.lastChunkDistance=Math.max(...this.getDistance(new p1(s[0],0,s[2])))}if(t.type==="sectionFinished"){if(this.logWorkerWork(`<- ${t.workerIndex} sectionFinished ${t.key} ${JSON.stringify({processTime:t.processTime})}`),!this.sectionsWaiting.has(t.key))return;this.sectionsWaiting.set(t.key,this.sectionsWaiting.get(t.key)-1),this.sectionsWaiting.get(t.key)===0&&(this.sectionsWaiting.delete(t.key),this.finishedSections[t.key]=!0);let s=t.key.split(",").map(Number),o=`${s[0]},${s[2]}`;if(this.loadedChunks[o]){let a=!0,v=this.getSectionHeight();for(let l=this.worldMinYRender;l<this.worldSizeParams.worldHeight;l+=v)if(!this.finishedSections[`${s[0]},${l},${s[2]}`]){a=!1;break}if(a){this.finishedChunks[o]=!0;let l=16,c=`${Math.floor(s[0]/l)},${Math.floor(s[2]/l)}`;this.reactiveState.world.chunksLoaded[c]=!0,this.renderUpdateEmitter.emit("chunkFinished",`${s[0]},${s[2]}`),this.checkAllFinished()}}if(this.renderUpdateEmitter.emit("update"),t.processTime&&(this.workersProcessAverageTimeCount++,this.workersProcessAverageTime=(this.workersProcessAverageTime*(this.workersProcessAverageTimeCount-1)+t.processTime)/this.workersProcessAverageTimeCount,this.maxWorkersProcessTime=Math.max(this.maxWorkersProcessTime,t.processTime)),typeof t.pre=="number"&&typeof t.wasm=="number"&&typeof t.post=="number"&&(t.pre>0||t.wasm>0||t.post>0)){let a=++this.workersPhaseSampleCount;this.workersPreAverageTime=(this.workersPreAverageTime*(a-1)+t.pre)/a,this.workersWasmAverageTime=(this.workersWasmAverageTime*(a-1)+t.wasm)/a,this.workersPostAverageTime=(this.workersPostAverageTime*(a-1)+t.post)/a;let v=typeof t.preTargetConvert=="number"?t.preTargetConvert:0,l=typeof t.preNeighborConvert=="number"?t.preNeighborConvert:0,c=typeof t.preNeighborCount=="number"?t.preNeighborCount:0,u=typeof t.preTypedArrayBuild=="number"?t.preTypedArrayBuild:0,h=typeof t.preOther=="number"?t.preOther:0,p=typeof t.preCacheHits=="number"?t.preCacheHits:0,g=typeof t.preCacheMisses=="number"?t.preCacheMisses:0;if(this.workersPreTargetConvertAverageTime=(this.workersPreTargetConvertAverageTime*(a-1)+v)/a,this.workersPreNeighborConvertAverageTime=(this.workersPreNeighborConvertAverageTime*(a-1)+l)/a,this.workersPreNeighborCountAverage=(this.workersPreNeighborCountAverage*(a-1)+c)/a,this.workersPreTypedArrayBuildAverageTime=(this.workersPreTypedArrayBuildAverageTime*(a-1)+u)/a,this.workersPreOtherAverageTime=(this.workersPreOtherAverageTime*(a-1)+h)/a,this.workersPreCacheHitsTotal+=p,this.workersPreCacheMissesTotal+=g,this.worldRendererConfig.debugWasmPerf&&a%R0.PHASE_PERF_LOG_INTERVAL===0){let y=this.workersPreAverageTime+this.workersWasmAverageTime+this.workersPostAverageTime,A=y>0?this.workersPreAverageTime/y*100:0,b=y>0?this.workersWasmAverageTime/y*100:0,w=y>0?this.workersPostAverageTime/y*100:0,S=this.workersPreAverageTime,C=S>0?this.workersPreTargetConvertAverageTime/S*100:0,M=S>0?this.workersPreNeighborConvertAverageTime/S*100:0,I=S>0?this.workersPreTypedArrayBuildAverageTime/S*100:0,B=S>0?this.workersPreOtherAverageTime/S*100:0,H=this.workersPreNeighborCountAverage,G=H>0?this.workersPreNeighborConvertAverageTime/H:0,O=this.workersPreCacheHitsTotal+this.workersPreCacheMissesTotal,j=O>0?this.workersPreCacheHitsTotal/O*100:0}}}if(t.type==="blockStateModelInfo")for(let[s,o]of Object.entries(t.info))this.blockStateModelInfo.set(s,o);if(t.type==="heightmap"){let s=new Int16Array(t.heightmap);this.reactiveState.world.heightmaps[t.key]=s}}}downloadMesherLog(){let e=document.createElement("a");e.href="data:text/plain;charset=utf-8,"+encodeURIComponent(this.mesherLogger.contents.join(`
|
|
289
289
|
`)),e.download="mesher.log",e.click()}checkAllFinished(){this.sectionsWaiting.size===0&&(this.reactiveState.world.mesherWork=!1),Object.keys(this.finishedChunks).length>=this.chunksLength&&(this.allChunksLoaded?.(),this.allChunksFinished=!0,this.allLoadedIn??(this.allLoadedIn=Date.now()-this.initialChunkLoadWasStartedIn)),this.updateChunksStats()}changeHandSwingingState(e,t){}updateViewerPosition(e){this.viewerChunkPosition=e;for(let[i,s]of Object.entries(this.loadedChunks))s&&this.updatePosDataChunk?.(i);let t=Math.floor(e.x/16),r=Math.floor(e.z/16);(t!==this.lastViewerChunkGridX||r!==this.lastViewerChunkGridZ)&&(this.lastViewerChunkGridX=t,this.lastViewerChunkGridZ=r,this.onViewerChunkPositionChanged())}onViewerChunkPositionChanged(){}sendWorkers(e){for(let t of this.workers)t.postMessage(e)}getDistance(e){let[t,r]=Ht(this.viewerChunkPosition),i=16,s=Math.abs(t-Math.floor(e.x/i)),o=Math.abs(r-Math.floor(e.z/i));return[s,o]}resetWorld(){for(let e of this.workers)e.terminate();this.workers=[]}async resetWorkers(){this.resetWorld(),typeof document<"u"&&document?.readyState==="loading"&&await new Promise(e=>{document.addEventListener("DOMContentLoaded",e)}),this.initWorkers(),this.active=!0,this.sendMesherMcData()}getMesherConfig(){let e=this.timeOfTheDay,t=e<0||e>24e3?15:Zr(e);return{version:this.version,enableLighting:this.worldRendererConfig.enableLighting,skyLight:t,smoothLighting:this.worldRendererConfig.smoothLighting,shadingTheme:this.worldRendererConfig.shadingTheme,cardinalLight:this.worldRendererConfig.cardinalLight,outputFormat:this.outputFormat,debugModelVariant:this.worldRendererConfig.debugModelVariant,clipWorldBelowY:this.worldRendererConfig.clipWorldBelowY,disableBlockEntityTextures:!this.worldRendererConfig.extraBlockRenderers,worldMinY:this.worldMinYRender,worldMaxY:this.worldMinYRender+this.worldSizeParams.worldHeight,disableConversionCache:this.worldRendererConfig.disableMesherConversionCache,computeWireframeEdges:this.worldRendererConfig.futuristicReveal===!0,shaderCubeBlocks:this.isShaderCubeBlocksEnabled()}}sendMesherMcData(){let e=this.resourcesManager.currentResources.mcData;Cs(this.workers,this.version,at,e),this.logWorkerWork("# mcData sent")}async updateAssetsData(){let e=this.resourcesManager.currentResources;if(this.workers.length===0)throw new Error("workers not initialized yet");for(let[t,r]of this.workers.entries()){let{blockstatesModels:i}=e;r.postMessage({type:"mesherData",workerIndex:t,blocksAtlas:{latest:e.blocksAtlasJson},blockstatesModels:i,config:this.getMesherConfig()})}this.logWorkerWork("# mesherData sent")}getSectionHeight(){return Es}get worldMinYRender(){let e=this.getSectionHeight();return Math.floor(Math.max(this.worldSizeParams.minY,this.worldRendererConfig.clipWorldBelowY??-1/0)/e)*e}updateChunksStats(){let e=Object.keys(this.finishedChunks);this.displayOptions.nonReactiveState.world.chunksLoadedCount=e.length,this.displayOptions.nonReactiveState.world.chunksTotalNumber=this.chunksLength,this.reactiveState.world.allChunksLoaded=this.allChunksFinished;let t=`Q: ${this.messageQueue.length} ${Object.keys(this.loadedChunks).length}/${Object.keys(this.finishedChunks).length}/${this.chunksLength} chunks (${this.workers.length}:${this.workersProcessAverageTime.toFixed(0)}ms/${this.geometryReceiveCountPerSec}ss/${this.allLoadedIn?.toFixed(1)??"-"}s)`;this.chunksFullInfo=t,this.displayOptions.nonReactiveState.world.chunksFullInfo=t,Jr("downloaded-chunks",t)}addColumn(e,t,r,i){if(!this.active)return;if(this.workers.length===0)throw new Error("workers not initialized yet");this.initialChunksLoad=!1,this.initialChunkLoadWasStartedIn??(this.initialChunkLoadWasStartedIn=Date.now()),this.loadedChunks[`${e},${t}`]=!0,this.updateChunksStats();let s=`${e},${t}`,o=this.protocolCustomBlocks.get(s);for(let l of this.workers)l.postMessage({type:"chunk",x:e,z:t,chunk:r,customBlockModels:o||void 0});this.worldRendererConfig.wasmMesher||this.workers[0].postMessage({type:"getHeightmap",x:e,z:t}),this.logWorkerWork(()=>`-> chunk ${JSON.stringify({x:e,z:t,chunkLength:r.length,customBlockModelsLength:o?Object.keys(o).length:0})}`),this.mesherLogReader?.chunkReceived(e,t,r.length);let a=this.getSectionHeight(),v=16;for(let l=this.worldMinYRender;l<this.worldSizeParams.worldHeight;l+=a){let c=new p1(e,l,t);this.setSectionDirty(c),this.neighborChunkUpdates&&(!i||this.worldRendererConfig.smoothLighting)&&(this.setSectionDirty(c.offset(-v,0,0)),this.setSectionDirty(c.offset(v,0,0)),this.setSectionDirty(c.offset(0,0,-v)),this.setSectionDirty(c.offset(0,0,v)))}}markAsLoaded(e,t){this.loadedChunks[`${e},${t}`]=!0,this.finishedChunks[`${e},${t}`]=!0,this.logWorkerWork(`-> markAsLoaded ${JSON.stringify({x:e,z:t})}`),this.renderUpdateEmitter.emit("chunkFinished",`${e},${t}`),this.checkAllFinished()}removeColumn(e,t){var a;delete this.loadedChunks[`${e},${t}`];let r=`${e},${t}`,i=this.heightmapDebounceTimers.get(r);i&&(clearTimeout(i),this.heightmapDebounceTimers.delete(r));for(let[v,l]of this.sectionDirtyTimers)v.startsWith(`${e},`)&&v.endsWith(`,${t}`)&&(clearTimeout(l),this.sectionDirtyTimers.delete(v),this.sectionDirtyCount.delete(v),this.sectionDirtyPendingArgs.delete(v));for(let v=0;v<this.workers.length;v++)(a=this.toWorkerMessagesQueue)[v]??(a[v]=[]),this.toWorkerMessagesQueue[v].push({type:"unloadChunk",x:e,z:t});this.dispatchMessages(),this.logWorkerWork(`-> unloadChunk ${JSON.stringify({x:e,z:t})}`),delete this.finishedChunks[`${e},${t}`],this.allChunksFinished=Object.keys(this.finishedChunks).length===this.chunksLength,Object.keys(this.finishedChunks).length===0&&(this.allLoadedIn=void 0,this.initialChunkLoadWasStartedIn=void 0);let s=this.getSectionHeight();for(let v=this.worldMinYRender;v<this.worldSizeParams.worldHeight;v+=s){let l=`${e},${v},${t}`,c=this.sectionsWaiting.get(l);c!==void 0&&c>0,this.sectionsWaiting.delete(l),delete this.finishedSections[l]}this.highestBlocksByChunks.delete(`${e},${t}`);let o=`${Math.floor(e/16)},${Math.floor(t/16)}`;delete this.reactiveState.world.heightmaps[o],this.updateChunksStats(),Object.keys(this.loadedChunks).length===0&&(this.mesherLogger.contents=[],this.logWorkerWork("# all chunks unloaded. New log started"),this.mesherLogReader?.maybeStartReplay())}setBlockStateId(e,t,r=!0){(async()=>{let o=Math.floor(e.x/16)*16,a=Math.floor(e.z/16)*16;this.queuedChunks.has(`${o},${a}`)&&await new Promise(v=>{this.queuedFunctions.push(()=>{v()})}),this.loadedChunks[`${o},${a}`],this.setBlockStateIdInner(e,t,r)})()}updateEntity(e,t=!1){}lightUpdate(e,t){}connect(e){let t=e,r=this.abortController.signal;Ue(t,"entity",s=>{this.updateEntity(s,!1)},r),Ue(t,"entityMoved",s=>{this.updateEntity(s,!0)},r),Ue(t,"playerEntity",s=>{this.updatePlayerEntity?.(s)},r);let i=null;Ue(t,"loadChunk",({x:s,z:o,chunk:a,worldConfig:v,isLightUpdate:l})=>{this.worldSizeParams=v,this.queuedChunks.add(`${s},${o}`);let c=[s,o,a,l];i||(i={data:[],timeout:setTimeout(()=>{for(let u of i.data)this.queuedChunks.delete(`${u[0]},${u[1]}`),this.addColumn(...u);for(let u of this.queuedFunctions)u();this.queuedFunctions=[],i=null},this.worldRendererConfig.addChunksBatchWaitTime)}),i.data.push(c)},r),Ue(t,"blockEntities",s=>{this.blockEntities=s},r),Ue(t,"unloadChunk",({x:s,z:o})=>{this.removeColumn(s,o)},r),Ue(t,"blockUpdate",({pos:s,stateId:o})=>{this.setBlockStateId(new p1(s.x,s.y,s.z),o)},r),Ue(t,"chunkPosUpdate",({pos:s})=>{this.updateViewerPosition(s)},r),Ue(t,"end",()=>{this.worldStop?.()},r),Ue(t,"renderDistance",s=>{this.viewDistance=s,this.chunksLength=s===0?1:d5(s).length,this.allChunksFinished=Object.keys(this.finishedChunks).length===this.chunksLength,this.onRenderDistanceChanged?.(s)},r),Ue(t,"markAsLoaded",({x:s,z:o})=>{this.markAsLoaded(s,o)},r),Ue(t,"updateLight",({pos:s})=>{this.lightUpdate(s.x,s.z)},r),Ue(t,"onWorldSwitch",()=>{for(let s of this.onWorldSwitched)try{s()}catch(o){setTimeout(()=>{throw o},0)}},r),Ue(t,"time",s=>{this.worldRendererConfig.dayCycle&&(this.timeUpdated?.(s),this.timeOfTheDay=s)},r),Ue(t,"biomeUpdate",({biome:s})=>{this.biomeUpdated?.(s)},r),Ue(t,"biomeReset",()=>{this.biomeReset?.()},r)}setBlockStateIdInner(e,t,r=!0){let s=`${Math.floor(e.x/16)*16},${Math.floor(e.z/16)*16}`,o=`${e.x},${e.y},${e.z}`,a=this.protocolCustomBlocks.get(s)||{};for(let v of this.workers)v.postMessage({type:"blockUpdate",pos:e,stateId:t,customBlockModels:a});if(this.anyModuleRequiresHeightmap()){let v=Math.floor(e.x/16)*16,l=Math.floor(e.z/16)*16,c=`${v},${l}`;if(!this.worldRendererConfig.wasmMesher){let u=this.heightmapDebounceTimers.get(c);u&&clearTimeout(u),this.heightmapDebounceTimers.set(c,setTimeout(()=>{this.heightmapDebounceTimers.delete(c),this.workers[0]?.postMessage({type:"getHeightmap",x:v,z:l})},100))}}if(this.logWorkerWork(`-> blockUpdate ${JSON.stringify({pos:e,stateId:t,customBlockModels:a})}`),this.setSectionDirty(e,!0,!0),this.neighborChunkUpdates){let l=this.getSectionHeight();e.x&15||this.setSectionDirty(e.offset(-16,0,0),!0,!0),(e.x&15)===15&&this.setSectionDirty(e.offset(16,0,0),!0,!0),e.y&l-1||this.setSectionDirty(e.offset(0,-l,0),!0,!0),(e.y&l-1)===l-1&&this.setSectionDirty(e.offset(0,l,0),!0,!0),e.z&15||this.setSectionDirty(e.offset(0,0,-16),!0,!0),(e.z&15)===15&&this.setSectionDirty(e.offset(0,0,16),!0,!0),r&&(!(e.x&15)&&!(e.z&15)&&this.setSectionDirty(e.offset(-16,0,-16),!0,!0),(e.x&15)===15&&!(e.z&15)&&this.setSectionDirty(e.offset(16,0,-16),!0,!0),!(e.x&15)&&(e.z&15)===15&&this.setSectionDirty(e.offset(-16,0,16),!0,!0),(e.x&15)===15&&(e.z&15)===15&&this.setSectionDirty(e.offset(16,0,16),!0,!0),!(e.x&15)&&!(e.y&l-1)&&this.setSectionDirty(e.offset(-16,-l,0),!0,!0),(e.x&15)===15&&!(e.y&l-1)&&this.setSectionDirty(e.offset(16,-l,0),!0,!0),!(e.z&15)&&!(e.y&l-1)&&this.setSectionDirty(e.offset(0,-l,-16),!0,!0),(e.z&15)===15&&!(e.y&l-1)&&this.setSectionDirty(e.offset(0,-l,16),!0,!0),!(e.y&l-1)&&!(e.x&15)&&!(e.z&15)&&this.setSectionDirty(e.offset(-16,-l,-16),!0,!0),!(e.y&l-1)&&(e.x&15)===15&&!(e.z&15)&&this.setSectionDirty(e.offset(16,-l,-16),!0,!0),!(e.y&l-1)&&!(e.x&15)&&(e.z&15)===15&&this.setSectionDirty(e.offset(-16,-l,16),!0,!0),!(e.y&l-1)&&(e.x&15)===15&&(e.z&15)===15&&this.setSectionDirty(e.offset(16,-l,16),!0,!0))}}getWorkerNumber(e,t=!1){let i=this.getSectionHeight();if(this.worldRendererConfig.dedicatedChangeWorker&&this.workers.length>1){if(this.worldRendererConfig.wasmMesher)return x5(Math.floor(e.x/16)+Math.floor(e.z/16),this.workers.length);if(t){let a=`${Math.floor(e.x/16)*16},${Math.floor(e.y/i)*i},${Math.floor(e.z/16)*16}`;if(this.sectionsWaiting.get(a)&&!this.finishedSections[a]){let l=this.workers.length-1;return x5(Math.floor(e.x/16)+Math.floor(e.y/i)+Math.floor(e.z/16),l)}return this.workers.length-1}let o=this.workers.length-1;return x5(Math.floor(e.x/16)+Math.floor(e.y/i)+Math.floor(e.z/16),o)}if(this.worldRendererConfig.wasmMesher)return x5(Math.floor(e.x/16)+Math.floor(e.z/16),this.workers.length);if(t){let o=`${Math.floor(e.x/16)*16},${Math.floor(e.y/i)*i},${Math.floor(e.z/16)*16}`;if(!(this.sectionsWaiting.get(o)&&!this.finishedSections[o]))return 0}return x5(Math.floor(e.x/16)+Math.floor(e.y/i)+Math.floor(e.z/16),this.workers.length)}async debugGetWorkerCustomBlockModel(e){let t=[];for(let r of this.workers)t.push(new Promise(i=>{r.addEventListener("message",s=>{s.data.type==="customBlockModel"&&i(s.data.customBlockModel)})})),r.postMessage({type:"getCustomBlockModel",pos:e});return Promise.all(t)}setSectionDirty(e,t=!0,r=!1){if(!this.forceCallFromMesherReplayer&&this.mesherLogReader)return;if(this.viewDistance===-1)throw new Error("viewDistance not set");let i=this.getDistance(e);if(!this.workers.length||i[0]>this.viewDistance||i[1]>this.viewDistance)return;if(!t){this._dispatchDirtyImmediate(e,t,r);return}let s=16,o=this.getSectionHeight(),a=`${Math.floor(e.x/s)*s},${Math.floor(e.y/o)*o},${Math.floor(e.z/s)*s}`,v=(this.sectionDirtyCount.get(a)??0)+1;this.sectionDirtyCount.set(a,v),v<=R0.GEOMETRY_THROTTLE_THRESHOLD?(this._dispatchDirtyImmediate(e,t,r),this.sectionDirtyTimers.has(a)||this.sectionDirtyTimers.set(a,setTimeout(()=>{let l=this.sectionDirtyPendingArgs.get(a);this.sectionDirtyCount.delete(a),this.sectionDirtyTimers.delete(a),this.sectionDirtyPendingArgs.delete(a),l&&this._dispatchDirtyImmediate(l.pos,l.value,l.useChangeWorker)},R0.GEOMETRY_THROTTLE_DELAY))):(this.sectionDirtyPendingArgs.set(a,{pos:e,value:t,useChangeWorker:r}),this.sectionDirtyTimers.has(a)||this.sectionDirtyTimers.set(a,setTimeout(()=>{let l=this.sectionDirtyPendingArgs.get(a);this.sectionDirtyCount.delete(a),this.sectionDirtyTimers.delete(a),this.sectionDirtyPendingArgs.delete(a),l&&this._dispatchDirtyImmediate(l.pos,l.value,l.useChangeWorker)},R0.GEOMETRY_THROTTLE_DELAY)))}_dispatchDirtyImmediate(e,t,r){var v;this.reactiveState.world.mesherWork=!0;let i=16,s=this.getSectionHeight(),o=`${Math.floor(e.x/i)*i},${Math.floor(e.y/s)*s},${Math.floor(e.z/i)*i}`;this.renderUpdateEmitter.emit("dirty",e,t);let a=this.getWorkerNumber(e,r&&(this.mesherLogger.active||this.worldRendererConfig.dedicatedChangeWorker));this.sectionsWaiting.set(o,(this.sectionsWaiting.get(o)??0)+1),this.forceCallFromMesherReplayer?this.workers[a].postMessage({type:"dirty",x:e.x,y:e.y,z:e.z,value:t,config:this.getMesherConfig()}):((v=this.toWorkerMessagesQueue)[a]??(v[a]=[]),this.toWorkerMessagesQueue[a].push({type:"dirty",x:e.x,y:e.y,z:e.z,value:t,config:this.getMesherConfig()}),this.dispatchMessages())}dispatchMessages(){this.queueAwaited||(this.queueAwaited=!0,setTimeout(()=>{for(let e in this.toWorkerMessagesQueue){let t=this.workers[Number(e)],r=this.toWorkerMessagesQueue[e];t.postMessage(r);for(let i of r)this.logWorkerWork(`-> ${e} dispatchMessages ${i.type} ${JSON.stringify({x:i.x,y:i.y,z:i.z,value:i.value})}`)}this.toWorkerMessagesQueue={},this.queueAwaited=!1}))}async waitForChunksToRender(){return new Promise((e,t)=>{if([...this.sectionsWaiting].length===0){e();return}let r=()=>{this.sectionsWaiting.size===0&&(this.renderUpdateEmitter.removeListener("update",r),e())};this.renderUpdateEmitter.on("update",r)})}async waitForChunkToLoad(e){return new Promise((t,r)=>{let s=`${Math.floor(e.x/16)*16},${Math.floor(e.z/16)*16}`;if(this.loadedChunks[s]){t();return}let o=()=>{this.loadedChunks[s]&&(this.renderUpdateEmitter.removeListener("update",o),t())};this.renderUpdateEmitter.on("update",o)})}destroy(){for(let e of this.valtioUnsubs)e();this.valtioUnsubs=[];for(let e of this.heightmapDebounceTimers.values())clearTimeout(e);this.heightmapDebounceTimers.clear();for(let e of this.sectionDirtyTimers.values())clearTimeout(e);this.sectionDirtyTimers.clear(),this.sectionDirtyCount.clear(),this.sectionDirtyPendingArgs.clear();for(let e of this.workers)e.terminate();this.workers=[],this.soundSystem&&(this.soundSystem.destroy(),this.soundSystem=void 0),this.active=!1,this.loadedChunks={},this.finishedChunks={},this.finishedSections={},this.sectionsWaiting.clear(),this.queuedChunks.clear(),this.blockStateModelInfo.clear(),this.renderUpdateEmitter.removeAllListeners(),this.abortController.abort(),Ts()}};d(R0,"PHASE_PERF_LOG_INTERVAL",64),d(R0,"GEOMETRY_THROTTLE_THRESHOLD",1),d(R0,"GEOMETRY_THROTTLE_DELAY",100);var g1=R0,s7=(n,e="mesher.js")=>{let t;if(D.env.SINGLE_FILE_BUILD){let r=document.getElementById("mesher-worker-code").textContent,i=new Blob([r],{type:"text/javascript"});t=new Worker(window.URL.createObjectURL(i))}else t=new Worker(e);return t.onmessage=({data:r})=>{n(r)},t.on&&t.on("message",r=>{t.onmessage({data:r})}),t},Ss=!1,Cs=(n,e,t=at,r)=>{let i={version:JSON.parse(JSON.stringify(r.version))};for(let[s,o]of Object.entries(t))i[s]=r[o];"tints"in t&&!i.tints&&!Ss&&(Ss=!0);for(let s of n)s.postMessage({type:"mcData",mcData:i})},Xr=(n,e,t=at,r,i=1e4)=>Promise.all(n.map(s=>new Promise((o,a)=>{let v=setTimeout(()=>{s.removeEventListener("message",l),a(new Error(`mcData transfer timeout (${i}ms)`))},i),l=({data:c})=>{c?.type==="mcDataApplied"&&(clearTimeout(v),s.removeEventListener("message",l),o())};s.addEventListener("message",l),Cs([s],e,t,r)}))).then(()=>{});E();x();k();R();import{Vec3 as o7}from"vec3";import*as r0 from"three";E();x();k();R();function b1(n,e){let t=e/180*Math.PI,r=Math.cos(t),i=Math.sin(t),s={x:0,y:1,z:2}[n],o=(s+1)%3,a=(s+2)%3,v=[[0,0,0],[0,0,0],[0,0,0]];return v[s][s]=1,v[o][o]=r,v[o][a]=-i,v[a][o]=+i,v[a][a]=r,v}function $r(n,e){return e?[n[0]+e[0],n[1]+e[1],n[2]+e[2]]:n}function ei(n,e){return e?[n[0]-e[0],n[1]-e[1],n[2]-e[2]]:n}function Ot(n,e){return n?[n[0][0]*e[0]+n[0][1]*e[1]+n[0][2]*e[2],n[1][0]*e[0]+n[1][1]*e[1]+n[1][2]*e[2],n[2][0]*e[0]+n[2][1]*e[1]+n[2][2]*e[2]]:e}function Bs(n,e){let t=[[0,0,0],[0,0,0],[0,0,0]],r=n[0][0],i=n[1][0],s=n[2][0],o=n[0][1],a=n[1][1],v=n[2][1],l=n[0][2],c=n[1][2],u=n[2][2],h=e[0][0],p=e[1][0],g=e[2][0],y=e[0][1],A=e[1][1],b=e[2][1],w=e[0][2],S=e[1][2],C=e[2][2];return t[0][0]=r*h+i*y+s*w,t[1][0]=r*p+i*A+s*S,t[2][0]=r*g+i*b+s*C,t[0][1]=o*h+a*y+v*w,t[1][1]=o*p+a*A+v*S,t[2][1]=o*g+a*b+v*C,t[0][2]=l*h+c*y+u*w,t[1][2]=l*p+c*A+u*S,t[2][2]=l*g+c*b+u*C,t}var ti={up:{dir:[0,1,0],mask1:[1,1,0],mask2:[0,1,1],corners:[[0,1,1,0,1],[1,1,1,1,1],[0,1,0,0,0],[1,1,0,1,0]]},down:{dir:[0,-1,0],mask1:[1,1,0],mask2:[0,1,1],corners:[[1,0,1,0,1],[0,0,1,1,1],[1,0,0,0,0],[0,0,0,1,0]]},east:{dir:[1,0,0],mask1:[1,1,0],mask2:[1,0,1],corners:[[1,1,1,0,0],[1,0,1,0,1],[1,1,0,1,0],[1,0,0,1,1]]},west:{dir:[-1,0,0],mask1:[1,1,0],mask2:[1,0,1],corners:[[0,1,0,0,0],[0,0,0,0,1],[0,1,1,1,0],[0,0,1,1,1]]},north:{dir:[0,0,-1],mask1:[1,0,1],mask2:[0,1,1],corners:[[1,0,0,1,1],[0,0,0,0,1],[1,1,0,1,0],[0,1,0,0,0]]},south:{dir:[0,0,1],mask1:[1,0,1],mask2:[0,1,1],corners:[[0,0,1,0,1],[1,0,1,1,1],[0,1,1,0,0],[1,1,1,1,0]]}};function a7(n,e,t,r,i,s,o,a){let v=new o7(0,0,0);for(let l in n.faces){let c=n.faces[l],{corners:u,mask1:h,mask2:p}=ti[l],g=Ot(r,ti[l].dir);if(c.cullface&&a[l])continue;let y=n.from[0],A=n.from[1],b=n.from[2],w=n.to[0],S=n.to[1],C=n.to[2],M=c.texture,{u:I}=M,{v:B}=M,{su:H}=M,{sv:G}=M,O=Math.floor(t.positions.length/3),j=[1,1,1];c.tintindex!==void 0&&c.tintindex===0&&(j=[.5686274509803921,.7411764705882353,.34901960784313724]);let J=c.rotation||0,Z=Math.cos(J*Math.PI/180),$=-Math.sin(J*Math.PI/180),ue=null,le=null;n.rotation&&(ue=b1(n.rotation.axis,n.rotation.angle),le=ei(n.rotation.origin,Ot(ue,n.rotation.origin)));let ce=[],Ee=1;for(let Ie of u){let se=[Ie[0]?w:y,Ie[1]?S:A,Ie[2]?C:b];se=$r(Ot(ue,se),le),se=$r(Ot(r,se),i),se=se.map(Je=>Je/16),t.positions.push(se[0],se[1],se[2]),t.normals.push(...g);let Y=(Ie[3]-.5)*Z-(Ie[4]-.5)*$+.5,oe=(Ie[3]-.5)*$+(Ie[4]-.5)*Z+.5;t.uvs.push(Y*H+I,oe*G+B);let xe=1;e&&(xe=4/4*(15/15),ce.push(3)),t.colors.push(Ee*j[0]*xe,Ee*j[1]*xe,Ee*j[2]*xe)}e&&ce[0]+ce[3]>=ce[1]+ce[2]?t.indices.push(O,O+3,O+2,O,O+1,O+3):t.indices.push(O,O+1,O+2,O+2,O+1,O+3)}}var v7=(n,e,t,r,i=[],s={})=>{let l={sx:.5,sy:.5,sz:.5,positions:[],normals:[],colors:[],uvs:[],t_positions:[],t_normals:[],t_colors:[],t_uvs:[],indices:[],tiles:{}};for(let[u,h]of n.entries()){let p=h[i[u]]??h[0];if(!p)continue;let g=null,y=null;for(let b of["x","y","z"])b in p&&(g?g=Bs(g,b1(b,-(p[b]??0))):g=b1(b,-(p[b]??0)));g&&(y=[8,8,8],y=ei(y,Ot(g,y)));let A=p.ao??!0;for(let b of p.elements??[])a7(b,A,l,g,y,e,t,s)}let c=l.positions.length/3;for(let u=0;u<l.t_positions.length/12;u++)l.indices.push(c,c+1,c+2,c+2,c+1,c+3,c,c+2,c+1,c+2,c+3,c+1),c+=4;return l.positions.push(...l.t_positions),l.normals.push(...l.t_normals),l.colors.push(...l.t_colors),l.uvs.push(...l.t_uvs),delete l.t_positions,delete l.t_normals,delete l.t_colors,delete l.t_uvs,l.positions=new Float32Array(l.positions),l.normals=new Float32Array(l.normals),l.colors=new Float32Array(l.colors),l.uvs=new Float32Array(l.uvs),l},l7=(...n)=>{let t={geometry:v7(...n)},r=new r0.BufferGeometry;return r.setAttribute("position",new r0.BufferAttribute(t.geometry.positions,3)),r.setAttribute("normal",new r0.BufferAttribute(t.geometry.normals,3)),r.setAttribute("color",new r0.BufferAttribute(t.geometry.colors,3)),r.setAttribute("uv",new r0.BufferAttribute(t.geometry.uvs,2)),r.setIndex(t.geometry.indices),r.name="block-geometry",r},ri=(n,...e)=>{let t=l7(...e),r=new r0.Mesh(t,n);r.position.set(-.5,-.5,-.5);let i=new r0.Group;return i.add(r),i.rotation.set(0,-r0.MathUtils.degToRad(90),0,"ZYX"),globalThis.mesh=i,i},Ps=(n,e)=>{n.position.set(e.x+.5,e.y+.5,e.z+.5)};E();x();k();R();import*as De from"three";var R5=async(n,e)=>{let t;if(!n&&!e){let{canvas:l}=await y0($e);t=new De.CanvasTexture(l)}else{if(n||(n=await H0(e,"skin")),!n)return;let{canvas:l}=await y0(n);t=new De.CanvasTexture(l)}t.magFilter=De.NearestFilter,t.minFilter=De.NearestFilter;let r=!1,s=c7(40,16,r?-2:-3,-2,-2,r?3:4,12,4,64,64),o=new De.MeshStandardMaterial;o.map=t,o.needsUpdate=!0;let a=new De.Mesh(s,o),v=new De.Group;return v.add(a),v};function c7(n,e,t,r,i,s,o,a,v,l,c=!1){let u=t/16,h=r/16,p=i/16,g=(t+s)/16,y=(r+o)/16,A=(i+a)/16;c&&([u,g]=[g,u]);let b=[[u,h,p],[g,h,p],[g,y,p],[u,y,p],[u,h,A],[g,h,A],[g,y,A],[u,y,A]],w=n,S=n+a,C=n+a+s,M=n+a+s+s,I=n+a+s+a,B=n+a+s+a+s,H=e,G=e+a,O=e+a+o,j=[{vi:[5,4,0,1],uv:[S,H,C,G],n:[0,-1,0]},{vi:[2,3,7,6],uv:[C,G,M,H],n:[0,1,0]},{vi:[0,4,7,3],uv:[w,G,S,O],n:[-1,0,0]},{vi:[1,0,3,2],uv:[S,G,C,O],n:[0,0,-1]},{vi:[5,1,2,6],uv:[C,G,I,O],n:[1,0,0]},{vi:[4,5,6,7],uv:[I,G,B,O],n:[0,0,1]}],J=[],Z=[],$=[],ue=[];for(let ce=0;ce<j.length;ce++){let Ee=j[ce],Ie=ce*4,[se,Y,oe,xe]=Ee.uv,Je=[[oe/v,1-Y/l],[se/v,1-Y/l],[se/v,1-xe/l],[oe/v,1-xe/l]],Ne=c?[3,2,1,0]:[0,1,2,3],n0=c?-Ee.n[0]:Ee.n[0];for(let _e=0;_e<4;_e++){let f0=b[Ee.vi[Ne[_e]]];J.push(f0[0],f0[1],f0[2]),Z.push(Je[_e][0],Je[_e][1]),$.push(n0,Ee.n[1],Ee.n[2])}ue.push(Ie,Ie+1,Ie+2,Ie,Ie+2,Ie+3)}let le=new De.BufferGeometry;return le.setAttribute("position",new De.Float32BufferAttribute(J,3)),le.setAttribute("uv",new De.Float32BufferAttribute(Z,2)),le.setAttribute("normal",new De.Float32BufferAttribute($,3)),le.setIndex(ue),le}E();x();k();R();E();x();k();R();import*as Se from"three";E();x();k();R();E();x();k();R();var O0=class n{constructor(e,t,r,i,s="div"){this.parent=e,this.object=t,this.property=r,this._disabled=!1,this._hidden=!1,this.initialValue=this.getValue(),this.domElement=document.createElement("div"),this.domElement.classList.add("controller"),this.domElement.classList.add(i),this.$name=document.createElement("div"),this.$name.classList.add("name"),n.nextNameID=n.nextNameID||0,this.$name.id=`lil-gui-name-${++n.nextNameID}`,this.$widget=document.createElement(s),this.$widget.classList.add("widget"),this.$disable=this.$widget,this.domElement.appendChild(this.$name),this.domElement.appendChild(this.$widget),this.domElement.addEventListener("keydown",o=>o.stopPropagation()),this.domElement.addEventListener("keyup",o=>o.stopPropagation()),this.parent.children.push(this),this.parent.controllers.push(this),this.parent.$children.appendChild(this.domElement),this._listenCallback=this._listenCallback.bind(this),this.name(r)}name(e){return this._name=e,this.$name.innerHTML=e,this}onChange(e){return this._onChange=e,this}_callOnChange(){this.parent._callOnChange(this),this._onChange!==void 0&&this._onChange.call(this,this.getValue()),this._changed=!0}onFinishChange(e){return this._onFinishChange=e,this}_callOnFinishChange(){this._changed&&(this.parent._callOnFinishChange(this),this._onFinishChange!==void 0&&this._onFinishChange.call(this,this.getValue())),this._changed=!1}reset(){return this.setValue(this.initialValue),this._callOnFinishChange(),this}enable(e=!0){return this.disable(!e)}disable(e=!0){return e===this._disabled?this:(this._disabled=e,this.domElement.classList.toggle("disabled",e),this.$disable.toggleAttribute("disabled",e),this)}show(e=!0){return this._hidden=!e,this.domElement.style.display=this._hidden?"none":"",this}hide(){return this.show(!1)}options(e){let t=this.parent.add(this.object,this.property,e);return t.name(this._name),this.destroy(),t}min(e){return this}max(e){return this}step(e){return this}decimals(e){return this}listen(e=!0){return this._listening=e,this._listenCallbackID!==void 0&&(cancelAnimationFrame(this._listenCallbackID),this._listenCallbackID=void 0),this._listening&&this._listenCallback(),this}_listenCallback(){this._listenCallbackID=requestAnimationFrame(this._listenCallback);let e=this.save();e!==this._listenPrevValue&&this.updateDisplay(),this._listenPrevValue=e}getValue(){return this.object[this.property]}setValue(e){return this.object[this.property]=e,this._callOnChange(),this.updateDisplay(),this}updateDisplay(){return this}load(e){return this.setValue(e),this._callOnFinishChange(),this}save(){return this.getValue()}destroy(){this.listen(!1),this.parent.children.splice(this.parent.children.indexOf(this),1),this.parent.controllers.splice(this.parent.controllers.indexOf(this),1),this.parent.$children.removeChild(this.domElement)}},ii=class extends O0{constructor(e,t,r){super(e,t,r,"boolean","label"),this.$input=document.createElement("input"),this.$input.setAttribute("type","checkbox"),this.$input.setAttribute("aria-labelledby",this.$name.id),this.$widget.appendChild(this.$input),this.$input.addEventListener("change",()=>{this.setValue(this.$input.checked),this._callOnFinishChange()}),this.$disable=this.$input,this.updateDisplay()}updateDisplay(){return this.$input.checked=this.getValue(),this}};function ni(n){let e,t;return(e=n.match(/(#|0x)?([a-f0-9]{6})/i))?t=e[2]:(e=n.match(/rgb\(\s*(\d*)\s*,\s*(\d*)\s*,\s*(\d*)\s*\)/))?t=parseInt(e[1]).toString(16).padStart(2,0)+parseInt(e[2]).toString(16).padStart(2,0)+parseInt(e[3]).toString(16).padStart(2,0):(e=n.match(/^#?([a-f0-9])([a-f0-9])([a-f0-9])$/i))&&(t=e[1]+e[1]+e[2]+e[2]+e[3]+e[3]),t?"#"+t:!1}var d7={isPrimitive:!0,match:n=>typeof n=="string",fromHexString:ni,toHexString:ni},T5={isPrimitive:!0,match:n=>typeof n=="number",fromHexString:n=>parseInt(n.substring(1),16),toHexString:n=>"#"+n.toString(16).padStart(6,0)},u7={isPrimitive:!1,match:n=>Array.isArray(n),fromHexString(n,e,t=1){let r=T5.fromHexString(n);e[0]=(r>>16&255)/255*t,e[1]=(r>>8&255)/255*t,e[2]=(r&255)/255*t},toHexString([n,e,t],r=1){r=255/r;let i=n*r<<16^e*r<<8^t*r<<0;return T5.toHexString(i)}},f7={isPrimitive:!1,match:n=>Object(n)===n,fromHexString(n,e,t=1){let r=T5.fromHexString(n);e.r=(r>>16&255)/255*t,e.g=(r>>8&255)/255*t,e.b=(r&255)/255*t},toHexString({r:n,g:e,b:t},r=1){r=255/r;let i=n*r<<16^e*r<<8^t*r<<0;return T5.toHexString(i)}},h7=[d7,T5,u7,f7];function m7(n){return h7.find(e=>e.match(n))}var si=class extends O0{constructor(e,t,r,i){super(e,t,r,"color"),this.$input=document.createElement("input"),this.$input.setAttribute("type","color"),this.$input.setAttribute("tabindex",-1),this.$input.setAttribute("aria-labelledby",this.$name.id),this.$text=document.createElement("input"),this.$text.setAttribute("type","text"),this.$text.setAttribute("spellcheck","false"),this.$text.setAttribute("aria-labelledby",this.$name.id),this.$display=document.createElement("div"),this.$display.classList.add("display"),this.$display.appendChild(this.$input),this.$widget.appendChild(this.$display),this.$widget.appendChild(this.$text),this._format=m7(this.initialValue),this._rgbScale=i,this._initialValueHexString=this.save(),this._textFocused=!1,this.$input.addEventListener("input",()=>{this._setValueFromHexString(this.$input.value)}),this.$input.addEventListener("blur",()=>{this._callOnFinishChange()}),this.$text.addEventListener("input",()=>{let s=ni(this.$text.value);s&&this._setValueFromHexString(s)}),this.$text.addEventListener("focus",()=>{this._textFocused=!0,this.$text.select()}),this.$text.addEventListener("blur",()=>{this._textFocused=!1,this.updateDisplay(),this._callOnFinishChange()}),this.$disable=this.$text,this.updateDisplay()}reset(){return this._setValueFromHexString(this._initialValueHexString),this}_setValueFromHexString(e){if(this._format.isPrimitive){let t=this._format.fromHexString(e);this.setValue(t)}else this._format.fromHexString(e,this.getValue(),this._rgbScale),this._callOnChange(),this.updateDisplay()}save(){return this._format.toHexString(this.getValue(),this._rgbScale)}load(e){return this._setValueFromHexString(e),this._callOnFinishChange(),this}updateDisplay(){return this.$input.value=this._format.toHexString(this.getValue(),this._rgbScale),this._textFocused||(this.$text.value=this.$input.value.substring(1)),this.$display.style.backgroundColor=this.$input.value,this}},k5=class extends O0{constructor(e,t,r){super(e,t,r,"function"),this.$button=document.createElement("button"),this.$button.appendChild(this.$name),this.$widget.appendChild(this.$button),this.$button.addEventListener("click",i=>{i.preventDefault(),this.getValue().call(this.object),this._callOnChange()}),this.$button.addEventListener("touchstart",()=>{},{passive:!0}),this.$disable=this.$button}},oi=class extends O0{constructor(e,t,r,i,s,o){super(e,t,r,"number"),this._initInput(),this.min(i),this.max(s);let a=o!==void 0;this.step(a?o:this._getImplicitStep(),a),this.updateDisplay()}decimals(e){return this._decimals=e,this.updateDisplay(),this}min(e){return this._min=e,this._onUpdateMinMax(),this}max(e){return this._max=e,this._onUpdateMinMax(),this}step(e,t=!0){return this._step=e,this._stepExplicit=t,this}updateDisplay(){let e=this.getValue();if(this._hasSlider){let t=(e-this._min)/(this._max-this._min);t=Math.max(0,Math.min(t,1)),this.$fill.style.width=t*100+"%"}return this._inputFocused||(this.$input.value=this._decimals===void 0?e:e.toFixed(this._decimals)),this}_initInput(){this.$input=document.createElement("input"),this.$input.setAttribute("type","text"),this.$input.setAttribute("aria-labelledby",this.$name.id),window.matchMedia("(pointer: coarse)").matches&&(this.$input.setAttribute("type","number"),this.$input.setAttribute("step","any")),this.$widget.appendChild(this.$input),this.$disable=this.$input;let t=()=>{let w=parseFloat(this.$input.value);isNaN(w)||(this._stepExplicit&&(w=this._snap(w)),this.setValue(this._clamp(w)))},r=w=>{let S=parseFloat(this.$input.value);isNaN(S)||(this._snapClampSetValue(S+w),this.$input.value=this.getValue())},i=w=>{w.key==="Enter"&&this.$input.blur(),w.code==="ArrowUp"&&(w.preventDefault(),r(this._step*this._arrowKeyMultiplier(w))),w.code==="ArrowDown"&&(w.preventDefault(),r(this._step*this._arrowKeyMultiplier(w)*-1))},s=w=>{this._inputFocused&&(w.preventDefault(),r(this._step*this._normalizeMouseWheel(w)))},o=!1,a,v,l,c,u,h=5,p=w=>{a=w.clientX,v=l=w.clientY,o=!0,c=this.getValue(),u=0,window.addEventListener("mousemove",g),window.addEventListener("mouseup",y)},g=w=>{if(o){let S=w.clientX-a,C=w.clientY-v;Math.abs(C)>h?(w.preventDefault(),this.$input.blur(),o=!1,this._setDraggingStyle(!0,"vertical")):Math.abs(S)>h&&y()}if(!o){let S=w.clientY-l;u-=S*this._step*this._arrowKeyMultiplier(w),c+u>this._max?u=this._max-c:c+u<this._min&&(u=this._min-c),this._snapClampSetValue(c+u)}l=w.clientY},y=()=>{this._setDraggingStyle(!1,"vertical"),this._callOnFinishChange(),window.removeEventListener("mousemove",g),window.removeEventListener("mouseup",y)},A=()=>{this._inputFocused=!0},b=()=>{this._inputFocused=!1,this.updateDisplay(),this._callOnFinishChange()};this.$input.addEventListener("input",t),this.$input.addEventListener("keydown",i),this.$input.addEventListener("wheel",s,{passive:!1}),this.$input.addEventListener("mousedown",p),this.$input.addEventListener("focus",A),this.$input.addEventListener("blur",b)}_initSlider(){this._hasSlider=!0,this.$slider=document.createElement("div"),this.$slider.classList.add("slider"),this.$fill=document.createElement("div"),this.$fill.classList.add("fill"),this.$slider.appendChild(this.$fill),this.$widget.insertBefore(this.$slider,this.$input),this.domElement.classList.add("hasSlider");let e=(b,w,S,C,M)=>(b-w)/(S-w)*(M-C)+C,t=b=>{let w=this.$slider.getBoundingClientRect(),S=e(b,w.left,w.right,this._min,this._max);this._snapClampSetValue(S)},r=b=>{this._setDraggingStyle(!0),t(b.clientX),window.addEventListener("mousemove",i),window.addEventListener("mouseup",s)},i=b=>{t(b.clientX)},s=()=>{this._callOnFinishChange(),this._setDraggingStyle(!1),window.removeEventListener("mousemove",i),window.removeEventListener("mouseup",s)},o=!1,a,v,l=b=>{b.preventDefault(),this._setDraggingStyle(!0),t(b.touches[0].clientX),o=!1},c=b=>{b.touches.length>1||(this._hasScrollBar?(a=b.touches[0].clientX,v=b.touches[0].clientY,o=!0):l(b),window.addEventListener("touchmove",u,{passive:!1}),window.addEventListener("touchend",h))},u=b=>{if(o){let w=b.touches[0].clientX-a,S=b.touches[0].clientY-v;Math.abs(w)>Math.abs(S)?l(b):(window.removeEventListener("touchmove",u),window.removeEventListener("touchend",h))}else b.preventDefault(),t(b.touches[0].clientX)},h=()=>{this._callOnFinishChange(),this._setDraggingStyle(!1),window.removeEventListener("touchmove",u),window.removeEventListener("touchend",h)},p=this._callOnFinishChange.bind(this),g=400,y,A=b=>{if(Math.abs(b.deltaX)<Math.abs(b.deltaY)&&this._hasScrollBar)return;b.preventDefault();let S=this._normalizeMouseWheel(b)*this._step;this._snapClampSetValue(this.getValue()+S),this.$input.value=this.getValue(),clearTimeout(y),y=setTimeout(p,g)};this.$slider.addEventListener("mousedown",r),this.$slider.addEventListener("touchstart",c,{passive:!1}),this.$slider.addEventListener("wheel",A,{passive:!1})}_setDraggingStyle(e,t="horizontal"){this.$slider&&this.$slider.classList.toggle("active",e),document.body.classList.toggle("lil-gui-dragging",e),document.body.classList.toggle(`lil-gui-${t}`,e)}_getImplicitStep(){return this._hasMin&&this._hasMax?(this._max-this._min)/1e3:.1}_onUpdateMinMax(){!this._hasSlider&&this._hasMin&&this._hasMax&&(this._stepExplicit||this.step(this._getImplicitStep(),!1),this._initSlider(),this.updateDisplay())}_normalizeMouseWheel(e){let{deltaX:t,deltaY:r}=e;return Math.floor(e.deltaY)!==e.deltaY&&e.wheelDelta&&(t=0,r=-e.wheelDelta/120,r*=this._stepExplicit?1:10),t+-r}_arrowKeyMultiplier(e){let t=this._stepExplicit?1:10;return e.shiftKey?t*=10:e.altKey&&(t/=10),t}_snap(e){let t=Math.round(e/this._step)*this._step;return parseFloat(t.toPrecision(15))}_clamp(e){return e<this._min&&(e=this._min),e>this._max&&(e=this._max),e}_snapClampSetValue(e){this.setValue(this._clamp(this._snap(e)))}get _hasScrollBar(){let e=this.parent.root.$children;return e.scrollHeight>e.clientHeight}get _hasMin(){return this._min!==void 0}get _hasMax(){return this._max!==void 0}},ai=class extends O0{constructor(e,t,r,i){super(e,t,r,"option"),this.$select=document.createElement("select"),this.$select.setAttribute("aria-labelledby",this.$name.id),this.$display=document.createElement("div"),this.$display.classList.add("display"),this._values=Array.isArray(i)?i:Object.values(i),this._names=Array.isArray(i)?i:Object.keys(i),this._names.forEach(s=>{let o=document.createElement("option");o.innerHTML=s,this.$select.appendChild(o)}),this.$select.addEventListener("change",()=>{this.setValue(this._values[this.$select.selectedIndex]),this._callOnFinishChange()}),this.$select.addEventListener("focus",()=>{this.$display.classList.add("focus")}),this.$select.addEventListener("blur",()=>{this.$display.classList.remove("focus")}),this.$widget.appendChild(this.$select),this.$widget.appendChild(this.$display),this.$disable=this.$select,this.updateDisplay()}updateDisplay(){let e=this.getValue(),t=this._values.indexOf(e);return this.$select.selectedIndex=t,this.$display.innerHTML=t===-1?e:this._names[t],this}},vi=class extends O0{constructor(e,t,r){super(e,t,r,"string"),this.$input=document.createElement("input"),this.$input.setAttribute("type","text"),this.$input.setAttribute("aria-labelledby",this.$name.id),this.$input.addEventListener("input",()=>{this.setValue(this.$input.value)}),this.$input.addEventListener("keydown",i=>{i.code==="Enter"&&this.$input.blur()}),this.$input.addEventListener("blur",()=>{this._callOnFinishChange()}),this.$widget.appendChild(this.$input),this.$disable=this.$input,this.updateDisplay()}updateDisplay(){return this.$input.value=this.getValue(),this}},p7=`.lil-gui {
|
|
@@ -21506,7 +21506,7 @@ void main() {
|
|
|
21506
21506
|
|
|
21507
21507
|
#include <tonemapping_fragment>
|
|
21508
21508
|
#include <${r9>=154?"colorspace_fragment":"encodings_fragment"}>
|
|
21509
|
-
}`})}},vn=class{constructor(e){this.worldRenderer=e;d(this,"points");d(this,"clock",new Te.Clock);d(this,"enabled",!1);d(this,"currentTime");d(this,"enablementCheck",()=>this.currentTime?this.currentTime>13500&&this.currentTime<23e3:!1);d(this,"render",e=>{this.points&&(this.points.position.set(0,0,0),this.points.material.uniforms.time.value=this.clock.getElapsedTime()*.2)})}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}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,r=7e3,i=7,s=10,o=new Te.BufferGeometry,a=y=>new Te.Vector3().setFromSpherical(new Te.Spherical(y,Math.acos(1-Math.random()*2),Math.random()*2*Math.PI)),v=[],l=[],c=Array.from({length:r},()=>(.5+.5*Math.random())*i),u=new Te.Color,h=e+t,p=t/r;for(let y=0;y<r;y++)h-=p*Math.random(),v.push(...a(h).toArray()),u.setHSL(y/r,s,.9),l.push(u.r,u.g,u.b);o.setAttribute("position",new Te.Float32BufferAttribute(v,3)),o.setAttribute("color",new Te.Float32BufferAttribute(l,3)),o.setAttribute("size",new Te.Float32BufferAttribute(c,1));let g=new an;g.blending=Te.AdditiveBlending,g.depthTest=!0,g.depthWrite=!1,g.transparent=!0,this.points=new Te.Points(o,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)}},Ha={id:"starfield",controller:vn,enabledDefault:!0,cannotBeDisabled:!0};var Oa={starfield:Ha,futuristicReveal:Ia,rain:Ba,cameraBobbing:Ta,blockBreakParticles:ka};var yt=class yt extends g1{constructor(t,r,i){if(!i.resourcesManager)throw new Error("resourcesManager is required in displayOptions");super(i.resourcesManager,i,r);this.renderer=t;this.initOptions=r;this.displayOptions=i;d(this,"outputFormat","threeJs");d(this,"chunkMeshManager");d(this,"chunkTextures",new Map);d(this,"signsCache",new Map);d(this,"cameraSectionPos",new G0(0,0,0));d(this,"holdingBlock");d(this,"holdingBlockLeft");d(this,"scene",new Q.Scene);d(this,"ambientLight",new Q.AmbientLight(13421772));d(this,"directionalLight",new Q.DirectionalLight(16777215,.5));d(this,"entities",new z1(this,globalThis.mcData));d(this,"performanceMonitor");d(this,"cameraGroupVr");d(this,"material",new Q.MeshBasicMaterial({vertexColors:!0,transparent:!0,alphaTest:.1}));d(this,"itemsTexture");d(this,"cursorBlock");d(this,"onRender",[]);d(this,"lastRenderTime",0);d(this,"animatedFov",0);d(this,"lastFovAnimTime",0);d(this,"cameraShake");d(this,"cameraContainer");d(this,"media");d(this,"waypoints");d(this,"cinimaticScript");d(this,"camera");d(this,"renderTimeAvg",0);d(this,"pendingSectionUpdates",new Map);d(this,"pendingSectionBufferStartTimes",new Map);d(this,"modules",{});d(this,"sectionsOffsetsAnimations",{});d(this,"fountains",[]);d(this,"fireworksLegacy");d(this,"DEBUG_RAYCAST",!1);d(this,"skyboxRenderer");d(this,"fireworks");d(this,"sceneOrigin",new Z1(this.scene));d(this,"cameraWorldPos",{x:0,y:0,z:0});d(this,"_cameraPositionAccessWarned",!1);d(this,"_tmpCameraPos",new Q.Vector3);d(this,"currentPosTween");d(this,"currentRotTween");d(this,"_tpDirection",new Q.Vector3);d(this,"_tpPitchQuat",new Q.Quaternion);d(this,"_tpYawQuat",new Q.Quaternion);d(this,"_tpFinalQuat",new Q.Quaternion);d(this,"_tpScenePos",new Q.Vector3);d(this,"_tpAxisX",new Q.Vector3(1,0,0));d(this,"_tpAxisY",new Q.Vector3(0,1,0));d(this,"_tpRaycaster",new Q.Raycaster);d(this,"_tpChunkWorldPos",new Q.Vector3);d(this,"debugOverlayAdded",!1);d(this,"debugRaycastHelper");d(this,"debugHitPoint");d(this,"prevFramePerspective",null);this.performanceMonitor=new l5(this.reactiveState.world.instabilityFactors),this.renderer=t;let s=yt.getRendererInfo(t)??"...";i.rendererState.renderer=s,this.chunkMeshManager=new Y5(this,this.scene,this.material,this.worldSizeParams.worldHeight,this.viewDistance),this.onRenderDistanceChanged=o=>{this.chunkMeshManager.updateViewDistance(o)},this.cursorBlock=new L1(this),this.holdingBlock=U5(this),this.holdingBlockLeft=U5(this,!0);for(let o of Object.values(Oa))this.registerModule(o);this.skyboxRenderer=new K1(this.realScene,!1,null),this.skyboxRenderer.init(),this.addDebugOverlay(),this.resetScene(),this.init(),this.soundSystem=new G1(this),this.cameraShake=new N1(this,this.onRender),this.media=new W1(this),this.fireworksLegacy=new Y1(this),this.waypoints=new j1(this),this.cinimaticScript=new Q1(this,(o,a,v)=>this.setCinimaticCamera(o,a,v),o=>this.setCinimaticFov(o),()=>({position:new G0(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 J1(this.realScene,this.sceneOrigin),this.renderUpdateEmitter.on("chunkFinished",o=>{this.finishChunk(o)}),this.worldSwitchActions(),this.initializeModules()}isShaderCubeBlocksEnabled(){return this.worldRendererConfig.shaderCubeBlocks===!0&&!!this.renderer?.capabilities?.isWebGL2}get sectionObjects(){return this.chunkMeshManager.sectionObjects}get realScene(){return this.scene}get waitingChunksToDisplay(){return this.chunkMeshManager.waitingChunksToDisplay}get estimatedMemoryUsage(){return this.chunkMeshManager.getEstimatedMemoryUsage().total}get tilesRendered(){return this.chunkMeshManager.getTotalTiles()}get blocksRendered(){return this.chunkMeshManager.getTotalBlocks()}registerModule(t){if(t.id in this.modules)return;let r=new t.controller(this),i={manifest:t,controller:r,enabled:!1,toggle:()=>this.toggleModule(t.id)};this.modules[t.id]=i,t.enabledDefault&&this.toggleModule(t.id,!0)}enableModule(t){let r=this.modules[t];r&&(r.enabled||(r.enabled=!0,r.controller.enable(),r.controller.render&&this.onRender.push(r.controller.render)))}disableModule(t){let r=this.modules[t];if(r&&!r.manifest.cannotBeDisabled&&r.enabled&&(r.enabled=!1,r.controller.disable(),r.controller.render)){let i=this.onRender.indexOf(r.controller.render);i>-1&&this.onRender.splice(i,1)}}toggleModule(t,r){let i=this.modules[t];if(!i)return!1;let s=r!==void 0?r:!i.enabled;if(s===i.enabled)return i.enabled;if(!s&&i.manifest.cannotBeDisabled)return!0;if(i.enabled=s,s)i.controller.enable(),i.controller.render&&!this.onRender.includes(i.controller.render)&&this.onRender.push(i.controller.render);else if(i.controller.disable(),i.controller.render){let o=this.onRender.indexOf(i.controller.render);o>-1&&this.onRender.splice(o,1)}return s}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,r=this,i=20,s=(v,l,c)=>Math.abs(v)>i||Math.abs(l)>i||Math.abs(c)>i,o=()=>{!r._cameraPositionAccessWarned&&typeof D<"u"},a=new Proxy(t,{set(v,l,c){return(l==="x"||l==="y"||l==="z")&&typeof c=="number"&&Math.abs(c)>i&&o(),v[l]=c,!0},get(v,l,c){let u=v[l];return l==="set"?function(h,p,g){return s(h,p,g)&&o(),v.set(h,p,g)}:l==="setX"||l==="setY"||l==="setZ"?function(h){return Math.abs(h)>i&&o(),v[l](h)}:l==="copy"?function(h){return s(h.x,h.y,h.z)&&o(),v.copy(h)}:typeof u=="function"?u.bind(v):u}});Object.defineProperty(this.camera,"position",{value:a,configurable:!0,enumerable:!0})}worldSwitchActions(){this.onWorldSwitched.push(()=>{this.protocolCustomBlocks.clear(),this.sectionsOffsetsAnimations={},this.waypoints.clear(),this.cinimaticScript.stopScript(),this.fireworks.clear()})}downloadWorldGeometry(){Ki(this,new Q.Vector3(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),this.cameraShake.getBaseRotation(),"world-geometry.json")}updateEntity(t,r=!1){let i={rotation:{head:{x:t.headPitch??t.pitch,y:t.headYaw,z:0}}};r?this.entities.updateEntityPosition(t,!1,i):this.entities.update(t,i)}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 Q.Color(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 Q.Vector2);this.camera=new Q.PerspectiveCamera(75,t.x/t.y,.1,1e3),this._wrapCameraPositionWithWarning(),this.cameraContainer=new Q.Object3D,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)}),this.onReactivePlayerStateUpdated("directionalLight",t=>{t&&(this.directionalLight.intensity=t)}),this.onReactivePlayerStateUpdated("lookingAtBlock",t=>{this.cursorBlock.setHighlightCursorBlock(t?new G0(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 r=new G0(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z);this.updateCamera(r,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.onReactiveConfigUpdated("futuristicReveal",()=>{this.updateModulesFromConfig()});let t=this.displayOptions.inWorldRenderingConfig.handRenderer;this.onReactiveConfigUpdated("handRenderer",r=>{if(r===t)return;t=r;let i=this.holdingBlock.ready,s=this.holdingBlockLeft.ready;this.holdingBlock.dispose(),this.holdingBlockLeft.dispose(),this.holdingBlock=U5(this),this.holdingBlockLeft=U5(this,!0),i&&(this.holdingBlock.ready=!0,this.holdingBlock.updateItem()),s&&(this.holdingBlockLeft.ready=!0,this.holdingBlockLeft.updateItem())}),this.onReactiveConfigUpdated("*",()=>{this.updateModulesFromConfig()}),this.updateModulesFromConfig()}updateModulesFromConfig(){let{moduleStates:t}=this.worldRendererConfig;for(let[r,i]of Object.entries(this.modules)){let s=t[r];if(s==="enabled"){i.enabled||this.toggleModule(r,!0);continue}if(s==="disabled"){i.enabled&&!i.manifest.cannotBeDisabled&&this.toggleModule(r,!1);continue}if(s==="auto"||s===void 0)if(i.controller.autoEnableCheck){let o=i.controller.autoEnableCheck();o&&!i.enabled?this.toggleModule(r,!0):!o&&i.enabled&&!i.manifest.cannotBeDisabled&&this.toggleModule(r,!1)}else{let o=i.manifest.enabledDefault??!1;o&&!i.enabled?this.toggleModule(r,!0):!o&&i.enabled&&!i.manifest.cannotBeDisabled&&this.toggleModule(r,!1)}}}changeHandSwingingState(t,r=!1){let i=r?this.holdingBlockLeft:this.holdingBlock;t?i.startSwing():i.stopSwing()}async updateAssetsData(){let t=this.resourcesManager.currentResources,r=this.material.map,i=this.itemsTexture,s=I0(t.blocksAtlasImage);s.needsUpdate=!0,s.flipY=!1,this.material.map=s,this.chunkMeshManager.syncCubeShaderUniforms();let o=I0(t.itemsAtlasImage);o.needsUpdate=!0,o.flipY=!1,this.itemsTexture=o,r&&r.dispose(),i&&i.dispose(),await super.updateAssetsData(),this.onAllTexturesLoaded(),Object.keys(this.loadedChunks).length>0&&this.rerenderAllChunks()}onAllTexturesLoaded(){this.holdingBlock.ready=!0,this.holdingBlock.updateItem(),this.holdingBlockLeft.ready=!0,this.holdingBlockLeft.updateItem()}changeBackgroundColor(t){this.realScene.background=new Q.Color(t[0],t[1],t[2])}changeCardinalLight(t){this.worldRendererConfig.cardinalLight=t}timeUpdated(t){let r=this.getModule("starfield");r?.updateTimeOfDay&&r.updateTimeOfDay(t),this.skyboxRenderer.updateTime(t)}biomeUpdated(t){t?.temperature!==void 0&&this.skyboxRenderer.updateTemperature(t.temperature)}biomeReset(){this.skyboxRenderer.updateTemperature(Gi)}getItemRenderData(t,r){return Z3(t,r,this.resourcesManager,this.playerStateReactive)}async demoModel(){let t=cursorBlockRel(0,1,0).position,r=await R5();Ps(r,t);let i=new Q.BoxHelper(r,16776960);r.add(i),this.realScene.add(r)}demoItem(){let t=cursorBlockRel(0,1,0).position,{mesh:r}=this.entities.getItemMesh({itemId:541},{});r.position.set(t.x+.5,t.y+.5,t.z+.5);let i=new Q.BoxHelper(r,16776960);r.add(i),this.realScene.add(r)}addDebugOverlay(){if(this.debugOverlayAdded)return;this.debugOverlayAdded=!0;let t=lt("debug-overlay",80,0,void 0,{className:vt});setInterval(()=>{if(t.setVisibility(this.displayAdvancedStats),this.displayAdvancedStats){let r=v=>new Intl.NumberFormat("en-US",{}).format(v),i=v=>new Intl.NumberFormat("en-US",{notation:"compact",maximumFractionDigits:1}).format(v),s="";s+=`TE: ${r(this.renderer.info.memory.textures)} `,s+=`F: ${i(this.tilesRendered)} `,s+=`B: ${i(this.blocksRendered)} `,s+=`MEM: ${this.chunkMeshManager.getEstimatedMemoryUsage().total} `;let o=this.chunkMeshManager.getStats();s+=`POOL: ${o.activeCount}/${o.poolSize} `;let a=Er(this.reactiveState.world.instabilityFactors);a&&(s+=`PF: ${a} `),t.updateText(s),this.backendInfoReport=s}},200)}updatePosDataChunk(t){let r=this.sectionObjects[t];if(!r)return;let[i,s,o]=t.split(",").map(c=>Math.floor(+c/16)),v=500-(Math.abs(i-this.cameraSectionPos.x)+Math.abs(s-this.cameraSectionPos.y)+Math.abs(o-this.cameraSectionPos.z)),l=r.mesh??r.shaderMesh??r.children.find(c=>c.name==="mesh"||c.name==="shaderMesh");l&&(l.renderOrder=v)}updateViewerPosition(t){this.viewerChunkPosition=t}cameraSectionPositionUpdate(){for(let t in this.sectionObjects)this.sectionObjects[t]&&this.updatePosDataChunk(t)}getDir(t,r){return t===r?0:t<r?1:-1}finishChunk(t){this.chunkMeshManager.finishChunkDisplay(t)}applyPendingSectionUpdates(){if(this.pendingSectionUpdates.size===0)return;let t=performance.now(),r=this.getSectionHeight(),i=[];for(let s of this.pendingSectionUpdates.keys()){let o=this.pendingSectionBufferStartTimes.get(s)??t;if(t-o<yt.MAX_SECTION_UPDATE_BUFFER_MS){let[v,l,c]=s.split(",").map(Number),u=[`${v-16},${l},${c}`,`${v+16},${l},${c}`,`${v},${l-r},${c}`,`${v},${l+r},${c}`,`${v},${l},${c-16}`,`${v},${l},${c+16}`],h=!1;for(let p of u)if(this.sectionsWaiting.has(p)&&!this.pendingSectionUpdates.has(p)&&this.sectionObjects[p]){h=!0;break}if(h)continue}i.push(s)}if(i.length!==0)for(let s of i){let o=this.pendingSectionUpdates.get(s);this.pendingSectionUpdates.delete(s),this.pendingSectionBufferStartTimes.delete(s);let a=o.key.split(","),v=`${a[0]},${a[2]}`;if(!this.loadedChunks[v]||!this.active){this.chunkMeshManager.releaseSection(o.key);continue}if(!this.chunkMeshManager.sectionHasRenderableContent(o.geometry)){this.chunkMeshManager.releaseSection(o.key);continue}this.chunkMeshManager.updateSection(o.key,o.geometry),this.updatePosDataChunk(o.key)}}clearPendingSectionUpdatesForChunk(t,r){for(let i of[...this.pendingSectionUpdates.keys()])i.startsWith(`${t},`)&&i.endsWith(`,${r}`)&&(this.pendingSectionUpdates.delete(i),this.pendingSectionBufferStartTimes.delete(i))}handleWorkerMessage(t){if(t.type==="geometry"){let r=t.key.split(","),i=`${r[0]},${r[2]}`;if(!this.loadedChunks[i]||!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}this.chunkMeshManager.updateSection(t.key,t.geometry),this.updatePosDataChunk(t.key)}}getSignTexture(t,r,i,s=!1){let o=Ht(t),a=this.chunkTextures.get(`${o[0]},${o[1]}`);a||(a={},this.chunkTextures.set(`${o[0]},${o[1]}`,a));let v=`${t.x},${t.y},${t.z}`;if(a[v])return a[v];let l=i9(this.version),c=m1(r,i,l);if(!c)return;let u=new Q.Texture(c);return u.magFilter=Q.NearestFilter,u.minFilter=Q.NearestFilter,u.needsUpdate=!0,a[v]=u,u}getCameraPosition(t){return(t??this._tmpCameraPos).set(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z)}getSectionCameraPosition(){let t=this.getCameraPosition();return new G0(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,r,i){let s=this.playerStateReactive.eyeHeight;this.updateCamera(t?.offset(0,s,0)??null,r,i),this.updateCameraSectionPos()}getThirdPersonCamera(t,r,i){t??(t=new Q.Vector3(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z));let s=this.playerStateReactive.perspective==="third_person_back",o=4,a=this._tpDirection.set(0,0,-1),v=this._tpPitchQuat.setFromAxisAngle(this._tpAxisX,i),l=this._tpYawQuat.setFromAxisAngle(this._tpAxisY,r),c=this._tpFinalQuat.multiplyQuaternions(l,v);a.applyQuaternion(c),s&&a.multiplyScalar(-1),this.DEBUG_RAYCAST&&this.debugRaycast(t,a,o);let u=this._tpScenePos.set(this.sceneOrigin.toSceneX(t.x),this.sceneOrigin.toSceneY(t.y),this.sceneOrigin.toSceneZ(t.z)),h=this._tpRaycaster;h.set(u,a),h.far=o;let p=80,g=p*p,y=t.x,A=t.y,b=t.z,w=[];for(let B of Object.values(this.sectionObjects)){if(B.name!=="chunk"||!B.visible||B.worldX===void 0)continue;let H=B.worldX-y,G=B.worldY-A,O=B.worldZ-b;if(H*H+G*G+O*O>g)continue;let j=B.children.find(J=>J.name==="mesh"||J.name==="shaderMesh");j&&w.push(j)}let S=h.intersectObjects(w,!1),C=o;S.length>0&&(C=Math.max(.5,S[0].distance-.2));let M=this.chunkMeshManager.raycastShaderSectionAABBs(t,a,C,p);return M!==void 0&&(C=Math.max(.5,M-.2)),new G0(t.x+a.x*C,t.y+a.y*C,t.z+a.z*C)}debugRaycast(t,r,i){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 Q.Vector3(this.sceneOrigin.toSceneX(t.x),this.sceneOrigin.toSceneY(t.y),this.sceneOrigin.toSceneZ(t.z));this.debugRaycastHelper=new Q.ArrowHelper(r.clone().normalize(),s,i,16711680,i*.1,i*.05),this.realScene.add(this.debugRaycastHelper);let o=new Q.SphereGeometry(.2,8,8),a=new Q.MeshBasicMaterial({color:65280});this.debugHitPoint=new Q.Mesh(o,a),this.debugHitPoint.position.copy(s).add(r.clone().multiplyScalar(i)),this.realScene.add(this.debugHitPoint)}setCinimaticCamera(t,r,i){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(i,r),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,r=this.playerStateReactive.fovMultiplier,i=t*(Number.isFinite(r)?r:1),s=performance.now();if(this.animatedFov===0&&(this.animatedFov=i),Math.abs(this.animatedFov-i)>=.01){let o=s-this.lastFovAnimTime,a=Math.min(o/yt.FOV_TRANSITION_MS,1),v=l=>1-(1-l)**3;this.animatedFov+=(i-this.animatedFov)*v(a),Math.abs(this.animatedFov-i)<.01&&(this.animatedFov=i)}else this.animatedFov=i;this.lastFovAnimTime=s,this.camera.fov!==this.animatedFov&&(this.camera.fov=this.animatedFov,this.camera.updateProjectionMatrix())}updateCamera(t,r,i){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 Oe(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(),o=0,a=Math.PI/2;s.yaw<a&&r>Math.PI+a?o=-Math.PI*2:r<a&&s.yaw>Math.PI+a&&(o=Math.PI*2),this.currentRotTween?.stop(),this.currentRotTween=new Oe(s).to({pitch:i,yaw:r+o},100).onUpdate(v=>this.cameraShake.setBaseRotation(v.pitch,v.yaw-o)).start()}else{this.currentRotTween?.stop(),this.cameraShake.setBaseRotation(i,r);let{perspective:s}=this.playerStateReactive;if(s==="third_person_back"||s==="third_person_front"){let o=new Q.Vector3(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),a=this.getThirdPersonCamera(o,r,i),v=o.distanceTo(new Q.Vector3(a.x,a.y,a.z)),l=s==="third_person_back"?v:-v;this.camera.position.set(0,0,l),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:r,chunksRenderDistanceOverride:i,chunksRenderAboveEnabled:s,chunksRenderBelowEnabled:o,chunksRenderDistanceEnabled:a}=this.reactiveDebugParams,v=this.getSectionHeight(),l=this.cameraSectionPos.y*v;if(this.displayOptions.inWorldRenderingConfig.enableDebugOverlay&&t!==void 0||r!==void 0||i!==void 0)for(let[c,u]of Object.entries(this.sectionObjects)){if(u._waitingForChunkDisplay)continue;let[h,p,g]=c.split(",").map(Number),y=s&&t!==void 0?p<=l+t:o&&r!==void 0?p>=l-r:a&&i!==void 0?Math.abs(p-l)<=i:!0;u.visible=y}else this.chunkMeshManager.updateSectionsVisibility()}render(t=!1){if(this.currentRenderedFrames++,this.reactiveDebugParams.stopRendering)return;this.debugChunksVisibilityOverride();let r=performance.now();this.lastRendered=performance.now();let i=this.lastRenderTime>0?Math.min(Math.max((r-this.lastRenderTime)/1e3,0),.1):1/60;this.lastRenderTime=r,this.cursorBlock.render(),this.updateSectionOffsets();let s=this.getCameraPosition();if(this.skyboxRenderer.update(s,this.viewDistance),this.updateSmoothFov(),t){let u=this.renderer.getSize(new Q.Vector2);this.camera.aspect=u.width/u.height,this.camera.updateProjectionMatrix()}let o=0;if(!this.reactiveDebugParams.disableEntities){let u=performance.now();this.entities.render(),o=performance.now()-u}let a=this.cameraGroupVr instanceof Q.Group?this.cameraGroupVr.children.find(u=>u instanceof Q.PerspectiveCamera):this.camera;this.applyPendingSectionUpdates();let v=this.chunkMeshManager.globalBlockBuffer;v&&(v.setCameraOrigin(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),v.compactStep(),v.uploadDirtyRange()),this.renderer.render(this.scene,a),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 u of this.fountains)this.sectionObjects[u.sectionId]&&!this.sectionObjects[u.sectionId].foutain&&(u.createParticles(this.sectionObjects[u.sectionId]),this.sectionObjects[u.sectionId].foutain=!0),u.render();this.waypoints.render(),this.fireworks.update();for(let u of this.onRender)u(i);let c=performance.now()-r;this.worldRendererConfig.autoLowerRenderDistance&&this.chunkMeshManager.recordRenderTime(c),this.renderTimeAvgCount++,this.renderTimeAvg=(this.renderTimeAvg*(this.renderTimeAvgCount-1)+c)/this.renderTimeAvgCount,this.renderTimeMax=Math.max(this.renderTimeMax,c),this.performanceMonitor.onFrame({totalMs:c,entitiesMs:o,loadedTextureCount:this.renderer.info.memory.textures,fps:this.lastFps})}renderHead(t,r,i,s){let o;if(s.SkullOwner?o=s.SkullOwner.Properties?.textures?.[0]?.Value:o=s.profile?.properties?.find(a=>a.name==="textures")?.value,!!o)try{let v=JSON.parse(z.from(o,"base64").toString()).textures?.SKIN?.url,{skinTexturesProxy:l}=this.worldRendererConfig;l&&(v=v?.replace("http://textures.minecraft.net/",l).replace("https://textures.minecraft.net/",l));let c=D0(this,v,F0.head),u=new Q.Group;return i&&c.position.set(0,.3125,.3125),c.position.y-=23/16,u.add(c),this.sceneOrigin.track(u),u.position.set(t.x+.5,t.y+.045,t.z+.5),u.rotation.set(0,-Q.MathUtils.degToRad(r*(i?90:45/2)),0),u.scale.set(.8,.8,.8),u}catch{}}renderSign(t,r,i,s,o){let a=this.getSignTexture(t,o,s);if(!a)return;let v=new Q.Mesh(new Q.PlaneGeometry(1,1),new Q.MeshBasicMaterial({map:a,transparent:!0}));v.renderOrder=999;let l=7/16,c=s?1.3:1;v.scale.set(1*c,l*c,1*c);let u=(s?2:1.5)/16,h=.25/16;i&&!s?v.position.set(0,0,-.5+u+h+1e-4):v.position.set(0,0,u/2+1e-4);let p=new Q.Group;p.rotation.set(0,-Q.MathUtils.degToRad(r*(i?90:45/2)),0),p.add(v);let g=(s?10:8)/16,y=(s?0:i?4.333:9.333)/16,A=g/2+y;return this.sceneOrigin.track(p),p.position.set(t.x+.5,t.y+A,t.z+.5),p}lightUpdate(t,r){for(let i=this.worldSizeParams.minY;i<this.worldSizeParams.worldHeight;i+=16)this.setSectionDirty(new G0(t,i,r))}rerenderAllChunks(){for(let t of Object.keys(this.sectionObjects)){let[r,i,s]=t.split(",").map(Number);this.setSectionDirty(new G0(r,i,s))}}updateShowChunksBorder(t){this.chunkMeshManager.updateAllBoxHelpers(t)}resetWorld(){super.resetWorld(),this.pendingSectionUpdates.clear(),this.pendingSectionBufferStartTimes.clear(),this.chunkMeshManager.dispose(),this.chunkMeshManager=new Y5(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,r=!1){let[i,s,o]=Qr(t);return Object.fromEntries(Object.entries(this.sectionObjects).map(([a,v])=>{let[l,c,u]=a.split(",").map(Number),[h,p,g]=Qr({x:l,y:c,z:u});return[r?`${h-i},${p-s},${g-o}`:`${h-i},${g-o}`,v]}))}cleanChunkTextures(t,r){let i=this.chunkTextures.get(`${Math.floor(t/16)},${Math.floor(r/16)}`)??{};for(let s of Object.keys(i))i[s].dispose(),delete i[s];this.chunkMeshManager.cleanSignChunkTextures(t,r)}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 r of t)r.matrixWorldNeedsUpdate=!1,this.disableUpdates(r.children??[])}removeColumn(t,r){super.removeColumn(t,r),this.cleanChunkTextures(t,r),this.clearPendingSectionUpdatesForChunk(t,r);let i=this.getSectionHeight(),s=this.worldMinYRender;for(let o=s;o<this.worldSizeParams.worldHeight;o+=i){let a=`${t},${o},${r}`;this.chunkMeshManager.sectionObjects[a]&&this.chunkMeshManager.releaseSection(a)}this.chunkMeshManager.onChunkRemovedFromGate(`${t},${r}`)}updateViewerPosition(t){super.updateViewerPosition(t),this.chunkMeshManager.pendingNearReveal.size>0&&this.chunkMeshManager.tryRevealPending()}onViewerChunkPositionChanged(){this.chunkMeshManager.tryRevealPending()}setSectionDirty(...t){let[r]=t;this.cleanChunkTextures(r.x,r.z),super.setSectionDirty(...t)}static getRendererInfo(t){try{let r=t.getContext();return`${r.getParameter(r.getExtension("WEBGL_debug_renderer_info").UNMASKED_RENDERER_WEBGL)}`}catch{}}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 i=this.getSectionHeight(),s,o,a,v=this.sceneOrigin.getWorldPosition(t);v?(s=v.x,o=v.y,a=v.z):(s=this.sceneOrigin.toWorldX(t.position.x),o=this.sceneOrigin.toWorldY(t.position.y),a=this.sceneOrigin.toWorldZ(t.position.z));let l=Math.floor(s/16)*16,c=Math.floor(a/16)*16,u=Math.floor(o/i)*i,h=`${l},${c}`,p=`${l},${u},${c}`;return!!this.finishedChunks[h]||!!this.sectionObjects[p]}handleUserClick(t){this.media.handleUserClick(t)}updateSectionOffsets(){let t=performance.now();for(let[r,i]of Object.entries(this.sectionsOffsetsAnimations)){let s=(t-i.time)/1e3;i.time=t,i.currentOffsetX+=i.speedX*s,i.currentOffsetY+=i.speedY*s,i.currentOffsetZ+=i.speedZ*s,i.limitX!==void 0&&(i.speedX>0?i.currentOffsetX=Math.min(i.currentOffsetX,i.limitX):i.currentOffsetX=Math.max(i.currentOffsetX,i.limitX)),i.limitY!==void 0&&(i.speedY>0?i.currentOffsetY=Math.min(i.currentOffsetY,i.limitY):i.currentOffsetY=Math.max(i.currentOffsetY,i.limitY)),i.limitZ!==void 0&&(i.speedZ>0?i.currentOffsetZ=Math.min(i.currentOffsetZ,i.limitZ):i.currentOffsetZ=Math.max(i.currentOffsetZ,i.limitZ));let o=this.sectionObjects[r];o&&(o.position.set(i.currentOffsetX,i.currentOffsetY,i.currentOffsetZ),o.updateMatrix())}}reloadWorld(){this.entities.reloadEntities()}};d(yt,"FOV_TRANSITION_MS",200),d(yt,"MAX_SECTION_UPDATE_BUFFER_MS",500);var _t=yt;E();x();k();R();E();x();k();R();var N0="1.21.4";E();x();k();R();function wt(n,e){n.aspect=e.width/e.height,n.updateProjectionMatrix()}E();x();k();R();function ln(n,e=!1){return n?.mode?n.mode:e?"worldBlocks":b0.mode}E();x();k();R();import*as ve from"three";E();x();k();R();function cn(...n){let e=n.filter(r=>r.length>0).join("/"),t=typeof globalThis.location<"u"&&globalThis.location.href?globalThis.location.href:typeof import.meta<"u"&&import.meta.url?import.meta.url:`/${e}`;try{return new URL(e,t).href}catch{return`/${e}`}}var dn=new Date,Da=dn.getMonth()===11&&dn.getDate()>=24&&dn.getDate()<=26,n9=["panorama_3.webp","panorama_1.webp","panorama_4.webp","panorama_5.webp","panorama_0.webp","panorama_2.webp"],s9=200,Xt=class{constructor(e){this.documentRenderer=e;d(this,"scene");d(this,"camera");d(this,"startTimes",new Map);d(this,"time",0);d(this,"panoramaGroup",null);this.scene=new ve.Scene,this.scene.background=new ve.Color(3294568);let t=new ve.AmbientLight(13421772);this.scene.add(t);let r=new ve.DirectionalLight(16777215,.5);r.position.set(1,1,.5).normalize(),r.castShadow=!0,this.scene.add(r),this.camera=new ve.PerspectiveCamera(85,e.canvas.width/e.canvas.height,.05,1e3),this.camera.position.set(0,0,0),this.camera.rotation.set(0,0,0)}async init(){this.buildCubemap()}update(e,t){t&&wt(this.camera,this.documentRenderer.canvas)}dispose(){this.scene.clear(),this.panoramaGroup=null,this.startTimes.clear()}buildCubemap(){let e=new ve.BoxGeometry(1e3,1e3,1e3),t=[];for(let s of n9)(async()=>{let a=cn("background",Da?"christmas":"",s),v=await st(a),l=I0(v);l.matrixAutoUpdate=!1,l.matrix.set(-1,0,1,0,1,0,0,0,1),l.wrapS=ve.ClampToEdgeWrapping,l.wrapT=ve.ClampToEdgeWrapping,l.minFilter=ve.LinearFilter,l.magFilter=ve.LinearFilter;let c=new ve.MeshBasicMaterial({map:l,transparent:!0,side:ve.DoubleSide,depthWrite:!1,opacity:0});this.startTimes.set(c,Date.now()),t.push(c)})().catch(a=>{});let r=new ve.Mesh(e,t);r.onBeforeRender=()=>{this.time+=.01,r.rotation.y=Math.PI+this.time*.01,r.rotation.z=Math.sin(-this.time*.001)*.001;for(let s of t){let o=this.startTimes.get(s);if(o){let a=Date.now()-o;s.opacity=Math.min(1,a/s9)}}};let i=new ve.Object3D;if(i.add(r),!Da)for(let s=0;s<20;s++){let o=new M0("1.16.4","squid").mesh;o.position.set(Math.random()*30-15,Math.random()*20-10,Math.random()*10-17),o.rotation.set(0,Math.PI+Math.random(),-Math.PI/4,"ZYX");let a=Math.random()*.01;o.children[0].onBeforeRender=()=>{o.rotation.y+=a,o.rotation.z=Math.cos(r.rotation.y*3)*Math.PI/4-Math.PI/2},i.add(o)}this.scene.add(i),this.panoramaGroup=i}async debugImageInFrontOfCamera(){let e=await st(cn("background","panorama_0.webp")),t=I0(e),r=new ve.Mesh(new ve.PlaneGeometry(1e3,1e3),new ve.MeshBasicMaterial({map:t}));r.position.set(0,0,-500),this.scene.add(r)}};E();x();k();R();import*as W from"three";var Fa=.1,fn={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"]},za={galaxy:{bg:132114,fog:132114,fogD:.011,blocks:[61695,54527,47359,59647,2280703,43263],emit:[13158,8789,6724],nebula:[4403,1114146,4386],galFn:n=>new W.Color(n*.05,n*.2,n),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:n=>new W.Color(n,n*.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:n=>new W.Color(n*.4,0,n),ambient:393232,dir:10040319,pt1:11158783,pt2:4456618,name:"THE END"},cyber:{bg:2566,fog:2566,fogD:.01,blocks:[65535,65416,11206400,52479,6749952,65518],emit:[8721,6656,6690],nebula:[6674,5120,4634],galFn:n=>new W.Color(0,n,n*.6),ambient:6669,dir:65450,pt1:65484,pt2:4521728,name:"CYBER"},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:n=>{let e=new W.Color;return n<.4?e.lerpColors(new W.Color(16054527),new W.Color(14215423),n/.4):n<.75?e.lerpColors(new W.Color(14215423),new W.Color(11061488),(n-.4)/.35):e.lerpColors(new W.Color(11061488),new W.Color(9482464),(n-.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]}},o9={cruise:{pos:(n,e,t)=>({x:Math.sin(n*.28)*18+Math.cos(n*.11)*7+e*10,y:Math.sin(n*.19)*6+Math.cos(n*.31)*3+t*6,z:0}),look:(n,e,t)=>({x:Math.sin((n+.18)*.28)*18+e*8,y:Math.sin((n+.18)*.19)*6+t*4,z:-25}),roll:(n,e=0)=>e*.05+Math.sin(n*.22)*.015,spd:.18},barrel:{pos:(n,e,t)=>{let i=n*2.4;return{x:Math.cos(i)*10+e*4,y:Math.sin(i)*10+t*4,z:Math.sin(n*.4)*8}},look:n=>({x:Math.sin(n*.5)*5,y:Math.cos(n*.5)*5,z:-30}),roll:n=>n*2.4+Math.PI*.5,spd:.24},dive:{pos:(n,e,t)=>({x:Math.sin(n*.6)*30+e*8,y:Math.cos(n*.4)*18+t*6,z:Math.sin(n*.3)*12}),look:(n,e,t)=>({x:Math.sin(n*.6+.2)*30+e*6,y:Math.cos(n*.4+.2)*18-8+t*4,z:-35}),roll:(n,e=0)=>e*.08+Math.sin(n*.6)*.12,spd:.3},orbit:{pos:(n,e,t)=>({x:Math.cos(n*.5)*20+e*5,y:Math.sin(n*.25)*10+t*5,z:Math.sin(n*.5)*20}),look:()=>({x:0,y:0,z:-60}),roll:n=>Math.sin(n*.5)*.08,spd:.15},snake:{pos:(n,e,t)=>({x:Math.sin(n*1.1)*22+Math.sin(n*.37)*8+e*10,y:Math.sin(n*.7)*10+e*4+t*8,z:0}),look:(n,e,t)=>{let r=n+.12;return{x:Math.sin(r*1.1)*22+Math.sin(r*.37)*8+e*8,y:Math.sin(r*.7)*10+t*6,z:-22}},roll:(n,e=0)=>e*.1+Math.sin(n*1.1)*.06,spd:.22}},a9={cruise:1,barrel:1.6,dive:2.2,orbit:.7,snake:1.4},v9=250,dr=1e4,ur=3e3,$t=n=>n[Math.floor(Math.random()*n.length)],un=n=>"#"+n.toString(16).padStart(6,"0"),La=n=>{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 r=e.width,i=e.height,s=n.radial?t.createRadialGradient(r/2,i*.32,0,r/2,i*.32,i*.85):t.createLinearGradient(0,0,0,i);s.addColorStop(0,un(n.top)),n.mid!=null&&s.addColorStop(.45,un(n.mid)),s.addColorStop(1,un(n.bottom)),t.fillStyle=s,t.fillRect(0,0,r,i);let o=new W.CanvasTexture(e);return o.needsUpdate=!0,o},At=class{constructor(e,t={},r){this.documentRenderer=e;this.abortSignal=r;d(this,"scene");d(this,"camera");d(this,"ambient");d(this,"dir");d(this,"pt1");d(this,"pt2");d(this,"blocks",[]);d(this,"bGroup",new W.Group);d(this,"galaxy");d(this,"nebula");d(this,"stars");d(this,"galGeo");d(this,"nebGeo");d(this,"bGeo",new W.BoxGeometry(1,1,1));d(this,"eGeo",new W.EdgesGeometry(this.bGeo));d(this,"curScene");d(this,"curCam");d(this,"blockGroup");d(this,"cameraSpeed");d(this,"blockSpeed");d(this,"camT",0);d(this,"mx",0);d(this,"my",0);d(this,"tmx",0);d(this,"tmy",0);d(this,"transitioning",!1);d(this,"useMinecraftTextures",!1);d(this,"resourcesManager");d(this,"atlasTexture",null);d(this,"blockMaterialPool",new Map);d(this,"gradientSky",null);d(this,"gradientSkyTexture",null);d(this,"disposed",!1);d(this,"animTime",0);d(this,"texturesApplied",!1);d(this,"textureLoadInProgress",!1);d(this,"onAssetsTexturesUpdated");let i=b0;this.curScene=t.initialScene??i.v2Scene,this.curCam=t.initialCamera??i.v2Camera,this.blockGroup=t.initialBlockGroup??i.v2BlockGroup,this.cameraSpeed=t.initialCameraSpeed??b5.camera,this.blockSpeed=t.initialBlockSpeed??b5.block,this.useMinecraftTextures=t.useMinecraftTextures??i.minecraftTextures,this.resourcesManager=t.resourcesManager;let s=za[this.curScene];this.scene=new W.Scene,this.scene.fog=new W.FogExp2(s.fog,s.fogD),this.applyScenePalette(s),this.camera=new W.PerspectiveCamera(80,this.documentRenderer.canvas.width/this.documentRenderer.canvas.height,.1,700),this.ambient=new W.AmbientLight(s.ambient,2.5),this.scene.add(this.ambient),this.dir=new W.DirectionalLight(s.dir,4),this.dir.position.set(1,1,0),this.scene.add(this.dir),this.pt1=new W.PointLight(s.pt1,5,100),this.scene.add(this.pt1),this.pt2=new W.PointLight(s.pt2,4,80),this.pt2.position.set(30,20,-30),this.scene.add(this.pt2);for(let h=0;h<v9;h++)this.spawnBlock(s,!0);if(!this.useMinecraftTextures){let h=s.edgeLineColor??62975;for(let p=0;p<40;p++){let g=new W.LineBasicMaterial({color:h,transparent:!0,opacity:.25});$t(this.blocks).mesh.add(new W.LineSegments(this.eGeo,g))}}this.scene.add(this.bGroup);let o=new W.BufferGeometry,a=new Float32Array(5e3*3);for(let h=0;h<5e3*3;h++)a[h]=(Math.random()-.5)*500;o.setAttribute("position",new W.BufferAttribute(a,3)),this.stars=new W.Points(o,new W.PointsMaterial({color:s.starColor??16777215,size:.3,transparent:!0,opacity:s.starOpacity??.7,sizeAttenuation:!0})),this.scene.add(this.stars),this.galGeo=new W.BufferGeometry;let v=new Float32Array(dr*3),l=new Float32Array(dr*3);for(let h=0;h<dr;h++){let p=h%3,g=Math.random(),y=p/3*Math.PI*2+g*Math.PI*5,A=g*90+Math.random()*10,b=(1-g)*18;v[h*3]=Math.cos(y)*A+(Math.random()-.5)*b,v[h*3+1]=(Math.random()-.5)*7,v[h*3+2]=Math.sin(y)*A+(Math.random()-.5)*b-180;let w=.2+g*.8,S=s.galFn(w);l[h*3]=S.r,l[h*3+1]=S.g,l[h*3+2]=S.b}this.galGeo.setAttribute("position",new W.BufferAttribute(v,3)),this.galGeo.setAttribute("color",new W.BufferAttribute(l,3)),this.galaxy=new W.Points(this.galGeo,new W.PointsMaterial({size:.9,vertexColors:!0,transparent:!0,opacity:s.galaxyOpacity??.55,sizeAttenuation:!0})),this.scene.add(this.galaxy),this.nebGeo=new W.BufferGeometry;let c=new Float32Array(ur*3),u=new Float32Array(ur*3);for(let h=0;h<ur;h++){let p=25+Math.random()*110,g=Math.random()*Math.PI*2,y=(Math.random()-.5)*Math.PI*.5;c[h*3]=p*Math.cos(g)*Math.cos(y),c[h*3+1]=p*Math.sin(y)*.6,c[h*3+2]=p*Math.sin(g)*Math.cos(y)-80;let A=new W.Color($t(s.nebula));u[h*3]=A.r,u[h*3+1]=A.g,u[h*3+2]=A.b}this.nebGeo.setAttribute("position",new W.BufferAttribute(c,3)),this.nebGeo.setAttribute("color",new W.BufferAttribute(u,3)),this.nebula=new W.Points(this.nebGeo,new W.PointsMaterial({size:3,vertexColors:!0,transparent:!0,opacity:s.nebulaOpacity??.3,sizeAttenuation:!0})),this.scene.add(this.nebula),this.addBackgroundTextPlane(),this.setupMouseTracking()}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:N0,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 h0;if(!await this.ensureAtlasReady(e)){this.resourcesManager&&this.attachAssetsListener();return}if(this.disposed)return;this.applyMinecraftTexturesFromAtlas(e),this.texturesApplied=!0,this.detachAssetsListener()}catch{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=La(e.gradientBg);s&&(this.gradientSkyTexture.dispose(),this.gradientSkyTexture=s,this.gradientSky.material.map=s,this.gradientSky.material.needsUpdate=!0)}}else{let s=La(e.gradientBg);s?(this.gradientSkyTexture=s,this.gradientSky=new W.Mesh(new W.PlaneGeometry(900,700),new W.MeshBasicMaterial({map:s,depthWrite:!1,side:W.DoubleSide})),this.gradientSky.position.set(0,0,-280),this.gradientSky.renderOrder=-1e3,this.scene.add(this.gradientSky)):this.scene.background=new W.Color(e.bg)}else this.scene.background=new W.Color(e.bg),this.gradientSky&&(this.gradientSky.visible=!1);this.scene.fog instanceof W.FogExp2&&(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 r=this.galaxy?.material;r&&(r.opacity=e.galaxyOpacity??.55);let i=this.nebula?.material;i&&(i.opacity=e.nebulaOpacity??.3)}setupMouseTracking(){let e=r=>{let i=typeof window<"u"?window.innerWidth:this.documentRenderer.canvas.width,s=typeof window<"u"?window.innerHeight:this.documentRenderer.canvas.height;this.tmx=(r.clientX/i-.5)*2,this.tmy=-(r.clientY/s-.5)*2};(typeof document<"u"?document:void 0)?.addEventListener("mousemove",e,{signal:this.abortSignal})}addBackgroundTextPlane(){let r=typeof document<"u"?document.createElement("canvas"):null;if(!r)return;r.width=2048,r.height=768;let i=r.getContext("2d");if(!i)return;i.clearRect(0,0,2048,768),i.save(),i.font="bold 560px Orbitron, sans-serif",i.textAlign="center",i.textBaseline="middle",i.shadowColor="rgba(0,200,255,0.35)",i.shadowBlur=80,i.fillStyle="rgba(255,255,255,0.055)",i.fillText("V2",2048*.28,768*.5),i.restore(),i.save(),i.font="bold 148px Orbitron, sans-serif",i.textAlign="center",i.textBaseline="middle",i.shadowColor="rgba(0,200,255,0.2)",i.shadowBlur=40,i.fillStyle="rgba(255,255,255,0.038)",i.fillText("by ZARDOY",2048*.72,768*.52),i.restore();let s=new W.CanvasTexture(r),o=new W.Mesh(new W.PlaneGeometry(280,105),new W.MeshBasicMaterial({map:s,transparent:!0,opacity:1,depthWrite:!1,side:W.DoubleSide,blending:W.AdditiveBlending}));o.position.set(8,4,-320),this.scene.add(o)}spawnBlock(e,t,r){let i=this.createBlockMaterial(e,r),s=new W.Mesh(this.bGeo,i),o=.3+Math.random()*3;s.scale.setScalar(o),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 a={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:r};this.blocks.push(a),this.bGroup.add(s)}createBlockMaterial(e,t){if(this.useMinecraftTextures&&t){let s=this.blockMaterialPool.get(t);if(s)return s.clone()}let[r,i]=e.blockOpacity??[.32,.46];return new W.MeshBasicMaterial({color:$t(e.blocks),transparent:!0,opacity:r+Math.random()*(i-r),depthWrite:!1,blending:W.AdditiveBlending})}removeBlockEdgeLines(){for(let e of this.blocks){let t=e.mesh.children.filter(r=>r instanceof W.LineSegments);for(let r of t){e.mesh.remove(r),r.geometry?.dispose();let i=r.material;Array.isArray(i)?i.forEach(s=>s.dispose()):i.dispose()}}}async ensureMcDataLoaded(){let e=globalThis._LOAD_MC_DATA;e&&await e()}resolveBlockAtlasUv(e,t,r){let i=s=>{let o=t[s];return o?{u:o.u,v:o.v,su:o.su??r.suSv,sv:o.sv??r.suSv}:null};if(t[e])return i(e);for(let s of["_top","_side","_front","_0"]){let o=i(`${e}${s}`);if(o)return o}for(let s of Object.keys(t))if(s.startsWith(e))return i(s);return null}applyMinecraftTexturesFromAtlas(e){let t=e.currentResources;if(!t?.blocksAtlasImage||!t.blocksAtlasJson)throw new Error("Block atlas not available");let r=t.blocksAtlasJson,i=r.textures;this.atlasTexture=I0(t.blocksAtlasImage),this.atlasTexture.flipY=!1,this.atlasTexture.needsUpdate=!0;for(let s of fn[this.blockGroup]){let o=this.resolveBlockAtlasUv(s,i,r);if(!o)continue;let a=this.atlasTexture.clone();a.flipY=!1,a.offset.set(o.u,o.v),a.repeat.set(o.su,o.sv),a.needsUpdate=!0;let v=s.includes("glass"),l=new W.MeshBasicMaterial({map:a,side:W.DoubleSide,transparent:v,opacity:v?.85:1,alphaTest:v?.08:0,depthWrite:!0,toneMapped:!1});this.blockMaterialPool.set(s,l)}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 o=$t([...this.blockMaterialPool.keys()]);s.minecraftBlockName=o,s.mesh.material=this.blockMaterialPool.get(o).clone()}}setScene(e){if(!tt.includes(e)||e===this.curScene||this.transitioning)return;this.transitioning=!0,this.curScene=e;let t=za[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 W.MeshBasicMaterial&&s.mesh.material.color.set($t(t.blocks));let r=this.nebGeo.attributes.color;for(let s=0;s<ur;s++){let o=new W.Color($t(t.nebula));r.setXYZ(s,o.r,o.g,o.b)}r.needsUpdate=!0;let i=this.galGeo.attributes.color;for(let s=0;s<dr;s++){let o=.2+Math.random()*.8,a=t.galFn(o);i.setXYZ(s,a.r,a.g,a.b)}i.needsUpdate=!0,this.transitioning=!1},150)}setCamera(e){rt.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(it.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&&wt(this.camera,this.documentRenderer.canvas);let r=o9[this.curCam],i=this.cameraSpeed,s=this.blockSpeed;this.camT+=e*r.spd*i,this.mx+=(this.tmx-this.mx)*.05,this.my+=(this.tmy-this.my)*.05;let o=this.mx*Fa,a=this.my*Fa,v=r.pos(this.camT,o,a),l=r.look(this.camT,o,a);this.camera.position.set(v.x,v.y,v.z),this.camera.lookAt(l.x,l.y,l.z),this.camera.rotation.z=r.roll(this.camT,o);let c=a9[this.curCam]*s;this.animTime+=e*1e3*s;for(let u of this.blocks){if(u.mesh.position.z+=u.spd*c*60*e,u.mesh.position.x+=u.dx*60*e*s,u.mesh.position.y+=u.dy*60*e*s,u.mesh.rotation.x+=u.rx*c,u.mesh.rotation.y+=u.ry*c,u.mesh.rotation.z+=u.rz,!this.useMinecraftTextures&&u.mesh.material instanceof W.MeshBasicMaterial){let h=u.mesh.userData.baseOpacity??.38;u.mesh.userData.baseOpacity==null&&(u.mesh.userData.baseOpacity=h);let p=.88+Math.abs(Math.sin(this.animTime*8e-4+u.mesh.position.x*.3))*.12;u.mesh.material.opacity=h*p}u.mesh.position.z>this.camera.position.z+15&&u.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()}};E();x();k();R();import*as t5 from"three";import{Vec3 as Ga}from"vec3";E();x();k();R();import l9 from"prismarine-world";import c9 from"prismarine-chunk";var Ua=n=>{let e=l9(n),t=c9(n),r=new e(n).sync,i=d9(r);for(let s of i)if(s.startsWith("set")&&s!=="setColumn"){let o=r[s].bind(r);r[s]=(...a)=>{let v=a[0];v.x!==void 0&&!r.getColumnAt(v)&&r.setColumn(Math.floor(v.x/16),Math.floor(v.z/16),new t(void 0)),o(...a)}}return r};function d9(n){let e=new Set,t=n;do for(let r of Object.getOwnPropertyNames(t))typeof n[r]=="function"&&r!=="constructor"&&e.add(r);while(t=Object.getPrototypeOf(t));return[...e]}var e5=class{constructor(e,t,r){this.documentRenderer=e;this.options=t;this.abortSignal=r;d(this,"_scene");d(this,"_camera");d(this,"worldRenderer");d(this,"WorldRendererClass",_t);this._scene=new t5.Scene,this._scene.background=new t5.Color(3294568),this._camera=new t5.PerspectiveCamera(85,e.canvas.width/e.canvas.height,.05,1e3),this.camera.position.set(0,0,0),this.camera.rotation.set(0,0,0)}get scene(){return this._scene}get camera(){return this._camera}async init(){let e=N0,t=new h0;if(t.currentConfig={version:e,noInventoryGui:!0},await t.updateAssetsData?.({}),this.abortSignal.aborted)return;let r=Ua(e),s=Xa("prismarine-block")(e),a=globalThis.mcData.blocksArray.filter(p=>{if(!p.name.includes("stained_glass"))return!1;let g=s.fromStateId(p.defaultState,0);if(g.shapes?.length!==1)return!1;let y=g.shapes[0];return y[0]===0&&y[1]===0&&y[2]===0&&y[3]===1&&y[4]===1&&y[5]===1}),v=-15,l=100,c=100;for(let p=-l;p<l;p++)for(let g=-c;g<c;g++){let y=a[Math.floor(Math.random()*a.length)];r.setBlockStateId(new Ga(p,g,v),y.defaultState)}this._camera.updateProjectionMatrix(),this._camera.position.set(.5,c/2+.5,.5),this._camera.rotation.set(0,0,0);let u=new Ga(...this._camera.position.toArray()),h=new $0(r,2,u);this.abortSignal.aborted||(this.worldRenderer=new this.WorldRendererClass(this.documentRenderer.renderer,this.options,{version:e,worldView:h,inWorldRenderingConfig:c5,playerStateReactive:G2().reactive,rendererState:J0().reactive,nonReactiveState:J0().nonReactive,resourcesManager:t}),this.worldRenderer instanceof _t&&(this._scene=this.worldRenderer.realScene,this._camera=this.worldRenderer.camera),h.init(u),await this.worldRenderer.waitForChunksToRender(),!this.abortSignal.aborted&&this.setupMouseParallax())}update(e,t){t&&wt(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,r=e.position.y,i;document.body.addEventListener("pointermove",s=>{if(s.pointerType!=="mouse")return;let o=.2,a=s.clientX/window.innerWidth-.5,v=-(s.clientY/window.innerHeight-.5);i?.stop(),i=new Oe(e.position).to({x:t+a*o,y:r+v*o},0),i.start(),e.updateProjectionMatrix()},{signal:this.abortSignal})}};E();x();k();R();import*as Na from"three";var r5=class{constructor(e,t,r={},i=!1){this.documentRenderer=e;this.options=t;d(this,"active");d(this,"abortController",new AbortController);d(this,"mode");d(this,"lastFrameTime",0);this.mode=ln(r,i)}get v2(){return this.active instanceof At?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 Na.Color&&this.documentRenderer.renderer.setClearColor(this.active.scene.background),this.lastFrameTime=performance.now(),this.documentRenderer.render=(t=!1)=>{let r=performance.now(),i=Math.min((r-this.lastFrameTime)/1e3,.05);this.lastFrameTime=r;let s=this.active;s&&(s.update(i,t),this.documentRenderer.renderer.render(s.scene,s.camera))}}createImplementation(e){switch(this.mode){case"v2":return new At(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 e5(this.documentRenderer,this.options,this.abortController.signal);default:return new Xt(this.documentRenderer)}}dispose(){this.active?.dispose(),this.active=void 0,this.abortController.abort()}};Q5.ColorManagement.enabled=!1;globalThis.THREE=Q5;var Wa=n=>({updateMap:n.entities.updateMap.bind(n.entities),updateCustomBlock:n.updateCustomBlock.bind(n),getBlockInfo:n.getBlockInfo.bind(n),playEntityAnimation:n.entities.playAnimation.bind(n.entities),damageEntity:n.entities.handleDamageEvent.bind(n.entities),updatePlayerSkin:n.entities.updatePlayerSkin.bind(n.entities),changeHandSwingingState:n.changeHandSwingingState.bind(n),getHighestBlocks:n.getHighestBlocks.bind(n),reloadWorld:n.reloadWorld.bind(n),updateEntityModel:n.entities.updateEntityModel.bind(n.entities),playEntityModelAnimation:n.entities.playEntityModelAnimation.bind(n.entities),addMedia:n.media.addMedia.bind(n.media),destroyMedia:n.media.destroyMedia.bind(n.media),setControlMode:n.media.setControlMode.bind(n.media),setVideoPlaying:n.media.setVideoPlaying.bind(n.media),setVideoSeeking:n.media.setVideoSeeking.bind(n.media),setVideoVolume:n.media.setVideoVolume.bind(n.media),setVideoSpeed:n.media.setVideoSpeed.bind(n.media),handleUserClick:n.media.handleUserClick.bind(n.media),addSectionAnimation(e,t){n.sectionsOffsetsAnimations[e]=t},removeSectionAnimation(e){delete n.sectionsOffsetsAnimations[e]},shakeFromDamage:n.cameraShake.shakeFromDamage.bind(n.cameraShake),onPageInteraction:n.media.onPageInteraction.bind(n.media),downloadMesherLog:n.downloadMesherLog.bind(n),explodeFirework:n.fireworksLegacy.explode.bind(n.fireworksLegacy),explodeFireworkFacingCamera:n.fireworksLegacy.explodeFacingCamera.bind(n.fireworksLegacy),addWaypoint:n.waypoints.addWaypoint.bind(n.waypoints),removeWaypoint:n.waypoints.removeWaypoint.bind(n.waypoints),startCinimaticScript:n.cinimaticScript.startScript.bind(n.cinimaticScript),stopCinimaticScript:n.cinimaticScript.stopScript.bind(n.cinimaticScript),launchFirework:n.fireworks.launchFirework.bind(n.fireworks),setSkyboxImage:n.skyboxRenderer.setSkyboxImage.bind(n.skyboxRenderer),setRain:e=>n.toggleModule("rain",e),spawnBlockBreakParticles(e,t,r,i,s,o){n.getModule("blockBreakParticles")?.spawnBlockBreakParticles(e,t,r,i,s,o)},spawnBlockCrackParticle(e,t,r,i,s,o,a){n.getModule("blockBreakParticles")?.spawnCrackParticle(e,t,r,i,s,o,a)},async loadGeometryExport(e){let{applyWorldGeometryExport:t}=await Promise.resolve().then(()=>(Ji(),ha));return t(n,e)},feedChunkPacket(e){let{kind:t,...r}=e,i={type:t,...r};for(let s of n.workers)s.postMessage(i)},getChunksDebugState(){let e={};for(let t of Object.keys(n.sectionObjects)){let[r,,i]=t.split(",").map(Number);e[`${r},${i}`]=!0}return{loadedSectionsChunks:e,loadedChunks:{...n.loadedChunks},finishedChunks:{...n.finishedChunks}}}}),f9=[],fr=(n,...e)=>{for(let t of Object.values(globalThis.loadedMods??{}))try{t.threeJsBackendModule?.[n]?.(...e)}catch(r){let i=`[mod three.js] Error calling ${n} on ${t.name}: ${r}`;throw new Error(i)}},Va=()=>{let n,e=null,t=null,r=null,i=null,s=(c,u)=>{ae?n=E5(c,f9,globalThis):n=c,e=new h5(n,u?.canvas),globalThis.renderer=e.renderer,globalThis.documentRenderer=e,globalThis.threeJsBackend=l,fr("default",l)},o=async c=>{if(!e)throw new Error("Document renderer not initialized");r&&(r.destroy(),r=null,i=null,globalThis.world=void 0,globalThis.frameTimingCollector=void 0),t&&(t.dispose(),t=null);let u={...n.config.menuBackground,...c};t=new r5(e,{...n},u,!!D.env.SINGLE_FILE_BUILD_MODE),fr("menuBackgroundCreated",t),await t.start(u),fr("menuBackgroundReady",t)},a=async c=>{if(!e)throw new Error("Document renderer not initialized");t&&(t.dispose(),t=null),r&&(r.destroy(),r=null,i=null,globalThis.world=void 0,globalThis.frameTimingCollector=void 0);let h=ae?E5(c,[h0,X0],globalThis):c;e.nonReactiveState=h.nonReactiveState,globalThis.resourcesManager=h.resourcesManager,r=new _t(e.renderer,n,h),await r.worldReadyPromise,i=h.inWorldRenderingConfig.enableDebugOverlay?new h1(h.nonReactiveState):null,globalThis.frameTimingCollector=i;let p=e.render;e.render=function(g){p.call(this,g),i?.markFrameStart(),h.inWorldRenderingConfig.paused||r?.render(g),i?.markFrameEnd(),i?.markFrameDisplay()},e.inWorldRenderingConfig=h.inWorldRenderingConfig,globalThis.world=r,fr("worldReady",r)},v=()=>{t&&(t.dispose(),t=null),e&&e.dispose(),r&&(r.destroy(),r=null)},l={id:"threejs",displayName:`three.js ${Q5.REVISION}`,startMenuBackground:o,startWorld:a,disconnect:v,setRendering(c){e.setPaused(!c),r&&(r.renderingActive=c)},getMenuBackground:()=>t??void 0,getDebugOverlay:()=>({get entitiesString(){return r?.entities.getDebugString()},get left(){return{"Geo Memory":r?.chunkMeshManager.getEstimatedMemoryUsage().total??"-"}}}),updateCamera(c,u,h){i?.markCameraUpdate(!c),r?.setFirstPersonCamera(c,u,h)},get soundSystem(){return r?.soundSystem},get backendMethods(){if(r)return Wa(r)}};return{main:{init:s,backend:l},workerProxy(){return ps({init(c,u){s(c,{canvas:u})},updateSizeExternal(c,u,h){e?.updateSizeExternal(c,u,h)},startMenuBackground:o,startWorld:a,disconnect:v,setRendering:l.setRendering,updateCamera(c,u,h){let p=c?new u9(c.x,c.y,c.z):null;i?.markCameraUpdate(!p),l.updateCamera(p,u,h)},async callBackendMethod(c,...u){if(!r)throw new Error("World renderer not initialized");let p=Wa(r)[c];if(!p)throw new Error(`Backend method ${String(c)} is unavailable`);return p(...u)}})}}};var hr=n=>{let{main:e}=Va();return e.init(n),e.backend};hr.id="threejs";hr.displayName="three.js Blocking";hr.description="Simple, old and stable main thread graphics backend providing balanced performance on top of WebGL2.";E();x();k();R();import*as ja from"three";function h9(n){let e="threeWorker.js",t;if(D.env.SINGLE_FILE_BUILD){let r=document.getElementById("three-worker-code").textContent,i=new Blob([r],{type:"text/javascript"});t=new Worker(window.URL.createObjectURL(i))}else t=new Worker(e);return t.onmessage=({data:r})=>{n(r)},t.on&&t.on("message",r=>{t.onmessage({data:r})}),t}var mr=async n=>{let e=h9(()=>{}),t=gs(e),r=Pr();r.onSizeChanged((a,v)=>{t.updateSizeExternal(a,v,window.devicePixelRatio||1)});let i=A5(n,e);try{t.init(i,r.canvas)}catch(a){throw ot(i),a}let s=new Proxy({},{get(a,v){if(typeof v=="string")return async(...l)=>t.callBackendMethod(v,...l)}});return{id:"threejs",displayName:`three.js ${ja.REVISION}`,async startMenuBackground(a){let v=a?.resourcesManager?.currentResources?.mcData;if(v){let c={...at,items:"itemsArray",entities:"entitiesArray"};await Xr([e],N0,c,v)}let l=A5(a??{},e);try{await t.startMenuBackground(structuredClone(l))}catch(c){throw ot(l),c}},async startWorld(a){let v={...at,items:"itemsArray",entities:"entitiesArray"};await Xr([e],a.version,v,a.resourcesManager.currentResources.mcData),a.inWorldRenderingConfig.__syncToWorker=!0,a.playerStateReactive&&(a.playerStateReactive.__syncToWorker=!0),a.rendererState&&(a.rendererState.__syncFromWorker=!0),a.nonReactiveState&&(a.nonReactiveState.__syncFromWorker=!0),a.nonReactiveState.__syncFromWorkerInterval=200;let l=A5(a,e);try{await t.startWorld(structuredClone(l))}catch(h){throw ot(l),h}t.updateSizeExternal(r.size.width,r.size.height,window.devicePixelRatio||1);let c=lt("fps");setInterval(()=>{let{fps:h,avgRenderTime:p,worstRenderTime:g}=a.nonReactiveState;c.updateText(`FPS: ${h.toFixed(0)} (${p.toFixed(0)}ms/${g.toFixed(0)}ms)`),a.nonReactiveState.fps=0},1e3);let u=lt("downloaded-chunks",100,140,20,{className:vt});setInterval(()=>{let h=(n.config.statsVisible??0)>1;u.setVisibility(h),h&&u.updateText(a.nonReactiveState.world.chunksFullInfo)},200)},disconnect(){r.destroy(),t.disconnect(),e.terminate()},setRendering(a){t.setRendering(a)},updateCamera(a,v,l){t.updateCamera(a?{x:a.x,y:a.y,z:a.z}:null,v,l)},soundSystem:void 0,backendMethods:s}};mr.id="threejs-off-thread";mr.displayName="three.js Multi-thread";mr.description=["Edge-cutting technology that uses a dedicated thread for graphics.","Slightly higher power and RAM usage.","More stable FPS (mid-range devices), but possible inputlag if TPS is low.","On low-end devices it might result in device throttling and stuttering."].join(" ");export{ns as AppViewer,Xt as ClassicMenuBackground,h5 as DocumentRenderer,Ar as HIGH_TEXTURE_COUNT,r1 as LONG_RENDER_TIME_MS,wr as LOW_FPS_THRESHOLD,Bt as LoadedResourcesTransferrable,vt as MC_RENDERER_DEBUG_OVERLAY_CLASS,N0 as MENU_BACKGROUND_MC_VERSION,b5 as MENU_BACKGROUND_MOTION_DEFAULTS,b0 as MENU_BACKGROUND_OPTION_DEFAULTS,fn as MINECRAFT_BLOCK_GROUPS,it as MINECRAFT_BLOCK_GROUP_IDS,g5 as MINECRAFT_BLOCK_GROUP_LABELS,r5 as MenuBackgroundRenderer,l5 as PerformanceMonitor,ss as RENDERER_DEFAULT_OPTIONS,os as RENDERER_OPTIONS_META,as as RENDERER_RENDER_GUI_SECTIONS,h0 as ResourcesManager,At as V2MenuBackground,rt as V2_CAMERA_IDS,p5 as V2_CAMERA_LABELS,tt as V2_SCENE_IDS,m5 as V2_SCENE_LABELS,e5 as WorldBlocksMenuBackground,$0 as WorldView,X0 as WorldViewWorker,Pr as addCanvasForWorker,H6 as applyMenuBackgroundLiveOptions,_f as applyRendererEnableLighting,L6 as applyRendererOptions,bf as applyRendererWorldViewOptions,Mt as chunkPos,mr as createGraphicsBackendOffThread,hr as createGraphicsBackendSingleThread,El as createWorldRendererConfig,L2 as defaultGraphicsBackendConfig,_r as defaultPerformanceInstabilityFactors,c5 as defaultWorldRendererConfig,W2 as delayedIterator,Er as formatPerformanceFactorsDebug,J0 as getDefaultRendererState,ds as getInitialPlayerState,N6 as getInitialPlayerStateRenderer,G6 as getPlayerStateUtils,ae as isWebWorker,gf as menuBackgroundOptionsFromStorage,E0 as menuBackgroundSpeedToMultiplier,x6 as migrateRendererOptions,Or as rendererShaderCubeDebugModeToValue,d6 as sectionPos,yf as subscribeRendererOptions};
|
|
21509
|
+
}`})}},vn=class{constructor(e){this.worldRenderer=e;d(this,"points");d(this,"clock",new Te.Clock);d(this,"enabled",!1);d(this,"currentTime");d(this,"enablementCheck",()=>this.currentTime?this.currentTime>13500&&this.currentTime<23e3:!1);d(this,"render",e=>{this.points&&(this.points.position.set(0,0,0),this.points.material.uniforms.time.value=this.clock.getElapsedTime()*.2)})}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}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,r=7e3,i=7,s=10,o=new Te.BufferGeometry,a=y=>new Te.Vector3().setFromSpherical(new Te.Spherical(y,Math.acos(1-Math.random()*2),Math.random()*2*Math.PI)),v=[],l=[],c=Array.from({length:r},()=>(.5+.5*Math.random())*i),u=new Te.Color,h=e+t,p=t/r;for(let y=0;y<r;y++)h-=p*Math.random(),v.push(...a(h).toArray()),u.setHSL(y/r,s,.9),l.push(u.r,u.g,u.b);o.setAttribute("position",new Te.Float32BufferAttribute(v,3)),o.setAttribute("color",new Te.Float32BufferAttribute(l,3)),o.setAttribute("size",new Te.Float32BufferAttribute(c,1));let g=new an;g.blending=Te.AdditiveBlending,g.depthTest=!0,g.depthWrite=!1,g.transparent=!0,this.points=new Te.Points(o,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)}},Ha={id:"starfield",controller:vn,enabledDefault:!0,cannotBeDisabled:!0};var Oa={starfield:Ha,futuristicReveal:Ia,rain:Ba,cameraBobbing:Ta,blockBreakParticles:ka};var yt=class yt extends g1{constructor(t,r,i){if(!i.resourcesManager)throw new Error("resourcesManager is required in displayOptions");super(i.resourcesManager,i,r);this.renderer=t;this.initOptions=r;this.displayOptions=i;d(this,"outputFormat","threeJs");d(this,"chunkMeshManager");d(this,"chunkTextures",new Map);d(this,"signsCache",new Map);d(this,"cameraSectionPos",new G0(0,0,0));d(this,"holdingBlock");d(this,"holdingBlockLeft");d(this,"scene",new Q.Scene);d(this,"ambientLight",new Q.AmbientLight(13421772));d(this,"directionalLight",new Q.DirectionalLight(16777215,.5));d(this,"entities",new z1(this,globalThis.mcData));d(this,"performanceMonitor");d(this,"cameraGroupVr");d(this,"material",new Q.MeshBasicMaterial({vertexColors:!0,transparent:!0,alphaTest:.1}));d(this,"itemsTexture");d(this,"cursorBlock");d(this,"onRender",[]);d(this,"lastRenderTime",0);d(this,"animatedFov",0);d(this,"lastFovAnimTime",0);d(this,"cameraShake");d(this,"cameraContainer");d(this,"media");d(this,"waypoints");d(this,"cinimaticScript");d(this,"camera");d(this,"renderTimeAvg",0);d(this,"pendingSectionUpdates",new Map);d(this,"pendingSectionBufferStartTimes",new Map);d(this,"modules",{});d(this,"sectionsOffsetsAnimations",{});d(this,"fountains",[]);d(this,"fireworksLegacy");d(this,"DEBUG_RAYCAST",!1);d(this,"skyboxRenderer");d(this,"fireworks");d(this,"sceneOrigin",new Z1(this.scene));d(this,"cameraWorldPos",{x:0,y:0,z:0});d(this,"_cameraPositionAccessWarned",!1);d(this,"_tmpCameraPos",new Q.Vector3);d(this,"currentPosTween");d(this,"currentRotTween");d(this,"_tpDirection",new Q.Vector3);d(this,"_tpPitchQuat",new Q.Quaternion);d(this,"_tpYawQuat",new Q.Quaternion);d(this,"_tpFinalQuat",new Q.Quaternion);d(this,"_tpScenePos",new Q.Vector3);d(this,"_tpAxisX",new Q.Vector3(1,0,0));d(this,"_tpAxisY",new Q.Vector3(0,1,0));d(this,"_tpRaycaster",new Q.Raycaster);d(this,"_tpChunkWorldPos",new Q.Vector3);d(this,"debugOverlayAdded",!1);d(this,"debugRaycastHelper");d(this,"debugHitPoint");d(this,"prevFramePerspective",null);this.performanceMonitor=new l5(this.reactiveState.world.instabilityFactors),this.renderer=t;let s=yt.getRendererInfo(t)??"...";i.rendererState.renderer=s,this.chunkMeshManager=new Y5(this,this.scene,this.material,this.worldSizeParams.worldHeight,this.viewDistance),this.onRenderDistanceChanged=o=>{this.chunkMeshManager.updateViewDistance(o)},this.cursorBlock=new L1(this),this.holdingBlock=U5(this),this.holdingBlockLeft=U5(this,!0);for(let o of Object.values(Oa))this.registerModule(o);this.skyboxRenderer=new K1(this.realScene,!1,null),this.skyboxRenderer.init(),this.addDebugOverlay(),this.resetScene(),this.init(),this.soundSystem=new G1(this),this.cameraShake=new N1(this,this.onRender),this.media=new W1(this),this.fireworksLegacy=new Y1(this),this.waypoints=new j1(this),this.cinimaticScript=new Q1(this,(o,a,v)=>this.setCinimaticCamera(o,a,v),o=>this.setCinimaticFov(o),()=>({position:new G0(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 J1(this.realScene,this.sceneOrigin),this.renderUpdateEmitter.on("chunkFinished",o=>{this.finishChunk(o)}),this.worldSwitchActions(),this.initializeModules()}isShaderCubeBlocksEnabled(){return this.worldRendererConfig.shaderCubeBlocks===!0&&!!this.renderer?.capabilities?.isWebGL2}get sectionObjects(){return this.chunkMeshManager.sectionObjects}get realScene(){return this.scene}get waitingChunksToDisplay(){return this.chunkMeshManager.waitingChunksToDisplay}get estimatedMemoryUsage(){return this.chunkMeshManager.getEstimatedMemoryUsage().total}get tilesRendered(){return this.chunkMeshManager.getTotalTiles()}get blocksRendered(){return this.chunkMeshManager.getTotalBlocks()}registerModule(t){if(t.id in this.modules)return;let r=new t.controller(this),i={manifest:t,controller:r,enabled:!1,toggle:()=>this.toggleModule(t.id)};this.modules[t.id]=i,t.enabledDefault&&this.toggleModule(t.id,!0)}enableModule(t){let r=this.modules[t];r&&(r.enabled||(r.enabled=!0,r.controller.enable(),r.controller.render&&this.onRender.push(r.controller.render)))}disableModule(t){let r=this.modules[t];if(r&&!r.manifest.cannotBeDisabled&&r.enabled&&(r.enabled=!1,r.controller.disable(),r.controller.render)){let i=this.onRender.indexOf(r.controller.render);i>-1&&this.onRender.splice(i,1)}}toggleModule(t,r){let i=this.modules[t];if(!i)return!1;let s=r!==void 0?r:!i.enabled;if(s===i.enabled)return i.enabled;if(!s&&i.manifest.cannotBeDisabled)return!0;if(i.enabled=s,s)i.controller.enable(),i.controller.render&&!this.onRender.includes(i.controller.render)&&this.onRender.push(i.controller.render);else if(i.controller.disable(),i.controller.render){let o=this.onRender.indexOf(i.controller.render);o>-1&&this.onRender.splice(o,1)}return s}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,r=this,i=20,s=(v,l,c)=>Math.abs(v)>i||Math.abs(l)>i||Math.abs(c)>i,o=()=>{!r._cameraPositionAccessWarned&&typeof D<"u"},a=new Proxy(t,{set(v,l,c){return(l==="x"||l==="y"||l==="z")&&typeof c=="number"&&Math.abs(c)>i&&o(),v[l]=c,!0},get(v,l,c){let u=v[l];return l==="set"?function(h,p,g){return s(h,p,g)&&o(),v.set(h,p,g)}:l==="setX"||l==="setY"||l==="setZ"?function(h){return Math.abs(h)>i&&o(),v[l](h)}:l==="copy"?function(h){return s(h.x,h.y,h.z)&&o(),v.copy(h)}:typeof u=="function"?u.bind(v):u}});Object.defineProperty(this.camera,"position",{value:a,configurable:!0,enumerable:!0})}worldSwitchActions(){this.onWorldSwitched.push(()=>{this.protocolCustomBlocks.clear(),this.sectionsOffsetsAnimations={},this.waypoints.clear(),this.cinimaticScript.stopScript(),this.fireworks.clear()})}downloadWorldGeometry(){Ki(this,new Q.Vector3(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),this.cameraShake.getBaseRotation(),"world-geometry.json")}updateEntity(t,r=!1){let i={rotation:{head:{x:t.headPitch??t.pitch,y:t.headYaw,z:0}}};r?this.entities.updateEntityPosition(t,!1,i):this.entities.update(t,i)}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 Q.Color(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 Q.Vector2);this.camera=new Q.PerspectiveCamera(75,t.x/t.y,.1,1e3),this._wrapCameraPositionWithWarning(),this.cameraContainer=new Q.Object3D,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)}),this.onReactivePlayerStateUpdated("directionalLight",t=>{t&&(this.directionalLight.intensity=t)}),this.onReactivePlayerStateUpdated("lookingAtBlock",t=>{this.cursorBlock.setHighlightCursorBlock(t?new G0(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 r=new G0(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z);this.updateCamera(r,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.onReactiveConfigUpdated("futuristicReveal",()=>{this.updateModulesFromConfig()});let t=this.displayOptions.inWorldRenderingConfig.handRenderer;this.onReactiveConfigUpdated("handRenderer",r=>{if(r===t)return;t=r;let i=this.holdingBlock.ready,s=this.holdingBlockLeft.ready;this.holdingBlock.dispose(),this.holdingBlockLeft.dispose(),this.holdingBlock=U5(this),this.holdingBlockLeft=U5(this,!0),i&&(this.holdingBlock.ready=!0,this.holdingBlock.updateItem()),s&&(this.holdingBlockLeft.ready=!0,this.holdingBlockLeft.updateItem())}),this.onReactiveConfigUpdated("*",()=>{this.updateModulesFromConfig()}),this.updateModulesFromConfig()}updateModulesFromConfig(){let{moduleStates:t}=this.worldRendererConfig;for(let[r,i]of Object.entries(this.modules)){let s=t[r];if(s==="enabled"){i.enabled||this.toggleModule(r,!0);continue}if(s==="disabled"){i.enabled&&!i.manifest.cannotBeDisabled&&this.toggleModule(r,!1);continue}if(s==="auto"||s===void 0)if(i.controller.autoEnableCheck){let o=i.controller.autoEnableCheck();o&&!i.enabled?this.toggleModule(r,!0):!o&&i.enabled&&!i.manifest.cannotBeDisabled&&this.toggleModule(r,!1)}else{let o=i.manifest.enabledDefault??!1;o&&!i.enabled?this.toggleModule(r,!0):!o&&i.enabled&&!i.manifest.cannotBeDisabled&&this.toggleModule(r,!1)}}}changeHandSwingingState(t,r=!1){let i=r?this.holdingBlockLeft:this.holdingBlock;t?i.startSwing():i.stopSwing()}async updateAssetsData(){let t=this.resourcesManager.currentResources,r=this.material.map,i=this.itemsTexture,s=I0(t.blocksAtlasImage);s.needsUpdate=!0,s.flipY=!1,this.material.map=s,this.chunkMeshManager.syncCubeShaderUniforms();let o=I0(t.itemsAtlasImage);o.needsUpdate=!0,o.flipY=!1,this.itemsTexture=o,r&&r.dispose(),i&&i.dispose(),await super.updateAssetsData(),this.onAllTexturesLoaded(),Object.keys(this.loadedChunks).length>0&&this.rerenderAllChunks()}onAllTexturesLoaded(){this.holdingBlock.ready=!0,this.holdingBlock.updateItem(),this.holdingBlockLeft.ready=!0,this.holdingBlockLeft.updateItem()}changeBackgroundColor(t){this.realScene.background=new Q.Color(t[0],t[1],t[2])}changeCardinalLight(t){this.worldRendererConfig.cardinalLight=t}timeUpdated(t){let r=this.getModule("starfield");r?.updateTimeOfDay&&r.updateTimeOfDay(t),this.skyboxRenderer.updateTime(t)}biomeUpdated(t){t?.temperature!==void 0&&this.skyboxRenderer.updateTemperature(t.temperature)}biomeReset(){this.skyboxRenderer.updateTemperature(Gi)}getItemRenderData(t,r){return Z3(t,r,this.resourcesManager,this.playerStateReactive)}async demoModel(){let t=cursorBlockRel(0,1,0).position,r=await R5();Ps(r,t);let i=new Q.BoxHelper(r,16776960);r.add(i),this.realScene.add(r)}demoItem(){let t=cursorBlockRel(0,1,0).position,{mesh:r}=this.entities.getItemMesh({itemId:541},{});r.position.set(t.x+.5,t.y+.5,t.z+.5);let i=new Q.BoxHelper(r,16776960);r.add(i),this.realScene.add(r)}addDebugOverlay(){if(this.debugOverlayAdded)return;this.debugOverlayAdded=!0;let t=lt("debug-overlay",80,0,void 0,{className:vt});setInterval(()=>{if(t.setVisibility(this.displayAdvancedStats),this.displayAdvancedStats){let r=v=>new Intl.NumberFormat("en-US",{}).format(v),i=v=>new Intl.NumberFormat("en-US",{notation:"compact",maximumFractionDigits:1}).format(v),s="";s+=`TE: ${r(this.renderer.info.memory.textures)} `,s+=`F: ${i(this.tilesRendered)} `,s+=`B: ${i(this.blocksRendered)} `,s+=`MEM: ${this.chunkMeshManager.getEstimatedMemoryUsage().total} `;let o=this.chunkMeshManager.getStats();s+=`POOL: ${o.activeCount}/${o.poolSize} `;let a=Er(this.reactiveState.world.instabilityFactors);a&&(s+=`PF: ${a} `),t.updateText(s),this.backendInfoReport=s}},200)}updatePosDataChunk(t){let r=this.sectionObjects[t];if(!r)return;let[i,s,o]=t.split(",").map(c=>Math.floor(+c/16)),v=500-(Math.abs(i-this.cameraSectionPos.x)+Math.abs(s-this.cameraSectionPos.y)+Math.abs(o-this.cameraSectionPos.z)),l=r.mesh??r.shaderMesh??r.children.find(c=>c.name==="mesh"||c.name==="shaderMesh");l&&(l.renderOrder=v)}updateViewerPosition(t){this.viewerChunkPosition=t}cameraSectionPositionUpdate(){for(let t in this.sectionObjects)this.sectionObjects[t]&&this.updatePosDataChunk(t)}getDir(t,r){return t===r?0:t<r?1:-1}finishChunk(t){this.chunkMeshManager.finishChunkDisplay(t)}applyPendingSectionUpdates(){if(this.pendingSectionUpdates.size===0)return;let t=performance.now(),r=this.getSectionHeight(),i=[];for(let s of this.pendingSectionUpdates.keys()){let o=this.pendingSectionBufferStartTimes.get(s)??t;if(t-o<yt.MAX_SECTION_UPDATE_BUFFER_MS){let[v,l,c]=s.split(",").map(Number),u=[`${v-16},${l},${c}`,`${v+16},${l},${c}`,`${v},${l-r},${c}`,`${v},${l+r},${c}`,`${v},${l},${c-16}`,`${v},${l},${c+16}`],h=!1;for(let p of u)if(this.sectionsWaiting.has(p)&&!this.pendingSectionUpdates.has(p)&&this.sectionObjects[p]){h=!0;break}if(h)continue}i.push(s)}if(i.length!==0)for(let s of i){let o=this.pendingSectionUpdates.get(s);this.pendingSectionUpdates.delete(s),this.pendingSectionBufferStartTimes.delete(s);let a=o.key.split(","),v=`${a[0]},${a[2]}`;if(!this.loadedChunks[v]||!this.active){this.chunkMeshManager.releaseSection(o.key);continue}if(!this.chunkMeshManager.sectionHasRenderableContent(o.geometry)){this.chunkMeshManager.releaseSection(o.key);continue}this.chunkMeshManager.updateSection(o.key,o.geometry),this.updatePosDataChunk(o.key)}}clearPendingSectionUpdatesForChunk(t,r){for(let i of[...this.pendingSectionUpdates.keys()])i.startsWith(`${t},`)&&i.endsWith(`,${r}`)&&(this.pendingSectionUpdates.delete(i),this.pendingSectionBufferStartTimes.delete(i))}handleWorkerMessage(t){if(t.type==="geometry"){let r=t.key.split(","),i=`${r[0]},${r[2]}`;if(!this.loadedChunks[i]||!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}this.chunkMeshManager.updateSection(t.key,t.geometry),this.updatePosDataChunk(t.key)}}getSignTexture(t,r,i,s=!1){let o=Ht(t),a=this.chunkTextures.get(`${o[0]},${o[1]}`);a||(a={},this.chunkTextures.set(`${o[0]},${o[1]}`,a));let v=`${t.x},${t.y},${t.z}`;if(a[v])return a[v];let l=i9(this.version),c=m1(r,i,l);if(!c)return;let u=new Q.Texture(c);return u.magFilter=Q.NearestFilter,u.minFilter=Q.NearestFilter,u.needsUpdate=!0,a[v]=u,u}getCameraPosition(t){return(t??this._tmpCameraPos).set(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z)}getSectionCameraPosition(){let t=this.getCameraPosition();return new G0(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,r,i){let s=this.playerStateReactive.eyeHeight;this.updateCamera(t?.offset(0,s,0)??null,r,i),this.updateCameraSectionPos()}getThirdPersonCamera(t,r,i){t??(t=new Q.Vector3(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z));let s=this.playerStateReactive.perspective==="third_person_back",o=4,a=this._tpDirection.set(0,0,-1),v=this._tpPitchQuat.setFromAxisAngle(this._tpAxisX,i),l=this._tpYawQuat.setFromAxisAngle(this._tpAxisY,r),c=this._tpFinalQuat.multiplyQuaternions(l,v);a.applyQuaternion(c),s&&a.multiplyScalar(-1),this.DEBUG_RAYCAST&&this.debugRaycast(t,a,o);let u=this._tpScenePos.set(this.sceneOrigin.toSceneX(t.x),this.sceneOrigin.toSceneY(t.y),this.sceneOrigin.toSceneZ(t.z)),h=this._tpRaycaster;h.set(u,a),h.far=o;let p=80,g=p*p,y=t.x,A=t.y,b=t.z,w=[];for(let B of Object.values(this.sectionObjects)){if(B.name!=="chunk"||!B.visible||B.worldX===void 0)continue;let H=B.worldX-y,G=B.worldY-A,O=B.worldZ-b;if(H*H+G*G+O*O>g)continue;let j=B.children.find(J=>J.name==="mesh"||J.name==="shaderMesh");j&&w.push(j)}let S=h.intersectObjects(w,!1),C=o;S.length>0&&(C=Math.max(.5,S[0].distance-.2));let M=this.chunkMeshManager.raycastShaderSectionAABBs(t,a,C,p);return M!==void 0&&(C=Math.max(.5,M-.2)),new G0(t.x+a.x*C,t.y+a.y*C,t.z+a.z*C)}debugRaycast(t,r,i){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 Q.Vector3(this.sceneOrigin.toSceneX(t.x),this.sceneOrigin.toSceneY(t.y),this.sceneOrigin.toSceneZ(t.z));this.debugRaycastHelper=new Q.ArrowHelper(r.clone().normalize(),s,i,16711680,i*.1,i*.05),this.realScene.add(this.debugRaycastHelper);let o=new Q.SphereGeometry(.2,8,8),a=new Q.MeshBasicMaterial({color:65280});this.debugHitPoint=new Q.Mesh(o,a),this.debugHitPoint.position.copy(s).add(r.clone().multiplyScalar(i)),this.realScene.add(this.debugHitPoint)}setCinimaticCamera(t,r,i){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(i,r),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,r=this.playerStateReactive.fovMultiplier,i=t*(Number.isFinite(r)?r:1),s=performance.now();if(this.animatedFov===0&&(this.animatedFov=i),Math.abs(this.animatedFov-i)>=.01){let o=s-this.lastFovAnimTime,a=Math.min(o/yt.FOV_TRANSITION_MS,1),v=l=>1-(1-l)**3;this.animatedFov+=(i-this.animatedFov)*v(a),Math.abs(this.animatedFov-i)<.01&&(this.animatedFov=i)}else this.animatedFov=i;this.lastFovAnimTime=s,this.camera.fov!==this.animatedFov&&(this.camera.fov=this.animatedFov,this.camera.updateProjectionMatrix())}updateCamera(t,r,i){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 Oe(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(),o=0,a=Math.PI/2;s.yaw<a&&r>Math.PI+a?o=-Math.PI*2:r<a&&s.yaw>Math.PI+a&&(o=Math.PI*2),this.currentRotTween?.stop(),this.currentRotTween=new Oe(s).to({pitch:i,yaw:r+o},100).onUpdate(v=>this.cameraShake.setBaseRotation(v.pitch,v.yaw-o)).start()}else{this.currentRotTween?.stop(),this.cameraShake.setBaseRotation(i,r);let{perspective:s}=this.playerStateReactive;if(s==="third_person_back"||s==="third_person_front"){let o=new Q.Vector3(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),a=this.getThirdPersonCamera(o,r,i),v=o.distanceTo(new Q.Vector3(a.x,a.y,a.z)),l=s==="third_person_back"?v:-v;this.camera.position.set(0,0,l),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:r,chunksRenderDistanceOverride:i,chunksRenderAboveEnabled:s,chunksRenderBelowEnabled:o,chunksRenderDistanceEnabled:a}=this.reactiveDebugParams,v=this.getSectionHeight(),l=this.cameraSectionPos.y*v;if(this.displayOptions.inWorldRenderingConfig.enableDebugOverlay&&t!==void 0||r!==void 0||i!==void 0)for(let[c,u]of Object.entries(this.sectionObjects)){if(u._waitingForChunkDisplay)continue;let[h,p,g]=c.split(",").map(Number),y=s&&t!==void 0?p<=l+t:o&&r!==void 0?p>=l-r:a&&i!==void 0?Math.abs(p-l)<=i:!0;u.visible=y}else this.chunkMeshManager.updateSectionsVisibility()}render(t=!1){if(this.currentRenderedFrames++,this.reactiveDebugParams.stopRendering)return;this.debugChunksVisibilityOverride();let r=performance.now();this.lastRendered=performance.now();let i=this.lastRenderTime>0?Math.min(Math.max((r-this.lastRenderTime)/1e3,0),.1):1/60;this.lastRenderTime=r,this.cursorBlock.render(),this.updateSectionOffsets();let s=this.getCameraPosition();if(this.skyboxRenderer.update(s,this.viewDistance),this.updateSmoothFov(),t){let u=this.renderer.getSize(new Q.Vector2);this.camera.aspect=u.width/u.height,this.camera.updateProjectionMatrix()}let o=0;if(!this.reactiveDebugParams.disableEntities){let u=performance.now();this.entities.render(),o=performance.now()-u}let a=this.cameraGroupVr instanceof Q.Group?this.cameraGroupVr.children.find(u=>u instanceof Q.PerspectiveCamera):this.camera;this.applyPendingSectionUpdates();let v=this.chunkMeshManager.globalBlockBuffer;v&&(v.setCameraOrigin(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),v.compactStep(),v.uploadDirtyRange()),this.renderer.render(this.scene,a),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 u of this.fountains)this.sectionObjects[u.sectionId]&&!this.sectionObjects[u.sectionId].foutain&&(u.createParticles(this.sectionObjects[u.sectionId]),this.sectionObjects[u.sectionId].foutain=!0),u.render();this.waypoints.render(),this.fireworks.update();for(let u of this.onRender)u(i);let c=performance.now()-r;this.worldRendererConfig.autoLowerRenderDistance&&this.chunkMeshManager.recordRenderTime(c),this.renderTimeAvgCount++,this.renderTimeAvg=(this.renderTimeAvg*(this.renderTimeAvgCount-1)+c)/this.renderTimeAvgCount,this.renderTimeMax=Math.max(this.renderTimeMax,c),this.performanceMonitor.onFrame({totalMs:c,entitiesMs:o,loadedTextureCount:this.renderer.info.memory.textures,fps:this.lastFps})}renderHead(t,r,i,s){let o;if(s.SkullOwner?o=s.SkullOwner.Properties?.textures?.[0]?.Value:o=s.profile?.properties?.find(a=>a.name==="textures")?.value,!!o)try{let v=JSON.parse(z.from(o,"base64").toString()).textures?.SKIN?.url,{skinTexturesProxy:l}=this.worldRendererConfig;l&&(v=v?.replace("http://textures.minecraft.net/",l).replace("https://textures.minecraft.net/",l));let c=D0(this,v,F0.head),u=new Q.Group;return i&&c.position.set(0,.3125,.3125),c.position.y-=23/16,u.add(c),this.sceneOrigin.track(u),u.position.set(t.x+.5,t.y+.045,t.z+.5),u.rotation.set(0,-Q.MathUtils.degToRad(r*(i?90:45/2)),0),u.scale.set(.8,.8,.8),u}catch{}}renderSign(t,r,i,s,o){let a=this.getSignTexture(t,o,s);if(!a)return;let v=new Q.Mesh(new Q.PlaneGeometry(1,1),new Q.MeshBasicMaterial({map:a,transparent:!0}));v.renderOrder=999;let l=7/16,c=s?1.3:1;v.scale.set(1*c,l*c,1*c);let u=(s?2:1.5)/16,h=.25/16;i&&!s?v.position.set(0,0,-.5+u+h+1e-4):v.position.set(0,0,u/2+1e-4);let p=new Q.Group;p.rotation.set(0,-Q.MathUtils.degToRad(r*(i?90:45/2)),0),p.add(v);let g=(s?10:8)/16,y=(s?0:i?4.333:9.333)/16,A=g/2+y;return this.sceneOrigin.track(p),p.position.set(t.x+.5,t.y+A,t.z+.5),p}lightUpdate(t,r){for(let i=this.worldSizeParams.minY;i<this.worldSizeParams.worldHeight;i+=16)this.setSectionDirty(new G0(t,i,r))}rerenderAllChunks(){for(let t of Object.keys(this.sectionObjects)){let[r,i,s]=t.split(",").map(Number);this.setSectionDirty(new G0(r,i,s))}}updateShowChunksBorder(t){this.chunkMeshManager.updateAllBoxHelpers(t)}resetWorld(){super.resetWorld(),this.pendingSectionUpdates.clear(),this.pendingSectionBufferStartTimes.clear(),this.chunkMeshManager.dispose(),this.chunkMeshManager=new Y5(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,r=!1){let[i,s,o]=Qr(t);return Object.fromEntries(Object.entries(this.sectionObjects).map(([a,v])=>{let[l,c,u]=a.split(",").map(Number),[h,p,g]=Qr({x:l,y:c,z:u});return[r?`${h-i},${p-s},${g-o}`:`${h-i},${g-o}`,v]}))}cleanChunkTextures(t,r){let i=this.chunkTextures.get(`${Math.floor(t/16)},${Math.floor(r/16)}`)??{};for(let s of Object.keys(i))i[s].dispose(),delete i[s];this.chunkMeshManager.cleanSignChunkTextures(t,r)}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 r of t)r.matrixWorldNeedsUpdate=!1,this.disableUpdates(r.children??[])}removeColumn(t,r){super.removeColumn(t,r),this.cleanChunkTextures(t,r),this.clearPendingSectionUpdatesForChunk(t,r);let i=this.getSectionHeight(),s=this.worldMinYRender;for(let o=s;o<this.worldSizeParams.worldHeight;o+=i){let a=`${t},${o},${r}`;this.chunkMeshManager.sectionObjects[a]&&this.chunkMeshManager.releaseSection(a)}this.chunkMeshManager.onChunkRemovedFromGate(`${t},${r}`)}updateViewerPosition(t){super.updateViewerPosition(t),this.chunkMeshManager.pendingNearReveal.size>0&&this.chunkMeshManager.tryRevealPending()}onViewerChunkPositionChanged(){this.chunkMeshManager.tryRevealPending()}setSectionDirty(...t){let[r]=t;this.cleanChunkTextures(r.x,r.z),super.setSectionDirty(...t)}static getRendererInfo(t){try{let r=t.getContext();return`${r.getParameter(r.getExtension("WEBGL_debug_renderer_info").UNMASKED_RENDERER_WEBGL)}`}catch{}}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 i=this.getSectionHeight(),s,o,a,v=this.sceneOrigin.getWorldPosition(t);v?(s=v.x,o=v.y,a=v.z):(s=this.sceneOrigin.toWorldX(t.position.x),o=this.sceneOrigin.toWorldY(t.position.y),a=this.sceneOrigin.toWorldZ(t.position.z));let l=Math.floor(s/16)*16,c=Math.floor(a/16)*16,u=Math.floor(o/i)*i,h=`${l},${c}`,p=`${l},${u},${c}`;return!!this.finishedChunks[h]||!!this.sectionObjects[p]}handleUserClick(t){this.media.handleUserClick(t)}updateSectionOffsets(){let t=performance.now();for(let[r,i]of Object.entries(this.sectionsOffsetsAnimations)){let s=(t-i.time)/1e3;i.time=t,i.currentOffsetX+=i.speedX*s,i.currentOffsetY+=i.speedY*s,i.currentOffsetZ+=i.speedZ*s,i.limitX!==void 0&&(i.speedX>0?i.currentOffsetX=Math.min(i.currentOffsetX,i.limitX):i.currentOffsetX=Math.max(i.currentOffsetX,i.limitX)),i.limitY!==void 0&&(i.speedY>0?i.currentOffsetY=Math.min(i.currentOffsetY,i.limitY):i.currentOffsetY=Math.max(i.currentOffsetY,i.limitY)),i.limitZ!==void 0&&(i.speedZ>0?i.currentOffsetZ=Math.min(i.currentOffsetZ,i.limitZ):i.currentOffsetZ=Math.max(i.currentOffsetZ,i.limitZ));let o=this.sectionObjects[r];o&&(o.position.set(i.currentOffsetX,i.currentOffsetY,i.currentOffsetZ),o.updateMatrix())}}reloadWorld(){this.entities.reloadEntities()}};d(yt,"FOV_TRANSITION_MS",200),d(yt,"MAX_SECTION_UPDATE_BUFFER_MS",500);var _t=yt;E();x();k();R();E();x();k();R();var N0="1.21.4";E();x();k();R();function wt(n,e){n.aspect=e.width/e.height,n.updateProjectionMatrix()}E();x();k();R();function ln(n,e=!1){return n?.mode?n.mode:e?"worldBlocks":b0.mode}E();x();k();R();import*as ve from"three";E();x();k();R();function cn(...n){let e=n.filter(r=>r.length>0).join("/"),t=typeof globalThis.location<"u"&&globalThis.location.href?globalThis.location.href:typeof import.meta<"u"&&import.meta.url?import.meta.url:`/${e}`;try{return new URL(e,t).href}catch{return`/${e}`}}var dn=new Date,Da=dn.getMonth()===11&&dn.getDate()>=24&&dn.getDate()<=26,n9=["panorama_3.webp","panorama_1.webp","panorama_4.webp","panorama_5.webp","panorama_0.webp","panorama_2.webp"],s9=200,Xt=class{constructor(e){this.documentRenderer=e;d(this,"scene");d(this,"camera");d(this,"startTimes",new Map);d(this,"time",0);d(this,"panoramaGroup",null);this.scene=new ve.Scene,this.scene.background=new ve.Color(3294568);let t=new ve.AmbientLight(13421772);this.scene.add(t);let r=new ve.DirectionalLight(16777215,.5);r.position.set(1,1,.5).normalize(),r.castShadow=!0,this.scene.add(r),this.camera=new ve.PerspectiveCamera(85,e.canvas.width/e.canvas.height,.05,1e3),this.camera.position.set(0,0,0),this.camera.rotation.set(0,0,0)}async init(){this.buildCubemap()}update(e,t){t&&wt(this.camera,this.documentRenderer.canvas)}dispose(){this.scene.clear(),this.panoramaGroup=null,this.startTimes.clear()}buildCubemap(){let e=new ve.BoxGeometry(1e3,1e3,1e3),t=[];for(let s of n9)(async()=>{let a=cn("background",Da?"christmas":"",s),v=await st(a),l=I0(v);l.matrixAutoUpdate=!1,l.matrix.set(-1,0,1,0,1,0,0,0,1),l.wrapS=ve.ClampToEdgeWrapping,l.wrapT=ve.ClampToEdgeWrapping,l.minFilter=ve.LinearFilter,l.magFilter=ve.LinearFilter;let c=new ve.MeshBasicMaterial({map:l,transparent:!0,side:ve.DoubleSide,depthWrite:!1,opacity:0});this.startTimes.set(c,Date.now()),t.push(c)})().catch(a=>{});let r=new ve.Mesh(e,t);r.onBeforeRender=()=>{this.time+=.01,r.rotation.y=Math.PI+this.time*.01,r.rotation.z=Math.sin(-this.time*.001)*.001;for(let s of t){let o=this.startTimes.get(s);if(o){let a=Date.now()-o;s.opacity=Math.min(1,a/s9)}}};let i=new ve.Object3D;if(i.add(r),!Da)for(let s=0;s<20;s++){let o=new M0("1.16.4","squid").mesh;o.position.set(Math.random()*30-15,Math.random()*20-10,Math.random()*10-17),o.rotation.set(0,Math.PI+Math.random(),-Math.PI/4,"ZYX");let a=Math.random()*.01;o.children[0].onBeforeRender=()=>{o.rotation.y+=a,o.rotation.z=Math.cos(r.rotation.y*3)*Math.PI/4-Math.PI/2},i.add(o)}this.scene.add(i),this.panoramaGroup=i}async debugImageInFrontOfCamera(){let e=await st(cn("background","panorama_0.webp")),t=I0(e),r=new ve.Mesh(new ve.PlaneGeometry(1e3,1e3),new ve.MeshBasicMaterial({map:t}));r.position.set(0,0,-500),this.scene.add(r)}};E();x();k();R();import*as W from"three";var Fa=.1,fn={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"]},za={galaxy:{bg:132114,fog:132114,fogD:.011,blocks:[61695,54527,47359,59647,2280703,43263],emit:[13158,8789,6724],nebula:[4403,1114146,4386],galFn:n=>new W.Color(n*.05,n*.2,n),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:n=>new W.Color(n,n*.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:n=>new W.Color(n*.4,0,n),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:n=>new W.Color(n*.15,n*.85,n*.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:n=>{let e=new W.Color;return n<.4?e.lerpColors(new W.Color(16054527),new W.Color(14215423),n/.4):n<.75?e.lerpColors(new W.Color(14215423),new W.Color(11061488),(n-.4)/.35):e.lerpColors(new W.Color(11061488),new W.Color(9482464),(n-.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]}},o9={cruise:{pos:(n,e,t)=>({x:Math.sin(n*.28)*18+Math.cos(n*.11)*7+e*10,y:Math.sin(n*.19)*6+Math.cos(n*.31)*3+t*6,z:0}),look:(n,e,t)=>({x:Math.sin((n+.18)*.28)*18+e*8,y:Math.sin((n+.18)*.19)*6+t*4,z:-25}),roll:(n,e=0)=>e*.05+Math.sin(n*.22)*.015,spd:.18},barrel:{pos:(n,e,t)=>{let i=n*2.4;return{x:Math.cos(i)*10+e*4,y:Math.sin(i)*10+t*4,z:Math.sin(n*.4)*8}},look:n=>({x:Math.sin(n*.5)*5,y:Math.cos(n*.5)*5,z:-30}),roll:n=>n*2.4+Math.PI*.5,spd:.24},dive:{pos:(n,e,t)=>({x:Math.sin(n*.6)*30+e*8,y:Math.cos(n*.4)*18+t*6,z:Math.sin(n*.3)*12}),look:(n,e,t)=>({x:Math.sin(n*.6+.2)*30+e*6,y:Math.cos(n*.4+.2)*18-8+t*4,z:-35}),roll:(n,e=0)=>e*.08+Math.sin(n*.6)*.12,spd:.3},orbit:{pos:(n,e,t)=>({x:Math.cos(n*.5)*20+e*5,y:Math.sin(n*.25)*10+t*5,z:Math.sin(n*.5)*20}),look:()=>({x:0,y:0,z:-60}),roll:n=>Math.sin(n*.5)*.08,spd:.15},snake:{pos:(n,e,t)=>({x:Math.sin(n*1.1)*22+Math.sin(n*.37)*8+e*10,y:Math.sin(n*.7)*10+e*4+t*8,z:0}),look:(n,e,t)=>{let r=n+.12;return{x:Math.sin(r*1.1)*22+Math.sin(r*.37)*8+e*8,y:Math.sin(r*.7)*10+t*6,z:-22}},roll:(n,e=0)=>e*.1+Math.sin(n*1.1)*.06,spd:.22}},a9={cruise:1,barrel:1.6,dive:2.2,orbit:.7,snake:1.4},v9=250,dr=1e4,ur=3e3,$t=n=>n[Math.floor(Math.random()*n.length)],un=n=>"#"+n.toString(16).padStart(6,"0"),La=n=>{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 r=e.width,i=e.height,s=n.radial?t.createRadialGradient(r/2,i*.32,0,r/2,i*.32,i*.85):t.createLinearGradient(0,0,0,i);s.addColorStop(0,un(n.top)),n.mid!=null&&s.addColorStop(.45,un(n.mid)),s.addColorStop(1,un(n.bottom)),t.fillStyle=s,t.fillRect(0,0,r,i);let o=new W.CanvasTexture(e);return o.needsUpdate=!0,o},At=class{constructor(e,t={},r){this.documentRenderer=e;this.abortSignal=r;d(this,"scene");d(this,"camera");d(this,"ambient");d(this,"dir");d(this,"pt1");d(this,"pt2");d(this,"blocks",[]);d(this,"bGroup",new W.Group);d(this,"galaxy");d(this,"nebula");d(this,"stars");d(this,"galGeo");d(this,"nebGeo");d(this,"bGeo",new W.BoxGeometry(1,1,1));d(this,"eGeo",new W.EdgesGeometry(this.bGeo));d(this,"curScene");d(this,"curCam");d(this,"blockGroup");d(this,"cameraSpeed");d(this,"blockSpeed");d(this,"camT",0);d(this,"mx",0);d(this,"my",0);d(this,"tmx",0);d(this,"tmy",0);d(this,"transitioning",!1);d(this,"useMinecraftTextures",!1);d(this,"resourcesManager");d(this,"atlasTexture",null);d(this,"blockMaterialPool",new Map);d(this,"gradientSky",null);d(this,"gradientSkyTexture",null);d(this,"disposed",!1);d(this,"animTime",0);d(this,"texturesApplied",!1);d(this,"textureLoadInProgress",!1);d(this,"onAssetsTexturesUpdated");let i=b0;this.curScene=t.initialScene??i.v2Scene,this.curCam=t.initialCamera??i.v2Camera,this.blockGroup=t.initialBlockGroup??i.v2BlockGroup,this.cameraSpeed=t.initialCameraSpeed??b5.camera,this.blockSpeed=t.initialBlockSpeed??b5.block,this.useMinecraftTextures=t.useMinecraftTextures??i.minecraftTextures,this.resourcesManager=t.resourcesManager;let s=za[this.curScene];this.scene=new W.Scene,this.scene.fog=new W.FogExp2(s.fog,s.fogD),this.applyScenePalette(s),this.camera=new W.PerspectiveCamera(80,this.documentRenderer.canvas.width/this.documentRenderer.canvas.height,.1,700),this.ambient=new W.AmbientLight(s.ambient,2.5),this.scene.add(this.ambient),this.dir=new W.DirectionalLight(s.dir,4),this.dir.position.set(1,1,0),this.scene.add(this.dir),this.pt1=new W.PointLight(s.pt1,5,100),this.scene.add(this.pt1),this.pt2=new W.PointLight(s.pt2,4,80),this.pt2.position.set(30,20,-30),this.scene.add(this.pt2);for(let h=0;h<v9;h++)this.spawnBlock(s,!0);if(!this.useMinecraftTextures){let h=s.edgeLineColor??62975;for(let p=0;p<40;p++){let g=new W.LineBasicMaterial({color:h,transparent:!0,opacity:.25});$t(this.blocks).mesh.add(new W.LineSegments(this.eGeo,g))}}this.scene.add(this.bGroup);let o=new W.BufferGeometry,a=new Float32Array(5e3*3);for(let h=0;h<5e3*3;h++)a[h]=(Math.random()-.5)*500;o.setAttribute("position",new W.BufferAttribute(a,3)),this.stars=new W.Points(o,new W.PointsMaterial({color:s.starColor??16777215,size:.3,transparent:!0,opacity:s.starOpacity??.7,sizeAttenuation:!0})),this.scene.add(this.stars),this.galGeo=new W.BufferGeometry;let v=new Float32Array(dr*3),l=new Float32Array(dr*3);for(let h=0;h<dr;h++){let p=h%3,g=Math.random(),y=p/3*Math.PI*2+g*Math.PI*5,A=g*90+Math.random()*10,b=(1-g)*18;v[h*3]=Math.cos(y)*A+(Math.random()-.5)*b,v[h*3+1]=(Math.random()-.5)*7,v[h*3+2]=Math.sin(y)*A+(Math.random()-.5)*b-180;let w=.2+g*.8,S=s.galFn(w);l[h*3]=S.r,l[h*3+1]=S.g,l[h*3+2]=S.b}this.galGeo.setAttribute("position",new W.BufferAttribute(v,3)),this.galGeo.setAttribute("color",new W.BufferAttribute(l,3)),this.galaxy=new W.Points(this.galGeo,new W.PointsMaterial({size:.9,vertexColors:!0,transparent:!0,opacity:s.galaxyOpacity??.55,sizeAttenuation:!0})),this.scene.add(this.galaxy),this.nebGeo=new W.BufferGeometry;let c=new Float32Array(ur*3),u=new Float32Array(ur*3);for(let h=0;h<ur;h++){let p=25+Math.random()*110,g=Math.random()*Math.PI*2,y=(Math.random()-.5)*Math.PI*.5;c[h*3]=p*Math.cos(g)*Math.cos(y),c[h*3+1]=p*Math.sin(y)*.6,c[h*3+2]=p*Math.sin(g)*Math.cos(y)-80;let A=new W.Color($t(s.nebula));u[h*3]=A.r,u[h*3+1]=A.g,u[h*3+2]=A.b}this.nebGeo.setAttribute("position",new W.BufferAttribute(c,3)),this.nebGeo.setAttribute("color",new W.BufferAttribute(u,3)),this.nebula=new W.Points(this.nebGeo,new W.PointsMaterial({size:3,vertexColors:!0,transparent:!0,opacity:s.nebulaOpacity??.3,sizeAttenuation:!0})),this.scene.add(this.nebula),this.addBackgroundTextPlane(),this.setupMouseTracking()}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:N0,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 h0;if(!await this.ensureAtlasReady(e)){this.resourcesManager&&this.attachAssetsListener();return}if(this.disposed)return;this.applyMinecraftTexturesFromAtlas(e),this.texturesApplied=!0,this.detachAssetsListener()}catch{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=La(e.gradientBg);s&&(this.gradientSkyTexture.dispose(),this.gradientSkyTexture=s,this.gradientSky.material.map=s,this.gradientSky.material.needsUpdate=!0)}}else{let s=La(e.gradientBg);s?(this.gradientSkyTexture=s,this.gradientSky=new W.Mesh(new W.PlaneGeometry(900,700),new W.MeshBasicMaterial({map:s,depthWrite:!1,side:W.DoubleSide})),this.gradientSky.position.set(0,0,-280),this.gradientSky.renderOrder=-1e3,this.scene.add(this.gradientSky)):this.scene.background=new W.Color(e.bg)}else this.scene.background=new W.Color(e.bg),this.gradientSky&&(this.gradientSky.visible=!1);this.scene.fog instanceof W.FogExp2&&(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 r=this.galaxy?.material;r&&(r.opacity=e.galaxyOpacity??.55);let i=this.nebula?.material;i&&(i.opacity=e.nebulaOpacity??.3)}setupMouseTracking(){let e=r=>{let i=typeof window<"u"?window.innerWidth:this.documentRenderer.canvas.width,s=typeof window<"u"?window.innerHeight:this.documentRenderer.canvas.height;this.tmx=(r.clientX/i-.5)*2,this.tmy=-(r.clientY/s-.5)*2};(typeof document<"u"?document:void 0)?.addEventListener("mousemove",e,{signal:this.abortSignal})}addBackgroundTextPlane(){let r=typeof document<"u"?document.createElement("canvas"):null;if(!r)return;r.width=2048,r.height=768;let i=r.getContext("2d");if(!i)return;i.clearRect(0,0,2048,768),i.save(),i.font="bold 560px Orbitron, sans-serif",i.textAlign="center",i.textBaseline="middle",i.shadowColor="rgba(0,200,255,0.35)",i.shadowBlur=80,i.fillStyle="rgba(255,255,255,0.055)",i.fillText("V2",2048*.28,768*.5),i.restore(),i.save(),i.font="bold 148px Orbitron, sans-serif",i.textAlign="center",i.textBaseline="middle",i.shadowColor="rgba(0,200,255,0.2)",i.shadowBlur=40,i.fillStyle="rgba(255,255,255,0.038)",i.fillText("by ZARDOY",2048*.72,768*.52),i.restore();let s=new W.CanvasTexture(r),o=new W.Mesh(new W.PlaneGeometry(280,105),new W.MeshBasicMaterial({map:s,transparent:!0,opacity:1,depthWrite:!1,side:W.DoubleSide,blending:W.AdditiveBlending}));o.position.set(8,4,-320),this.scene.add(o)}spawnBlock(e,t,r){let i=this.createBlockMaterial(e,r),s=new W.Mesh(this.bGeo,i),o=.3+Math.random()*3;s.scale.setScalar(o),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 a={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:r};this.blocks.push(a),this.bGroup.add(s)}createBlockMaterial(e,t){if(this.useMinecraftTextures&&t){let s=this.blockMaterialPool.get(t);if(s)return s.clone()}let[r,i]=e.blockOpacity??[.32,.46];return new W.MeshBasicMaterial({color:$t(e.blocks),transparent:!0,opacity:r+Math.random()*(i-r),depthWrite:!1,blending:W.AdditiveBlending})}removeBlockEdgeLines(){for(let e of this.blocks){let t=e.mesh.children.filter(r=>r instanceof W.LineSegments);for(let r of t){e.mesh.remove(r),r.geometry?.dispose();let i=r.material;Array.isArray(i)?i.forEach(s=>s.dispose()):i.dispose()}}}async ensureMcDataLoaded(){let e=globalThis._LOAD_MC_DATA;e&&await e()}resolveBlockAtlasUv(e,t,r){let i=s=>{let o=t[s];return o?{u:o.u,v:o.v,su:o.su??r.suSv,sv:o.sv??r.suSv}:null};if(t[e])return i(e);for(let s of["_top","_side","_front","_0"]){let o=i(`${e}${s}`);if(o)return o}for(let s of Object.keys(t))if(s.startsWith(e))return i(s);return null}applyMinecraftTexturesFromAtlas(e){let t=e.currentResources;if(!t?.blocksAtlasImage||!t.blocksAtlasJson)throw new Error("Block atlas not available");let r=t.blocksAtlasJson,i=r.textures;this.atlasTexture=I0(t.blocksAtlasImage),this.atlasTexture.flipY=!1,this.atlasTexture.needsUpdate=!0;for(let s of fn[this.blockGroup]){let o=this.resolveBlockAtlasUv(s,i,r);if(!o)continue;let a=this.atlasTexture.clone();a.flipY=!1,a.offset.set(o.u,o.v),a.repeat.set(o.su,o.sv),a.needsUpdate=!0;let v=s.includes("glass"),l=new W.MeshBasicMaterial({map:a,side:W.DoubleSide,transparent:v,opacity:v?.85:1,alphaTest:v?.08:0,depthWrite:!0,toneMapped:!1});this.blockMaterialPool.set(s,l)}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 o=$t([...this.blockMaterialPool.keys()]);s.minecraftBlockName=o,s.mesh.material=this.blockMaterialPool.get(o).clone()}}setScene(e){if(!tt.includes(e)||e===this.curScene||this.transitioning)return;this.transitioning=!0,this.curScene=e;let t=za[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 W.MeshBasicMaterial&&s.mesh.material.color.set($t(t.blocks));let r=this.nebGeo.attributes.color;for(let s=0;s<ur;s++){let o=new W.Color($t(t.nebula));r.setXYZ(s,o.r,o.g,o.b)}r.needsUpdate=!0;let i=this.galGeo.attributes.color;for(let s=0;s<dr;s++){let o=.2+Math.random()*.8,a=t.galFn(o);i.setXYZ(s,a.r,a.g,a.b)}i.needsUpdate=!0,this.transitioning=!1},150)}setCamera(e){rt.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(it.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&&wt(this.camera,this.documentRenderer.canvas);let r=o9[this.curCam],i=this.cameraSpeed,s=this.blockSpeed;this.camT+=e*r.spd*i,this.mx+=(this.tmx-this.mx)*.05,this.my+=(this.tmy-this.my)*.05;let o=this.mx*Fa,a=this.my*Fa,v=r.pos(this.camT,o,a),l=r.look(this.camT,o,a);this.camera.position.set(v.x,v.y,v.z),this.camera.lookAt(l.x,l.y,l.z),this.camera.rotation.z=r.roll(this.camT,o);let c=a9[this.curCam]*s;this.animTime+=e*1e3*s;for(let u of this.blocks){if(u.mesh.position.z+=u.spd*c*60*e,u.mesh.position.x+=u.dx*60*e*s,u.mesh.position.y+=u.dy*60*e*s,u.mesh.rotation.x+=u.rx*c,u.mesh.rotation.y+=u.ry*c,u.mesh.rotation.z+=u.rz,!this.useMinecraftTextures&&u.mesh.material instanceof W.MeshBasicMaterial){let h=u.mesh.userData.baseOpacity??.38;u.mesh.userData.baseOpacity==null&&(u.mesh.userData.baseOpacity=h);let p=.88+Math.abs(Math.sin(this.animTime*8e-4+u.mesh.position.x*.3))*.12;u.mesh.material.opacity=h*p}u.mesh.position.z>this.camera.position.z+15&&u.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()}};E();x();k();R();import*as t5 from"three";import{Vec3 as Ga}from"vec3";E();x();k();R();import l9 from"prismarine-world";import c9 from"prismarine-chunk";var Ua=n=>{let e=l9(n),t=c9(n),r=new e(n).sync,i=d9(r);for(let s of i)if(s.startsWith("set")&&s!=="setColumn"){let o=r[s].bind(r);r[s]=(...a)=>{let v=a[0];v.x!==void 0&&!r.getColumnAt(v)&&r.setColumn(Math.floor(v.x/16),Math.floor(v.z/16),new t(void 0)),o(...a)}}return r};function d9(n){let e=new Set,t=n;do for(let r of Object.getOwnPropertyNames(t))typeof n[r]=="function"&&r!=="constructor"&&e.add(r);while(t=Object.getPrototypeOf(t));return[...e]}var e5=class{constructor(e,t,r){this.documentRenderer=e;this.options=t;this.abortSignal=r;d(this,"_scene");d(this,"_camera");d(this,"worldRenderer");d(this,"WorldRendererClass",_t);this._scene=new t5.Scene,this._scene.background=new t5.Color(3294568),this._camera=new t5.PerspectiveCamera(85,e.canvas.width/e.canvas.height,.05,1e3),this.camera.position.set(0,0,0),this.camera.rotation.set(0,0,0)}get scene(){return this._scene}get camera(){return this._camera}async init(){let e=N0,t=new h0;if(t.currentConfig={version:e,noInventoryGui:!0},await t.updateAssetsData?.({}),this.abortSignal.aborted)return;let r=Ua(e),s=Xa("prismarine-block")(e),a=globalThis.mcData.blocksArray.filter(p=>{if(!p.name.includes("stained_glass"))return!1;let g=s.fromStateId(p.defaultState,0);if(g.shapes?.length!==1)return!1;let y=g.shapes[0];return y[0]===0&&y[1]===0&&y[2]===0&&y[3]===1&&y[4]===1&&y[5]===1}),v=-15,l=100,c=100;for(let p=-l;p<l;p++)for(let g=-c;g<c;g++){let y=a[Math.floor(Math.random()*a.length)];r.setBlockStateId(new Ga(p,g,v),y.defaultState)}this._camera.updateProjectionMatrix(),this._camera.position.set(.5,c/2+.5,.5),this._camera.rotation.set(0,0,0);let u=new Ga(...this._camera.position.toArray()),h=new $0(r,2,u);this.abortSignal.aborted||(this.worldRenderer=new this.WorldRendererClass(this.documentRenderer.renderer,this.options,{version:e,worldView:h,inWorldRenderingConfig:c5,playerStateReactive:G2().reactive,rendererState:J0().reactive,nonReactiveState:J0().nonReactive,resourcesManager:t}),this.worldRenderer instanceof _t&&(this._scene=this.worldRenderer.realScene,this._camera=this.worldRenderer.camera),h.init(u),await this.worldRenderer.waitForChunksToRender(),!this.abortSignal.aborted&&this.setupMouseParallax())}update(e,t){t&&wt(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,r=e.position.y,i;document.body.addEventListener("pointermove",s=>{if(s.pointerType!=="mouse")return;let o=.2,a=s.clientX/window.innerWidth-.5,v=-(s.clientY/window.innerHeight-.5);i?.stop(),i=new Oe(e.position).to({x:t+a*o,y:r+v*o},0),i.start(),e.updateProjectionMatrix()},{signal:this.abortSignal})}};E();x();k();R();import*as Na from"three";var r5=class{constructor(e,t,r={},i=!1){this.documentRenderer=e;this.options=t;d(this,"active");d(this,"abortController",new AbortController);d(this,"mode");d(this,"lastFrameTime",0);this.mode=ln(r,i)}get v2(){return this.active instanceof At?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 Na.Color&&this.documentRenderer.renderer.setClearColor(this.active.scene.background),this.lastFrameTime=performance.now(),this.documentRenderer.render=(t=!1)=>{let r=performance.now(),i=Math.min((r-this.lastFrameTime)/1e3,.05);this.lastFrameTime=r;let s=this.active;s&&(s.update(i,t),this.documentRenderer.renderer.render(s.scene,s.camera))}}createImplementation(e){switch(this.mode){case"v2":return new At(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 e5(this.documentRenderer,this.options,this.abortController.signal);default:return new Xt(this.documentRenderer)}}dispose(){this.active?.dispose(),this.active=void 0,this.abortController.abort()}};Q5.ColorManagement.enabled=!1;globalThis.THREE=Q5;var Wa=n=>({updateMap:n.entities.updateMap.bind(n.entities),updateCustomBlock:n.updateCustomBlock.bind(n),getBlockInfo:n.getBlockInfo.bind(n),playEntityAnimation:n.entities.playAnimation.bind(n.entities),damageEntity:n.entities.handleDamageEvent.bind(n.entities),updatePlayerSkin:n.entities.updatePlayerSkin.bind(n.entities),changeHandSwingingState:n.changeHandSwingingState.bind(n),getHighestBlocks:n.getHighestBlocks.bind(n),reloadWorld:n.reloadWorld.bind(n),updateEntityModel:n.entities.updateEntityModel.bind(n.entities),playEntityModelAnimation:n.entities.playEntityModelAnimation.bind(n.entities),addMedia:n.media.addMedia.bind(n.media),destroyMedia:n.media.destroyMedia.bind(n.media),setControlMode:n.media.setControlMode.bind(n.media),setVideoPlaying:n.media.setVideoPlaying.bind(n.media),setVideoSeeking:n.media.setVideoSeeking.bind(n.media),setVideoVolume:n.media.setVideoVolume.bind(n.media),setVideoSpeed:n.media.setVideoSpeed.bind(n.media),handleUserClick:n.media.handleUserClick.bind(n.media),addSectionAnimation(e,t){n.sectionsOffsetsAnimations[e]=t},removeSectionAnimation(e){delete n.sectionsOffsetsAnimations[e]},shakeFromDamage:n.cameraShake.shakeFromDamage.bind(n.cameraShake),onPageInteraction:n.media.onPageInteraction.bind(n.media),downloadMesherLog:n.downloadMesherLog.bind(n),explodeFirework:n.fireworksLegacy.explode.bind(n.fireworksLegacy),explodeFireworkFacingCamera:n.fireworksLegacy.explodeFacingCamera.bind(n.fireworksLegacy),addWaypoint:n.waypoints.addWaypoint.bind(n.waypoints),removeWaypoint:n.waypoints.removeWaypoint.bind(n.waypoints),startCinimaticScript:n.cinimaticScript.startScript.bind(n.cinimaticScript),stopCinimaticScript:n.cinimaticScript.stopScript.bind(n.cinimaticScript),launchFirework:n.fireworks.launchFirework.bind(n.fireworks),setSkyboxImage:n.skyboxRenderer.setSkyboxImage.bind(n.skyboxRenderer),setRain:e=>n.toggleModule("rain",e),spawnBlockBreakParticles(e,t,r,i,s,o){n.getModule("blockBreakParticles")?.spawnBlockBreakParticles(e,t,r,i,s,o)},spawnBlockCrackParticle(e,t,r,i,s,o,a){n.getModule("blockBreakParticles")?.spawnCrackParticle(e,t,r,i,s,o,a)},async loadGeometryExport(e){let{applyWorldGeometryExport:t}=await Promise.resolve().then(()=>(Ji(),ha));return t(n,e)},feedChunkPacket(e){let{kind:t,...r}=e,i={type:t,...r};for(let s of n.workers)s.postMessage(i)},getChunksDebugState(){let e={};for(let t of Object.keys(n.sectionObjects)){let[r,,i]=t.split(",").map(Number);e[`${r},${i}`]=!0}return{loadedSectionsChunks:e,loadedChunks:{...n.loadedChunks},finishedChunks:{...n.finishedChunks}}}}),f9=[],fr=(n,...e)=>{for(let t of Object.values(globalThis.loadedMods??{}))try{t.threeJsBackendModule?.[n]?.(...e)}catch(r){let i=`[mod three.js] Error calling ${n} on ${t.name}: ${r}`;throw new Error(i)}},Va=()=>{let n,e=null,t=null,r=null,i=null,s=(c,u)=>{ae?n=E5(c,f9,globalThis):n=c,e=new h5(n,u?.canvas),globalThis.renderer=e.renderer,globalThis.documentRenderer=e,globalThis.threeJsBackend=l,fr("default",l)},o=async c=>{if(!e)throw new Error("Document renderer not initialized");r&&(r.destroy(),r=null,i=null,globalThis.world=void 0,globalThis.frameTimingCollector=void 0),t&&(t.dispose(),t=null);let u={...n.config.menuBackground,...c};t=new r5(e,{...n},u,!!D.env.SINGLE_FILE_BUILD_MODE),fr("menuBackgroundCreated",t),await t.start(u),fr("menuBackgroundReady",t)},a=async c=>{if(!e)throw new Error("Document renderer not initialized");t&&(t.dispose(),t=null),r&&(r.destroy(),r=null,i=null,globalThis.world=void 0,globalThis.frameTimingCollector=void 0);let h=ae?E5(c,[h0,X0],globalThis):c;e.nonReactiveState=h.nonReactiveState,globalThis.resourcesManager=h.resourcesManager,r=new _t(e.renderer,n,h),await r.worldReadyPromise,i=h.inWorldRenderingConfig.enableDebugOverlay?new h1(h.nonReactiveState):null,globalThis.frameTimingCollector=i;let p=e.render;e.render=function(g){p.call(this,g),i?.markFrameStart(),h.inWorldRenderingConfig.paused||r?.render(g),i?.markFrameEnd(),i?.markFrameDisplay()},e.inWorldRenderingConfig=h.inWorldRenderingConfig,globalThis.world=r,fr("worldReady",r)},v=()=>{t&&(t.dispose(),t=null),e&&e.dispose(),r&&(r.destroy(),r=null)},l={id:"threejs",displayName:`three.js ${Q5.REVISION}`,startMenuBackground:o,startWorld:a,disconnect:v,setRendering(c){e.setPaused(!c),r&&(r.renderingActive=c)},getMenuBackground:()=>t??void 0,getDebugOverlay:()=>({get entitiesString(){return r?.entities.getDebugString()},get left(){return{"Geo Memory":r?.chunkMeshManager.getEstimatedMemoryUsage().total??"-"}}}),updateCamera(c,u,h){i?.markCameraUpdate(!c),r?.setFirstPersonCamera(c,u,h)},get soundSystem(){return r?.soundSystem},get backendMethods(){if(r)return Wa(r)}};return{main:{init:s,backend:l},workerProxy(){return ps({init(c,u){s(c,{canvas:u})},updateSizeExternal(c,u,h){e?.updateSizeExternal(c,u,h)},startMenuBackground:o,startWorld:a,disconnect:v,setRendering:l.setRendering,updateCamera(c,u,h){let p=c?new u9(c.x,c.y,c.z):null;i?.markCameraUpdate(!p),l.updateCamera(p,u,h)},async callBackendMethod(c,...u){if(!r)throw new Error("World renderer not initialized");let p=Wa(r)[c];if(!p)throw new Error(`Backend method ${String(c)} is unavailable`);return p(...u)}})}}};var hr=n=>{let{main:e}=Va();return e.init(n),e.backend};hr.id="threejs";hr.displayName="three.js Blocking Beta";hr.description="Simple, old and stable main thread graphics backend providing balanced performance on top of WebGL2.";E();x();k();R();import*as ja from"three";function h9(n){let e="threeWorker.js",t;if(D.env.SINGLE_FILE_BUILD){let r=document.getElementById("three-worker-code").textContent,i=new Blob([r],{type:"text/javascript"});t=new Worker(window.URL.createObjectURL(i))}else t=new Worker(e);return t.onmessage=({data:r})=>{n(r)},t.on&&t.on("message",r=>{t.onmessage({data:r})}),t}var mr=async n=>{let e=h9(()=>{}),t=gs(e),r=Pr();r.onSizeChanged((a,v)=>{t.updateSizeExternal(a,v,window.devicePixelRatio||1)});let i=A5(n,e);try{t.init(i,r.canvas)}catch(a){throw ot(i),a}let s=new Proxy({},{get(a,v){if(typeof v=="string")return async(...l)=>t.callBackendMethod(v,...l)}});return{id:"threejs",displayName:`three.js ${ja.REVISION}`,async startMenuBackground(a){let v=a?.resourcesManager?.currentResources?.mcData;if(v){let c={...at,items:"itemsArray",entities:"entitiesArray"};await Xr([e],N0,c,v)}let l=A5(a??{},e);try{await t.startMenuBackground(structuredClone(l))}catch(c){throw ot(l),c}},async startWorld(a){let v={...at,items:"itemsArray",entities:"entitiesArray"};await Xr([e],a.version,v,a.resourcesManager.currentResources.mcData),a.inWorldRenderingConfig.__syncToWorker=!0,a.playerStateReactive&&(a.playerStateReactive.__syncToWorker=!0),a.rendererState&&(a.rendererState.__syncFromWorker=!0),a.nonReactiveState&&(a.nonReactiveState.__syncFromWorker=!0),a.nonReactiveState.__syncFromWorkerInterval=200;let l=A5(a,e);try{await t.startWorld(structuredClone(l))}catch(h){throw ot(l),h}t.updateSizeExternal(r.size.width,r.size.height,window.devicePixelRatio||1);let c=lt("fps");setInterval(()=>{let{fps:h,avgRenderTime:p,worstRenderTime:g}=a.nonReactiveState;c.updateText(`FPS: ${h.toFixed(0)} (${p.toFixed(0)}ms/${g.toFixed(0)}ms)`),a.nonReactiveState.fps=0},1e3);let u=lt("downloaded-chunks",100,140,20,{className:vt});setInterval(()=>{let h=(n.config.statsVisible??0)>1;u.setVisibility(h),h&&u.updateText(a.nonReactiveState.world.chunksFullInfo)},200)},disconnect(){r.destroy(),t.disconnect(),e.terminate()},setRendering(a){t.setRendering(a)},updateCamera(a,v,l){t.updateCamera(a?{x:a.x,y:a.y,z:a.z}:null,v,l)},soundSystem:void 0,backendMethods:s}};mr.id="threejs-off-thread";mr.displayName="three.js Multi-thread EXPERIMENTAL";mr.description=["(UNSTABLE, DO NOT USE ON ANDROID).","Edge-cutting technology that uses a dedicated thread for graphics.","Slightly higher power and RAM usage.","More stable FPS (mid-range devices), but possible inputlag if TPS is low.","On low-end devices it might result in device throttling and stuttering."].join(" ");export{ns as AppViewer,Xt as ClassicMenuBackground,h5 as DocumentRenderer,Ar as HIGH_TEXTURE_COUNT,r1 as LONG_RENDER_TIME_MS,wr as LOW_FPS_THRESHOLD,Bt as LoadedResourcesTransferrable,vt as MC_RENDERER_DEBUG_OVERLAY_CLASS,N0 as MENU_BACKGROUND_MC_VERSION,b5 as MENU_BACKGROUND_MOTION_DEFAULTS,b0 as MENU_BACKGROUND_OPTION_DEFAULTS,fn as MINECRAFT_BLOCK_GROUPS,it as MINECRAFT_BLOCK_GROUP_IDS,g5 as MINECRAFT_BLOCK_GROUP_LABELS,r5 as MenuBackgroundRenderer,l5 as PerformanceMonitor,ss as RENDERER_DEFAULT_OPTIONS,os as RENDERER_OPTIONS_META,as as RENDERER_RENDER_GUI_SECTIONS,h0 as ResourcesManager,At as V2MenuBackground,rt as V2_CAMERA_IDS,p5 as V2_CAMERA_LABELS,tt as V2_SCENE_IDS,m5 as V2_SCENE_LABELS,e5 as WorldBlocksMenuBackground,$0 as WorldView,X0 as WorldViewWorker,Pr as addCanvasForWorker,H6 as applyMenuBackgroundLiveOptions,_f as applyRendererEnableLighting,L6 as applyRendererOptions,bf as applyRendererWorldViewOptions,Mt as chunkPos,mr as createGraphicsBackendOffThread,hr as createGraphicsBackendSingleThread,El as createWorldRendererConfig,L2 as defaultGraphicsBackendConfig,_r as defaultPerformanceInstabilityFactors,c5 as defaultWorldRendererConfig,W2 as delayedIterator,Er as formatPerformanceFactorsDebug,J0 as getDefaultRendererState,ds as getInitialPlayerState,N6 as getInitialPlayerStateRenderer,G6 as getPlayerStateUtils,ae as isWebWorker,gf as menuBackgroundOptionsFromStorage,E0 as menuBackgroundSpeedToMultiplier,x6 as migrateRendererOptions,Or as rendererShaderCubeDebugModeToValue,d6 as sectionPos,yf as subscribeRendererOptions};
|
|
21510
21510
|
/*! Bundled license information:
|
|
21511
21511
|
|
|
21512
21512
|
@jspm/core/nodelibs/browser/chunk-DtuTasat.js:
|