minecraft-renderer 0.1.85 → 0.1.86

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.
@@ -29558,7 +29558,7 @@ void main() {
29558
29558
  vFogDepth = -mvPosition.z;
29559
29559
  #endif
29560
29560
  }
29561
- `,TP={u_atlas:{value:null},u_originDelta:{value:new X},u_cameraOriginFrac:{value:new X},u_skyLevel:{value:1},u_lightCurve:{value:Ri.curve},u_minBrightness:{value:Ri.minBrightness},u_lightGamma:{value:Ri.gamma}};function $_e(){return new Xn({vertexShader:kYe,fragmentShader:kP,uniforms:Gs.merge([at.fog,TP]),transparent:!0,depthWrite:!0,depthTest:!0,vertexColors:!0,glslVersion:Eo,fog:!0})}function Y_e(){return new Xn({vertexShader:X_e,fragmentShader:kP,uniforms:Gs.merge([at.fog,TP]),transparent:!1,depthWrite:!0,depthTest:!0,vertexColors:!0,glslVersion:Eo,fog:!0})}function J_e(){return new Xn({vertexShader:X_e,fragmentShader:kP,uniforms:Gs.merge([at.fog,TP]),transparent:!0,depthWrite:!0,depthTest:!0,vertexColors:!0,glslVersion:Eo,fog:!0})}function i9(i,e,t,n,r){let{originDelta:s,cameraOriginFrac:a}=$d(e,t,n,r),o=i.uniforms.u_originDelta;o?.value?.set&&o.value.set(s.x,s.y,s.z);let l=i.uniforms.u_cameraOriginFrac;l?.value?.set&&l.value.set(a.x,a.y,a.z)}function s9(i,e){let t=i.uniforms.u_skyLevel;t&&(t.value=e)}function a9(i,e){if(e.curve!==void 0){let t=i.uniforms.u_lightCurve;t&&(t.value=e.curve)}if(e.minBrightness!==void 0){let t=i.uniforms.u_minBrightness;t&&(t.value=e.minBrightness)}if(e.gamma!==void 0){let t=i.uniforms.u_lightGamma;t&&(t.value=e.gamma)}}h();p();m();var TYe=8,IYe=.01;function IP(i,e,t,n,r){i.matrix.makeTranslation(e-r.x,t-r.y,n-r.z),i.matrixWorldNeedsUpdate=!0,i.frustumCulled=!1}function o9(i,e,t,n,r,s,a,o,l,c){let u=i-n,d=e-r,f=t-s,v=TYe+IYe;return l.set(u-v,d-v,f-v),c.set(u+v,d+v,f+v),o.set(l,c),{visible:a.intersectsBox(o),distSq:u*u+d*d+f*f}}function K_e(i,e,t,n,r,s,a,o,l,c,u){let{visible:d,distSq:f}=o9(e,t,n,r,s,a,o,l,c,u);i.visible=d,i.renderOrder=-f}EP();h();p();m();Lt();h();p();m();h();p();m();h();p();m();Lt();h();p();m();function Q_e(){return{counts:new Int32Array(c0),offsets:new Int32Array(c0)}}function RYe(i,e){if(i.counts.length>=e)return;let t=i.counts.length;for(;t<e;)t*=2;i.counts=new Int32Array(t),i.offsets=new Int32Array(t)}function e4e(i){let e=i.getExtension("WEBGL_multi_draw");return e?{tier:"A",ext:e}:{tier:"B",ext:null}}var Z_e=!1;function t4e(i,e){Z_e||!e||(Z_e=!0,console.info("[globalLegacyBuffer] legacy multi_draw tier",i))}function n4e(i,e,t,n){let r=t.length;if(r===0)return;RYe(n,r);let s=i.TRIANGLES,a=i.UNSIGNED_INT;for(let o=0;o<r;o++){let l=t[o];n.counts[o]=l.indexCount,n.offsets[o]=l.indexStart*4}if(e.tier==="A"&&e.ext){e.ext.multiDrawElementsWEBGL(s,n.counts,0,a,n.offsets,0,r);return}for(let o=0;o<r;o++)i.drawElements(s,n.counts[o],a,n.offsets[o])}var Ci=4,Tr=6,Cn=3,Us=2,Ir=1,CYe=128e3,PYe=128e3,r4e=5e3,LYe=.25,i4e=Ci*(Cn*3+Ir*2+Us)*4+Tr*4,RP=.75,c0=64;function CP(i,e,t){for(let n of i)for(let r=n.start;r<n.start+n.count;r++){let s=!1;for(let a of e)if(r>=a.start&&r<a.start+a.count){s=!0;break}s||console.error("[GlobalLegacyBuffer] draw span covers non-live quad",{buffer:t,quad:r,span:n,liveRanges:e})}}function l9(i,e){if(e.length===0)return i;let t=[];for(let n of i){let r=[n];for(let s of e){let a=[];for(let o of r){let l=o.start+o.count-1;if(s.end<o.start||s.start>l){a.push(o);continue}s.start>o.start&&a.push({start:o.start,count:s.start-o.start}),s.end<l&&a.push({start:s.end+1,count:l-s.end})}r=a}t.push(...r)}return t.filter(n=>n.count>0)}var ug=class{mesh;material;growthIncrementQuads;capacityQuads;positions;colors;skyLights;blockLights;uvs;aOrigin;indices;sectionSlots=new Map;freeList=[];highWatermark=0;pendingRanges=[];_spanScratch=[];renderOrigin={x:0,y:0,z:0};layoutVersion=0;pendingMove=null;pendingReplace=new Map;uploadEpoch=0;visibleIndexSpans=[];_drawScratch=Q_e();multiDrawCaps=null;debugOverlay=!1;constructor(e,t,n){this.material=e,this.growthIncrementQuads=n?.growthIncrementQuads??PYe,this.capacityQuads=n?.initialCapacityQuads??CYe;let r=this.capacityQuads*Ci;this.positions=new Float32Array(r*Cn),this.colors=new Float32Array(r*Cn),this.skyLights=new Float32Array(r*Ir),this.blockLights=new Float32Array(r*Ir),this.uvs=new Float32Array(r*Us),this.aOrigin=new Float32Array(r*Cn),this.indices=new Uint32Array(this.capacityQuads*Tr);let s=new dt,a=(l,c,u)=>{let d=new Mt(l,c);return d.setUsage(So),s.setAttribute(u,d),d};a(this.positions,Cn,"position"),a(this.colors,Cn,"color"),a(this.skyLights,Ir,"a_skyLight"),a(this.blockLights,Ir,"a_blockLight"),a(this.uvs,Us,"uv"),a(this.aOrigin,Cn,"a_origin");let o=new Mt(this.indices,1);o.setUsage(So),s.setIndex(o),s.setDrawRange(0,0),s.boundingSphere=new Tn(new X,1/0),this.mesh=new Ke(s,[e]),this.mesh.name=n?.name??"globalLegacyOpaque",this.mesh.frustumCulled=!1,this.mesh.matrixAutoUpdate=!1,this.mesh.matrix.identity(),this.mesh.position.set(0,0,0),t.add(this.mesh),this.syncDefaultDrawGroups(),this.mesh.onAfterRender=(l,c,u,d,f)=>{if(this.visibleIndexSpans.length===0)return;let v=l.getContext();this.multiDrawCaps||(this.multiDrawCaps=e4e(v),t4e(this.multiDrawCaps.tier,this.debugOverlay)),n4e(v,this.multiDrawCaps,this.visibleIndexSpans,this._drawScratch)}}setDebugOverlay(e){this.debugOverlay=e}suppressThreeDraw(){this.mesh.geometry.setDrawRange(0,3)}setVisibleIndexSpans(e){this.visibleIndexSpans=e}getVisibleIndexSpans(){return this.visibleIndexSpans}syncDefaultDrawGroups(){let e=this.mesh.geometry;e.clearGroups();let t=this.highWatermark*Tr;t>0&&e.addGroup(0,t,0),e.setDrawRange(0,t)}addSection(e,t,n,r,s){let a=t.positions.length/Cn,o=a/Ci;if(a===0||o*Ci!==a)return this.removeSection(e),!1;if(t.indices.length%Tr!==0||t.indices.length/Tr!==o)return!1;let l=this.sectionSlots.has(e),c;if(l){let A=this.sectionSlots.get(e),T=this.pendingReplace.get(e),P=this.pendingMove?.key===e?this.pendingMove:void 0;T?(this.zeroAndFreeSlot(A.start,A.count),c={start:T.oldStart,count:T.oldCount},this.pendingReplace.delete(e)):P?(this.zeroAndFreeSlot(A.start,A.count),c={start:P.oldStart,count:P.count},this.pendingMove=null):c=A}o>this.capacityQuads&&this.growCapacity(o);let u=this.takeFreeSlot(o);u||(this.highWatermark+o>this.capacityQuads&&this.growCapacity(this.highWatermark+o),u={start:this.highWatermark,count:o},this.highWatermark+=o);let d=u.start*Ci,f=d*Cn,v=d*Us,g=d*Ir;this.positions.set(t.positions,f),this.colors.set(t.colors,f),this.skyLights.set(t.skyLights,g),this.blockLights.set(t.blockLights,g),this.uvs.set(t.uvs,v);let b=f,y=n-this.renderOrigin.x,_=r-this.renderOrigin.y,x=s-this.renderOrigin.z;for(let A=0;A<a;A++){let T=b+A*Cn;this.aOrigin[T]=y,this.aOrigin[T+1]=_,this.aOrigin[T+2]=x}let w=u.start*Tr,S=d;for(let A=0;A<t.indices.length;A++)this.indices[w+A]=t.indices[A]+S;return this.sectionSlots.set(e,u),l&&c&&this.pendingReplace.set(e,{oldStart:c.start,oldCount:c.count}),this.markDirty(u.start,u.start+o-1),this.syncDefaultDrawGroups(),this.layoutVersion++,!0}getLayoutVersion(){return this.layoutVersion}getUploadEpoch(){return this.uploadEpoch}hasPendingReplace(){return this.pendingReplace.size>0}canUseFullDrawShortcut(){return this.pendingRanges.length===0&&this.interiorFreeQuads()===0&&this.pendingMove===null&&this.pendingReplace.size===0}isRangeFullyUploaded(e,t){return this.rangeFullyUploaded(e,t)}getPendingDirtyRanges(){return this.pendingRanges}getSectionDrawStart(e){let t=this.sectionSlots.get(e);if(!t)return;if(this.pendingMove?.key===e)return this.pendingMove.oldStart;let n=this.pendingReplace.get(e);if(n)return n.oldStart;if(this.rangeFullyUploaded(t.start,t.start+t.count-1))return t.start}getSectionDrawCount(e){let t=this.sectionSlots.get(e);if(!t)return;if(this.pendingMove?.key===e)return this.pendingMove.count;let n=this.pendingReplace.get(e);if(n)return n.oldCount;if(this.rangeFullyUploaded(t.start,t.start+t.count-1))return t.count}getPendingMove(){return this.pendingMove}compactStep(){if(this.pendingMove){let{newStart:o,count:l}=this.pendingMove;this.rangeFullyUploaded(o,o+l-1)&&this.finalizePendingMove();return}for(let o of[...this.pendingReplace.keys()]){let l=this.sectionSlots.get(o);l&&this.rangeFullyUploaded(l.start,l.start+l.count-1)&&this.finalizePendingReplace(o)}if(this.highWatermark===0||this.interiorFreeQuads()/this.highWatermark<=LYe)return;let t=this.findMovableSection(r4e);if(!t)return;let n=this.findLowestInteriorHole(t.start,t.count);if(!n)return;let r=this.reserveFreeSlotAt(n.index,t.count),s=t.start,a=r.start;this.copySectionRange(s,a,t.count),this.sectionSlots.set(t.key,{start:a,count:t.count}),this.markDirty(a,a+t.count-1),this.pendingMove={key:t.key,oldStart:s,newStart:a,count:t.count},this.layoutVersion++}updateDrawSpans(e,t){if(this.visibleIndexSpans=[],this.highWatermark===0)return;let n=this._spanScratch;n.length=0;let r=0;for(let a of e){let o=this.getSectionDrawStart(a.key),l=this.getSectionDrawCount(a.key),c=this.sectionSlots.get(a.key);o===void 0||l===void 0||!c||(n.push({start:o,count:l}),r+=l)}if(n.length===0)return;let s=(a,o)=>{this.visibleIndexSpans.push({indexStart:a*Tr,indexCount:o*Tr})};if(t==="opaque"){let a,o=n.map(c=>({...c})),l=this.canUseFullDrawShortcut()&&r>=this.highWatermark*RP;l?a=[{start:0,count:this.highWatermark}]:(n.sort((c,u)=>c.start-u.start),this.mergeOpaqueSpans(n),a=n),a=l9(a,this.pendingRanges),l||CP(a,o,this.mesh.name);for(let c of a)s(c.start,c.count)}else{e.sort((a,o)=>o.distSq-a.distSq);for(let a of e){let o=this.getSectionDrawStart(a.key),l=this.getSectionDrawCount(a.key);o===void 0||l===void 0||s(o,l)}}}mergeOpaqueSpans(e){if(e.length<2)return;let t=0;for(;t<e.length-1;){let n=e[t],r=e[t+1];n.start+n.count===r.start?(n.count=r.start+r.count-n.start,e.splice(t+1,1)):t++}}hasSection(e){return this.sectionSlots.has(e)}getSectionSlot(e){return this.sectionSlots.get(e)}takeSectionData(e){let t=this.getSectionGeometryData(e);if(t)return this.removeSection(e),t}getSectionGeometryData(e){let t=this.sectionSlots.get(e);if(!t)return;let n=t.count*Ci,r=t.start*Ci,s=r*Cn,a=r*Us,o=t.start*Tr,l=t.count*Tr,c=r*Ir,u=this.positions.slice(s,s+n*Cn),d=this.colors.slice(s,s+n*Cn),f=this.skyLights.slice(c,c+n*Ir),v=this.blockLights.slice(c,c+n*Ir),g=this.uvs.slice(a,a+n*Us),b=this.indices.slice(o,o+l),y=r;for(let S=0;S<b.length;S++)b[S]=b[S]-y;let _=this.aOrigin[s]+this.renderOrigin.x,x=this.aOrigin[s+1]+this.renderOrigin.y,w=this.aOrigin[s+2]+this.renderOrigin.z;return{positions:u,colors:d,skyLights:f,blockLights:v,uvs:g,indices:b,sx:_,sy:x,sz:w}}removeSection(e){let t=this.sectionSlots.get(e);if(!t)return;if(this.pendingReplace.has(e)){let s=this.pendingReplace.get(e);this.zeroAndFreeSlot(s.oldStart,s.oldCount),this.pendingReplace.delete(e)}if(this.pendingMove?.key===e){let{oldStart:s,count:a}=this.pendingMove;this.zeroAndFreeSlot(s,a),this.pendingMove=null}let n=t.start*Tr,r=t.count*Tr;for(let s=0;s<r;s++)this.indices[n+s]=0;this.markDirty(t.start,t.start+t.count-1),this.sectionSlots.delete(e),this.insertFreeSlot(t),this.shrinkHighWatermark(),this.syncDefaultDrawGroups(),this.layoutVersion++}hasPendingUploads(){return this.pendingRanges.length>0}uploadDirtyRange(){let e=this.pendingRanges[0];if(!e)return;let t=e.start,n=Math.min(e.end-e.start+1,r4e),r=t*Ci,s=n*Ci,a=t*Tr,o=n*Tr,l=this.mesh.geometry,c=l.getAttribute("position");c.clearUpdateRanges(),c.addUpdateRange(r*Cn,s*Cn),c.needsUpdate=!0;let u=l.getAttribute("color");u.clearUpdateRanges(),u.addUpdateRange(r*Cn,s*Cn),u.needsUpdate=!0;let d=l.getAttribute("a_skyLight");d.clearUpdateRanges(),d.addUpdateRange(r*Ir,s*Ir),d.needsUpdate=!0;let f=l.getAttribute("a_blockLight");f.clearUpdateRanges(),f.addUpdateRange(r*Ir,s*Ir),f.needsUpdate=!0;let v=l.getAttribute("uv");v.clearUpdateRanges(),v.addUpdateRange(r*Us,s*Us),v.needsUpdate=!0;let g=l.getAttribute("a_origin");g.clearUpdateRanges(),g.addUpdateRange(r*Cn,s*Cn),g.needsUpdate=!0;let b=l.index;b.clearUpdateRanges(),b.addUpdateRange(a,o),b.needsUpdate=!0,t+n>e.end?this.pendingRanges.shift():e.start=t+n,this.uploadEpoch++}setRenderOrigin(e){this.renderOrigin={...e}}rebase(e){if(this.highWatermark!==0){for(let t of this.sectionSlots.values()){let n=t.start*Ci,r=t.count*Ci,s=n*Cn;for(let a=0;a<r;a++){let o=s+a*Cn;this.aOrigin[o]-=e.x,this.aOrigin[o+1]-=e.y,this.aOrigin[o+2]-=e.z}}this.markDirty(0,this.highWatermark-1),this.renderOrigin.x+=e.x,this.renderOrigin.y+=e.y,this.renderOrigin.z+=e.z}}setCameraOrigin(e,t,n){let{originDelta:r,cameraOriginFrac:s}=$d(this.renderOrigin,e,t,n),a=this.material.uniforms.u_originDelta;a?.value?.set&&a.value.set(r.x,r.y,r.z);let o=this.material.uniforms.u_cameraOriginFrac;o?.value?.set&&o.value.set(s.x,s.y,s.z)}getHighWatermark(){return this.highWatermark}getCapacityQuads(){return this.capacityQuads}getSectionCount(){return this.sectionSlots.size}getMemoryBytes(){return this.capacityQuads*i4e}getUsedMemoryBytes(){return this.highWatermark*i4e}reset(){this.sectionSlots.clear(),this.freeList.length=0,this.highWatermark=0,this.pendingRanges.length=0,this.pendingMove=null,this.pendingReplace.clear(),this.uploadEpoch=0,this.visibleIndexSpans=[],this.syncDefaultDrawGroups()}dispose(){this.mesh.parent?.remove(this.mesh),this.mesh.geometry.dispose(),this.reset()}markDirty(e,t){this.pendingRanges.push({start:e,end:t}),this.pendingRanges.sort((n,r)=>n.start-r.start),this.mergePendingRanges()}mergePendingRanges(){if(this.pendingRanges.length<2)return;let e=[],t=this.pendingRanges[0];for(let n=1;n<this.pendingRanges.length;n++){let r=this.pendingRanges[n];r.start<=t.end+1?t={start:t.start,end:Math.max(t.end,r.end)}:(e.push(t),t=r)}e.push(t),this.pendingRanges=e}takeFreeSlot(e){for(let t=0;t<this.freeList.length;t++){let n=this.freeList[t];if(n.count>=e){if(this.freeList.splice(t,1),n.count===e)return n;let r={start:n.start,count:e};return this.insertFreeSlot({start:n.start+e,count:n.count-e}),r}}}insertFreeSlot(e){this.freeList.push(e),this.freeList.sort((t,n)=>t.start-n.start),this.mergeFreeList()}mergeFreeList(){if(this.freeList.length<2)return;let e=[],t=this.freeList[0];for(let n=1;n<this.freeList.length;n++){let r=this.freeList[n];t.start+t.count===r.start?t={start:t.start,count:t.count+r.count}:(e.push(t),t=r)}e.push(t),this.freeList=e}shrinkHighWatermark(){for(;this.highWatermark>0;){let e=this.highWatermark-1,t=this.freeList.find(r=>r.start<=e&&r.start+r.count>e);if(!t||t.start+t.count!==this.highWatermark)break;this.highWatermark=t.start;let n=this.freeList.indexOf(t);this.freeList.splice(n,1)}}interiorFreeQuads(){let e=0;for(let t of this.freeList)t.start<this.highWatermark&&(e+=t.count);return e}findMovableSection(e){let t=[];for(let[s,a]of this.sectionSlots)t.push({key:s,start:a.start,count:a.count});if(t.length===0)return;t.sort((s,a)=>a.start!==s.start?a.start-s.start:a.start+a.count-(s.start+s.count));let n=t[0];if(n.count<=e&&this.findLowestInteriorHole(n.start,n.count))return n;let r=t.filter(s=>s.count<=e).sort((s,a)=>a.count-s.count);for(let s of r)if(this.findLowestInteriorHole(s.start,s.count))return s}findLowestInteriorHole(e,t){for(let n=0;n<this.freeList.length;n++){let r=this.freeList[n];if(r.start<e&&r.count>=t)return{start:r.start,count:r.count,index:n}}}reserveFreeSlotAt(e,t){let n=this.freeList[e];if(this.freeList.splice(e,1),n.count===t)return{start:n.start,count:t};let r={start:n.start,count:t};return this.insertFreeSlot({start:n.start+t,count:n.count-t}),r}copySectionRange(e,t,n){let r=e*Ci,s=t*Ci,a=n*Ci,o=s-r,l=r*Cn,c=s*Cn,u=a*Cn;this.positions.copyWithin(c,l,l+u),this.colors.copyWithin(c,l,l+u),this.aOrigin.copyWithin(c,l,l+u);let d=r*Ir,f=s*Ir,v=a*Ir;this.skyLights.copyWithin(f,d,d+v),this.blockLights.copyWithin(f,d,d+v);let g=r*Us,b=s*Us,y=a*Us;this.uvs.copyWithin(b,g,g+y);let _=e*Tr,x=t*Tr,w=n*Tr;for(let S=0;S<w;S++)this.indices[x+S]=this.indices[_+S]+o}rangeFullyUploaded(e,t){for(let n of this.pendingRanges)if(n.start<=t&&n.end>=e)return!1;return!0}zeroAndFreeSlot(e,t){let n=e*Tr,r=t*Tr;for(let s=0;s<r;s++)this.indices[n+s]=0;this.markDirty(e,e+t-1),this.insertFreeSlot({start:e,count:t})}finalizePendingReplace(e){let t=this.pendingReplace.get(e);t&&(this.zeroAndFreeSlot(t.oldStart,t.oldCount),this.pendingReplace.delete(e),this.shrinkHighWatermark(),this.syncDefaultDrawGroups(),this.layoutVersion++,this.uploadEpoch++)}finalizePendingMove(){let e=this.pendingMove;if(!e)return;let{oldStart:t,count:n}=e;this.zeroAndFreeSlot(t,n),this.shrinkHighWatermark(),this.syncDefaultDrawGroups(),this.pendingMove=null,this.layoutVersion++,this.uploadEpoch++}growCapacity(e){this.pendingMove&&this.finalizePendingMove();for(let y of[...this.pendingReplace.keys()])this.finalizePendingReplace(y);let t=this.capacityQuads;for(;t<e;)t+=this.growthIncrementQuads;let n=this.capacityQuads*Ci,r=t*Ci,s=new Float32Array(r*Cn),a=new Float32Array(r*Cn),o=new Float32Array(r*Ir),l=new Float32Array(r*Ir),c=new Float32Array(r*Us),u=new Float32Array(r*Cn),d=new Uint32Array(t*Tr);s.set(this.positions),a.set(this.colors),o.set(this.skyLights),l.set(this.blockLights),c.set(this.uvs),u.set(this.aOrigin),d.set(this.indices),this.positions=s,this.colors=a,this.skyLights=o,this.blockLights=l,this.uvs=c,this.aOrigin=u,this.indices=d,this.capacityQuads=t;let f=this.mesh.geometry,v=(y,_,x)=>{f.getAttribute(x)&&f.deleteAttribute(x);let S=new Mt(y,_);S.setUsage(So),f.setAttribute(x,S)};v(this.positions,Cn,"position"),v(this.colors,Cn,"color"),v(this.skyLights,Ir,"a_skyLight"),v(this.blockLights,Ir,"a_blockLight"),v(this.uvs,Us,"uv"),v(this.aOrigin,Cn,"a_origin"),f.index&&f.setIndex(null);let b=new Mt(this.indices,1);b.setUsage(So),f.setIndex(b),this.pendingRanges.length=0}};function BYe(i){if(i.length<2)return;let e=0;for(;e<i.length-1;){let t=i[e],n=i[e+1];t.start+t.count===n.start?(t.count=n.start+n.count-t.start,i.splice(e+1,1)):e++}}function s4e(i,e,t=!0,n,r=[]){if(i.length===0||e===0)return[];let s=0;for(let l of i)s+=l.count;let a;if(t&&s>=e*RP)a=[{start:0,count:e}];else{a=i.map(c=>({start:c.start,count:c.count})),a.sort((c,u)=>c.start-u.start);let l=a.map(c=>({...c}));return BYe(a),a=l9(a,r),CP(a,l,"globalBlockBuffer"),a}return l9(a,r)}Kc();function o4e(){return{firsts:new Int32Array(c0),counts:new Int32Array(c0),instanceCounts:new Int32Array(c0),baseInstances:new Int32Array(c0)}}function l4e(i){let e=i.getExtension("WEBGL_multi_draw_instanced_base_vertex_base_instance");if(e)return{tier:"A",ext:e};let t=i.getExtension("WEBGL_draw_instanced_base_vertex_base_instance");return t?{tier:"B",ext:t}:{tier:"C",ext:null}}var a4e=!1;function c4e(i,e){a4e||!e||(a4e=!0,console.info("[globalBlockBuffer] cube multi_draw tier",i))}function u4e(i,e,t,n,r){let s=t.length;if(s===0)return;let a=i.TRIANGLES;if(e.tier==="A"&&e.ext){let o=e.ext;for(let l=0;l<s;l++){let c=t[l];n.firsts[l]=0,n.counts[l]=l0,n.instanceCounts[l]=c.count,n.baseInstances[l]=c.start}o.multiDrawArraysInstancedBaseInstanceWEBGL(a,n.firsts,0,n.counts,0,n.instanceCounts,0,n.baseInstances,0,s);return}if(e.tier==="B"&&e.ext){let o=e.ext;for(let l=0;l<s;l++){let c=t[l];o.drawArraysInstancedBaseInstanceWEBGL(a,0,l0,c.count,c.start)}return}r?.(i,t)}Kc();z5();var DYe=512e3,OYe=1e6,d4e=15e3,NYe=.25,dg=F_e(),f4e=16,c9=class{mesh;capacityFaces;w0;w1;w2;w3;sectionSlots=new Map;freeList=[];highWatermark=0;pendingRanges=[];pendingMove=null;pendingReplace=new Map;uploadEpoch=0;visibleSpans=[];_drawScratch=o4e();multiDrawCaps=null;tierCVao=null;tierCAttrs=null;tierCGl=null;debugOverlay=!1;layoutVersion=0;constructor(e,t){this.capacityFaces=DYe,this.w0=new Uint32Array(this.capacityFaces),this.w1=new Uint32Array(this.capacityFaces),this.w2=new Uint32Array(this.capacityFaces),this.w3=new Uint32Array(this.capacityFaces),this.w2.fill(dg);let n=new Sa,r=new Float32Array(l0*3);n.setAttribute("position",new Mt(r,3));let s=a=>{let o=new Ar(a,1);return o.setUsage(So),o};n.setAttribute("a_w0",s(this.w0)),n.setAttribute("a_w1",s(this.w1)),n.setAttribute("a_w2",s(this.w2)),n.setAttribute("a_w3",s(this.w3)),n.instanceCount=0,this.mesh=new Ke(n,e),this.mesh.name="globalShaderCubes",this.mesh.frustumCulled=!1,this.mesh.matrixAutoUpdate=!1,this.mesh.matrix.identity(),this.mesh.position.set(0,0,0),t.add(this.mesh),this.mesh.onAfterRender=(a,o,l,c,u)=>{if(this.visibleSpans.length===0)return;let d=u,f=a.getContext();this.multiDrawCaps||(this.multiDrawCaps=l4e(f),c4e(this.multiDrawCaps.tier,this.debugOverlay)),u4e(f,this.multiDrawCaps,this.visibleSpans,this._drawScratch,this.multiDrawCaps.tier==="C"?(v,g)=>this.drawTierCSpans(v,g,a,d):void 0)}}setDebugOverlay(e){this.debugOverlay=e}suppressThreeDraw(){let e=this.mesh.geometry;e.setDrawRange(0,l0),e.instanceCount=0}setVisibleSpans(e){this.visibleSpans=e}getVisibleSpans(){return this.visibleSpans}forEachSectionSlot(e){for(let[t,n]of this.sectionSlots)e(t,n)}getSectionDrawStart(e){let t=this.sectionSlots.get(e);if(!t)return;if(this.pendingMove?.key===e)return this.pendingMove.oldStart;let n=this.pendingReplace.get(e);if(n)return n.oldStart;if(this.rangeFullyUploaded(t.start,t.start+t.count-1))return t.start}getSectionDrawCount(e){let t=this.sectionSlots.get(e);if(!t)return;if(this.pendingMove?.key===e)return this.pendingMove.count;let n=this.pendingReplace.get(e);if(n)return n.oldCount;if(this.rangeFullyUploaded(t.start,t.start+t.count-1))return t.count}getUploadEpoch(){return this.uploadEpoch}hasPendingReplace(){return this.pendingReplace.size>0}canUseFullDrawShortcut(){return this.pendingRanges.length===0&&this.interiorFreeFaces()===0&&this.pendingMove===null&&this.pendingReplace.size===0}isRangeFullyUploaded(e,t){return this.rangeFullyUploaded(e,t)}getPendingDirtyRanges(){return this.pendingRanges}getHighWatermark(){return this.highWatermark}getCapacityFaces(){return this.capacityFaces}getSectionCount(){return this.sectionSlots.size}getMemoryBytes(){return this.capacityFaces*f4e}getUsedMemoryBytes(){return this.highWatermark*f4e}hasPendingUploads(){return this.pendingRanges.length>0}getPendingMove(){return this.pendingMove}addSection(e,t,n){if(n<=0){this.removeSection(e);return}let r=this.sectionSlots.has(e),s;if(r){let l=this.sectionSlots.get(e),c=this.pendingReplace.get(e),u=this.pendingMove?.key===e?this.pendingMove:void 0;c?(this.zeroAndFreeSlot(l.start,l.count),s={start:c.oldStart,count:c.oldCount},this.pendingReplace.delete(e)):u?(this.zeroAndFreeSlot(l.start,l.count),s={start:u.oldStart,count:u.count},this.pendingMove=null):s=l}n>this.capacityFaces&&this.growCapacity(n);let a=this.takeFreeSlot(n);a||(this.highWatermark+n>this.capacityFaces&&this.growCapacity(this.highWatermark+n),a={start:this.highWatermark,count:n},this.highWatermark+=n);let o=4;for(let l=0;l<n;l++){let c=a.start+l,u=l*o;this.w0[c]=t[u],this.w1[c]=t[u+1],this.w2[c]=t[u+2],this.w3[c]=t[u+3]}this.sectionSlots.set(e,a),r&&s&&this.pendingReplace.set(e,{oldStart:s.start,oldCount:s.count}),this.markDirty(a.start,a.start+n-1),this.mesh.geometry.instanceCount=this.highWatermark,this.layoutVersion++}getLayoutVersion(){return this.layoutVersion}hasSection(e){return this.sectionSlots.has(e)}getSectionSlot(e){return this.sectionSlots.get(e)}getW0(){return this.w0}takeSectionData(e){let t=this.sectionSlots.get(e);if(!t)return;let n=4,r=new Uint32Array(t.count*n);for(let s=0;s<t.count;s++){let a=t.start+s,o=s*n;r[o]=this.w0[a],r[o+1]=this.w1[a],r[o+2]=this.w2[a],r[o+3]=this.w3[a]}return this.removeSection(e),{words:r,count:t.count}}removeSection(e){let t=this.sectionSlots.get(e);if(t){if(this.pendingReplace.has(e)){let n=this.pendingReplace.get(e);this.zeroAndFreeSlot(n.oldStart,n.oldCount),this.pendingReplace.delete(e)}if(this.pendingMove?.key===e){let{oldStart:n,count:r}=this.pendingMove;this.zeroAndFreeSlot(n,r),this.pendingMove=null}for(let n=t.start;n<t.start+t.count;n++)this.w0[n]=0,this.w1[n]=0,this.w2[n]=dg,this.w3[n]=0;this.markDirty(t.start,t.start+t.count-1),this.sectionSlots.delete(e),this.insertFreeSlot(t),this.shrinkHighWatermark(),this.mesh.geometry.instanceCount=this.highWatermark,this.layoutVersion++}}compactStep(){if(this.pendingMove){let{newStart:o,count:l}=this.pendingMove;this.rangeFullyUploaded(o,o+l-1)&&this.finalizePendingMove();return}for(let o of[...this.pendingReplace.keys()]){let l=this.sectionSlots.get(o);l&&this.rangeFullyUploaded(l.start,l.start+l.count-1)&&this.finalizePendingReplace(o)}if(this.highWatermark===0||this.interiorFreeFaces()/this.highWatermark<=NYe)return;let t=this.findMovableSection(d4e);if(!t)return;let n=this.findLowestInteriorHole(t.start,t.count);if(!n)return;let r=this.reserveFreeSlotAt(n.index,t.count),s=t.start,a=r.start;this.copySectionRange(s,a,t.count),this.sectionSlots.set(t.key,{start:a,count:t.count}),this.markDirty(a,a+t.count-1),this.pendingMove={key:t.key,oldStart:s,newStart:a,count:t.count},this.layoutVersion++}uploadDirtyRange(){let e=this.pendingRanges[0];if(!e)return;let t=e.start,n=Math.min(e.end-e.start+1,d4e),r=this.mesh.geometry;for(let s of["a_w0","a_w1","a_w2","a_w3"]){let a=r.getAttribute(s);a.clearUpdateRanges(),a.addUpdateRange(t,n),a.needsUpdate=!0}t+n>e.end?this.pendingRanges.shift():e.start=t+n,this.uploadEpoch++}setCameraOrigin(e,t,n,r){let{originDelta:s,cameraOriginFrac:a}=$d(e,t,n,r),o=Kb(e),l=this.mesh.material.uniforms.u_originDelta;l?.value?.set&&l.value.set(s.x,s.y,s.z);let c=this.mesh.material.uniforms.u_cameraOriginFrac;c?.value?.set&&c.value.set(a.x,a.y,a.z);let u=this.mesh.material.uniforms.u_sectionOriginRel;u?.value?.set&&u.value.set(o.x,o.y,o.z)}reset(){this.sectionSlots.clear(),this.freeList.length=0,this.highWatermark=0,this.pendingRanges.length=0,this.pendingMove=null,this.pendingReplace.clear(),this.uploadEpoch=0,this.visibleSpans=[],this.w0.fill(0),this.w1.fill(0),this.w2.fill(dg),this.w3.fill(0),this.mesh.geometry.instanceCount=0,this.invalidateTierCVao()}dispose(){this.invalidateTierCVao(),this.mesh.parent?.remove(this.mesh),this.mesh.geometry.dispose(),this.reset()}invalidateTierCVao(){this.tierCVao&&this.tierCGl&&this.tierCGl.deleteVertexArray(this.tierCVao),this.tierCVao=null,this.tierCAttrs=null}drawTierCSpans(e,t,n,r){if(this.ensureTierCVao(e,n,r),!this.tierCVao||!this.tierCAttrs)return;let s=this.tierCAttrs;e.bindVertexArray(this.tierCVao);for(let a of t){let o=a.start*4,l=c=>{e.bindBuffer(e.ARRAY_BUFFER,c.buffer),e.vertexAttribIPointer(c.loc,1,e.UNSIGNED_INT,4,o)};l(s.w0),l(s.w1),l(s.w2),l(s.w3),e.drawArraysInstanced(e.TRIANGLES,0,l0,a.count)}e.bindVertexArray(null)}ensureTierCVao(e,t,n){this.tierCGl=e;let a=t.properties.get(n).currentProgram.program,o=e.getAttribLocation(a,"a_w0"),l=e.getAttribLocation(a,"a_w1"),c=e.getAttribLocation(a,"a_w2"),u=e.getAttribLocation(a,"a_w3"),d=w=>w<0?null:e.getVertexAttrib(w,e.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING),f=d(o);if(this.tierCVao&&this.tierCAttrs&&f&&this.tierCAttrs.w0.buffer!==f&&this.invalidateTierCVao(),this.tierCVao)return;let v=d(o),g=d(l),b=d(c),y=d(u);if(!v||!g||!b||!y)return;let _=e.createVertexArray();if(!_)return;e.bindVertexArray(_);let x=(w,S)=>{e.enableVertexAttribArray(w),e.bindBuffer(e.ARRAY_BUFFER,S),e.vertexAttribIPointer(w,1,e.UNSIGNED_INT,4,0),e.vertexAttribDivisor(w,1)};x(o,v),x(l,g),x(c,b),x(u,y),e.bindVertexArray(null),this.tierCVao=_,this.tierCAttrs={w0:{loc:o,buffer:v},w1:{loc:l,buffer:g},w2:{loc:c,buffer:b},w3:{loc:u,buffer:y}}}markDirty(e,t){this.pendingRanges.push({start:e,end:t}),this.pendingRanges.sort((n,r)=>n.start-r.start),this.mergePendingRanges()}mergePendingRanges(){if(this.pendingRanges.length<2)return;let e=[],t=this.pendingRanges[0];for(let n=1;n<this.pendingRanges.length;n++){let r=this.pendingRanges[n];r.start<=t.end+1?t={start:t.start,end:Math.max(t.end,r.end)}:(e.push(t),t=r)}e.push(t),this.pendingRanges=e}takeFreeSlot(e){for(let t=0;t<this.freeList.length;t++){let n=this.freeList[t];if(n.count>=e){if(this.freeList.splice(t,1),n.count===e)return n;let r={start:n.start,count:e};return this.insertFreeSlot({start:n.start+e,count:n.count-e}),r}}}insertFreeSlot(e){this.freeList.push(e),this.freeList.sort((t,n)=>t.start-n.start),this.mergeFreeList()}mergeFreeList(){if(this.freeList.length<2)return;let e=[],t=this.freeList[0];for(let n=1;n<this.freeList.length;n++){let r=this.freeList[n];t.start+t.count===r.start?t={start:t.start,count:t.count+r.count}:(e.push(t),t=r)}e.push(t),this.freeList=e}interiorFreeFaces(){let e=0;for(let t of this.freeList)t.start<this.highWatermark&&(e+=t.count);return e}findMovableSection(e){let t=[];for(let[s,a]of this.sectionSlots)t.push({key:s,start:a.start,count:a.count});if(t.length===0)return;t.sort((s,a)=>a.start!==s.start?a.start-s.start:a.start+a.count-(s.start+s.count));let n=t[0];if(n.count<=e&&this.findLowestInteriorHole(n.start,n.count))return n;let r=t.filter(s=>s.count<=e).sort((s,a)=>a.count-s.count);for(let s of r)if(this.findLowestInteriorHole(s.start,s.count))return s}findLowestInteriorHole(e,t){for(let n=0;n<this.freeList.length;n++){let r=this.freeList[n];if(r.start<e&&r.count>=t)return{start:r.start,count:r.count,index:n}}}reserveFreeSlotAt(e,t){let n=this.freeList[e];if(this.freeList.splice(e,1),n.count===t)return{start:n.start,count:t};let r={start:n.start,count:t};return this.insertFreeSlot({start:n.start+t,count:n.count-t}),r}copySectionRange(e,t,n){this.w0.copyWithin(t,e,e+n),this.w1.copyWithin(t,e,e+n),this.w2.copyWithin(t,e,e+n),this.w3.copyWithin(t,e,e+n)}rangeFullyUploaded(e,t){for(let n of this.pendingRanges)if(n.start<=t&&n.end>=e)return!1;return!0}zeroAndFreeSlot(e,t){for(let n=e;n<e+t;n++)this.w0[n]=0,this.w1[n]=0,this.w2[n]=dg,this.w3[n]=0;this.markDirty(e,e+t-1),this.insertFreeSlot({start:e,count:t})}finalizePendingReplace(e){let t=this.pendingReplace.get(e);t&&(this.zeroAndFreeSlot(t.oldStart,t.oldCount),this.pendingReplace.delete(e),this.shrinkHighWatermark(),this.mesh.geometry.instanceCount=this.highWatermark,this.layoutVersion++,this.uploadEpoch++)}finalizePendingMove(){let e=this.pendingMove;if(!e)return;let{oldStart:t,count:n}=e;this.zeroAndFreeSlot(t,n),this.shrinkHighWatermark(),this.mesh.geometry.instanceCount=this.highWatermark,this.pendingMove=null,this.layoutVersion++,this.uploadEpoch++}shrinkHighWatermark(){for(;this.highWatermark>0;){let e=this.highWatermark-1,t=this.freeList.find(r=>r.start<=e&&r.start+r.count>e);if(!t||t.start+t.count!==this.highWatermark)break;this.highWatermark=t.start;let n=this.freeList.indexOf(t);this.freeList.splice(n,1)}}growCapacity(e){this.pendingMove&&this.finalizePendingMove();for(let c of[...this.pendingReplace.keys()])this.finalizePendingReplace(c);console.warn("[globalBlockBuffer] growing faces",this.capacityFaces,"->","(need",e,")");let t=this.capacityFaces;for(;t<e;)t+=OYe;console.warn("[globalBlockBuffer] growing faces",this.capacityFaces,"->",t);let n=new Uint32Array(t),r=new Uint32Array(t),s=new Uint32Array(t),a=new Uint32Array(t);n.set(this.w0),r.set(this.w1),s.set(this.w2),a.set(this.w3),s.fill(dg,this.w0.length),this.w0=n,this.w1=r,this.w2=s,this.w3=a,this.capacityFaces=t;let o=this.mesh.geometry,l=(c,u)=>{let d=o.getAttribute(u);d&&(o.deleteAttribute(u),"dispose"in d&&typeof d.dispose=="function"&&d.dispose());let f=new Ar(c,1);f.setUsage(So),o.setAttribute(u,f)};l(this.w0,"a_w0"),l(this.w1,"a_w1"),l(this.w2,"a_w2"),l(this.w3,"a_w3"),this.pendingRanges.length=0,this.invalidateTierCVao()}};h();p();m();z5();Kc();function h4e(i,e,t,n,r){if(e<=0)return;let s=t-8,a=n-8,o=r-8,l=t9,c=16,u=16,d=16,f=-1,v=-1,g=-1;for(let A=0;A<e;A++){let T=i[A*l],P=T&(1<<Xd.LX_BITS)-1,I=T>>Xd.LY_SHIFT&(1<<Xd.LY_BITS)-1,k=T>>Xd.LZ_SHIFT&(1<<Xd.LZ_BITS)-1;P<c&&(c=P),I<u&&(u=I),k<d&&(d=k),P>f&&(f=P),I>v&&(v=I),k>g&&(g=k)}if(f<0)return;let b=s+c,y=a+u,_=o+d,x=s+f+1,w=a+v+1,S=o+g+1;return{minX:b,minY:y,minZ:_,maxX:x,maxY:w,maxZ:S,cx:(b+x)*.5,cy:(y+w)*.5,cz:(_+S)*.5}}function UYe(i,e,t,n,r,s,a,o,l){return i>=n&&i<=a&&e>=r&&e<=o&&t>=s&&t<=l}function m4e(i,e,t,n,r,s,a,o,l,c,u,d,f){if(UYe(i,e,t,a,o,l,c,u,d))return;let v=0,g=f;if(Math.abs(n)<1e-8){if(i<a||i>c)return}else{let b=1/n,y=(a-i)*b,_=(c-i)*b;if(y>_){let x=y;y=_,_=x}if(v=Math.max(v,y),g=Math.min(g,_),v>g)return}if(Math.abs(r)<1e-8){if(e<o||e>u)return}else{let b=1/r,y=(o-e)*b,_=(u-e)*b;if(y>_){let x=y;y=_,_=x}if(v=Math.max(v,y),g=Math.min(g,_),v>g)return}if(Math.abs(s)<1e-8){if(t<l||t>d)return}else{let b=1/s,y=(l-t)*b,_=(d-t)*b;if(y>_){let x=y;y=_,_=x}if(v=Math.max(v,y),g=Math.min(g,_),v>g)return}return v<=g&&v>=0?v:void 0}function p4e(i,e,t,n,r,s,a,o,l,c,u,d,f){let v=f;if(Math.abs(n)>=1e-8){let g=n>0?(c-i)/n:(a-i)/n;g>1e-6&&(v=Math.min(v,g))}else if(i<a||i>c)return;if(Math.abs(r)>=1e-8){let g=r>0?(u-e)/r:(o-e)/r;g>1e-6&&(v=Math.min(v,g))}else if(e<o||e>u)return;if(Math.abs(s)>=1e-8){let g=s>0?(d-t)/s:(l-t)/s;g>1e-6&&(v=Math.min(v,g))}else if(t<l||t>d)return;return v<=f?v:void 0}h();p();m();Lt();h();p();m();$b();var u9=class{entries=new Set;skyLevel=1;lightmapParams={...Ri};register(e){this.entries.add(e),this.applyBrightness(e)}unregister(e){for(let t of this.entries)if(t.material===e){this.entries.delete(t);break}}setSkyLevel(e){this.skyLevel=e,this.refreshAll()}setLightmapParams(e){this.lightmapParams={...this.lightmapParams,...e},this.refreshAll()}getSkyLevel(){return this.skyLevel}refreshAll(){for(let e of this.entries)this.applyBrightness(e)}applyBrightness(e){let t=yP(e.blockLightNorm,e.skyLightNorm,this.skyLevel,this.lightmapParams);e.material.color.setScalar(t)}};function v4e(i,e,t,n,r=Ri){let s=yP(e,t,n,r);return i.color.setScalar(s),s}var g4e=20,_4e=40,FYe={white_banner:15,orange_banner:14,magenta_banner:13,light_blue_banner:12,yellow_banner:11,lime_banner:10,pink_banner:9,gray_banner:8,light_gray_banner:7,cyan_banner:6,purple_banner:5,blue_banner:4,brown_banner:3,green_banner:2,red_banner:1,black_banner:0},y4e={0:"#1d1d21",1:"#b02e26",2:"#5e7c16",3:"#835432",4:"#3c44aa",5:"#8932b8",6:"#169c9c",7:"#9d9d97",8:"#474f52",9:"#f38baa",10:"#80c71f",11:"#fed83d",12:"#3ab3da",13:"#c74ebd",14:"#f9801d",15:"#f9fffe"};function VYe(i){let e=i.replace("_wall_banner","_banner");return FYe[e]??15}var zYe=(i,e,t,n,r,s,a)=>{switch(i.fillStyle=t,e){case"bs":i.fillRect(n,r,s,a);break;case"ls":i.fillRect(n,r,s/3,a);break;case"rs":i.fillRect(n+s*2/3,r,s/3,a);break;case"ts":i.fillRect(n,r,s,a/3);break;case"ms":i.fillRect(n,r+a/3,s,a/3);break;case"drs":i.fillRect(n,r,s/2,a/2);break;case"dls":i.fillRect(n+s/2,r,s/2,a/2);break;case"ss":for(let o=0;o<s;o+=2)i.fillRect(n+o,r,1,a);break;case"cr":i.fillRect(n,r+a/3,s,a/3),i.fillRect(n+s/3,r,s/3,a);break;case"sc":i.fillRect(n,r+a/2-1,s,2),i.fillRect(n+s/2-1,r,2,a);break;default:i.fillRect(n,r,s,a)}};function HYe(i,e){if(!e||e.length===0)return`banner_${i}_empty`;let t=e.map(n=>`${n.Pattern??"bs"}_${n.Color??0}`).join(",");return`banner_${i}_${t}`}var qYe=(i,e,t=(n,r)=>yi(n,r))=>{let r=t(g4e*1,_4e*1),s=r.getContext("2d");if(!s){console.warn("Failed to get 2d context for banner rendering");return}if(s.imageSmoothingEnabled=!1,e?.Patterns&&e.Patterns.length>0)for(let a of e.Patterns){let o=a.Color??0,l=a.Pattern??"bs",c=y4e[o]||y4e[0];zYe(s,l,c,0,0,g4e*1,_4e*1)}return r},d9=new Map;function b4e(i,e,t){let n=VYe(e),r=HYe(n,t?.Patterns),s=d9.get(r);if(s)return s.refCount++,s.texture;let a=qYe(n,t);if(!a)return;let o=new sn(a);return o.magFilter=ct,o.minFilter=ct,o.needsUpdate=!0,d9.set(r,{texture:o,refCount:1}),o}function x4e(i){for(let[e,t]of d9.entries())if(t.texture===i){t.refCount--,t.refCount<=0&&(t.texture.dispose(),d9.delete(e));return}}function w4e(i,e,t,n,r=0,s=1,a=1){let u,d,f;t?(u=(-14.6+13.4)/2/16-.5,d=1-14.75/16-.5,f=1/2):(u=(1.4+29.4)/2/16,d=1-7.25/16-.5,f=0);let v=new _t({map:n,transparent:!0});v4e(v,r,s,a);let g=new Ke(new zn(.85,1.75),v);g.renderOrder=999;let b=.5/16,y=.25/16;t?g.position.set(0,u,d+y+.004):g.position.set(0,u,d+b/2+.004);let _=new bt;return _.rotation.set(0,-Ot.degToRad(e*(t?90:45/2)),0),_.add(g),_.bannerTexture=n,_.bannerMaterial=v,_.position.set(i.x+.5,i.y+f,i.z+.5),_}h();p();m();Lt();var S4e=Yr(V8(),1);var H5=new Map;function GYe(i,e,t){let n,r;return i&&"front_text"in i?(n=i.front_text?.messages??[],r=i.front_text?.color||"black"):(n=[i?.Text1,i?.Text2,i?.Text3,i?.Text4],r=i?.Color||"black"),`${e?1:0}|${t?1:0}|${r}|${n.join("\0")}`}function E4e(i,e,t,n=!1){let r=GYe(e,t,n),s=H5.get(r);if(s)return s.refCount++,s.texture;let a=(0,S4e.default)(i.version),o=k6e(e,t,a);if(!o)return;let l=new sn(o);return l.magFilter=ct,l.minFilter=ct,l.needsUpdate=!0,H5.set(r,{texture:l,refCount:1}),l}function M4e(i){for(let[e,t]of H5.entries())if(t.texture===i){t.refCount--,t.refCount<=0&&(t.texture.dispose(),H5.delete(e));return}}function A4e(){for(let[,i]of H5)i.texture.dispose();H5.clear()}var ro=class ro{constructor(e,t,n,r,s=3){this.worldRenderer=e;this.scene=t;this.material=n;this.worldHeight=r;this.updateViewDistance(s),this.signHeadsRenderer=new PP(e),this.initializePool()}renderOrigin={x:0,y:0,z:0};meshPool=[];activeSections=new Map;sectionObjects={};waitingChunksToDisplay={};pendingNearReveal=new Map;nearRevealTimers=new Map;nearRevealGraceTimers=new Map;poolSize;maxPoolSize;minPoolSize;signHeadsRenderer;blockEntityLightRegistry=new u9;chunkBoxMaterial=new _t({color:0,transparent:!0,opacity:0});cubeShaderMaterial=null;legacyShaderMaterial=null;globalLegacyShaderMaterial=null;globalLegacyBlendShaderMaterial=null;_legacyCullFrustum=new va;_legacyCullProjScreen=new Et;_legacyCullBox=new kn;_legacyCullBoxMin=new X;_legacyCullBoxMax=new X;_visibleSectionSpans=[];legacyCullSections=new Map;_lastCullFingerprint="";lastBufferStateKey="";cullDirty=!0;_lastCullCamPos=new X;_lastCullCamQuat=new qt;_cullViewQuat=new qt;_cullCamInitialized=!1;globalBlockBuffer=null;globalLegacyBuffer=null;globalLegacyBlendBuffer=null;shaderSectionRaycastBoxes=new Map;hits=0;misses=0;bypassPooling=!1;renderTimes=[];maxRenderTimeSamples=30;_performanceOverrideDistance;lastPerformanceCheck=0;performanceCheckInterval=2e3;get performanceOverrideDistance(){return this._performanceOverrideDistance??0}set performanceOverrideDistance(e){this._performanceOverrideDistance=e,this.updateSectionsVisibility()}initializePool(){for(let e=0;e<this.poolSize;e++){let t=new dt,n=new Ke(t,this.getLegacyShaderMaterial());n.visible=!1,n.matrixAutoUpdate=!1,n.name="pooled-section-mesh";let r={mesh:n,inUse:!1,lastUsedTime:0};this.meshPool.push(r)}}sectionHasRenderableContent(e){return e.positions.length>0||(e.blend?.positions.length??0)>0?!0:this.isShaderCubesGpuEnabled()?(e.shaderCubes?.count??0)>0:!1}isShaderCubesGpuEnabled(){return this.worldRenderer.shaderCubeBlocksEnabled()}syncCubeShaderUniforms(){if(!this.isShaderCubesGpuEnabled())return;let e=this.cubeShaderMaterial??this.getCubeShaderMaterial();if(!e)return;let t=this.material.map??null;e.uniforms.u_atlas.value=t;let n=n9();if(!n)return;let{tintPalette:r}=n;r.isReady()||r.createTexture(),e.uniforms.u_tintPalette.value=r.getTexture(),e.uniforms.u_debugMode.value=this.worldRenderer.worldRendererConfig.shaderCubeDebugMode??0,e.needsUpdate=!0}syncLegacyShaderUniforms(){let e=this.material.map??null;this.legacyShaderMaterial&&(this.legacyShaderMaterial.uniforms.u_atlas.value=e,this.legacyShaderMaterial.needsUpdate=!0),this.globalLegacyShaderMaterial&&(this.globalLegacyShaderMaterial.uniforms.u_atlas.value=e,this.globalLegacyShaderMaterial.needsUpdate=!0),this.globalLegacyBlendShaderMaterial&&(this.globalLegacyBlendShaderMaterial.uniforms.u_atlas.value=e,this.globalLegacyBlendShaderMaterial.needsUpdate=!0)}setSkyLevel(e){let t=this.cubeShaderMaterial??(this.isShaderCubesGpuEnabled()?this.getCubeShaderMaterial():null);t&&Jb(t,e),this.legacyShaderMaterial&&s9(this.legacyShaderMaterial,e),this.globalLegacyShaderMaterial&&s9(this.globalLegacyShaderMaterial,e),this.globalLegacyBlendShaderMaterial&&s9(this.globalLegacyBlendShaderMaterial,e),this.blockEntityLightRegistry.setSkyLevel(e)}setShadingTheme(e,t){let n=this.cubeShaderMaterial??(this.isShaderCubesGpuEnabled()?this.getCubeShaderMaterial():null);n&&bP(n,e,t)}setBlockLightmapParams(e){let t=this.cubeShaderMaterial??(this.isShaderCubesGpuEnabled()?this.getCubeShaderMaterial():null);t&&B_e(t,e),this.legacyShaderMaterial&&a9(this.legacyShaderMaterial,e),this.globalLegacyShaderMaterial&&a9(this.globalLegacyShaderMaterial,e),this.globalLegacyBlendShaderMaterial&&a9(this.globalLegacyBlendShaderMaterial,e),this.blockEntityLightRegistry.setLightmapParams(e)}getLegacyShaderMaterial(){return this.legacyShaderMaterial||(this.legacyShaderMaterial=$_e(),this.syncLegacyShaderUniforms()),this.legacyShaderMaterial}getGlobalLegacyShaderMaterial(){return this.globalLegacyShaderMaterial||(this.globalLegacyShaderMaterial=Y_e(),this.syncLegacyShaderUniforms()),this.globalLegacyShaderMaterial}getGlobalLegacyBuffer(){return this.globalLegacyBuffer||(this.globalLegacyBuffer=new ug(this.getGlobalLegacyShaderMaterial(),this.scene),this.globalLegacyBuffer.setRenderOrigin(this.renderOrigin)),this.globalLegacyBuffer}getGlobalLegacyBlendShaderMaterial(){return this.globalLegacyBlendShaderMaterial||(this.globalLegacyBlendShaderMaterial=J_e(),this.syncLegacyShaderUniforms()),this.globalLegacyBlendShaderMaterial}getGlobalLegacyBlendBuffer(){return this.globalLegacyBlendBuffer||(this.globalLegacyBlendBuffer=new ug(this.getGlobalLegacyBlendShaderMaterial(),this.scene,{name:"globalLegacyBlend",initialCapacityQuads:32e3,growthIncrementQuads:32e3}),this.globalLegacyBlendBuffer.setRenderOrigin(this.renderOrigin)),this.globalLegacyBlendBuffer}getRenderOrigin(){return this.renderOrigin}maybeRebase(e){let t=this.renderOrigin;if(Math.abs(e.x-t.x)<=ro.REBASE_THRESHOLD&&Math.abs(e.y-t.y)<=ro.REBASE_THRESHOLD&&Math.abs(e.z-t.z)<=ro.REBASE_THRESHOLD)return;let n={x:Math.round(e.x/16)*16,y:Math.round(e.y/16)*16,z:Math.round(e.z/16)*16},r={x:n.x-t.x,y:n.y-t.y,z:n.z-t.z};this.globalLegacyBuffer?.rebase(r),this.globalLegacyBlendBuffer?.rebase(r);for(let s of this.activeSections.values()){let a=s.sectionKey;if(!a)continue;let o=this.sectionObjects[a];o&&IP(s.mesh,o.worldX??0,o.worldY??0,o.worldZ??0,n)}this.renderOrigin=n,this.globalLegacyBuffer?.setRenderOrigin(n),this.globalLegacyBlendBuffer?.setRenderOrigin(n)}sectionUsesPooledLegacyMesh(e){return this.activeSections.has(e)}registerLegacyCullSection(e,t,n,r){this.legacyCullSections.set(e,{worldX:t,worldY:n,worldZ:r})}maybeUnregisterLegacyCullSection(e){let t=this.globalLegacyBuffer?.hasSection(e)??!1,n=this.globalLegacyBlendBuffer?.hasSection(e)??!1;!t&&!n&&this.legacyCullSections.delete(e)}updatePooledLegacyCullState(e,t,n){for(let r of this.activeSections.values()){let s=r.sectionKey;if(!s)continue;let a=this.sectionObjects[s];a&&K_e(r.mesh,a.worldX??0,a.worldY??0,a.worldZ??0,e,t,n,this._legacyCullFrustum,this._legacyCullBox,this._legacyCullBoxMin,this._legacyCullBoxMax)}}updateSectionCullAndSort(e,t,n,r){this._legacyCullProjScreen.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),this._legacyCullFrustum.setFromProjectionMatrix(this._legacyCullProjScreen);let s=this._visibleSectionSpans;s.length=0;for(let[b]of this.legacyCullSections){let y=this.sectionObjects[b];if(!y?.visible||y.worldX===void 0)continue;let{visible:_,distSq:x}=o9(y.worldX,y.worldY??0,y.worldZ??0,t,n,r,this._legacyCullFrustum,this._legacyCullBox,this._legacyCullBoxMin,this._legacyCullBoxMax);_&&s.push({key:b,distSq:x})}let a=this.globalLegacyBuffer,o=this.globalLegacyBlendBuffer,l=this.globalBlockBuffer,c=[];for(let b of s)a?.hasSection(b.key)&&c.push(b.key);c.sort();let u=s.filter(b=>o?.hasSection(b.key));u.sort((b,y)=>y.distSq-b.distSq);let d=u.map(b=>b.key),f=[],v=[];l&&l.forEachSectionSlot((b,y)=>{if(!this.sectionObjects[b]?.visible)return;let x=this.shaderSectionRaycastBoxes.get(b);if(!x)return;let{visible:w}=o9(x.sectionCenterX,x.sectionCenterY,x.sectionCenterZ,t,n,r,this._legacyCullFrustum,this._legacyCullBox,this._legacyCullBoxMin,this._legacyCullBoxMax);if(!w)return;f.push(b);let S=l.getSectionDrawStart(b),A=l.getSectionDrawCount(b);S!==void 0&&A!==void 0&&v.push({start:S,count:A})}),f.sort();let g=[c.join(","),d.join(","),f.join(","),a?.getLayoutVersion()??0,o?.getLayoutVersion()??0,l?.getLayoutVersion()??0,a?.getUploadEpoch()??0,o?.getUploadEpoch()??0,l?.getUploadEpoch()??0].join("|");if(g===this._lastCullFingerprint&&!this.hasPendingBufferWork()){this.updatePooledLegacyCullState(t,n,r);return}if(this._lastCullFingerprint=g,a?.updateDrawSpans(s,"opaque"),o?.updateDrawSpans(s,"sortedBlend"),l){let b=s4e(v,l.getHighWatermark(),l.canUseFullDrawShortcut(),(y,_)=>l.isRangeFullyUploaded(y,_),l.getPendingDirtyRanges());l.setVisibleSpans(b)}this.lastBufferStateKey=this.bufferStateKey(),this.updatePooledLegacyCullState(t,n,r)}bufferStateKey(){let e=this.globalBlockBuffer,t=this.globalLegacyBuffer,n=this.globalLegacyBlendBuffer;return[t?.getLayoutVersion()??0,t?.getUploadEpoch()??0,n?.getLayoutVersion()??0,n?.getUploadEpoch()??0,e?.getLayoutVersion()??0,e?.getUploadEpoch()??0].join("|")}markCullDirtyIfBufferStateChanged(){this.bufferStateKey()!==this.lastBufferStateKey&&this.markCullDirty()}markCullDirty(){this.cullDirty=!0}hasPendingBufferWork(){return[this.globalLegacyBuffer,this.globalLegacyBlendBuffer,this.globalBlockBuffer].some(t=>t!=null&&(t.hasPendingUploads()||t.hasPendingReplace()||t.getPendingMove()!=null))}updateCullDirtyFromCamera(e,t,n,r){if(e.getWorldQuaternion(this._cullViewQuat),!this._cullCamInitialized){this._lastCullCamPos.set(t,n,r),this._lastCullCamQuat.copy(this._cullViewQuat),this._cullCamInitialized=!0,this.cullDirty=!0;return}let s=this._lastCullCamPos.x!==t||this._lastCullCamPos.y!==n||this._lastCullCamPos.z!==r,a=this._lastCullCamQuat.x!==this._cullViewQuat.x||this._lastCullCamQuat.y!==this._cullViewQuat.y||this._lastCullCamQuat.z!==this._cullViewQuat.z||this._lastCullCamQuat.w!==this._cullViewQuat.w;(s||a)&&(this._lastCullCamPos.set(t,n,r),this._lastCullCamQuat.copy(this._cullViewQuat),this.markCullDirty())}clearCullDirty(){this.cullDirty=!1}setLegacyCameraOrigin(e,t,n){let r=this.renderOrigin;i9(this.getLegacyShaderMaterial(),r,e,t,n),i9(this.getGlobalLegacyShaderMaterial(),r,e,t,n),i9(this.getGlobalLegacyBlendShaderMaterial(),r,e,t,n),this.globalLegacyBuffer?.setCameraOrigin(e,t,n),this.globalLegacyBlendBuffer?.setCameraOrigin(e,t,n);let s=this.cubeShaderMaterial;if(s){let{originDelta:a,cameraOriginFrac:o}=$d(r,e,t,n),l=Kb(r),c=s.uniforms.u_originDelta;c?.value?.set&&c.value.set(a.x,a.y,a.z);let u=s.uniforms.u_cameraOriginFrac;u?.value?.set&&u.value.set(o.x,o.y,o.z);let d=s.uniforms.u_sectionOriginRel;d?.value?.set&&d.value.set(l.x,l.y,l.z)}}getCubeShaderMaterial(){if(!this.isShaderCubesGpuEnabled())return null;if(!this.cubeShaderMaterial){this.cubeShaderMaterial=Yb(),this.syncCubeShaderUniforms();let e=this.worldRenderer.worldRendererConfig;bP(this.cubeShaderMaterial,e.shadingTheme,e.cardinalLight)}return this.cubeShaderMaterial}getGlobalBlockBuffer(){let e=this.getCubeShaderMaterial();return e?(this.globalBlockBuffer||(this.globalBlockBuffer=new c9(e,this.scene)),this.globalBlockBuffer):null}shouldDeferLegacyOpaqueToPerSection(e){return this.shouldDeferShaderToPerSection(e)}shouldDeferShaderToPerSection(e){return this.worldRenderer.getModule("futuristicReveal")?.shouldDeferSectionGeometry?.(e)===!0}migrateDeferredShaderToGlobal(e){let t=this.sectionObjects[e];if(!t?.deferredShaderCubes)return;let{words:n,count:r}=t.deferredShaderCubes,s=t.worldX,a=t.worldY,o=t.worldZ;s!==void 0&&a!==void 0&&o!==void 0&&this.registerShaderSectionRaycastBox(e,n,r,s,a,o),this.getGlobalBlockBuffer()?.addSection(e,n,r),this.markCullDirty();let c=t.mesh===t.shaderMesh;t.shaderMesh&&(SP(t.shaderMesh),t.remove(t.shaderMesh),t.shaderMesh=void 0),delete t.deferredShaderCubes,c&&(t.mesh=void 0)}migrateDeferredLegacyToGlobal(e){let t=this.sectionObjects[e];if(t){if(t.deferredLegacyOpaque){let{positions:n,colors:r,skyLights:s,blockLights:a,uvs:o,indices:l}=t.deferredLegacyOpaque,c=t.worldX,u=t.worldY,d=t.worldZ;c!==void 0&&u!==void 0&&d!==void 0&&this.getGlobalLegacyBuffer().addSection(e,{positions:n,colors:r,skyLights:s,blockLights:a,uvs:o,indices:l},c,u,d)&&this.registerLegacyCullSection(e,c,u,d),delete t.deferredLegacyOpaque}if(t.deferredLegacyBlend){let{positions:n,colors:r,skyLights:s,blockLights:a,uvs:o,indices:l}=t.deferredLegacyBlend,c=t.worldX,u=t.worldY,d=t.worldZ;c!==void 0&&u!==void 0&&d!==void 0&&this.getGlobalLegacyBlendBuffer().addSection(e,{positions:n,colors:r,skyLights:s,blockLights:a,uvs:o,indices:l},c,u,d)&&this.registerLegacyCullSection(e,c,u,d),delete t.deferredLegacyBlend,t.hasBlendMesh=!1}if(!t.hasBlendMesh){let n=t.mesh===this.activeSections.get(e)?.mesh;this.releasePooledMesh(e),n&&(t.mesh=t.shaderMesh??void 0)}this.markCullDirty()}}registerShaderSectionRaycastBox(e,t,n,r,s,a){let o=h4e(t,n,r,s,a);o?this.shaderSectionRaycastBoxes.set(e,{box:o,sectionCenterX:r,sectionCenterY:s,sectionCenterZ:a}):this.shaderSectionRaycastBoxes.delete(e)}unregisterShaderSectionRaycastBox(e){this.shaderSectionRaycastBoxes.delete(e)}uploadLegacyPooledMesh(e,t,n,r,s){let{mesh:a}=e,o=t;return this.updateGeometryAttribute(a.geometry,"position",o.positions,3),this.updateGeometryAttribute(a.geometry,"normal",o.normals,3),this.updateGeometryAttribute(a.geometry,"color",o.colors,3),this.updateGeometryAttribute(a.geometry,"a_skyLight",o.skyLights,1),this.updateGeometryAttribute(a.geometry,"a_blockLight",o.blockLights,1),this.updateGeometryAttribute(a.geometry,"uv",o.uvs,2),a.geometry.index=new Mt(o.indices,1),a.geometry.boundingBox=new kn(new X(-8,-8,-8),new X(8,8,8)),a.geometry.boundingSphere=new Tn(new X(0,0,0),Math.sqrt(3*8**2)),IP(a,n,r,s,this.renderOrigin),a.visible=!1,a.name="mesh",e.lastUsedTime=performance.now(),a}acquirePooledSectionMesh(e){let t=this.activeSections.get(e);if(!t){if(t=this.acquireMesh(),!t)return console.warn(`ChunkMeshManager: No available mesh in pool for section ${e}`),null;this.activeSections.set(e,t),t.sectionKey=e}return t}updateSection(e,t){let n=t.positions.length>0,r=(t.blend?.positions.length??0)>0,s=n||r,a=t.shaderCubes,o=this.isShaderCubesGpuEnabled()&&(a?.count??0)>0,l=n&&this.shouldDeferLegacyOpaqueToPerSection(e),c=r&&this.shouldDeferLegacyOpaqueToPerSection(e),u=o&&this.shouldDeferShaderToPerSection(e),d=n&&!l,f=r&&!c,v=o&&!!a&&!u;if(!s&&!o)return this.releaseSection(e),null;let g=this.sectionObjects[e],b=g!=null;g&&this.cleanupSection(e,{forRemesh:!0}),b&&(v||this.globalBlockBuffer?.removeSection(e),d||this.globalLegacyBuffer?.removeSection(e),f||this.globalLegacyBlendBuffer?.removeSection(e),o&&a||this.unregisterShaderSectionRaycastBox(e),!d&&!f&&this.maybeUnregisterLegacyCullSection(e)),r||this.releasePooledMesh(e);let y,_,x,w=!1;if(n){let B={positions:t.positions,colors:t.colors,skyLights:t.skyLights,blockLights:t.blockLights,uvs:t.uvs,indices:t.indices};if(l){if(_={positions:new Float32Array(B.positions),colors:new Float32Array(B.colors),skyLights:new Float32Array(B.skyLights),blockLights:new Float32Array(B.blockLights),uvs:new Float32Array(B.uvs),indices:B.indices instanceof Uint32Array?new Uint32Array(B.indices):new Uint16Array(B.indices)},!r){let U=this.acquirePooledSectionMesh(e);if(!U)return null;y=this.uploadLegacyPooledMesh(U,t,t.sx,t.sy,t.sz)}}else if(this.getGlobalLegacyBuffer().addSection(e,B,t.sx,t.sy,t.sz))this.registerLegacyCullSection(e,t.sx,t.sy,t.sz);else{let O=this.acquirePooledSectionMesh(e);if(!O)return null;y=this.uploadLegacyPooledMesh(O,t,t.sx,t.sy,t.sz)}}if(r&&t.blend){let B={positions:t.blend.positions,colors:t.blend.colors,skyLights:t.blend.skyLights,blockLights:t.blend.blockLights,uvs:t.blend.uvs,indices:t.blend.indices};if(c){x={positions:new Float32Array(B.positions),colors:new Float32Array(B.colors),skyLights:new Float32Array(B.skyLights),blockLights:new Float32Array(B.blockLights),uvs:new Float32Array(B.uvs),indices:B.indices instanceof Uint32Array?new Uint32Array(B.indices):new Uint16Array(B.indices)};let U=this.acquirePooledSectionMesh(e);if(!U)return null;let O=this.uploadLegacyPooledMesh(U,t.blend,t.sx,t.sy,t.sz);y=y??O,w=!0}else if(this.getGlobalLegacyBlendBuffer().addSection(e,B,t.sx,t.sy,t.sz))this.registerLegacyCullSection(e,t.sx,t.sy,t.sz);else{console.warn(`ChunkMeshManager: blend invariant violation for section ${e}, using pooled mesh fallback`);let O=this.acquirePooledSectionMesh(e);if(!O)return null;let V=this.uploadLegacyPooledMesh(O,t.blend,t.sx,t.sy,t.sz);y=y??V,w=!0}}let S=o?this.getCubeShaderMaterial():null,A;o&&a&&(u&&S?(A=r9(a,S),A.visible=!0):this.getGlobalBlockBuffer()?.addSection(e,a.words,a.count)),g=new bt,y&&(g.add(y),g.mesh=y),A&&(g.add(A),g.shaderMesh=A,a&&(g.deferredShaderCubes={words:a.words,count:a.count}),g.mesh||(g.mesh=A)),_&&(g.deferredLegacyOpaque=_),x&&(g.deferredLegacyBlend=x),o&&a&&this.registerShaderSectionRaycastBox(e,a.words,a.count,t.sx,t.sy,t.sz);let T=0;n&&(T+=t.positions.length/3/4),r&&t.blend&&(T+=t.blend.positions.length/3/4),o&&a&&(T+=a.count),g.tilesCount=T,g.hasBlendMesh=w,g.blocksCount=t.blocksCount,g.worldX=t.sx,g.worldY=t.sy,g.worldZ=t.sz,g.sectionKey=e,g.name="chunk";try{if(Object.keys(t.signs).length>0){let B=new bt;B.name="signs";for(let[U,{isWall:O,isHanging:V,rotation:F}]of Object.entries(t.signs)){let J=this.worldRenderer.blockEntities[U];if(!J)continue;let[$,ne,se]=U.split(","),j=this.signHeadsRenderer.renderSign(new kt(+$,+ne,+se),F,O,V,f9.simplify(J));j&&B.add(j)}g.add(B),g.signsContainer=B}if(Object.keys(t.heads).length>0){let B=new bt;B.name="heads";for(let[U,{isWall:O,rotation:V}]of Object.entries(t.heads)){let F=this.worldRenderer.blockEntities[U];if(!F)continue;let[J,$,ne]=U.split(","),se=this.signHeadsRenderer.renderHead(new kt(+J,+$,+ne),V,O,f9.simplify(F));se&&B.add(se)}g.add(B),g.headsContainer=B}if(Object.keys(t.banners).length>0){let B=new bt;B.name="banners",g.bannersContainer=B,g.add(B);for(let[U,O]of Object.entries(t.banners)){let{isWall:V,rotation:F,blockName:J,blockLightNorm:$=0,skyLightNorm:ne=1}=O,se=this.worldRenderer.blockEntities[U];if(!se)continue;let[j,q,z]=U.split(","),K=b4e(this.worldRenderer,J,f9.simplify(se));if(!K)continue;let re=this.blockEntityLightRegistry.getSkyLevel(),Z=w4e(new kt(+j,+q,+z),F,V,K,$,ne,re);Z.bannerMaterial&&this.blockEntityLightRegistry.register({material:Z.bannerMaterial,blockLightNorm:$,skyLightNorm:ne});let{x:Y,y:Q,z:ue}=Z.position;this.worldRenderer.sceneOrigin.track(Z),Z.position.set(Y,Q,ue),B.add(Z)}}}catch(B){console.error("ChunkMeshManager: Error adding signs, heads, or banners to section",B)}this.sectionObjects[e]=g,this.scene.add(g),g.matrixAutoUpdate=!1,this.worldRenderer.displayOptions?.inWorldRenderingConfig?.showChunkBorders&&this.updateBoxHelper(e,!0);let P=e.split(","),I=`${P[0]},${P[2]}`,k=!!this.worldRenderer.displayOptions?.inWorldRenderingConfig?._renderByChunks,L=!!this.worldRenderer.worldRendererConfig?.wasmMesher;if((k||L)&&!this.worldRenderer.finishedChunks[I]){g.visible=!1,g._waitingForChunkDisplay=!0;let B=this.waitingChunksToDisplay[I]??(this.waitingChunksToDisplay[I]=[]);B.includes(e)||B.push(e)}return this.markCullDirty(),g}finishChunkDisplay(e){if(!this.waitingChunksToDisplay[e]){this.tryRevealPending();return}if(this.isWasmGateActive()&&this.isBlockedByNearer(e,0)){this.pendingNearReveal.set(e,Date.now()),this.armNearRevealTimer(e),this.armExpectedGraceTimer(e),this.tryRevealPending();return}this.flushChunkDisplay(e),this.tryRevealPending()}flushChunkDisplay(e){let t=this.waitingChunksToDisplay[e];if(this.pendingNearReveal.delete(e),this.clearNearRevealTimer(e),this.clearExpectedGraceTimer(e),!!t){for(let n of t){let r=this.sectionObjects[n];r&&(r._waitingForChunkDisplay=!1,r.visible=!0)}delete this.waitingChunksToDisplay[e],this.markCullDirty()}}tryRevealPending(){if(this.pendingNearReveal.size===0)return;let e=Date.now();for(let[t,n]of[...this.pendingNearReveal])this.isBlockedByNearer(t,e-n)||this.flushChunkDisplay(t)}onChunkRemovedFromGate(e){this.pendingNearReveal.delete(e),this.clearNearRevealTimer(e),this.clearExpectedGraceTimer(e),delete this.waitingChunksToDisplay[e],this.tryRevealPending()}isWasmGateActive(){return!!this.worldRenderer.worldRendererConfig?.wasmMesher}isBlockedByNearer(e,t){let n=this.worldRenderer.viewerChunkPosition;if(!n)return!1;let r=e.split(",");if(r.length!==2)return!1;let s=Number(r[0]),a=Number(r[1]),o=Math.floor(n.x/16),l=Math.floor(n.z/16),c=(s>>4)-o,u=(a>>4)-l,d=c*c+u*u;if(d===0)return!1;let f=this.worldRenderer.finishedChunks,v=this.worldRenderer.loadedChunks,g=this.worldRenderer.viewDistance;if(t<ro.EXPECTED_NEAR_GRACE_MS&&g>0){let y=g*g,_=Math.min(g,Math.ceil(Math.sqrt(Math.max(0,d-1))));for(let x=-_;x<=_;x++)for(let w=-_;w<=_;w++){let S=x*x+w*w;if(S>=d||S>y)continue;let A=o+x<<4,T=l+w<<4,P=`${A},${T}`;if(P!==e&&v[P]&&!f[P])return!0}return!1}for(let y in v){if(y===e||f[y])continue;let _=y.split(",");if(_.length!==2)continue;let x=(Number(_[0])>>4)-o,w=(Number(_[1])>>4)-l;if(x*x+w*w<d)return!0}return!1}armNearRevealTimer(e){if(this.nearRevealTimers.has(e))return;let t=setTimeout(()=>{this.nearRevealTimers.delete(e),this.pendingNearReveal.has(e)&&(console.warn(`[chunk-reveal] safety timeout for ${e} \u2014 a nearer pending column never finished, force-revealing`),this.flushChunkDisplay(e),this.tryRevealPending())},ro.NEAR_REVEAL_TIMEOUT_MS);this.nearRevealTimers.set(e,t)}clearNearRevealTimer(e){let t=this.nearRevealTimers.get(e);t&&(clearTimeout(t),this.nearRevealTimers.delete(e))}armExpectedGraceTimer(e){if(this.nearRevealGraceTimers.has(e))return;let t=setTimeout(()=>{this.nearRevealGraceTimers.delete(e),this.pendingNearReveal.has(e)&&this.tryRevealPending()},ro.EXPECTED_NEAR_GRACE_MS+50);this.nearRevealGraceTimers.set(e,t)}clearExpectedGraceTimer(e){let t=this.nearRevealGraceTimers.get(e);t&&(clearTimeout(t),this.nearRevealGraceTimers.delete(e))}cleanupSection(e,t){let n=this.sectionObjects[e];if(n){if(n._waitingForChunkDisplay){let r=e.split(","),s=`${r[0]},${r[2]}`,a=this.waitingChunksToDisplay[s];if(a){let o=a.indexOf(e);o!==-1&&a.splice(o,1),a.length===0&&delete this.waitingChunksToDisplay[s]}}if(n.bannersContainer){for(let r of n.bannersContainer.children){let s=r;s.bannerMaterial&&this.blockEntityLightRegistry.unregister(s.bannerMaterial),s.bannerTexture&&x4e(s.bannerTexture)}this.disposeContainer(n.bannersContainer)}if(t?.forRemesh||(this.globalBlockBuffer?.removeSection(e),this.globalLegacyBuffer?.removeSection(e),this.globalLegacyBlendBuffer?.removeSection(e),this.maybeUnregisterLegacyCullSection(e),this.unregisterShaderSectionRaycastBox(e)),this.markCullDirty(),delete n.deferredLegacyOpaque,delete n.deferredLegacyBlend,n.shaderMesh&&(SP(n.shaderMesh),n.shaderMesh=void 0),delete n.deferredShaderCubes,n.signsContainer){for(let r of n.signsContainer.children){let s=r;s.signTexture&&M4e(s.signTexture)}this.disposeContainer(n.signsContainer,!1)}if(n.headsContainer&&this.disposeContainer(n.headsContainer),this.worldRenderer.sceneOrigin.removeAndUntrackAll(n),this.scene.remove(n),n.boxHelper){this.worldRenderer.sceneOrigin.removeAndUntrack(n.boxHelper),this.scene.remove(n.boxHelper),n.boxHelper.geometry.dispose();let r=n.boxHelper.material;if(Array.isArray(r))for(let s of r)s.dispose();else r.dispose();n.boxHelper=void 0}delete this.sectionObjects[e],t?.forRemesh||this.worldRenderer.getModule("futuristicReveal")?.onSectionRemoved?.(e)}}releasePooledMesh(e){let t=this.activeSections.get(e);t&&(t.mesh.visible=!1,t.inUse=!1,t.sectionKey=void 0,t.lastUsedTime=0,this.clearGeometry(t.mesh.geometry),this.activeSections.delete(e),this.cleanupExcessMeshes())}releaseSection(e){this.cleanupSection(e);let t=this.activeSections.get(e);return t?(t.mesh.visible=!1,t.inUse=!1,t.sectionKey=void 0,t.lastUsedTime=0,this.clearGeometry(t.mesh.geometry),this.activeSections.delete(e),this.cleanupExcessMeshes(),!0):!1}getSectionObject(e){return this.sectionObjects[e]}updateBoxHelper(e,t,n=this.chunkBoxMaterial){let r=this.sectionObjects[e];if(r)if(t){if(!r.boxHelper){let s=new Ke(new Sn(16,16,16),n),a=new Ea(s,16776960);a.name="helper";let o=r.worldX??0,l=r.worldY??0,c=r.worldZ??0;this.worldRenderer.sceneOrigin.track(a,{updateMatrix:!0}),a.position.set(o,l,c),a.updateMatrix(),this.scene.add(a),r.boxHelper=a}r.boxHelper.visible=!0}else r.boxHelper&&(r.boxHelper.visible=!1)}updateAllBoxHelpers(e){for(let t of Object.keys(this.sectionObjects))this.updateBoxHelper(t,e)}getSectionMesh(e){return this.activeSections.get(e)?.mesh}hasSection(e){return this.activeSections.has(e)}updateViewDistance(e){let t=(e*2+1)**2,n=this.worldHeight/16,r=5;if(this.minPoolSize=Math.floor(t*r),this.maxPoolSize=Math.floor(t*n)+1,this.poolSize??=this.minPoolSize,this.minPoolSize>this.poolSize){let s=Math.min(this.minPoolSize,this.maxPoolSize);this.expandPool(s)}console.log(`ChunkMeshManager: Updated view max distance to ${e}, pool: ${this.poolSize}/${this.maxPoolSize}, optimal: ${this.minPoolSize}`)}getGlobalBufferStats(){let e=n=>n?{used:n.getHighWatermark(),capacity:n.getCapacityQuads(),sections:n.getSectionCount(),usedBytes:n.getUsedMemoryBytes(),capacityBytes:n.getMemoryBytes()}:null,t=this.globalBlockBuffer;return{shaderFaces:t?{used:t.getHighWatermark(),capacity:t.getCapacityFaces(),sections:t.getSectionCount(),usedBytes:t.getUsedMemoryBytes(),capacityBytes:t.getMemoryBytes()}:null,legacyOpaque:e(this.globalLegacyBuffer),legacyBlend:e(this.globalLegacyBlendBuffer)}}getStats(){let e=this.meshPool.filter(r=>!r.inUse).length,t=this.hits+this.misses>0?(this.hits/(this.hits+this.misses)*100).toFixed(1):"0",n=this.getEstimatedMemoryUsage();return{poolSize:this.poolSize,activeCount:this.activeSections.size,freeCount:e,hitRate:`${t}%`,hits:this.hits,misses:this.misses,memoryUsage:n}}getTotalTiles(){return Object.values(this.sectionObjects).reduce((e,t)=>e+(t.tilesCount||0),0)}getTotalBlocks(){return Object.values(this.sectionObjects).reduce((e,t)=>e+(t.blocksCount||0),0)}getEstimatedMemoryUsage(){let e=0,t=0,n=0,r=0,s=0,a=0,o=0,l=this.globalBlockBuffer?.mesh.geometry;if(l)for(let f of["a_w0","a_w1","a_w2","a_w3"]){let v=l.getAttribute(f);if(v){let g=v.array.byteLength;o+=g,e+=g}}let c=this.globalLegacyBuffer?.getMemoryBytes()??0,u=this.globalLegacyBlendBuffer?.getMemoryBytes()??0;e+=c+u,t+=c+u;for(let f of Object.values(this.sectionObjects)){let v=f.shaderMesh?.geometry;if(v)for(let g of["a_w0","a_w1","a_w2","a_w3"]){let b=v.getAttribute(g);if(b){let y=b.array.byteLength;o+=y,e+=y}}}for(let f of this.meshPool)if(f.inUse&&f.mesh.geometry){let{geometry:v}=f.mesh,g=v.getAttribute("position");if(g){let x=g.array.byteLength;t+=x,e+=x}let b=v.getAttribute("normal");if(b){let x=b.array.byteLength;n+=x,e+=x}let y=v.getAttribute("color");if(y){let x=y.array.byteLength;r+=x,e+=x}let _=v.getAttribute("uv");if(_){let x=_.array.byteLength;s+=x,e+=x}if(v.index){let x=v.index.array.byteLength;a+=x,e+=x}}return{total:`${(e/(1024*1024)).toFixed(2)} MB`,breakdown:{position:`${(t/(1024*1024)).toFixed(2)} MB`,normal:`${(n/(1024*1024)).toFixed(2)} MB`,color:`${(r/(1024*1024)).toFixed(2)} MB`,uv:`${(s/(1024*1024)).toFixed(2)} MB`,index:`${(a/(1024*1024)).toFixed(2)} MB`,shaderInstances:`${(o/(1024*1024)).toFixed(2)} MB`}}}dispose(){let e=[...this.activeSections.keys()];for(let t of e)this.releaseSection(t);this.signHeadsRenderer.dispose();for(let t of this.meshPool)t.mesh.geometry.dispose();this.meshPool.length=0,this.activeSections.clear(),this.chunkBoxMaterial.dispose(),this.shaderSectionRaycastBoxes.clear(),this.lastBufferStateKey="",this.globalBlockBuffer?.dispose(),this.globalBlockBuffer=null,this.globalLegacyBuffer?.dispose(),this.globalLegacyBuffer=null,this.globalLegacyBlendBuffer?.dispose(),this.globalLegacyBlendBuffer=null,this.cubeShaderMaterial?.dispose(),this.cubeShaderMaterial=null,this.legacyShaderMaterial?.dispose(),this.legacyShaderMaterial=null,this.globalLegacyShaderMaterial?.dispose(),this.globalLegacyShaderMaterial=null,this.globalLegacyBlendShaderMaterial?.dispose(),this.globalLegacyBlendShaderMaterial=null,this.pendingNearReveal.clear();for(let t of this.nearRevealTimers.values())clearTimeout(t);this.nearRevealTimers.clear();for(let t of this.nearRevealGraceTimers.values())clearTimeout(t);this.nearRevealGraceTimers.clear()}acquireMesh(){if(this.bypassPooling){let t={mesh:new Ke(new dt,this.getLegacyShaderMaterial()),inUse:!0,lastUsedTime:performance.now()};return this.meshPool.push(t),this.poolSize++,t}for(let t of this.meshPool)if(!t.inUse)return t.inUse=!0,t.lastUsedTime=performance.now(),this.hits++,t;this.misses++;let e=Math.min(this.poolSize+16,this.maxPoolSize);e<=this.meshPool.length&&(e=this.meshPool.length+8,this.maxPoolSize=e,console.warn(`ChunkMeshManager: Pool exhausted (${this.poolSize}/${this.maxPoolSize}). Emergency expansion to ${e}`)),this.expandPool(e);for(let t=this.meshPool.length-1;t>=0;t--){let n=this.meshPool[t];if(!n.inUse)return n.inUse=!0,n.lastUsedTime=performance.now(),n}throw new Error("ChunkMeshManager: Failed to acquire mesh after pool expansion")}expandPool(e){let t=this.meshPool.length;this.poolSize=e;for(let n=t;n<e;n++){let r=new dt,s=new Ke(r,this.getLegacyShaderMaterial());s.visible=!1,s.matrixAutoUpdate=!1,s.name="pooled-section-mesh";let a={mesh:s,inUse:!1,lastUsedTime:0};this.meshPool.push(a)}}updateGeometryAttribute(e,t,n,r){let s=e.getAttribute(t);s&&s.count===n.length/r?(s.array.set(n),s.needsUpdate=!0):e.setAttribute(t,new Mt(n,r))}clearGeometry(e){let t=["position","normal","color","a_skyLight","a_blockLight","uv"];for(let n of t)e.hasAttribute(n)&&e.deleteAttribute(n);e.index&&e.setIndex(null),e.boundingBox=null,e.boundingSphere=null}cleanupExcessMeshes(){if(this.poolSize>this.maxPoolSize){let e=this.meshPool.filter(t=>!t.inUse).length;if(e>0){let t=Math.min(this.poolSize-this.maxPoolSize,e);for(let n=0;n<t;n++){let r=this.meshPool.findIndex(s=>!s.inUse);r!==-1&&(this.meshPool[r].mesh.geometry.dispose(),this.meshPool.splice(r,1),this.poolSize--)}}}}disposeContainer(e,t=!0){dr(e,t)}recordRenderTime(e){this.renderTimes.push(e),this.renderTimes.length>this.maxRenderTimeSamples&&this.renderTimes.shift();let t=performance.now();t-this.lastPerformanceCheck>this.performanceCheckInterval&&(this.checkPerformance(),this.lastPerformanceCheck=t)}getEffectiveRenderDistance(){return this.performanceOverrideDistance||this.worldRenderer.viewDistance}resetPerformanceOverride(){this.performanceOverrideDistance=void 0,this.renderTimes.length=0,console.log("ChunkMeshManager: Performance override reset")}getAverageRenderTime(){return this.renderTimes.length===0?0:this.renderTimes.reduce((e,t)=>e+t,0)/this.renderTimes.length}checkPerformance(){if(this.renderTimes.length<this.maxRenderTimeSamples)return;let e=this.getAverageRenderTime(),t=16.67,n=t*1.5;if(e>n){let r=this.worldRenderer.viewDistance,s=Math.max(1,Math.floor(r*.8));(!this.performanceOverrideDistance||s<this.performanceOverrideDistance)&&(this.performanceOverrideDistance=s,console.warn(`ChunkMeshManager: Performance degraded (${e.toFixed(2)}ms avg). Reducing effective render distance to ${s}`))}else if(this.performanceOverrideDistance&&e<t*1.1){let r=this.worldRenderer.viewDistance,s=Math.min(r,this.performanceOverrideDistance+1);s!==this.performanceOverrideDistance&&(this.performanceOverrideDistance=s>=r?void 0:s,console.log(`ChunkMeshManager: Performance improved. Restoring render distance to ${s}`))}}updateSectionsVisibility(){let e=this.worldRenderer.cameraSectionPos;for(let[t,n]of Object.entries(this.sectionObjects)){if(n._waitingForChunkDisplay){n.visible=!1;continue}if(!this.performanceOverrideDistance){n.visible=!0;continue}let[r,s,a]=t.split(",").map(Number),o={x:r/16,y:s/16,z:a/16},l=o.x-e.x,c=o.z-e.z,u=Math.floor(Math.hypot(l,c));n.visible=u<=this.performanceOverrideDistance}}};Wn(ro,"REBASE_THRESHOLD",65536),Wn(ro,"NEAR_REVEAL_TIMEOUT_MS",5e3),Wn(ro,"EXPECTED_NEAR_GRACE_MS",1500);var fg=ro,PP=class{constructor(e){this.worldRendererThree=e}dispose(){A4e()}renderHead(e,t,n,r){let s;if(r.SkullOwner?s=r.SkullOwner.Properties?.textures?.[0]?.Value:s=r.profile?.properties?.find(a=>a.name==="textures")?.value,!!s)try{let o=JSON.parse(Buffer.from(s,"base64").toString()).textures?.SKIN?.url,{skinTexturesProxy:l}=this.worldRendererThree.worldRendererConfig;l&&(o=o?.replace("http://textures.minecraft.net/",l).replace("https://textures.minecraft.net/",l));let c=$c(this.worldRendererThree,o,Yc.head),u=new bt;return n&&c.position.set(0,.3125,.3125),c.position.y-=23/16,u.add(c),this.worldRendererThree.sceneOrigin.track(u),u.position.set(e.x+.5,e.y+.045,e.z+.5),u.rotation.set(0,-Ot.degToRad(t*(n?90:45/2)),0),u.scale.set(.8,.8,.8),u}catch(a){console.error("Error decoding player texture:",a)}}renderSign(e,t,n,r,s){let a=E4e(this.worldRendererThree,s,r);if(!a)return;let o=new Ke(new zn(1,1),new _t({map:a,transparent:!0}));o.renderOrder=999;let l=7/16,c=r?1.3:1;o.scale.set(1*c,l*c,1*c);let u=(r?2:1.5)/16,d=.25/16;n&&!r?o.position.set(0,0,-.5+u+d+1e-4):o.position.set(0,0,u/2+1e-4);let f=new bt;f.rotation.set(0,-Ot.degToRad(t*(n?90:45/2)),0),f.add(o),f.signTexture=a;let v=(r?10:8)/16,g=(r?0:n?4.333:9.333)/16,b=v/2+g;return this.worldRendererThree.sceneOrigin.track(f),f.position.set(e.x+.5,e.y+b,e.z+.5),f}};h();p();m();var h9=(i,e)=>e===0?1/0:e<0?h9(-i,-e):(1-(i-Math.floor(i)))/e,WYe=(i,e,t,n,r,s,a,o,l,c,u,d)=>{let f=a-u,v=o-u,g=l-u,b=a+1+u,y=o+1+u,_=l+1+u,x=m4e(i,e,t,n,r,s,f,v,g,b,y,_,c);if(x===void 0&&(x=p4e(i,e,t,n,r,s,f,v,g,b,y,_,c)),x!==void 0)return Math.max(d,x)};function k4e(i,e,t,n,r,s,a,o,l,c){if(a<=0)return;let u=Math.floor(i),d=Math.floor(e),f=Math.floor(t),v=n>0?1:n<0?-1:0,g=r>0?1:r<0?-1:0,b=s>0?1:s<0?-1:0,y=v!==0?Math.abs(1/n):1/0,_=g!==0?Math.abs(1/r):1/0,x=b!==0?Math.abs(1/s):1/0,w=v!==0?h9(i,n):1/0,S=g!==0?h9(e,r):1/0,A=b!==0?h9(t,s):1/0,T=(k,L,B)=>{if(!c(k,L,B))return;let U=WYe(i,e,t,n,r,s,k,L,B,a,o,l);if(!(U===void 0||U>a))return{distance:U,blockX:k,blockY:L,blockZ:B}},P=T(u,d,f);if(P)return P;let I=0;for(;I<=a&&(w<S?w<A?(u+=v,I=w,w+=y):(f+=b,I=A,A+=x):S<A?(d+=g,I=S,S+=_):(f+=b,I=A,A+=x),!(I>a));)if(P=T(u,d,f),P)return P}h();p();m();h();p();m();Lt();var m9={},T4e=!1;function jYe(){if(T4e)return;let i=globalThis.loadedData?.tints;if(i){for(let e of Object.keys(i))m9[e]=XYe(i[e]);T4e=!0}}function XYe(i){let e={},t=I4e(i.default??16777215);if(i.data)for(let n of i.data){let r=I4e(n.color);for(let s of n.keys)e[s]=r}return new Proxy(e,{get(n,r){return n[r]??t}})}function I4e(i){return[(i>>16&255)/255,(i>>8&255)/255,(i&255)/255]}function R4e(i,e){return jYe(),i==="grass_block"?[1,1,1]:i==="redstone_wire"?[1,1,1]:i==="birch_leaves"||i==="spruce_leaves"||i==="lily_pad"?m9.constant?.[i]??[1,1,1]:i.includes("leaves")||i==="vine"?m9.foliage?.[e]??[1,1,1]:["short_grass","tall_grass","fern","large_fern","sugar_cane","grass"].includes(i)?m9.grass?.[e]??[1,1,1]:[1,1,1]}var $Ye=512,LP=1/20,BP=class{constructor(e){this.worldRenderer=e}particles=[];sharedMaterial;enabled=!1;tickAccumulator=0;nextParticleIndex=0;enable(){this.enabled||(this.enabled=!0,this.ensureMaterial())}disable(){this.enabled&&(this.enabled=!1)}dispose(){for(let e of this.particles)e.active&&this.worldRenderer.sceneOrigin.removeAndUntrack(e.mesh),e.mesh.geometry.dispose();this.particles=[],this.sharedMaterial?.dispose(),this.sharedMaterial=void 0,this.nextParticleIndex=0}render=e=>{if(!this.enabled)return;for(this.tickAccumulator+=e;this.tickAccumulator>=LP;)this.tickAccumulator-=LP,this.tickPhysics();let t=this.tickAccumulator/LP;this.updateVisuals(t)};spawnBlockBreakParticles(e,t,n,r,s,a="plains"){if(!this.enabled)return;let o=this.resolveBlockTexture(r);if(!o)return;let l=R4e(r,a);for(let c=0;c<4;c++)for(let u=0;u<4;u++)for(let d=0;d<4;d++){let f=e+(c+.5)/4,v=t+(u+.5)/4,g=n+(d+.5)/4,b=f-e-.5,y=v-t-.5,_=g-n-.5;b+=(Math.random()*2-1)*.4,y+=(Math.random()*2-1)*.4,_+=(Math.random()*2-1)*.4;let x=(Math.random()+Math.random()+1)*.15,w=Math.sqrt(b*b+y*y+_*_),S=b/w*x*.4,A=y/w*x*.4+.1,T=_/w*x*.4,P=Math.floor(4/(Math.random()*.9+.1));this.createParticle(f,v,g,S,A,T,P,o,s,e,n,1,l)}}tickPhysics(){for(let e of this.particles){if(!e.active)continue;if(e.prevX=e.x,e.prevY=e.y,e.prevZ=e.z,e.age++,e.age>=e.maxAge){this.deactivateParticle(e);continue}e.yd-=.04,e.x+=e.xd,e.y+=e.yd,e.z+=e.zd;let t=this.getFloorY(e);e.y<=t?(e.y=t,e.yd=0,e.onGround=!0):e.onGround=!1,e.xd*=.98,e.yd*=.98,e.zd*=.98,e.onGround&&(e.xd*=.7,e.zd*=.7)}}updateVisuals(e){let t=this.worldRenderer.camera.position;for(let n of this.particles){if(!n.active)continue;let r=n.prevX+(n.x-n.prevX)*e,s=n.prevY+(n.y-n.prevY)*e,a=n.prevZ+(n.z-n.prevZ)*e;n.mesh.position.set(r,s,a),n.mesh.lookAt(t.x,t.y,t.z)}}spawnCrackParticle(e,t,n,r,s,a,o="plains"){if(!this.enabled)return;let l=this.resolveBlockTexture(s);if(!l)return;let c=R4e(s,o),u=e+Math.random()*.8+.1,d=t+Math.random()*.8+.1,f=n+Math.random()*.8+.1;switch(r){case 0:d=t-.1;break;case 1:d=t+1+.1;break;case 2:f=n-.1;break;case 3:f=n+1+.1;break;case 4:u=e-.1;break;case 5:u=e+1+.1;break}let v=(Math.random()*2-1)*.4*.2,g=(Math.random()*2-1)*.4*.2+.1*.2,b=(Math.random()*2-1)*.4*.2,y=Math.floor(4/(Math.random()*.9+.1));this.createParticle(u,d,f,v,g,b,y,l,a,e,n,.6,c)}createParticle(e,t,n,r,s,a,o,l,c,u,d,f=1,v=[1,1,1]){this.ensureMaterial();let g=this.findInactiveParticle();g||(this.particles.length<$Ye?g=this.allocateParticle():g=this.recycleOldest());let b=Math.floor(Math.random()*4),y=Math.floor(Math.random()*4),_=l.u+b/4*l.su,x=l.v+y/4*l.sv,w=l.su/4,S=l.sv/4;this.setGeometryUVs(g.mesh.geometry,_,x,w,S),g.active=!0,g.x=e,g.y=t,g.z=n,g.prevX=e,g.prevY=t,g.prevZ=n,g.xd=r,g.yd=s,g.zd=a,g.age=0,g.maxAge=o,g.onGround=!1,g.floorMap=c,g.blockX=Math.floor(u),g.blockZ=Math.floor(d);let A=.1*(.5+Math.random()*.5)*2*f;g.mesh.scale.set(A,A,A),g.mesh.position.set(e,t,n),g.mesh.visible=!0;let T=.6*v[0],P=.6*v[1],I=.6*v[2],k=new Float32Array([T,P,I,T,P,I,T,P,I,T,P,I]),L=g.mesh.geometry.getAttribute("color");L?(L.set(k),L.needsUpdate=!0):g.mesh.geometry.setAttribute("color",new Je(k,3)),this.worldRenderer.sceneOrigin.addAndTrack(g.mesh)}allocateParticle(){let e=new zn(1,1),t=new Ke(e,this.sharedMaterial);t.visible=!1;let n={mesh:t,active:!1,x:0,y:0,z:0,prevX:0,prevY:0,prevZ:0,xd:0,yd:0,zd:0,age:0,maxAge:0,onGround:!1,floorMap:[],blockX:0,blockZ:0};return this.particles.push(n),n}findInactiveParticle(){for(let e=0;e<this.particles.length;e++){let t=(this.nextParticleIndex+e)%this.particles.length;if(!this.particles[t].active)return this.nextParticleIndex=(t+1)%this.particles.length,this.particles[t]}}recycleOldest(){let e=this.particles[0];for(let t of this.particles)t.age>e.age&&(e=t);return this.deactivateParticle(e),e}deactivateParticle(e){e.active&&(e.active=!1,e.mesh.visible=!1,this.worldRenderer.sceneOrigin.removeAndUntrack(e.mesh))}getFloorY(e){let t=Math.floor(e.x)-e.blockX,n=Math.floor(e.z)-e.blockZ;return t=Math.max(-2,Math.min(2,t)),n=Math.max(-2,Math.min(2,n)),e.floorMap[(n+2)*5+(t+2)]}resolveBlockTexture(e){let t=this.worldRenderer.resourcesManager.currentResources;if(!t)return null;let n=t.blocksAtlasJson,r=n.textures;if(r[e])return this.extractUV(r[e],n);for(let s of["_side","_top","_front","_0",""]){let a=e+s;if(r[a])return this.extractUV(r[a],n)}for(let s of Object.keys(r))if(s.startsWith(e))return this.extractUV(r[s],n);return null}extractUV(e,t){return{u:e.u,v:e.v,su:e.su??t.suSv,sv:e.sv??t.suSv}}setGeometryUVs(e,t,n,r,s){let a=e.getAttribute("uv");a.setXY(0,t,n),a.setXY(1,t+r,n),a.setXY(2,t,n+s),a.setXY(3,t+r,n+s),a.needsUpdate=!0}ensureMaterial(){if(this.sharedMaterial)return;let e=this.worldRenderer.material.map;e&&(this.sharedMaterial=new _t({map:e,vertexColors:!0,transparent:!0,alphaTest:.1}))}},C4e={id:"blockBreakParticles",controller:BP,enabledDefault:!0,cannotBeDisabled:!0,requiresHeightmap:!1};h();p();m();var DP=class{constructor(e){this.worldRenderer=e}enabled=!1;lastBobWalkDist=0;lastBobTickTime=0;enable(){this.enabled=!0}disable(){this.enabled=!1,this.worldRenderer.cameraShake.setCameraBobInput(null);let{perspective:e}=this.worldRenderer.playerStateReactive;e==="first_person"&&this.worldRenderer.camera.position.set(0,0,0)}render=()=>{if(!this.enabled)return;let e=this.worldRenderer.displayOptions.inWorldRenderingConfig,{perspective:t}=this.worldRenderer.playerStateReactive;if(e.viewBobbing&&t==="first_person"&&!this.worldRenderer.playerStateUtils.isSpectator()){this.worldRenderer.playerStateReactive.walkDist!==this.lastBobWalkDist&&(this.lastBobTickTime=performance.now(),this.lastBobWalkDist=this.worldRenderer.playerStateReactive.walkDist);let r=Math.min((performance.now()-this.lastBobTickTime)/50,1);this.worldRenderer.cameraShake.setCameraBobInput({walkDist:this.worldRenderer.playerStateReactive.walkDist,prevWalkDist:this.worldRenderer.playerStateReactive.prevWalkDist,bob:this.worldRenderer.playerStateReactive.bob,prevBob:this.worldRenderer.playerStateReactive.prevBob,partialTick:r})}else this.worldRenderer.cameraShake.setCameraBobInput(null)};dispose(){this.disable()}},P4e={id:"cameraBobbing",controller:DP,enabledDefault:!0,cannotBeDisabled:!0};h();p();m();Lt();var OP=2e3,L4e=32,B4e=32,p9=12,D4e=24,v9=1.2,YYe=-5,NP=class{constructor(e){this.worldRenderer=e;this.configUnsubs.push(this.worldRenderer.onReactiveConfigUpdated("rainColor",()=>this.syncRainAppearance()),this.worldRenderer.onReactiveConfigUpdated("rainOpacity",()=>this.syncRainAppearance()))}instancedMesh;geometry;material;particles=[];enabled=!1;dummy=new Et;tempPosition=new X;tempQuaternion=new qt;tempScale=new X;configUnsubs=[];enable(){this.enabled||(this.enabled=!0,this.instancedMesh?(this.instancedMesh.visible=!0,this.syncRainAppearance()):this.createRain())}disable(){this.enabled&&(this.enabled=!1,this.instancedMesh&&(this.instancedMesh.visible=!1))}autoEnableCheck(){return this.worldRenderer.worldRendererConfig.isRaining===!0}render=e=>{if(!this.enabled||!this.instancedMesh||!this.material)return;let t=this.worldRenderer.getCameraPosition();this.instancedMesh.position.set(0,0,0);let n=this.worldRenderer.reactiveState.world.heightmaps,{dummy:r,tempPosition:s,tempQuaternion:a,tempScale:o}=this,l=NaN,c=NaN,u;for(let d=0;d<OP;d++){let f=this.particles[d];this.instancedMesh.getMatrixAt(d,r),r.decompose(s,a,o),s.addScaledVector(f.velocity,e);let v=s.y,g=Math.sqrt(s.x*s.x+s.z*s.z),b=t.x+s.x,y=t.y+s.y,_=t.z+s.z,x=Math.floor(b/16),w=Math.floor(_/16);(x!==l||w!==c)&&(u=n[`${x},${w}`],l=x,c=w);let S=(Math.floor(b)%16+16)%16,A=(Math.floor(_)%16+16)%16,T=u?.[A*16+S];if(g>L4e||T!==void 0&&T!==-32768&&y<=T+1+f.despawnOffset||v<YYe){this.respawnParticle(s);let I=p9+Math.random()*(D4e-p9);f.velocity.set((Math.random()-.5)*v9,-I,(Math.random()-.5)*v9),f.despawnOffset=Math.random()*.5}r.compose(s,a,o),this.instancedMesh.setMatrixAt(d,r)}this.instancedMesh.instanceMatrix.needsUpdate=!0};dispose(){for(let e of this.configUnsubs)e();this.configUnsubs.length=0,this.instancedMesh&&this.worldRenderer.scene.remove(this.instancedMesh),this.geometry?.dispose(),this.material?.dispose(),this.instancedMesh=void 0,this.geometry=void 0,this.material=void 0,this.particles=[]}syncRainAppearance(){if(!this.material)return;let{rainColor:e,rainOpacity:t}=this.worldRenderer.worldRendererConfig;this.material.color.set(e),this.material.opacity=Math.max(0,Math.min(1,t)),this.material.needsUpdate=!0}createRain(){let{rainColor:e,rainOpacity:t}=this.worldRenderer.worldRendererConfig;this.geometry=new Sn(.03,.3,.03),this.material=new _t({color:e,transparent:!0,opacity:Math.max(0,Math.min(1,t)),depthWrite:!0,fog:!1}),this.instancedMesh=new cl(this.geometry,this.material,OP),this.instancedMesh.name="rain-particles",this.instancedMesh.frustumCulled=!1;let n=new Et,r=new X;for(let s=0;s<OP;s++){this.respawnParticle(r),r.y=Math.random()*B4e,n.setPosition(r),this.instancedMesh.setMatrixAt(s,n);let a=p9+Math.random()*(D4e-p9);this.particles.push({velocity:new X((Math.random()-.5)*v9,-a,(Math.random()-.5)*v9),age:0,despawnOffset:Math.random()*.5})}this.instancedMesh.instanceMatrix.needsUpdate=!0,this.worldRenderer.scene.add(this.instancedMesh)}respawnParticle(e){let t=Math.random()*Math.PI*2,n=Math.random()*L4e;e.set(Math.cos(t)*n,B4e,Math.sin(t)*n)}},O4e={id:"rain",controller:NP,enabledDefault:!1,requiresHeightmap:!0};h();p();m();Lt();var N4e=new We(13/255,234/255,238/255),JYe=9,KYe=12e3,ZYe=1500,QYe=1e4,eJe=350,tJe=650,U4e=120,F4e=280,UP=class{constructor(e){this.worldRenderer=e;e.worldRendererConfig.futuristicReveal!==!0&&(this.enabled=!1)}enabled=!0;sections=new Map;completed=new Set;globalWaveStarted=!1;globalWaveStartMs=0;finishedChunkCount=0;firstQueuedMs=null;pulseTime=0;wireframeMaterial=new Pn({color:N4e,transparent:!0,opacity:1,blending:es,depthWrite:!1});wireframeGlowMaterial=new Pn({color:N4e,transparent:!0,opacity:.55,blending:es,depthWrite:!1});autoEnableCheck(){return this.worldRenderer.worldRendererConfig.futuristicReveal===!0}enable(){this.autoEnableCheck()&&this.setEnabled(!0)}disable(){this.setEnabled(!1)}dispose(){this.reset(),this.wireframeMaterial.dispose(),this.wireframeGlowMaterial.dispose()}shouldDeferSectionGeometry(e){return this.enabled&&!this.completed.has(e)}onSectionMeshed(e,t,n){let r=n.children.find(s=>s.name==="mesh");r instanceof Ke&&this.onSectionMeshedMesh(e,t,r)}onChunkFinished(){this.enabled&&(this.finishedChunkCount++,this.tryStartGlobalWave(performance.now()))}onSectionRemoved(e){this.cancelSection(e,!0),this.completed.delete(e)}onWorldSwitched(){this.reset()}tick(e,t=performance.now()){if(!this.enabled||(this.tryStartGlobalWave(t),!this.globalWaveStarted&&this.firstQueuedMs!==null&&this.sections.size>0&&t-this.firstQueuedMs>=KYe&&this.startGlobalWave(t),this.sections.size===0))return;this.pulseTime+=e*.001;let n=[];for(let r of this.sections.values()){if(t-r.phaseStartMs>QYe){n.push(r);continue}if(r.phase==="queued"){this.globalWaveStarted&&t>=r.revealAtMs&&this.beginWireframe(r,t);continue}let s=t-r.phaseStartMs;if(r.phase==="wireframe"){this.animateWireframe(r,s),s>=r.wireframeMs&&this.beginFade(r,t);continue}if(r.phase==="fade"){let a=Math.min(1,s/r.fadeMs);this.animateFade(r,a),a>=1&&n.push(r)}}for(let r of n)this.finishSection(r)}setEnabled(e){e!==this.enabled&&(this.enabled=e,e||this.forceFinishAll())}onSectionMeshedMesh(e,t,n){if(!this.enabled||!t.positions?.length||this.completed.has(e))return;let r=this.sections.get(e);if(r){r.mesh=n,r.geometry=t,(r.phase==="wireframe"||r.phase==="fade")&&this.finishSection(r);return}let s=performance.now();this.firstQueuedMs===null&&(this.firstQueuedMs=s);let a=this.globalWaveStarted;this.sections.set(e,{key:e,geometry:t,phase:"queued",phaseStartMs:s,revealAtMs:this.globalWaveStarted?s:0,wireframeMs:a?U4e:eJe,fadeMs:a?F4e:tJe,wireframeGroup:null,mesh:n,savedMaterial:null,pulseOffset:Math.random()*Math.PI*2}),n.visible=!1,this.setShaderMeshesVisible(e,!1),this.tryStartGlobalWave(s)}reset(){this.forceFinishAll(),this.sections.clear(),this.completed.clear(),this.globalWaveStarted=!1,this.globalWaveStartMs=0,this.finishedChunkCount=0,this.firstQueuedMs=null,this.pulseTime=0}forceFinishAll(){for(let e of[...this.sections.values()])this.finishSection(e);this.sections.clear(),this.unhideAllSectionMeshes()}tryStartGlobalWave(e){if(!this.globalWaveStarted&&this.sections.size!==0){if(this.finishedChunkCount>=JYe){this.startGlobalWave(e);return}this.worldRenderer.allChunksFinished&&this.startGlobalWave(e)}}startGlobalWave(e){if(this.globalWaveStarted)return;this.globalWaveStarted=!0,this.globalWaveStartMs=e;let t=this.worldRenderer.getCameraPosition(),n=1,r=new Map;for(let[s,a]of this.sections){if(a.phase!=="queued")continue;let{sx:o,sy:l,sz:c}=a.geometry,u=Math.hypot(o-t.x,l-t.y,c-t.z);r.set(s,u),n=Math.max(n,u)}for(let[,s]of this.sections){if(s.phase!=="queued")continue;let a=r.get(s.key)??0;s.revealAtMs=e+a/n*ZYe,s.wireframeMs=U4e,s.fadeMs=F4e}}beginWireframe(e,t){let n=e.mesh??this.getSectionMesh(e.key);if(e.mesh=n,!n){this.sections.delete(e.key);return}let r=this.createWireframeGeometry(e.geometry),s=new Kn(r,this.wireframeMaterial.clone());this.worldRenderer.sceneOrigin.track(s),s.position.set(e.geometry.sx,e.geometry.sy,e.geometry.sz),s.name="scifi-wireframe",s.renderOrder=1e3;let a=new Kn(r.clone(),this.wireframeGlowMaterial.clone());this.worldRenderer.sceneOrigin.track(a),a.position.copy(s.position),a.scale.setScalar(1.02),a.name="scifi-glow",a.renderOrder=999;let o=new bt;o.name="scifi-reveal-group",o.add(s,a),this.worldRenderer.realScene.add(o),n.visible=!1,this.setShaderMeshesVisible(e.key,!1),e.wireframeGroup=o,e.phase="wireframe",e.phaseStartMs=t}beginFade(e,t){let n=e.mesh??this.getSectionMesh(e.key);if(e.mesh=n,n){n.visible=!0;let r=n.material;if(!Array.isArray(r)&&r&&typeof r.clone=="function"){e.savedMaterial=r;let s=r.clone();s.transparent=!0,s.opacity=0,s.needsUpdate=!0,n.material=s}}this.setShaderMeshesVisible(e.key,!0),e.phase="fade",e.phaseStartMs=t}animateWireframe(e,t){if(!e.wireframeGroup)return;let n=e.wireframeGroup.children[0],r=e.wireframeGroup.children[1],s=.6+.4*Math.sin(this.pulseTime*4+e.pulseOffset);if(n?.material){let a=n.material;a.opacity=s;let o=.85+.15*Math.sin(this.pulseTime*6+t*.002);a.color.setRGB(13/255*o,234/255*o,238/255*o)}r?.material&&(r.material.opacity=s*.4)}animateFade(e,t){let n=1-(1-t)**3;if(e.wireframeGroup){let s=e.wireframeGroup.children[0],a=e.wireframeGroup.children[1];s?.material&&(s.material.opacity=1-n),a?.material&&(a.material.opacity=(1-n)*.55)}let r=e.mesh;r&&e.savedMaterial&&!Array.isArray(r.material)&&(r.material.opacity=n),this.setShaderMeshesVisible(e.key,n>.001)}finishSection(e){let t=e.mesh??this.getSectionMesh(e.key);if(t){if(e.savedMaterial){let r=t.material;t.material=e.savedMaterial,r.dispose(),e.savedMaterial=null}t.visible=!0}this.setShaderMeshesVisible(e.key,!0);let{chunkMeshManager:n}=this.worldRenderer;n.migrateDeferredShaderToGlobal(e.key),n.migrateDeferredLegacyToGlobal(e.key),e.wireframeGroup&&(this.disposeWireframeGroup(e.wireframeGroup),e.wireframeGroup=null),this.sections.delete(e.key),this.completed.add(e.key)}cancelSection(e,t){let n=this.sections.get(e);if(n){if(n.wireframeGroup&&this.disposeWireframeGroup(n.wireframeGroup),t){let r=n.mesh??this.getSectionMesh(e);if(r){if(n.savedMaterial){let s=r.material;r.material=n.savedMaterial,s.dispose()}r.visible=!0}this.setShaderMeshesVisible(e,!0)}this.sections.delete(e)}}getSectionMesh(e){let t=this.worldRenderer.chunkMeshManager.sectionObjects[e];if(!t)return null;let n=t.children.find(r=>r.name==="mesh");return n instanceof Ke?n:null}getShaderMesh(e){let t=this.worldRenderer.chunkMeshManager.sectionObjects[e];if(!t)return null;let n=t.children.find(r=>r.name==="shaderMesh");return n instanceof Ke?n:null}setShaderMeshesVisible(e,t){let n=this.getShaderMesh(e);n&&(n.visible=t)}unhideAllSectionMeshes(){for(let e of Object.values(this.worldRenderer.chunkMeshManager.sectionObjects))e&&e.traverse(t=>{t instanceof Ke&&(t.name==="mesh"||t.name==="shaderMesh")&&(t.visible=!0)})}disposeWireframeGroup(e){this.worldRenderer.sceneOrigin.removeAndUntrackAll(e),this.worldRenderer.realScene.remove(e),e.traverse(t=>{let n=t;n.geometry?.dispose();let r=n.material;Array.isArray(r)?r.forEach(s=>s.dispose()):r?.dispose()}),e.clear()}createWireframeGeometry(e){let t=e.positions,n=e.indices,r=[],s=new Set;for(let o=0;o<n.length;o+=3){let l=n[o],c=n[o+1],u=n[o+2];this.addEdge(t,l,c,r,s),this.addEdge(t,c,u,r,s),this.addEdge(t,u,l,r,s)}let a=new dt;return a.setAttribute("position",new Je(r,3)),a}addEdge(e,t,n,r,s){let a=Math.min(t,n),o=Math.max(t,n),l=`${a}-${o}`;s.has(l)||(s.add(l),r.push(e[t*3],e[t*3+1],e[t*3+2],e[n*3],e[n*3+1],e[n*3+2]))}},V4e={id:"futuristicReveal",controller:UP,enabledDefault:!0};h();p();m();Lt();var nJe=parseInt(Ma.replaceAll(/\D+/g,""),10),FP=class extends Xn{constructor(){super({uniforms:{time:{value:0},fade:{value:1}},vertexShader:`
29561
+ `,TP={u_atlas:{value:null},u_originDelta:{value:new X},u_cameraOriginFrac:{value:new X},u_skyLevel:{value:1},u_lightCurve:{value:Ri.curve},u_minBrightness:{value:Ri.minBrightness},u_lightGamma:{value:Ri.gamma}};function $_e(){return new Xn({vertexShader:kYe,fragmentShader:kP,uniforms:Gs.merge([at.fog,TP]),transparent:!0,depthWrite:!0,depthTest:!0,vertexColors:!0,glslVersion:Eo,fog:!0})}function Y_e(){return new Xn({vertexShader:X_e,fragmentShader:kP,uniforms:Gs.merge([at.fog,TP]),transparent:!1,depthWrite:!0,depthTest:!0,vertexColors:!0,glslVersion:Eo,fog:!0})}function J_e(){return new Xn({vertexShader:X_e,fragmentShader:kP,uniforms:Gs.merge([at.fog,TP]),transparent:!0,depthWrite:!0,depthTest:!0,vertexColors:!0,glslVersion:Eo,fog:!0})}function i9(i,e,t,n,r){let{originDelta:s,cameraOriginFrac:a}=$d(e,t,n,r),o=i.uniforms.u_originDelta;o?.value?.set&&o.value.set(s.x,s.y,s.z);let l=i.uniforms.u_cameraOriginFrac;l?.value?.set&&l.value.set(a.x,a.y,a.z)}function s9(i,e){let t=i.uniforms.u_skyLevel;t&&(t.value=e)}function a9(i,e){if(e.curve!==void 0){let t=i.uniforms.u_lightCurve;t&&(t.value=e.curve)}if(e.minBrightness!==void 0){let t=i.uniforms.u_minBrightness;t&&(t.value=e.minBrightness)}if(e.gamma!==void 0){let t=i.uniforms.u_lightGamma;t&&(t.value=e.gamma)}}h();p();m();var TYe=8,IYe=.01;function IP(i,e,t,n,r){i.matrix.makeTranslation(e-r.x,t-r.y,n-r.z),i.matrixWorldNeedsUpdate=!0,i.frustumCulled=!1}function o9(i,e,t,n,r,s,a,o,l,c){let u=i-n,d=e-r,f=t-s,v=TYe+IYe;return l.set(u-v,d-v,f-v),c.set(u+v,d+v,f+v),o.set(l,c),{visible:a.intersectsBox(o),distSq:u*u+d*d+f*f}}function K_e(i,e,t,n,r,s,a,o,l,c,u){let{visible:d,distSq:f}=o9(e,t,n,r,s,a,o,l,c,u);i.visible=d,i.renderOrder=-f}EP();h();p();m();Lt();h();p();m();h();p();m();h();p();m();Lt();h();p();m();function Q_e(){return{counts:new Int32Array(c0),offsets:new Int32Array(c0)}}function RYe(i,e){if(i.counts.length>=e)return;let t=i.counts.length;for(;t<e;)t*=2;i.counts=new Int32Array(t),i.offsets=new Int32Array(t)}function e4e(i){let e=i.getExtension("WEBGL_multi_draw");return e?{tier:"A",ext:e}:{tier:"B",ext:null}}var Z_e=!1;function t4e(i,e){Z_e||!e||(Z_e=!0,console.info("[globalLegacyBuffer] legacy multi_draw tier",i))}function n4e(i,e,t,n){let r=t.length;if(r===0)return;RYe(n,r);let s=i.TRIANGLES,a=i.UNSIGNED_INT;for(let o=0;o<r;o++){let l=t[o];n.counts[o]=l.indexCount,n.offsets[o]=l.indexStart*4}if(e.tier==="A"&&e.ext){e.ext.multiDrawElementsWEBGL(s,n.counts,0,a,n.offsets,0,r);return}for(let o=0;o<r;o++)i.drawElements(s,n.counts[o],a,n.offsets[o])}var Ci=4,Tr=6,Cn=3,Us=2,Ir=1,CYe=128e3,PYe=128e3,r4e=5e3,LYe=.25,i4e=Ci*(Cn*3+Ir*2+Us)*4+Tr*4,RP=.75,c0=64;function CP(i,e,t){for(let n of i)for(let r=n.start;r<n.start+n.count;r++){let s=!1;for(let a of e)if(r>=a.start&&r<a.start+a.count){s=!0;break}s||console.error("[GlobalLegacyBuffer] draw span covers non-live quad",{buffer:t,quad:r,span:n,liveRanges:e})}}function l9(i,e){if(e.length===0)return i;let t=[];for(let n of i){let r=[n];for(let s of e){let a=[];for(let o of r){let l=o.start+o.count-1;if(s.end<o.start||s.start>l){a.push(o);continue}s.start>o.start&&a.push({start:o.start,count:s.start-o.start}),s.end<l&&a.push({start:s.end+1,count:l-s.end})}r=a}t.push(...r)}return t.filter(n=>n.count>0)}var ug=class{mesh;material;growthIncrementQuads;capacityQuads;positions;colors;skyLights;blockLights;uvs;aOrigin;indices;sectionSlots=new Map;freeList=[];highWatermark=0;pendingRanges=[];_spanScratch=[];renderOrigin={x:0,y:0,z:0};layoutVersion=0;pendingMove=null;pendingReplace=new Map;uploadEpoch=0;visibleIndexSpans=[];_drawScratch=Q_e();multiDrawCaps=null;debugOverlay=!1;constructor(e,t,n){this.material=e,this.growthIncrementQuads=n?.growthIncrementQuads??PYe,this.capacityQuads=n?.initialCapacityQuads??CYe;let r=this.capacityQuads*Ci;this.positions=new Float32Array(r*Cn),this.colors=new Float32Array(r*Cn),this.skyLights=new Float32Array(r*Ir),this.blockLights=new Float32Array(r*Ir),this.uvs=new Float32Array(r*Us),this.aOrigin=new Float32Array(r*Cn),this.indices=new Uint32Array(this.capacityQuads*Tr);let s=new dt,a=(l,c,u)=>{let d=new Mt(l,c);return d.setUsage(So),s.setAttribute(u,d),d};a(this.positions,Cn,"position"),a(this.colors,Cn,"color"),a(this.skyLights,Ir,"a_skyLight"),a(this.blockLights,Ir,"a_blockLight"),a(this.uvs,Us,"uv"),a(this.aOrigin,Cn,"a_origin");let o=new Mt(this.indices,1);o.setUsage(So),s.setIndex(o),s.setDrawRange(0,0),s.boundingSphere=new Tn(new X,1/0),this.mesh=new Ke(s,[e]),this.mesh.name=n?.name??"globalLegacyOpaque",this.mesh.frustumCulled=!1,this.mesh.matrixAutoUpdate=!1,this.mesh.matrix.identity(),this.mesh.position.set(0,0,0),t.add(this.mesh),this.syncDefaultDrawGroups(),this.mesh.onAfterRender=(l,c,u,d,f)=>{if(this.visibleIndexSpans.length===0)return;let v=l.getContext();this.multiDrawCaps||(this.multiDrawCaps=e4e(v),t4e(this.multiDrawCaps.tier,this.debugOverlay)),n4e(v,this.multiDrawCaps,this.visibleIndexSpans,this._drawScratch)}}setDebugOverlay(e){this.debugOverlay=e}suppressThreeDraw(){this.mesh.geometry.setDrawRange(0,3)}setVisibleIndexSpans(e){this.visibleIndexSpans=e}getVisibleIndexSpans(){return this.visibleIndexSpans}syncDefaultDrawGroups(){let e=this.mesh.geometry;e.clearGroups();let t=this.highWatermark*Tr;t>0&&e.addGroup(0,t,0),e.setDrawRange(0,t)}addSection(e,t,n,r,s){let a=t.positions.length/Cn,o=a/Ci;if(a===0||o*Ci!==a)return this.removeSection(e),!1;if(t.indices.length%Tr!==0||t.indices.length/Tr!==o)return!1;let l=this.sectionSlots.has(e),c;if(l){let A=this.sectionSlots.get(e),T=this.pendingReplace.get(e),P=this.pendingMove?.key===e?this.pendingMove:void 0;T?(this.zeroAndFreeSlot(A.start,A.count),c={start:T.oldStart,count:T.oldCount},this.pendingReplace.delete(e)):P?(this.zeroAndFreeSlot(A.start,A.count),c={start:P.oldStart,count:P.count},this.pendingMove=null):c=A}o>this.capacityQuads&&this.growCapacity(o);let u=this.takeFreeSlot(o);u||(this.highWatermark+o>this.capacityQuads&&this.growCapacity(this.highWatermark+o),u={start:this.highWatermark,count:o},this.highWatermark+=o);let d=u.start*Ci,f=d*Cn,v=d*Us,g=d*Ir;this.positions.set(t.positions,f),this.colors.set(t.colors,f),this.skyLights.set(t.skyLights,g),this.blockLights.set(t.blockLights,g),this.uvs.set(t.uvs,v);let b=f,y=n-this.renderOrigin.x,_=r-this.renderOrigin.y,x=s-this.renderOrigin.z;for(let A=0;A<a;A++){let T=b+A*Cn;this.aOrigin[T]=y,this.aOrigin[T+1]=_,this.aOrigin[T+2]=x}let w=u.start*Tr,S=d;for(let A=0;A<t.indices.length;A++)this.indices[w+A]=t.indices[A]+S;return this.sectionSlots.set(e,u),l&&c&&this.pendingReplace.set(e,{oldStart:c.start,oldCount:c.count}),this.markDirty(u.start,u.start+o-1),this.syncDefaultDrawGroups(),this.layoutVersion++,!0}getLayoutVersion(){return this.layoutVersion}getUploadEpoch(){return this.uploadEpoch}hasPendingReplace(){return this.pendingReplace.size>0}canUseFullDrawShortcut(){return this.pendingRanges.length===0&&this.interiorFreeQuads()===0&&this.pendingMove===null&&this.pendingReplace.size===0}isRangeFullyUploaded(e,t){return this.rangeFullyUploaded(e,t)}getPendingDirtyRanges(){return this.pendingRanges}getSectionDrawStart(e){let t=this.sectionSlots.get(e);if(!t)return;if(this.pendingMove?.key===e)return this.pendingMove.oldStart;let n=this.pendingReplace.get(e);if(n)return n.oldStart;if(this.rangeFullyUploaded(t.start,t.start+t.count-1))return t.start}getSectionDrawCount(e){let t=this.sectionSlots.get(e);if(!t)return;if(this.pendingMove?.key===e)return this.pendingMove.count;let n=this.pendingReplace.get(e);if(n)return n.oldCount;if(this.rangeFullyUploaded(t.start,t.start+t.count-1))return t.count}getPendingMove(){return this.pendingMove}compactStep(){if(this.pendingMove){let{newStart:o,count:l}=this.pendingMove;this.rangeFullyUploaded(o,o+l-1)&&this.finalizePendingMove();return}for(let o of[...this.pendingReplace.keys()]){let l=this.sectionSlots.get(o);l&&this.rangeFullyUploaded(l.start,l.start+l.count-1)&&this.finalizePendingReplace(o)}if(this.highWatermark===0||this.interiorFreeQuads()/this.highWatermark<=LYe)return;let t=this.findMovableSection(r4e);if(!t)return;let n=this.findLowestInteriorHole(t.start,t.count);if(!n)return;let r=this.reserveFreeSlotAt(n.index,t.count),s=t.start,a=r.start;this.copySectionRange(s,a,t.count),this.sectionSlots.set(t.key,{start:a,count:t.count}),this.markDirty(a,a+t.count-1),this.pendingMove={key:t.key,oldStart:s,newStart:a,count:t.count},this.layoutVersion++}updateDrawSpans(e,t){if(this.visibleIndexSpans=[],this.highWatermark===0)return;let n=this._spanScratch;n.length=0;let r=0;for(let a of e){let o=this.getSectionDrawStart(a.key),l=this.getSectionDrawCount(a.key),c=this.sectionSlots.get(a.key);o===void 0||l===void 0||!c||(n.push({start:o,count:l}),r+=l)}if(n.length===0)return;let s=(a,o)=>{this.visibleIndexSpans.push({indexStart:a*Tr,indexCount:o*Tr})};if(t==="opaque"){let a,o=n.map(c=>({...c})),l=this.canUseFullDrawShortcut()&&r>=this.highWatermark*RP;l?a=[{start:0,count:this.highWatermark}]:(n.sort((c,u)=>c.start-u.start),this.mergeOpaqueSpans(n),a=n),a=l9(a,this.pendingRanges),l||CP(a,o,this.mesh.name);for(let c of a)s(c.start,c.count)}else{e.sort((a,o)=>o.distSq-a.distSq);for(let a of e){let o=this.getSectionDrawStart(a.key),l=this.getSectionDrawCount(a.key);o===void 0||l===void 0||s(o,l)}}}mergeOpaqueSpans(e){if(e.length<2)return;let t=0;for(;t<e.length-1;){let n=e[t],r=e[t+1];n.start+n.count===r.start?(n.count=r.start+r.count-n.start,e.splice(t+1,1)):t++}}hasSection(e){return this.sectionSlots.has(e)}getSectionSlot(e){return this.sectionSlots.get(e)}takeSectionData(e){let t=this.getSectionGeometryData(e);if(t)return this.removeSection(e),t}getSectionGeometryData(e){let t=this.sectionSlots.get(e);if(!t)return;let n=t.count*Ci,r=t.start*Ci,s=r*Cn,a=r*Us,o=t.start*Tr,l=t.count*Tr,c=r*Ir,u=this.positions.slice(s,s+n*Cn),d=this.colors.slice(s,s+n*Cn),f=this.skyLights.slice(c,c+n*Ir),v=this.blockLights.slice(c,c+n*Ir),g=this.uvs.slice(a,a+n*Us),b=this.indices.slice(o,o+l),y=r;for(let S=0;S<b.length;S++)b[S]=b[S]-y;let _=this.aOrigin[s]+this.renderOrigin.x,x=this.aOrigin[s+1]+this.renderOrigin.y,w=this.aOrigin[s+2]+this.renderOrigin.z;return{positions:u,colors:d,skyLights:f,blockLights:v,uvs:g,indices:b,sx:_,sy:x,sz:w}}removeSection(e){let t=this.sectionSlots.get(e);if(!t)return;if(this.pendingReplace.has(e)){let s=this.pendingReplace.get(e);this.zeroAndFreeSlot(s.oldStart,s.oldCount),this.pendingReplace.delete(e)}if(this.pendingMove?.key===e){let{oldStart:s,count:a}=this.pendingMove;this.zeroAndFreeSlot(s,a),this.pendingMove=null}let n=t.start*Tr,r=t.count*Tr;for(let s=0;s<r;s++)this.indices[n+s]=0;this.markDirty(t.start,t.start+t.count-1),this.sectionSlots.delete(e),this.insertFreeSlot(t),this.shrinkHighWatermark(),this.syncDefaultDrawGroups(),this.layoutVersion++}hasPendingUploads(){return this.pendingRanges.length>0}uploadDirtyRange(){let e=this.pendingRanges[0];if(!e)return;let t=e.start,n=Math.min(e.end-e.start+1,r4e),r=t*Ci,s=n*Ci,a=t*Tr,o=n*Tr,l=this.mesh.geometry,c=l.getAttribute("position");c.clearUpdateRanges(),c.addUpdateRange(r*Cn,s*Cn),c.needsUpdate=!0;let u=l.getAttribute("color");u.clearUpdateRanges(),u.addUpdateRange(r*Cn,s*Cn),u.needsUpdate=!0;let d=l.getAttribute("a_skyLight");d.clearUpdateRanges(),d.addUpdateRange(r*Ir,s*Ir),d.needsUpdate=!0;let f=l.getAttribute("a_blockLight");f.clearUpdateRanges(),f.addUpdateRange(r*Ir,s*Ir),f.needsUpdate=!0;let v=l.getAttribute("uv");v.clearUpdateRanges(),v.addUpdateRange(r*Us,s*Us),v.needsUpdate=!0;let g=l.getAttribute("a_origin");g.clearUpdateRanges(),g.addUpdateRange(r*Cn,s*Cn),g.needsUpdate=!0;let b=l.index;b.clearUpdateRanges(),b.addUpdateRange(a,o),b.needsUpdate=!0,t+n>e.end?this.pendingRanges.shift():e.start=t+n,this.uploadEpoch++}setRenderOrigin(e){this.renderOrigin={...e}}rebase(e){if(this.highWatermark!==0){for(let t of this.sectionSlots.values()){let n=t.start*Ci,r=t.count*Ci,s=n*Cn;for(let a=0;a<r;a++){let o=s+a*Cn;this.aOrigin[o]-=e.x,this.aOrigin[o+1]-=e.y,this.aOrigin[o+2]-=e.z}}this.markDirty(0,this.highWatermark-1),this.renderOrigin.x+=e.x,this.renderOrigin.y+=e.y,this.renderOrigin.z+=e.z}}setCameraOrigin(e,t,n){let{originDelta:r,cameraOriginFrac:s}=$d(this.renderOrigin,e,t,n),a=this.material.uniforms.u_originDelta;a?.value?.set&&a.value.set(r.x,r.y,r.z);let o=this.material.uniforms.u_cameraOriginFrac;o?.value?.set&&o.value.set(s.x,s.y,s.z)}getHighWatermark(){return this.highWatermark}getCapacityQuads(){return this.capacityQuads}getSectionCount(){return this.sectionSlots.size}getMemoryBytes(){return this.capacityQuads*i4e}getUsedMemoryBytes(){return this.highWatermark*i4e}reset(){this.sectionSlots.clear(),this.freeList.length=0,this.highWatermark=0,this.pendingRanges.length=0,this.pendingMove=null,this.pendingReplace.clear(),this.uploadEpoch=0,this.visibleIndexSpans=[],this.syncDefaultDrawGroups()}dispose(){this.mesh.parent?.remove(this.mesh),this.mesh.geometry.dispose(),this.reset()}markDirty(e,t){this.pendingRanges.push({start:e,end:t}),this.pendingRanges.sort((n,r)=>n.start-r.start),this.mergePendingRanges()}mergePendingRanges(){if(this.pendingRanges.length<2)return;let e=[],t=this.pendingRanges[0];for(let n=1;n<this.pendingRanges.length;n++){let r=this.pendingRanges[n];r.start<=t.end+1?t={start:t.start,end:Math.max(t.end,r.end)}:(e.push(t),t=r)}e.push(t),this.pendingRanges=e}takeFreeSlot(e){for(let t=0;t<this.freeList.length;t++){let n=this.freeList[t];if(n.count>=e){if(this.freeList.splice(t,1),n.count===e)return n;let r={start:n.start,count:e};return this.insertFreeSlot({start:n.start+e,count:n.count-e}),r}}}insertFreeSlot(e){this.freeList.push(e),this.freeList.sort((t,n)=>t.start-n.start),this.mergeFreeList()}mergeFreeList(){if(this.freeList.length<2)return;let e=[],t=this.freeList[0];for(let n=1;n<this.freeList.length;n++){let r=this.freeList[n];t.start+t.count===r.start?t={start:t.start,count:t.count+r.count}:(e.push(t),t=r)}e.push(t),this.freeList=e}shrinkHighWatermark(){for(;this.highWatermark>0;){let e=this.highWatermark-1,t=this.freeList.find(r=>r.start<=e&&r.start+r.count>e);if(!t||t.start+t.count!==this.highWatermark)break;this.highWatermark=t.start;let n=this.freeList.indexOf(t);this.freeList.splice(n,1)}}interiorFreeQuads(){let e=0;for(let t of this.freeList)t.start<this.highWatermark&&(e+=t.count);return e}findMovableSection(e){let t=[];for(let[s,a]of this.sectionSlots)t.push({key:s,start:a.start,count:a.count});if(t.length===0)return;t.sort((s,a)=>a.start!==s.start?a.start-s.start:a.start+a.count-(s.start+s.count));let n=t[0];if(n.count<=e&&this.findLowestInteriorHole(n.start,n.count))return n;let r=t.filter(s=>s.count<=e).sort((s,a)=>a.count-s.count);for(let s of r)if(this.findLowestInteriorHole(s.start,s.count))return s}findLowestInteriorHole(e,t){for(let n=0;n<this.freeList.length;n++){let r=this.freeList[n];if(r.start<e&&r.count>=t)return{start:r.start,count:r.count,index:n}}}reserveFreeSlotAt(e,t){let n=this.freeList[e];if(this.freeList.splice(e,1),n.count===t)return{start:n.start,count:t};let r={start:n.start,count:t};return this.insertFreeSlot({start:n.start+t,count:n.count-t}),r}copySectionRange(e,t,n){let r=e*Ci,s=t*Ci,a=n*Ci,o=s-r,l=r*Cn,c=s*Cn,u=a*Cn;this.positions.copyWithin(c,l,l+u),this.colors.copyWithin(c,l,l+u),this.aOrigin.copyWithin(c,l,l+u);let d=r*Ir,f=s*Ir,v=a*Ir;this.skyLights.copyWithin(f,d,d+v),this.blockLights.copyWithin(f,d,d+v);let g=r*Us,b=s*Us,y=a*Us;this.uvs.copyWithin(b,g,g+y);let _=e*Tr,x=t*Tr,w=n*Tr;for(let S=0;S<w;S++)this.indices[x+S]=this.indices[_+S]+o}rangeFullyUploaded(e,t){for(let n of this.pendingRanges)if(n.start<=t&&n.end>=e)return!1;return!0}zeroAndFreeSlot(e,t){let n=e*Tr,r=t*Tr;for(let s=0;s<r;s++)this.indices[n+s]=0;this.markDirty(e,e+t-1),this.insertFreeSlot({start:e,count:t})}finalizePendingReplace(e){let t=this.pendingReplace.get(e);t&&(this.zeroAndFreeSlot(t.oldStart,t.oldCount),this.pendingReplace.delete(e),this.shrinkHighWatermark(),this.syncDefaultDrawGroups(),this.layoutVersion++,this.uploadEpoch++)}finalizePendingMove(){let e=this.pendingMove;if(!e)return;let{oldStart:t,count:n}=e;this.zeroAndFreeSlot(t,n),this.shrinkHighWatermark(),this.syncDefaultDrawGroups(),this.pendingMove=null,this.layoutVersion++,this.uploadEpoch++}growCapacity(e){this.pendingMove&&this.finalizePendingMove();for(let y of[...this.pendingReplace.keys()])this.finalizePendingReplace(y);let t=this.capacityQuads;for(;t<e;)t+=this.growthIncrementQuads;let n=this.capacityQuads*Ci,r=t*Ci,s=new Float32Array(r*Cn),a=new Float32Array(r*Cn),o=new Float32Array(r*Ir),l=new Float32Array(r*Ir),c=new Float32Array(r*Us),u=new Float32Array(r*Cn),d=new Uint32Array(t*Tr);s.set(this.positions),a.set(this.colors),o.set(this.skyLights),l.set(this.blockLights),c.set(this.uvs),u.set(this.aOrigin),d.set(this.indices),this.positions=s,this.colors=a,this.skyLights=o,this.blockLights=l,this.uvs=c,this.aOrigin=u,this.indices=d,this.capacityQuads=t;let f=this.mesh.geometry,v=(y,_,x)=>{f.getAttribute(x)&&f.deleteAttribute(x);let S=new Mt(y,_);S.setUsage(So),f.setAttribute(x,S)};v(this.positions,Cn,"position"),v(this.colors,Cn,"color"),v(this.skyLights,Ir,"a_skyLight"),v(this.blockLights,Ir,"a_blockLight"),v(this.uvs,Us,"uv"),v(this.aOrigin,Cn,"a_origin"),f.index&&f.setIndex(null);let b=new Mt(this.indices,1);b.setUsage(So),f.setIndex(b),this.pendingRanges.length=0}};function BYe(i){if(i.length<2)return;let e=0;for(;e<i.length-1;){let t=i[e],n=i[e+1];t.start+t.count===n.start?(t.count=n.start+n.count-t.start,i.splice(e+1,1)):e++}}function s4e(i,e,t=!0,n,r=[]){if(i.length===0||e===0)return[];let s=0;for(let l of i)s+=l.count;let a;if(t&&s>=e*RP)a=[{start:0,count:e}];else{a=i.map(c=>({start:c.start,count:c.count})),a.sort((c,u)=>c.start-u.start);let l=a.map(c=>({...c}));return BYe(a),a=l9(a,r),CP(a,l,"globalBlockBuffer"),a}return l9(a,r)}Kc();function o4e(){return{firsts:new Int32Array(c0),counts:new Int32Array(c0),instanceCounts:new Int32Array(c0),baseInstances:new Int32Array(c0)}}function l4e(i){let e=i.getExtension("WEBGL_multi_draw_instanced_base_vertex_base_instance");if(e)return{tier:"A",ext:e};let t=i.getExtension("WEBGL_draw_instanced_base_vertex_base_instance");return t?{tier:"B",ext:t}:{tier:"C",ext:null}}var a4e=!1;function c4e(i,e){a4e||!e||(a4e=!0,console.info("[globalBlockBuffer] cube multi_draw tier",i))}function u4e(i,e,t,n,r){let s=t.length;if(s===0)return;let a=i.TRIANGLES;if(e.tier==="A"&&e.ext){let o=e.ext;for(let l=0;l<s;l++){let c=t[l];n.firsts[l]=0,n.counts[l]=l0,n.instanceCounts[l]=c.count,n.baseInstances[l]=c.start}o.multiDrawArraysInstancedBaseInstanceWEBGL(a,n.firsts,0,n.counts,0,n.instanceCounts,0,n.baseInstances,0,s);return}if(e.tier==="B"&&e.ext){let o=e.ext;for(let l=0;l<s;l++){let c=t[l];o.drawArraysInstancedBaseInstanceWEBGL(a,0,l0,c.count,c.start)}return}r?.(i,t)}Kc();z5();var DYe=512e3,OYe=1e6,d4e=15e3,NYe=.25,dg=F_e(),f4e=16,c9=class{mesh;capacityFaces;w0;w1;w2;w3;sectionSlots=new Map;freeList=[];highWatermark=0;pendingRanges=[];pendingMove=null;pendingReplace=new Map;uploadEpoch=0;visibleSpans=[];_drawScratch=o4e();multiDrawCaps=null;tierCVao=null;tierCAttrs=null;tierCGl=null;debugOverlay=!1;layoutVersion=0;constructor(e,t){this.capacityFaces=DYe,this.w0=new Uint32Array(this.capacityFaces),this.w1=new Uint32Array(this.capacityFaces),this.w2=new Uint32Array(this.capacityFaces),this.w3=new Uint32Array(this.capacityFaces),this.w2.fill(dg);let n=new Sa,r=new Float32Array(l0*3);n.setAttribute("position",new Mt(r,3));let s=a=>{let o=new Ar(a,1);return o.setUsage(So),o};n.setAttribute("a_w0",s(this.w0)),n.setAttribute("a_w1",s(this.w1)),n.setAttribute("a_w2",s(this.w2)),n.setAttribute("a_w3",s(this.w3)),n.instanceCount=0,this.mesh=new Ke(n,e),this.mesh.name="globalShaderCubes",this.mesh.frustumCulled=!1,this.mesh.matrixAutoUpdate=!1,this.mesh.matrix.identity(),this.mesh.position.set(0,0,0),t.add(this.mesh),this.mesh.onAfterRender=(a,o,l,c,u)=>{if(this.visibleSpans.length===0)return;let d=u,f=a.getContext();this.multiDrawCaps||(this.multiDrawCaps=l4e(f),c4e(this.multiDrawCaps.tier,this.debugOverlay)),u4e(f,this.multiDrawCaps,this.visibleSpans,this._drawScratch,this.multiDrawCaps.tier==="C"?(v,g)=>this.drawTierCSpans(v,g,a,d):void 0)}}setDebugOverlay(e){this.debugOverlay=e}suppressThreeDraw(){let e=this.mesh.geometry;e.setDrawRange(0,l0),e.instanceCount=0}setVisibleSpans(e){this.visibleSpans=e}getVisibleSpans(){return this.visibleSpans}forEachSectionSlot(e){for(let[t,n]of this.sectionSlots)e(t,n)}getSectionDrawStart(e){let t=this.sectionSlots.get(e);if(!t)return;if(this.pendingMove?.key===e)return this.pendingMove.oldStart;let n=this.pendingReplace.get(e);if(n)return n.oldStart;if(this.rangeFullyUploaded(t.start,t.start+t.count-1))return t.start}getSectionDrawCount(e){let t=this.sectionSlots.get(e);if(!t)return;if(this.pendingMove?.key===e)return this.pendingMove.count;let n=this.pendingReplace.get(e);if(n)return n.oldCount;if(this.rangeFullyUploaded(t.start,t.start+t.count-1))return t.count}getUploadEpoch(){return this.uploadEpoch}hasPendingReplace(){return this.pendingReplace.size>0}canUseFullDrawShortcut(){return this.pendingRanges.length===0&&this.interiorFreeFaces()===0&&this.pendingMove===null&&this.pendingReplace.size===0}isRangeFullyUploaded(e,t){return this.rangeFullyUploaded(e,t)}getPendingDirtyRanges(){return this.pendingRanges}getHighWatermark(){return this.highWatermark}getCapacityFaces(){return this.capacityFaces}getSectionCount(){return this.sectionSlots.size}getMemoryBytes(){return this.capacityFaces*f4e}getUsedMemoryBytes(){return this.highWatermark*f4e}hasPendingUploads(){return this.pendingRanges.length>0}getPendingMove(){return this.pendingMove}addSection(e,t,n){if(n<=0){this.removeSection(e);return}let r=this.sectionSlots.has(e),s;if(r){let l=this.sectionSlots.get(e),c=this.pendingReplace.get(e),u=this.pendingMove?.key===e?this.pendingMove:void 0;c?(this.zeroAndFreeSlot(l.start,l.count),s={start:c.oldStart,count:c.oldCount},this.pendingReplace.delete(e)):u?(this.zeroAndFreeSlot(l.start,l.count),s={start:u.oldStart,count:u.count},this.pendingMove=null):s=l}n>this.capacityFaces&&this.growCapacity(n);let a=this.takeFreeSlot(n);a||(this.highWatermark+n>this.capacityFaces&&this.growCapacity(this.highWatermark+n),a={start:this.highWatermark,count:n},this.highWatermark+=n);let o=4;for(let l=0;l<n;l++){let c=a.start+l,u=l*o;this.w0[c]=t[u],this.w1[c]=t[u+1],this.w2[c]=t[u+2],this.w3[c]=t[u+3]}this.sectionSlots.set(e,a),r&&s&&this.pendingReplace.set(e,{oldStart:s.start,oldCount:s.count}),this.markDirty(a.start,a.start+n-1),this.mesh.geometry.instanceCount=this.highWatermark,this.layoutVersion++}getLayoutVersion(){return this.layoutVersion}hasSection(e){return this.sectionSlots.has(e)}getSectionSlot(e){return this.sectionSlots.get(e)}getW0(){return this.w0}takeSectionData(e){let t=this.sectionSlots.get(e);if(!t)return;let n=4,r=new Uint32Array(t.count*n);for(let s=0;s<t.count;s++){let a=t.start+s,o=s*n;r[o]=this.w0[a],r[o+1]=this.w1[a],r[o+2]=this.w2[a],r[o+3]=this.w3[a]}return this.removeSection(e),{words:r,count:t.count}}removeSection(e){let t=this.sectionSlots.get(e);if(t){if(this.pendingReplace.has(e)){let n=this.pendingReplace.get(e);this.zeroAndFreeSlot(n.oldStart,n.oldCount),this.pendingReplace.delete(e)}if(this.pendingMove?.key===e){let{oldStart:n,count:r}=this.pendingMove;this.zeroAndFreeSlot(n,r),this.pendingMove=null}for(let n=t.start;n<t.start+t.count;n++)this.w0[n]=0,this.w1[n]=0,this.w2[n]=dg,this.w3[n]=0;this.markDirty(t.start,t.start+t.count-1),this.sectionSlots.delete(e),this.insertFreeSlot(t),this.shrinkHighWatermark(),this.mesh.geometry.instanceCount=this.highWatermark,this.layoutVersion++}}compactStep(){if(this.pendingMove){let{newStart:o,count:l}=this.pendingMove;this.rangeFullyUploaded(o,o+l-1)&&this.finalizePendingMove();return}for(let o of[...this.pendingReplace.keys()]){let l=this.sectionSlots.get(o);l&&this.rangeFullyUploaded(l.start,l.start+l.count-1)&&this.finalizePendingReplace(o)}if(this.highWatermark===0||this.interiorFreeFaces()/this.highWatermark<=NYe)return;let t=this.findMovableSection(d4e);if(!t)return;let n=this.findLowestInteriorHole(t.start,t.count);if(!n)return;let r=this.reserveFreeSlotAt(n.index,t.count),s=t.start,a=r.start;this.copySectionRange(s,a,t.count),this.sectionSlots.set(t.key,{start:a,count:t.count}),this.markDirty(a,a+t.count-1),this.pendingMove={key:t.key,oldStart:s,newStart:a,count:t.count},this.layoutVersion++}uploadDirtyRange(){let e=this.pendingRanges[0];if(!e)return;let t=e.start,n=Math.min(e.end-e.start+1,d4e),r=this.mesh.geometry;for(let s of["a_w0","a_w1","a_w2","a_w3"]){let a=r.getAttribute(s);a.clearUpdateRanges(),a.addUpdateRange(t,n),a.needsUpdate=!0}t+n>e.end?this.pendingRanges.shift():e.start=t+n,this.uploadEpoch++}setCameraOrigin(e,t,n,r){let{originDelta:s,cameraOriginFrac:a}=$d(e,t,n,r),o=Kb(e),l=this.mesh.material.uniforms.u_originDelta;l?.value?.set&&l.value.set(s.x,s.y,s.z);let c=this.mesh.material.uniforms.u_cameraOriginFrac;c?.value?.set&&c.value.set(a.x,a.y,a.z);let u=this.mesh.material.uniforms.u_sectionOriginRel;u?.value?.set&&u.value.set(o.x,o.y,o.z)}reset(){this.sectionSlots.clear(),this.freeList.length=0,this.highWatermark=0,this.pendingRanges.length=0,this.pendingMove=null,this.pendingReplace.clear(),this.uploadEpoch=0,this.visibleSpans=[],this.w0.fill(0),this.w1.fill(0),this.w2.fill(dg),this.w3.fill(0),this.mesh.geometry.instanceCount=0,this.invalidateTierCVao()}dispose(){this.invalidateTierCVao(),this.mesh.parent?.remove(this.mesh),this.mesh.geometry.dispose(),this.reset()}invalidateTierCVao(){this.tierCVao&&this.tierCGl&&this.tierCGl.deleteVertexArray(this.tierCVao),this.tierCVao=null,this.tierCAttrs=null}drawTierCSpans(e,t,n,r){if(this.ensureTierCVao(e,n,r),!this.tierCVao||!this.tierCAttrs)return;let s=this.tierCAttrs;e.bindVertexArray(this.tierCVao);for(let a of t){let o=a.start*4,l=c=>{e.bindBuffer(e.ARRAY_BUFFER,c.buffer),e.vertexAttribIPointer(c.loc,1,e.UNSIGNED_INT,4,o)};l(s.w0),l(s.w1),l(s.w2),l(s.w3),e.drawArraysInstanced(e.TRIANGLES,0,l0,a.count)}e.bindVertexArray(null)}ensureTierCVao(e,t,n){this.tierCGl=e;let a=t.properties.get(n).currentProgram.program,o=e.getAttribLocation(a,"a_w0"),l=e.getAttribLocation(a,"a_w1"),c=e.getAttribLocation(a,"a_w2"),u=e.getAttribLocation(a,"a_w3"),d=w=>w<0?null:e.getVertexAttrib(w,e.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING),f=d(o);if(this.tierCVao&&this.tierCAttrs&&f&&this.tierCAttrs.w0.buffer!==f&&this.invalidateTierCVao(),this.tierCVao)return;let v=d(o),g=d(l),b=d(c),y=d(u);if(!v||!g||!b||!y)return;let _=e.createVertexArray();if(!_)return;e.bindVertexArray(_);let x=(w,S)=>{e.enableVertexAttribArray(w),e.bindBuffer(e.ARRAY_BUFFER,S),e.vertexAttribIPointer(w,1,e.UNSIGNED_INT,4,0),e.vertexAttribDivisor(w,1)};x(o,v),x(l,g),x(c,b),x(u,y),e.bindVertexArray(null),this.tierCVao=_,this.tierCAttrs={w0:{loc:o,buffer:v},w1:{loc:l,buffer:g},w2:{loc:c,buffer:b},w3:{loc:u,buffer:y}}}markDirty(e,t){this.pendingRanges.push({start:e,end:t}),this.pendingRanges.sort((n,r)=>n.start-r.start),this.mergePendingRanges()}mergePendingRanges(){if(this.pendingRanges.length<2)return;let e=[],t=this.pendingRanges[0];for(let n=1;n<this.pendingRanges.length;n++){let r=this.pendingRanges[n];r.start<=t.end+1?t={start:t.start,end:Math.max(t.end,r.end)}:(e.push(t),t=r)}e.push(t),this.pendingRanges=e}takeFreeSlot(e){for(let t=0;t<this.freeList.length;t++){let n=this.freeList[t];if(n.count>=e){if(this.freeList.splice(t,1),n.count===e)return n;let r={start:n.start,count:e};return this.insertFreeSlot({start:n.start+e,count:n.count-e}),r}}}insertFreeSlot(e){this.freeList.push(e),this.freeList.sort((t,n)=>t.start-n.start),this.mergeFreeList()}mergeFreeList(){if(this.freeList.length<2)return;let e=[],t=this.freeList[0];for(let n=1;n<this.freeList.length;n++){let r=this.freeList[n];t.start+t.count===r.start?t={start:t.start,count:t.count+r.count}:(e.push(t),t=r)}e.push(t),this.freeList=e}interiorFreeFaces(){let e=0;for(let t of this.freeList)t.start<this.highWatermark&&(e+=t.count);return e}findMovableSection(e){let t=[];for(let[s,a]of this.sectionSlots)t.push({key:s,start:a.start,count:a.count});if(t.length===0)return;t.sort((s,a)=>a.start!==s.start?a.start-s.start:a.start+a.count-(s.start+s.count));let n=t[0];if(n.count<=e&&this.findLowestInteriorHole(n.start,n.count))return n;let r=t.filter(s=>s.count<=e).sort((s,a)=>a.count-s.count);for(let s of r)if(this.findLowestInteriorHole(s.start,s.count))return s}findLowestInteriorHole(e,t){for(let n=0;n<this.freeList.length;n++){let r=this.freeList[n];if(r.start<e&&r.count>=t)return{start:r.start,count:r.count,index:n}}}reserveFreeSlotAt(e,t){let n=this.freeList[e];if(this.freeList.splice(e,1),n.count===t)return{start:n.start,count:t};let r={start:n.start,count:t};return this.insertFreeSlot({start:n.start+t,count:n.count-t}),r}copySectionRange(e,t,n){this.w0.copyWithin(t,e,e+n),this.w1.copyWithin(t,e,e+n),this.w2.copyWithin(t,e,e+n),this.w3.copyWithin(t,e,e+n)}rangeFullyUploaded(e,t){for(let n of this.pendingRanges)if(n.start<=t&&n.end>=e)return!1;return!0}zeroAndFreeSlot(e,t){for(let n=e;n<e+t;n++)this.w0[n]=0,this.w1[n]=0,this.w2[n]=dg,this.w3[n]=0;this.markDirty(e,e+t-1),this.insertFreeSlot({start:e,count:t})}finalizePendingReplace(e){let t=this.pendingReplace.get(e);t&&(this.zeroAndFreeSlot(t.oldStart,t.oldCount),this.pendingReplace.delete(e),this.shrinkHighWatermark(),this.mesh.geometry.instanceCount=this.highWatermark,this.layoutVersion++,this.uploadEpoch++)}finalizePendingMove(){let e=this.pendingMove;if(!e)return;let{oldStart:t,count:n}=e;this.zeroAndFreeSlot(t,n),this.shrinkHighWatermark(),this.mesh.geometry.instanceCount=this.highWatermark,this.pendingMove=null,this.layoutVersion++,this.uploadEpoch++}shrinkHighWatermark(){for(;this.highWatermark>0;){let e=this.highWatermark-1,t=this.freeList.find(r=>r.start<=e&&r.start+r.count>e);if(!t||t.start+t.count!==this.highWatermark)break;this.highWatermark=t.start;let n=this.freeList.indexOf(t);this.freeList.splice(n,1)}}growCapacity(e){this.pendingMove&&this.finalizePendingMove();for(let c of[...this.pendingReplace.keys()])this.finalizePendingReplace(c);console.warn("[globalBlockBuffer] growing faces",this.capacityFaces,"->","(need",e,")");let t=this.capacityFaces;for(;t<e;)t+=OYe;console.warn("[globalBlockBuffer] growing faces",this.capacityFaces,"->",t);let n=new Uint32Array(t),r=new Uint32Array(t),s=new Uint32Array(t),a=new Uint32Array(t);n.set(this.w0),r.set(this.w1),s.set(this.w2),a.set(this.w3),s.fill(dg,this.w0.length),this.w0=n,this.w1=r,this.w2=s,this.w3=a,this.capacityFaces=t;let o=this.mesh.geometry,l=(c,u)=>{let d=o.getAttribute(u);d&&(o.deleteAttribute(u),"dispose"in d&&typeof d.dispose=="function"&&d.dispose());let f=new Ar(c,1);f.setUsage(So),o.setAttribute(u,f)};l(this.w0,"a_w0"),l(this.w1,"a_w1"),l(this.w2,"a_w2"),l(this.w3,"a_w3"),this.pendingRanges.length=0,this.invalidateTierCVao()}};h();p();m();z5();Kc();function h4e(i,e,t,n,r){if(e<=0)return;let s=t-8,a=n-8,o=r-8,l=t9,c=16,u=16,d=16,f=-1,v=-1,g=-1;for(let A=0;A<e;A++){let T=i[A*l],P=T&(1<<Xd.LX_BITS)-1,I=T>>Xd.LY_SHIFT&(1<<Xd.LY_BITS)-1,k=T>>Xd.LZ_SHIFT&(1<<Xd.LZ_BITS)-1;P<c&&(c=P),I<u&&(u=I),k<d&&(d=k),P>f&&(f=P),I>v&&(v=I),k>g&&(g=k)}if(f<0)return;let b=s+c,y=a+u,_=o+d,x=s+f+1,w=a+v+1,S=o+g+1;return{minX:b,minY:y,minZ:_,maxX:x,maxY:w,maxZ:S,cx:(b+x)*.5,cy:(y+w)*.5,cz:(_+S)*.5}}function UYe(i,e,t,n,r,s,a,o,l){return i>=n&&i<=a&&e>=r&&e<=o&&t>=s&&t<=l}function m4e(i,e,t,n,r,s,a,o,l,c,u,d,f){if(UYe(i,e,t,a,o,l,c,u,d))return;let v=0,g=f;if(Math.abs(n)<1e-8){if(i<a||i>c)return}else{let b=1/n,y=(a-i)*b,_=(c-i)*b;if(y>_){let x=y;y=_,_=x}if(v=Math.max(v,y),g=Math.min(g,_),v>g)return}if(Math.abs(r)<1e-8){if(e<o||e>u)return}else{let b=1/r,y=(o-e)*b,_=(u-e)*b;if(y>_){let x=y;y=_,_=x}if(v=Math.max(v,y),g=Math.min(g,_),v>g)return}if(Math.abs(s)<1e-8){if(t<l||t>d)return}else{let b=1/s,y=(l-t)*b,_=(d-t)*b;if(y>_){let x=y;y=_,_=x}if(v=Math.max(v,y),g=Math.min(g,_),v>g)return}return v<=g&&v>=0?v:void 0}function p4e(i,e,t,n,r,s,a,o,l,c,u,d,f){let v=f;if(Math.abs(n)>=1e-8){let g=n>0?(c-i)/n:(a-i)/n;g>1e-6&&(v=Math.min(v,g))}else if(i<a||i>c)return;if(Math.abs(r)>=1e-8){let g=r>0?(u-e)/r:(o-e)/r;g>1e-6&&(v=Math.min(v,g))}else if(e<o||e>u)return;if(Math.abs(s)>=1e-8){let g=s>0?(d-t)/s:(l-t)/s;g>1e-6&&(v=Math.min(v,g))}else if(t<l||t>d)return;return v<=f?v:void 0}h();p();m();Lt();h();p();m();$b();var u9=class{entries=new Set;skyLevel=1;lightmapParams={...Ri};register(e){this.entries.add(e),this.applyBrightness(e)}unregister(e){for(let t of this.entries)if(t.material===e){this.entries.delete(t);break}}setSkyLevel(e){this.skyLevel=e,this.refreshAll()}setLightmapParams(e){this.lightmapParams={...this.lightmapParams,...e},this.refreshAll()}getSkyLevel(){return this.skyLevel}refreshAll(){for(let e of this.entries)this.applyBrightness(e)}applyBrightness(e){let t=yP(e.blockLightNorm,e.skyLightNorm,this.skyLevel,this.lightmapParams);e.material.color.setScalar(t)}};function v4e(i,e,t,n,r=Ri){let s=yP(e,t,n,r);return i.color.setScalar(s),s}var g4e=20,_4e=40,FYe={white_banner:15,orange_banner:14,magenta_banner:13,light_blue_banner:12,yellow_banner:11,lime_banner:10,pink_banner:9,gray_banner:8,light_gray_banner:7,cyan_banner:6,purple_banner:5,blue_banner:4,brown_banner:3,green_banner:2,red_banner:1,black_banner:0},y4e={0:"#1d1d21",1:"#b02e26",2:"#5e7c16",3:"#835432",4:"#3c44aa",5:"#8932b8",6:"#169c9c",7:"#9d9d97",8:"#474f52",9:"#f38baa",10:"#80c71f",11:"#fed83d",12:"#3ab3da",13:"#c74ebd",14:"#f9801d",15:"#f9fffe"};function VYe(i){let e=i.replace("_wall_banner","_banner");return FYe[e]??15}var zYe=(i,e,t,n,r,s,a)=>{switch(i.fillStyle=t,e){case"bs":i.fillRect(n,r,s,a);break;case"ls":i.fillRect(n,r,s/3,a);break;case"rs":i.fillRect(n+s*2/3,r,s/3,a);break;case"ts":i.fillRect(n,r,s,a/3);break;case"ms":i.fillRect(n,r+a/3,s,a/3);break;case"drs":i.fillRect(n,r,s/2,a/2);break;case"dls":i.fillRect(n+s/2,r,s/2,a/2);break;case"ss":for(let o=0;o<s;o+=2)i.fillRect(n+o,r,1,a);break;case"cr":i.fillRect(n,r+a/3,s,a/3),i.fillRect(n+s/3,r,s/3,a);break;case"sc":i.fillRect(n,r+a/2-1,s,2),i.fillRect(n+s/2-1,r,2,a);break;default:i.fillRect(n,r,s,a)}};function HYe(i,e){if(!e||e.length===0)return`banner_${i}_empty`;let t=e.map(n=>`${n.Pattern??"bs"}_${n.Color??0}`).join(",");return`banner_${i}_${t}`}var qYe=(i,e,t=(n,r)=>yi(n,r))=>{let r=t(g4e*1,_4e*1),s=r.getContext("2d");if(!s){console.warn("Failed to get 2d context for banner rendering");return}if(s.imageSmoothingEnabled=!1,e?.Patterns&&e.Patterns.length>0)for(let a of e.Patterns){let o=a.Color??0,l=a.Pattern??"bs",c=y4e[o]||y4e[0];zYe(s,l,c,0,0,g4e*1,_4e*1)}return r},d9=new Map;function b4e(i,e,t){let n=VYe(e),r=HYe(n,t?.Patterns),s=d9.get(r);if(s)return s.refCount++,s.texture;let a=qYe(n,t);if(!a)return;let o=new sn(a);return o.magFilter=ct,o.minFilter=ct,o.needsUpdate=!0,d9.set(r,{texture:o,refCount:1}),o}function x4e(i){for(let[e,t]of d9.entries())if(t.texture===i){t.refCount--,t.refCount<=0&&(t.texture.dispose(),d9.delete(e));return}}function w4e(i,e,t,n,r=0,s=1,a=1){let u,d,f;t?(u=(-14.6+13.4)/2/16-.5,d=1-14.75/16-.5,f=1/2):(u=(1.4+29.4)/2/16,d=1-7.25/16-.5,f=0);let v=new _t({map:n,transparent:!0});v4e(v,r,s,a);let g=new Ke(new zn(.85,1.75),v);g.renderOrder=999;let b=.5/16,y=.25/16;t?g.position.set(0,u,d+y+.004):g.position.set(0,u,d+b/2+.004);let _=new bt;return _.rotation.set(0,-Ot.degToRad(e*(t?90:45/2)),0),_.add(g),_.bannerTexture=n,_.bannerMaterial=v,_.position.set(i.x+.5,i.y+f,i.z+.5),_}h();p();m();Lt();var S4e=Yr(V8(),1);var H5=new Map;function GYe(i,e,t){let n,r;return i&&"front_text"in i?(n=i.front_text?.messages??[],r=i.front_text?.color||"black"):(n=[i?.Text1,i?.Text2,i?.Text3,i?.Text4],r=i?.Color||"black"),`${e?1:0}|${t?1:0}|${r}|${n.join("\0")}`}function E4e(i,e,t,n=!1){let r=GYe(e,t,n),s=H5.get(r);if(s)return s.refCount++,s.texture;let a=(0,S4e.default)(i.version),o=k6e(e,t,a);if(!o)return;let l=new sn(o);return l.magFilter=ct,l.minFilter=ct,l.needsUpdate=!0,H5.set(r,{texture:l,refCount:1}),l}function M4e(i){for(let[e,t]of H5.entries())if(t.texture===i){t.refCount--,t.refCount<=0&&(t.texture.dispose(),H5.delete(e));return}}function A4e(){for(let[,i]of H5)i.texture.dispose();H5.clear()}var ro=class ro{constructor(e,t,n,r,s=3){this.worldRenderer=e;this.scene=t;this.material=n;this.worldHeight=r;this.updateViewDistance(s),this.signHeadsRenderer=new PP(e),this.initializePool()}renderOrigin={x:0,y:0,z:0};meshPool=[];activeSections=new Map;sectionObjects={};waitingChunksToDisplay={};pendingNearReveal=new Map;nearRevealTimers=new Map;nearRevealGraceTimers=new Map;poolSize;maxPoolSize;minPoolSize;signHeadsRenderer;blockEntityLightRegistry=new u9;chunkBoxMaterial=new _t({color:0,transparent:!0,opacity:0});cubeShaderMaterial=null;legacyShaderMaterial=null;globalLegacyShaderMaterial=null;globalLegacyBlendShaderMaterial=null;_legacyCullFrustum=new va;_legacyCullProjScreen=new Et;_legacyCullBox=new kn;_legacyCullBoxMin=new X;_legacyCullBoxMax=new X;_visibleSectionSpans=[];legacyCullSections=new Map;_lastCullFingerprint="";lastBufferStateKey="";cullDirty=!0;_lastCullCamPos=new X;_lastCullCamQuat=new qt;_cullViewQuat=new qt;_cullCamInitialized=!1;globalBlockBuffer=null;globalLegacyBuffer=null;globalLegacyBlendBuffer=null;shaderSectionRaycastBoxes=new Map;hits=0;misses=0;bypassPooling=!1;renderTimes=[];maxRenderTimeSamples=30;_performanceOverrideDistance;lastPerformanceCheck=0;performanceCheckInterval=2e3;get performanceOverrideDistance(){return this._performanceOverrideDistance??0}set performanceOverrideDistance(e){this._performanceOverrideDistance=e,this.updateSectionsVisibility()}initializePool(){for(let e=0;e<this.poolSize;e++){let t=new dt,n=new Ke(t,this.getLegacyShaderMaterial());n.visible=!1,n.matrixAutoUpdate=!1,n.name="pooled-section-mesh";let r={mesh:n,inUse:!1,lastUsedTime:0};this.meshPool.push(r)}}sectionHasRenderableContent(e){return e.positions.length>0||(e.blend?.positions.length??0)>0?!0:this.isShaderCubesGpuEnabled()?(e.shaderCubes?.count??0)>0:!1}isShaderCubesGpuEnabled(){return this.worldRenderer.shaderCubeBlocksEnabled()}syncCubeShaderUniforms(){if(!this.isShaderCubesGpuEnabled())return;let e=this.cubeShaderMaterial??this.getCubeShaderMaterial();if(!e)return;let t=this.material.map??null;e.uniforms.u_atlas.value=t;let n=n9();if(!n)return;let{tintPalette:r}=n;r.isReady()||r.createTexture(),e.uniforms.u_tintPalette.value=r.getTexture(),e.uniforms.u_debugMode.value=this.worldRenderer.worldRendererConfig.shaderCubeDebugMode??0,e.needsUpdate=!0}syncLegacyShaderUniforms(){let e=this.material.map??null;this.legacyShaderMaterial&&(this.legacyShaderMaterial.uniforms.u_atlas.value=e,this.legacyShaderMaterial.needsUpdate=!0),this.globalLegacyShaderMaterial&&(this.globalLegacyShaderMaterial.uniforms.u_atlas.value=e,this.globalLegacyShaderMaterial.needsUpdate=!0),this.globalLegacyBlendShaderMaterial&&(this.globalLegacyBlendShaderMaterial.uniforms.u_atlas.value=e,this.globalLegacyBlendShaderMaterial.needsUpdate=!0)}setSkyLevel(e){let t=this.cubeShaderMaterial??(this.isShaderCubesGpuEnabled()?this.getCubeShaderMaterial():null);t&&Jb(t,e),this.legacyShaderMaterial&&s9(this.legacyShaderMaterial,e),this.globalLegacyShaderMaterial&&s9(this.globalLegacyShaderMaterial,e),this.globalLegacyBlendShaderMaterial&&s9(this.globalLegacyBlendShaderMaterial,e),this.blockEntityLightRegistry.setSkyLevel(e)}setShadingTheme(e,t){let n=this.cubeShaderMaterial??(this.isShaderCubesGpuEnabled()?this.getCubeShaderMaterial():null);n&&bP(n,e,t)}setBlockLightmapParams(e){let t=this.cubeShaderMaterial??(this.isShaderCubesGpuEnabled()?this.getCubeShaderMaterial():null);t&&B_e(t,e),this.legacyShaderMaterial&&a9(this.legacyShaderMaterial,e),this.globalLegacyShaderMaterial&&a9(this.globalLegacyShaderMaterial,e),this.globalLegacyBlendShaderMaterial&&a9(this.globalLegacyBlendShaderMaterial,e),this.blockEntityLightRegistry.setLightmapParams(e)}getLegacyShaderMaterial(){return this.legacyShaderMaterial||(this.legacyShaderMaterial=$_e(),this.syncLegacyShaderUniforms()),this.legacyShaderMaterial}getGlobalLegacyShaderMaterial(){return this.globalLegacyShaderMaterial||(this.globalLegacyShaderMaterial=Y_e(),this.syncLegacyShaderUniforms()),this.globalLegacyShaderMaterial}getGlobalLegacyBuffer(){return this.globalLegacyBuffer||(this.globalLegacyBuffer=new ug(this.getGlobalLegacyShaderMaterial(),this.scene),this.globalLegacyBuffer.setRenderOrigin(this.renderOrigin)),this.globalLegacyBuffer}getGlobalLegacyBlendShaderMaterial(){return this.globalLegacyBlendShaderMaterial||(this.globalLegacyBlendShaderMaterial=J_e(),this.syncLegacyShaderUniforms()),this.globalLegacyBlendShaderMaterial}getGlobalLegacyBlendBuffer(){return this.globalLegacyBlendBuffer||(this.globalLegacyBlendBuffer=new ug(this.getGlobalLegacyBlendShaderMaterial(),this.scene,{name:"globalLegacyBlend",initialCapacityQuads:32e3,growthIncrementQuads:32e3}),this.globalLegacyBlendBuffer.setRenderOrigin(this.renderOrigin)),this.globalLegacyBlendBuffer}getRenderOrigin(){return this.renderOrigin}maybeRebase(e){let t=this.renderOrigin;if(Math.abs(e.x-t.x)<=ro.REBASE_THRESHOLD&&Math.abs(e.y-t.y)<=ro.REBASE_THRESHOLD&&Math.abs(e.z-t.z)<=ro.REBASE_THRESHOLD)return;let n={x:Math.round(e.x/16)*16,y:Math.round(e.y/16)*16,z:Math.round(e.z/16)*16},r={x:n.x-t.x,y:n.y-t.y,z:n.z-t.z};this.globalLegacyBuffer?.rebase(r),this.globalLegacyBlendBuffer?.rebase(r);for(let s of this.activeSections.values()){let a=s.sectionKey;if(!a)continue;let o=this.sectionObjects[a];o&&IP(s.mesh,o.worldX??0,o.worldY??0,o.worldZ??0,n)}this.renderOrigin=n,this.globalLegacyBuffer?.setRenderOrigin(n),this.globalLegacyBlendBuffer?.setRenderOrigin(n)}sectionUsesPooledLegacyMesh(e){return this.activeSections.has(e)}registerLegacyCullSection(e,t,n,r){this.legacyCullSections.set(e,{worldX:t,worldY:n,worldZ:r})}maybeUnregisterLegacyCullSection(e){let t=this.globalLegacyBuffer?.hasSection(e)??!1,n=this.globalLegacyBlendBuffer?.hasSection(e)??!1;!t&&!n&&this.legacyCullSections.delete(e)}updatePooledLegacyCullState(e,t,n){for(let r of this.activeSections.values()){let s=r.sectionKey;if(!s)continue;let a=this.sectionObjects[s];a&&K_e(r.mesh,a.worldX??0,a.worldY??0,a.worldZ??0,e,t,n,this._legacyCullFrustum,this._legacyCullBox,this._legacyCullBoxMin,this._legacyCullBoxMax)}}updateSectionCullAndSort(e,t,n,r){this._legacyCullProjScreen.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),this._legacyCullFrustum.setFromProjectionMatrix(this._legacyCullProjScreen);let s=this._visibleSectionSpans;s.length=0;for(let[b]of this.legacyCullSections){let y=this.sectionObjects[b];if(!y?.visible||y.worldX===void 0)continue;let{visible:_,distSq:x}=o9(y.worldX,y.worldY??0,y.worldZ??0,t,n,r,this._legacyCullFrustum,this._legacyCullBox,this._legacyCullBoxMin,this._legacyCullBoxMax);_&&s.push({key:b,distSq:x})}let a=this.globalLegacyBuffer,o=this.globalLegacyBlendBuffer,l=this.globalBlockBuffer,c=[];for(let b of s)a?.hasSection(b.key)&&c.push(b.key);c.sort();let u=s.filter(b=>o?.hasSection(b.key));u.sort((b,y)=>y.distSq-b.distSq);let d=u.map(b=>b.key),f=[],v=[];l&&l.forEachSectionSlot((b,y)=>{if(!this.sectionObjects[b]?.visible)return;let x=this.shaderSectionRaycastBoxes.get(b);if(!x)return;let{visible:w}=o9(x.sectionCenterX,x.sectionCenterY,x.sectionCenterZ,t,n,r,this._legacyCullFrustum,this._legacyCullBox,this._legacyCullBoxMin,this._legacyCullBoxMax);if(!w)return;f.push(b);let S=l.getSectionDrawStart(b),A=l.getSectionDrawCount(b);S!==void 0&&A!==void 0&&v.push({start:S,count:A})}),f.sort();let g=[c.join(","),d.join(","),f.join(","),a?.getLayoutVersion()??0,o?.getLayoutVersion()??0,l?.getLayoutVersion()??0,a?.getUploadEpoch()??0,o?.getUploadEpoch()??0,l?.getUploadEpoch()??0].join("|");if(g===this._lastCullFingerprint&&!this.hasPendingBufferWork()){this.updatePooledLegacyCullState(t,n,r);return}if(this._lastCullFingerprint=g,a?.updateDrawSpans(s,"opaque"),o?.updateDrawSpans(s,"sortedBlend"),l){let b=s4e(v,l.getHighWatermark(),l.canUseFullDrawShortcut(),(y,_)=>l.isRangeFullyUploaded(y,_),l.getPendingDirtyRanges());l.setVisibleSpans(b)}this.lastBufferStateKey=this.bufferStateKey(),this.updatePooledLegacyCullState(t,n,r)}bufferStateKey(){let e=this.globalBlockBuffer,t=this.globalLegacyBuffer,n=this.globalLegacyBlendBuffer;return[t?.getLayoutVersion()??0,t?.getUploadEpoch()??0,n?.getLayoutVersion()??0,n?.getUploadEpoch()??0,e?.getLayoutVersion()??0,e?.getUploadEpoch()??0].join("|")}markCullDirtyIfBufferStateChanged(){this.bufferStateKey()!==this.lastBufferStateKey&&this.markCullDirty()}markCullDirty(){this.cullDirty=!0}hasPendingBufferWork(){return[this.globalLegacyBuffer,this.globalLegacyBlendBuffer,this.globalBlockBuffer].some(t=>t!=null&&(t.hasPendingUploads()||t.hasPendingReplace()||t.getPendingMove()!=null))}updateCullDirtyFromCamera(e,t,n,r){if(e.getWorldQuaternion(this._cullViewQuat),!this._cullCamInitialized){this._lastCullCamPos.set(t,n,r),this._lastCullCamQuat.copy(this._cullViewQuat),this._cullCamInitialized=!0,this.cullDirty=!0;return}let s=this._lastCullCamPos.x!==t||this._lastCullCamPos.y!==n||this._lastCullCamPos.z!==r,a=this._lastCullCamQuat.x!==this._cullViewQuat.x||this._lastCullCamQuat.y!==this._cullViewQuat.y||this._lastCullCamQuat.z!==this._cullViewQuat.z||this._lastCullCamQuat.w!==this._cullViewQuat.w;(s||a)&&(this._lastCullCamPos.set(t,n,r),this._lastCullCamQuat.copy(this._cullViewQuat),this.markCullDirty())}clearCullDirty(){this.cullDirty=!1}setLegacyCameraOrigin(e,t,n){let r=this.renderOrigin;i9(this.getLegacyShaderMaterial(),r,e,t,n),i9(this.getGlobalLegacyShaderMaterial(),r,e,t,n),i9(this.getGlobalLegacyBlendShaderMaterial(),r,e,t,n),this.globalLegacyBuffer?.setCameraOrigin(e,t,n),this.globalLegacyBlendBuffer?.setCameraOrigin(e,t,n);let s=this.cubeShaderMaterial;if(s){let{originDelta:a,cameraOriginFrac:o}=$d(r,e,t,n),l=Kb(r),c=s.uniforms.u_originDelta;c?.value?.set&&c.value.set(a.x,a.y,a.z);let u=s.uniforms.u_cameraOriginFrac;u?.value?.set&&u.value.set(o.x,o.y,o.z);let d=s.uniforms.u_sectionOriginRel;d?.value?.set&&d.value.set(l.x,l.y,l.z)}}getCubeShaderMaterial(){if(!this.isShaderCubesGpuEnabled())return null;if(!this.cubeShaderMaterial){this.cubeShaderMaterial=Yb(),this.syncCubeShaderUniforms();let e=this.worldRenderer.worldRendererConfig;bP(this.cubeShaderMaterial,e.shadingTheme,e.cardinalLight)}return this.cubeShaderMaterial}getGlobalBlockBuffer(){let e=this.getCubeShaderMaterial();return e?(this.globalBlockBuffer||(this.globalBlockBuffer=new c9(e,this.scene)),this.globalBlockBuffer):null}shouldDeferLegacyOpaqueToPerSection(e){return this.shouldDeferShaderToPerSection(e)}shouldDeferShaderToPerSection(e){return this.worldRenderer.getModule("futuristicReveal")?.shouldDeferSectionGeometry?.(e)===!0}migrateDeferredShaderToGlobal(e){let t=this.sectionObjects[e];if(!t?.deferredShaderCubes)return;let{words:n,count:r}=t.deferredShaderCubes,s=t.worldX,a=t.worldY,o=t.worldZ;s!==void 0&&a!==void 0&&o!==void 0&&this.registerShaderSectionRaycastBox(e,n,r,s,a,o),this.getGlobalBlockBuffer()?.addSection(e,n,r),this.markCullDirty();let c=t.mesh===t.shaderMesh;t.shaderMesh&&(SP(t.shaderMesh),t.remove(t.shaderMesh),t.shaderMesh=void 0),delete t.deferredShaderCubes,c&&(t.mesh=void 0)}migrateDeferredLegacyToGlobal(e){let t=this.sectionObjects[e];if(t){if(t.deferredLegacyOpaque){let{positions:n,colors:r,skyLights:s,blockLights:a,uvs:o,indices:l}=t.deferredLegacyOpaque,c=t.worldX,u=t.worldY,d=t.worldZ;c!==void 0&&u!==void 0&&d!==void 0&&this.getGlobalLegacyBuffer().addSection(e,{positions:n,colors:r,skyLights:s,blockLights:a,uvs:o,indices:l},c,u,d)&&this.registerLegacyCullSection(e,c,u,d),delete t.deferredLegacyOpaque}if(t.deferredLegacyBlend){let{positions:n,colors:r,skyLights:s,blockLights:a,uvs:o,indices:l}=t.deferredLegacyBlend,c=t.worldX,u=t.worldY,d=t.worldZ;c!==void 0&&u!==void 0&&d!==void 0&&this.getGlobalLegacyBlendBuffer().addSection(e,{positions:n,colors:r,skyLights:s,blockLights:a,uvs:o,indices:l},c,u,d)&&this.registerLegacyCullSection(e,c,u,d),delete t.deferredLegacyBlend,t.hasBlendMesh=!1}if(!t.hasBlendMesh){let n=t.mesh===this.activeSections.get(e)?.mesh;this.releasePooledMesh(e),n&&(t.mesh=t.shaderMesh??void 0)}this.markCullDirty()}}registerShaderSectionRaycastBox(e,t,n,r,s,a){let o=h4e(t,n,r,s,a);o?this.shaderSectionRaycastBoxes.set(e,{box:o,sectionCenterX:r,sectionCenterY:s,sectionCenterZ:a}):this.shaderSectionRaycastBoxes.delete(e)}unregisterShaderSectionRaycastBox(e){this.shaderSectionRaycastBoxes.delete(e)}uploadLegacyPooledMesh(e,t,n,r,s){let{mesh:a}=e,o=t;return this.updateGeometryAttribute(a.geometry,"position",o.positions,3),this.updateGeometryAttribute(a.geometry,"normal",o.normals,3),this.updateGeometryAttribute(a.geometry,"color",o.colors,3),this.updateGeometryAttribute(a.geometry,"a_skyLight",o.skyLights,1),this.updateGeometryAttribute(a.geometry,"a_blockLight",o.blockLights,1),this.updateGeometryAttribute(a.geometry,"uv",o.uvs,2),a.geometry.index=new Mt(o.indices,1),a.geometry.boundingBox=new kn(new X(-8,-8,-8),new X(8,8,8)),a.geometry.boundingSphere=new Tn(new X(0,0,0),Math.sqrt(3*8**2)),IP(a,n,r,s,this.renderOrigin),a.visible=!1,a.name="mesh",e.lastUsedTime=performance.now(),a}acquirePooledSectionMesh(e){let t=this.activeSections.get(e);if(!t){if(t=this.acquireMesh(),!t)return console.warn(`ChunkMeshManager: No available mesh in pool for section ${e}`),null;this.activeSections.set(e,t),t.sectionKey=e}return t}updateSection(e,t){let n=t.positions.length>0,r=(t.blend?.positions.length??0)>0,s=n||r,a=t.shaderCubes,o=this.isShaderCubesGpuEnabled()&&(a?.count??0)>0,l=n&&this.shouldDeferLegacyOpaqueToPerSection(e),c=r&&this.shouldDeferLegacyOpaqueToPerSection(e),u=o&&this.shouldDeferShaderToPerSection(e),d=n&&!l,f=r&&!c,v=o&&!!a&&!u;if(!s&&!o)return this.releaseSection(e),null;let g=this.sectionObjects[e],b=g!=null;g&&this.cleanupSection(e,{forRemesh:!0}),b&&(v||this.globalBlockBuffer?.removeSection(e),d||this.globalLegacyBuffer?.removeSection(e),f||this.globalLegacyBlendBuffer?.removeSection(e),o&&a||this.unregisterShaderSectionRaycastBox(e),!d&&!f&&this.maybeUnregisterLegacyCullSection(e)),r||this.releasePooledMesh(e);let y,_,x,w=!1;if(n){let B={positions:t.positions,colors:t.colors,skyLights:t.skyLights,blockLights:t.blockLights,uvs:t.uvs,indices:t.indices};if(l){if(_={positions:new Float32Array(B.positions),colors:new Float32Array(B.colors),skyLights:new Float32Array(B.skyLights),blockLights:new Float32Array(B.blockLights),uvs:new Float32Array(B.uvs),indices:B.indices instanceof Uint32Array?new Uint32Array(B.indices):new Uint16Array(B.indices)},!r){let U=this.acquirePooledSectionMesh(e);if(!U)return null;y=this.uploadLegacyPooledMesh(U,t,t.sx,t.sy,t.sz)}}else if(this.getGlobalLegacyBuffer().addSection(e,B,t.sx,t.sy,t.sz))this.registerLegacyCullSection(e,t.sx,t.sy,t.sz);else{let O=this.acquirePooledSectionMesh(e);if(!O)return null;y=this.uploadLegacyPooledMesh(O,t,t.sx,t.sy,t.sz)}}if(r&&t.blend){let B={positions:t.blend.positions,colors:t.blend.colors,skyLights:t.blend.skyLights,blockLights:t.blend.blockLights,uvs:t.blend.uvs,indices:t.blend.indices};if(c){x={positions:new Float32Array(B.positions),colors:new Float32Array(B.colors),skyLights:new Float32Array(B.skyLights),blockLights:new Float32Array(B.blockLights),uvs:new Float32Array(B.uvs),indices:B.indices instanceof Uint32Array?new Uint32Array(B.indices):new Uint16Array(B.indices)};let U=this.acquirePooledSectionMesh(e);if(!U)return null;let O=this.uploadLegacyPooledMesh(U,t.blend,t.sx,t.sy,t.sz);y=y??O,w=!0}else if(this.getGlobalLegacyBlendBuffer().addSection(e,B,t.sx,t.sy,t.sz))this.registerLegacyCullSection(e,t.sx,t.sy,t.sz);else{console.warn(`ChunkMeshManager: blend invariant violation for section ${e}, using pooled mesh fallback`);let O=this.acquirePooledSectionMesh(e);if(!O)return null;let V=this.uploadLegacyPooledMesh(O,t.blend,t.sx,t.sy,t.sz);y=y??V,w=!0}}let S=o?this.getCubeShaderMaterial():null,A;o&&a&&(u&&S?(A=r9(a,S),A.visible=!0):this.getGlobalBlockBuffer()?.addSection(e,a.words,a.count)),g=new bt,y&&(g.add(y),g.mesh=y),A&&(g.add(A),g.shaderMesh=A,a&&(g.deferredShaderCubes={words:a.words,count:a.count}),g.mesh||(g.mesh=A)),_&&(g.deferredLegacyOpaque=_),x&&(g.deferredLegacyBlend=x),o&&a&&this.registerShaderSectionRaycastBox(e,a.words,a.count,t.sx,t.sy,t.sz);let T=0;n&&(T+=t.positions.length/3/4),r&&t.blend&&(T+=t.blend.positions.length/3/4),o&&a&&(T+=a.count),g.tilesCount=T,g.hasBlendMesh=w,g.blocksCount=t.blocksCount,g.worldX=t.sx,g.worldY=t.sy,g.worldZ=t.sz,g.sectionKey=e,g.name="chunk";try{if(Object.keys(t.signs).length>0){let B=new bt;B.name="signs";for(let[U,{isWall:O,isHanging:V,rotation:F}]of Object.entries(t.signs)){let J=this.worldRenderer.blockEntities[U];if(!J)continue;let[$,ne,se]=U.split(","),j=this.signHeadsRenderer.renderSign(new kt(+$,+ne,+se),F,O,V,f9.simplify(J));j&&B.add(j)}g.add(B),g.signsContainer=B}if(Object.keys(t.heads).length>0){let B=new bt;B.name="heads";for(let[U,{isWall:O,rotation:V}]of Object.entries(t.heads)){let F=this.worldRenderer.blockEntities[U];if(!F)continue;let[J,$,ne]=U.split(","),se=this.signHeadsRenderer.renderHead(new kt(+J,+$,+ne),V,O,f9.simplify(F));se&&B.add(se)}g.add(B),g.headsContainer=B}if(Object.keys(t.banners).length>0){let B=new bt;B.name="banners",g.bannersContainer=B,g.add(B);for(let[U,O]of Object.entries(t.banners)){let{isWall:V,rotation:F,blockName:J,blockLightNorm:$=0,skyLightNorm:ne=1}=O,se=this.worldRenderer.blockEntities[U];if(!se)continue;let[j,q,z]=U.split(","),K=b4e(this.worldRenderer,J,f9.simplify(se));if(!K)continue;let re=this.blockEntityLightRegistry.getSkyLevel(),Z=w4e(new kt(+j,+q,+z),F,V,K,$,ne,re);Z.bannerMaterial&&this.blockEntityLightRegistry.register({material:Z.bannerMaterial,blockLightNorm:$,skyLightNorm:ne});let{x:Y,y:Q,z:ue}=Z.position;this.worldRenderer.sceneOrigin.track(Z),Z.position.set(Y,Q,ue),B.add(Z)}}}catch(B){console.error("ChunkMeshManager: Error adding signs, heads, or banners to section",B)}this.sectionObjects[e]=g,this.scene.add(g),g.matrixAutoUpdate=!1,this.worldRenderer.displayOptions?.inWorldRenderingConfig?.showChunkBorders&&this.updateBoxHelper(e,!0);let P=e.split(","),I=`${P[0]},${P[2]}`,k=!!this.worldRenderer.displayOptions?.inWorldRenderingConfig?._renderByChunks,L=!!this.worldRenderer.worldRendererConfig?.wasmMesher;if((k||L)&&!this.worldRenderer.finishedChunks[I]){g.visible=!1,g._waitingForChunkDisplay=!0;let B=this.waitingChunksToDisplay[I]??(this.waitingChunksToDisplay[I]=[]);B.includes(e)||B.push(e)}return this.markCullDirty(),g}finishChunkDisplay(e){if(!this.waitingChunksToDisplay[e]){this.tryRevealPending();return}if(this.isWasmGateActive()&&this.isBlockedByNearer(e,0)){this.pendingNearReveal.set(e,Date.now()),this.armNearRevealTimer(e),this.armExpectedGraceTimer(e),this.tryRevealPending();return}this.flushChunkDisplay(e),this.tryRevealPending()}flushChunkDisplay(e){let t=this.waitingChunksToDisplay[e];if(this.pendingNearReveal.delete(e),this.clearNearRevealTimer(e),this.clearExpectedGraceTimer(e),!!t){for(let n of t){let r=this.sectionObjects[n];r&&(r._waitingForChunkDisplay=!1,r.visible=!0)}delete this.waitingChunksToDisplay[e],this.markCullDirty()}}tryRevealPending(){if(this.pendingNearReveal.size===0)return;let e=Date.now();for(let[t,n]of[...this.pendingNearReveal])this.isBlockedByNearer(t,e-n)||this.flushChunkDisplay(t)}onChunkRemovedFromGate(e){this.pendingNearReveal.delete(e),this.clearNearRevealTimer(e),this.clearExpectedGraceTimer(e),delete this.waitingChunksToDisplay[e],this.tryRevealPending()}isWasmGateActive(){return!!this.worldRenderer.worldRendererConfig?.wasmMesher}isBlockedByNearer(e,t){let n=this.worldRenderer.viewerChunkPosition;if(!n)return!1;let r=e.split(",");if(r.length!==2)return!1;let s=Number(r[0]),a=Number(r[1]),o=Math.floor(n.x/16),l=Math.floor(n.z/16),c=(s>>4)-o,u=(a>>4)-l,d=c*c+u*u;if(d===0)return!1;let f=this.worldRenderer.finishedChunks,v=this.worldRenderer.loadedChunks,g=this.worldRenderer.viewDistance;if(t<ro.EXPECTED_NEAR_GRACE_MS&&g>0){let y=g*g,_=Math.min(g,Math.ceil(Math.sqrt(Math.max(0,d-1))));for(let x=-_;x<=_;x++)for(let w=-_;w<=_;w++){let S=x*x+w*w;if(S>=d||S>y)continue;let A=o+x<<4,T=l+w<<4,P=`${A},${T}`;if(P!==e&&v[P]&&!f[P])return!0}return!1}for(let y in v){if(y===e||f[y])continue;let _=y.split(",");if(_.length!==2)continue;let x=(Number(_[0])>>4)-o,w=(Number(_[1])>>4)-l;if(x*x+w*w<d)return!0}return!1}armNearRevealTimer(e){if(this.nearRevealTimers.has(e))return;let t=setTimeout(()=>{this.nearRevealTimers.delete(e),this.pendingNearReveal.has(e)&&(console.warn(`[chunk-reveal] safety timeout for ${e} \u2014 a nearer pending column never finished, force-revealing`),this.flushChunkDisplay(e),this.tryRevealPending())},ro.NEAR_REVEAL_TIMEOUT_MS);this.nearRevealTimers.set(e,t)}clearNearRevealTimer(e){let t=this.nearRevealTimers.get(e);t&&(clearTimeout(t),this.nearRevealTimers.delete(e))}armExpectedGraceTimer(e){if(this.nearRevealGraceTimers.has(e))return;let t=setTimeout(()=>{this.nearRevealGraceTimers.delete(e),this.pendingNearReveal.has(e)&&this.tryRevealPending()},ro.EXPECTED_NEAR_GRACE_MS+50);this.nearRevealGraceTimers.set(e,t)}clearExpectedGraceTimer(e){let t=this.nearRevealGraceTimers.get(e);t&&(clearTimeout(t),this.nearRevealGraceTimers.delete(e))}cleanupSection(e,t){let n=this.sectionObjects[e];if(n){if(n._waitingForChunkDisplay){let r=e.split(","),s=`${r[0]},${r[2]}`,a=this.waitingChunksToDisplay[s];if(a){let o=a.indexOf(e);o!==-1&&a.splice(o,1),a.length===0&&delete this.waitingChunksToDisplay[s]}}if(n.bannersContainer){for(let r of n.bannersContainer.children){let s=r;s.bannerMaterial&&this.blockEntityLightRegistry.unregister(s.bannerMaterial),s.bannerTexture&&x4e(s.bannerTexture)}this.disposeContainer(n.bannersContainer)}if(t?.forRemesh||(this.globalBlockBuffer?.removeSection(e),this.globalLegacyBuffer?.removeSection(e),this.globalLegacyBlendBuffer?.removeSection(e),this.maybeUnregisterLegacyCullSection(e),this.unregisterShaderSectionRaycastBox(e)),this.markCullDirty(),delete n.deferredLegacyOpaque,delete n.deferredLegacyBlend,n.shaderMesh&&(SP(n.shaderMesh),n.shaderMesh=void 0),delete n.deferredShaderCubes,n.signsContainer){for(let r of n.signsContainer.children){let s=r;s.signTexture&&M4e(s.signTexture)}this.disposeContainer(n.signsContainer,!1)}if(n.headsContainer&&this.disposeContainer(n.headsContainer),this.worldRenderer.sceneOrigin.removeAndUntrackAll(n),this.scene.remove(n),n.boxHelper){this.worldRenderer.sceneOrigin.removeAndUntrack(n.boxHelper),this.scene.remove(n.boxHelper),n.boxHelper.geometry.dispose();let r=n.boxHelper.material;if(Array.isArray(r))for(let s of r)s.dispose();else r.dispose();n.boxHelper=void 0}delete this.sectionObjects[e],t?.forRemesh||this.worldRenderer.getModule("futuristicReveal")?.onSectionRemoved?.(e)}}releasePooledMesh(e){let t=this.activeSections.get(e);t&&(t.mesh.visible=!1,t.inUse=!1,t.sectionKey=void 0,t.lastUsedTime=0,this.clearGeometry(t.mesh.geometry),this.activeSections.delete(e),this.cleanupExcessMeshes())}releaseSection(e){this.cleanupSection(e);let t=this.activeSections.get(e);return t?(t.mesh.visible=!1,t.inUse=!1,t.sectionKey=void 0,t.lastUsedTime=0,this.clearGeometry(t.mesh.geometry),this.activeSections.delete(e),this.cleanupExcessMeshes(),!0):!1}getSectionObject(e){return this.sectionObjects[e]}updateBoxHelper(e,t,n=this.chunkBoxMaterial){let r=this.sectionObjects[e];if(r)if(t){if(!r.boxHelper){let s=new Ke(new Sn(16,16,16),n),a=new Ea(s,16776960);a.name="helper";let o=r.worldX??0,l=r.worldY??0,c=r.worldZ??0;this.worldRenderer.sceneOrigin.track(a,{updateMatrix:!0}),a.position.set(o,l,c),a.updateMatrix(),this.scene.add(a),r.boxHelper=a}r.boxHelper.visible=!0}else r.boxHelper&&(r.boxHelper.visible=!1)}updateAllBoxHelpers(e){for(let t of Object.keys(this.sectionObjects))this.updateBoxHelper(t,e)}getSectionMesh(e){return this.activeSections.get(e)?.mesh}hasSection(e){return this.activeSections.has(e)}updateViewDistance(e){let t=(e*2+1)**2,n=this.worldHeight/16,r=5;if(this.minPoolSize=Math.floor(t*r),this.maxPoolSize=Math.floor(t*n)+1,this.poolSize??=this.minPoolSize,this.minPoolSize>this.poolSize){let s=Math.min(this.minPoolSize,this.maxPoolSize);this.expandPool(s)}console.log(`ChunkMeshManager: Updated view max distance to ${e}, pool: ${this.poolSize}/${this.maxPoolSize}, optimal: ${this.minPoolSize}`)}getGlobalBufferStats(){let e=n=>n?{used:n.getHighWatermark(),capacity:n.getCapacityQuads(),sections:n.getSectionCount(),usedBytes:n.getUsedMemoryBytes(),capacityBytes:n.getMemoryBytes()}:null,t=this.globalBlockBuffer;return{shaderFaces:t?{used:t.getHighWatermark(),capacity:t.getCapacityFaces(),sections:t.getSectionCount(),usedBytes:t.getUsedMemoryBytes(),capacityBytes:t.getMemoryBytes()}:null,legacyOpaque:e(this.globalLegacyBuffer),legacyBlend:e(this.globalLegacyBlendBuffer)}}getStats(){let e=this.meshPool.filter(r=>!r.inUse).length,t=this.hits+this.misses>0?(this.hits/(this.hits+this.misses)*100).toFixed(1):"0",n=this.getEstimatedMemoryUsage();return{poolSize:this.poolSize,activeCount:this.activeSections.size,freeCount:e,hitRate:`${t}%`,hits:this.hits,misses:this.misses,memoryUsage:n}}getTotalTiles(){return Object.values(this.sectionObjects).reduce((e,t)=>e+(t.tilesCount||0),0)}getTotalBlocks(){return Object.values(this.sectionObjects).reduce((e,t)=>e+(t.blocksCount||0),0)}getEstimatedMemoryUsage(){let e=0,t=0,n=0,r=0,s=0,a=0,o=0,l=this.globalBlockBuffer?.mesh.geometry;if(l)for(let f of["a_w0","a_w1","a_w2","a_w3"]){let v=l.getAttribute(f);if(v){let g=v.array.byteLength;o+=g,e+=g}}let c=this.globalLegacyBuffer?.getMemoryBytes()??0,u=this.globalLegacyBlendBuffer?.getMemoryBytes()??0;e+=c+u,t+=c+u;for(let f of Object.values(this.sectionObjects)){let v=f.shaderMesh?.geometry;if(v)for(let g of["a_w0","a_w1","a_w2","a_w3"]){let b=v.getAttribute(g);if(b){let y=b.array.byteLength;o+=y,e+=y}}}for(let f of this.meshPool)if(f.inUse&&f.mesh.geometry){let{geometry:v}=f.mesh,g=v.getAttribute("position");if(g){let x=g.array.byteLength;t+=x,e+=x}let b=v.getAttribute("normal");if(b){let x=b.array.byteLength;n+=x,e+=x}let y=v.getAttribute("color");if(y){let x=y.array.byteLength;r+=x,e+=x}let _=v.getAttribute("uv");if(_){let x=_.array.byteLength;s+=x,e+=x}if(v.index){let x=v.index.array.byteLength;a+=x,e+=x}}return{total:`${(e/(1024*1024)).toFixed(2)} MB`,breakdown:{position:`${(t/(1024*1024)).toFixed(2)} MB`,normal:`${(n/(1024*1024)).toFixed(2)} MB`,color:`${(r/(1024*1024)).toFixed(2)} MB`,uv:`${(s/(1024*1024)).toFixed(2)} MB`,index:`${(a/(1024*1024)).toFixed(2)} MB`,shaderInstances:`${(o/(1024*1024)).toFixed(2)} MB`}}}dispose(){let e=[...this.activeSections.keys()];for(let t of e)this.releaseSection(t);this.signHeadsRenderer.dispose();for(let t of this.meshPool)t.mesh.geometry.dispose();this.meshPool.length=0,this.activeSections.clear(),this.chunkBoxMaterial.dispose(),this.shaderSectionRaycastBoxes.clear(),this.lastBufferStateKey="",this.globalBlockBuffer?.dispose(),this.globalBlockBuffer=null,this.globalLegacyBuffer?.dispose(),this.globalLegacyBuffer=null,this.globalLegacyBlendBuffer?.dispose(),this.globalLegacyBlendBuffer=null,this.cubeShaderMaterial?.dispose(),this.cubeShaderMaterial=null,this.legacyShaderMaterial?.dispose(),this.legacyShaderMaterial=null,this.globalLegacyShaderMaterial?.dispose(),this.globalLegacyShaderMaterial=null,this.globalLegacyBlendShaderMaterial?.dispose(),this.globalLegacyBlendShaderMaterial=null,this.pendingNearReveal.clear();for(let t of this.nearRevealTimers.values())clearTimeout(t);this.nearRevealTimers.clear();for(let t of this.nearRevealGraceTimers.values())clearTimeout(t);this.nearRevealGraceTimers.clear()}acquireMesh(){if(this.bypassPooling){let t={mesh:new Ke(new dt,this.getLegacyShaderMaterial()),inUse:!0,lastUsedTime:performance.now()};return this.meshPool.push(t),this.poolSize++,t}for(let t of this.meshPool)if(!t.inUse)return t.inUse=!0,t.lastUsedTime=performance.now(),this.hits++,t;this.misses++;let e=Math.min(this.poolSize+16,this.maxPoolSize);e<=this.meshPool.length&&(e=this.meshPool.length+8,this.maxPoolSize=e,console.warn(`ChunkMeshManager: Pool exhausted (${this.poolSize}/${this.maxPoolSize}). Emergency expansion to ${e}`)),this.expandPool(e);for(let t=this.meshPool.length-1;t>=0;t--){let n=this.meshPool[t];if(!n.inUse)return n.inUse=!0,n.lastUsedTime=performance.now(),n}throw new Error("ChunkMeshManager: Failed to acquire mesh after pool expansion")}expandPool(e){let t=this.meshPool.length;this.poolSize=e;for(let n=t;n<e;n++){let r=new dt,s=new Ke(r,this.getLegacyShaderMaterial());s.visible=!1,s.matrixAutoUpdate=!1,s.name="pooled-section-mesh";let a={mesh:s,inUse:!1,lastUsedTime:0};this.meshPool.push(a)}}updateGeometryAttribute(e,t,n,r){let s=e.getAttribute(t);s&&s.count===n.length/r?(s.array.set(n),s.needsUpdate=!0):e.setAttribute(t,new Mt(n,r))}clearGeometry(e){let t=["position","normal","color","a_skyLight","a_blockLight","uv"];for(let n of t)e.hasAttribute(n)&&e.deleteAttribute(n);e.index&&e.setIndex(null),e.boundingBox=null,e.boundingSphere=null}cleanupExcessMeshes(){if(this.poolSize>this.maxPoolSize){let e=this.meshPool.filter(t=>!t.inUse).length;if(e>0){let t=Math.min(this.poolSize-this.maxPoolSize,e);for(let n=0;n<t;n++){let r=this.meshPool.findIndex(s=>!s.inUse);r!==-1&&(this.meshPool[r].mesh.geometry.dispose(),this.meshPool.splice(r,1),this.poolSize--)}}}}disposeContainer(e,t=!0){dr(e,t)}recordRenderTime(e){this.renderTimes.push(e),this.renderTimes.length>this.maxRenderTimeSamples&&this.renderTimes.shift();let t=performance.now();t-this.lastPerformanceCheck>this.performanceCheckInterval&&(this.checkPerformance(),this.lastPerformanceCheck=t)}getEffectiveRenderDistance(){return this.performanceOverrideDistance||this.worldRenderer.viewDistance}resetPerformanceOverride(){this.performanceOverrideDistance=void 0,this.renderTimes.length=0,console.log("ChunkMeshManager: Performance override reset")}getAverageRenderTime(){return this.renderTimes.length===0?0:this.renderTimes.reduce((e,t)=>e+t,0)/this.renderTimes.length}checkPerformance(){if(this.renderTimes.length<this.maxRenderTimeSamples)return;let e=this.getAverageRenderTime(),t=16.67,n=t*1.5;if(e>n){let r=this.worldRenderer.viewDistance,s=Math.max(1,Math.floor(r*.8));(!this.performanceOverrideDistance||s<this.performanceOverrideDistance)&&(this.performanceOverrideDistance=s,console.warn(`ChunkMeshManager: Performance degraded (${e.toFixed(2)}ms avg). Reducing effective render distance to ${s}`))}else if(this.performanceOverrideDistance&&e<t*1.1){let r=this.worldRenderer.viewDistance,s=Math.min(r,this.performanceOverrideDistance+1);s!==this.performanceOverrideDistance&&(this.performanceOverrideDistance=s>=r?void 0:s,console.log(`ChunkMeshManager: Performance improved. Restoring render distance to ${s}`))}}updateSectionsVisibility(){let e=this.worldRenderer.cameraSectionPos;for(let[t,n]of Object.entries(this.sectionObjects)){if(n._waitingForChunkDisplay){n.visible=!1;continue}if(!this.performanceOverrideDistance){n.visible=!0;continue}let[r,s,a]=t.split(",").map(Number),o={x:r/16,y:s/16,z:a/16},l=o.x-e.x,c=o.z-e.z,u=Math.floor(Math.hypot(l,c));n.visible=u<=this.performanceOverrideDistance}}};Wn(ro,"REBASE_THRESHOLD",65536),Wn(ro,"NEAR_REVEAL_TIMEOUT_MS",5e3),Wn(ro,"EXPECTED_NEAR_GRACE_MS",1500);var fg=ro,PP=class{constructor(e){this.worldRendererThree=e}dispose(){A4e()}renderHead(e,t,n,r){let s;if(r.SkullOwner?s=r.SkullOwner.Properties?.textures?.[0]?.Value:s=r.profile?.properties?.find(a=>a.name==="textures")?.value,!!s)try{let o=JSON.parse(Buffer.from(s,"base64").toString()).textures?.SKIN?.url,{skinTexturesProxy:l}=this.worldRendererThree.worldRendererConfig;l&&(o=o?.replace("http://textures.minecraft.net/",l).replace("https://textures.minecraft.net/",l));let c=$c(this.worldRendererThree,o,Yc.head),u=new bt;return n&&c.position.set(0,.3125,.3125),c.position.y-=23/16,u.add(c),this.worldRendererThree.sceneOrigin.track(u),u.position.set(e.x+.5,e.y+.045,e.z+.5),u.rotation.set(0,-Ot.degToRad(t*(n?90:45/2)),0),u.scale.set(.8,.8,.8),u}catch(a){console.error("Error decoding player texture:",a)}}renderSign(e,t,n,r,s){let a=E4e(this.worldRendererThree,s,r);if(!a)return;let o=new Ke(new zn(1,1),new _t({map:a,transparent:!0}));o.renderOrder=999;let l=7/16,c=r?1.3:1;o.scale.set(1*c,l*c,1*c);let u=(r?2:1.5)/16,d=.25/16;n&&!r?o.position.set(0,0,-.5+u+d+1e-4):o.position.set(0,0,u/2+1e-4);let f=new bt;f.rotation.set(0,-Ot.degToRad(t*(n?90:45/2)),0),f.add(o),f.signTexture=a;let v=(r?10:8)/16,g=(r?0:n?4.333:9.333)/16,b=v/2+g;return this.worldRendererThree.sceneOrigin.track(f),f.position.set(e.x+.5,e.y+b,e.z+.5),f}};h();p();m();var h9=(i,e)=>e===0?1/0:e<0?h9(-i,-e):(1-(i-Math.floor(i)))/e,WYe=(i,e,t,n,r,s,a,o,l,c,u,d)=>{let f=a-u,v=o-u,g=l-u,b=a+1+u,y=o+1+u,_=l+1+u,x=m4e(i,e,t,n,r,s,f,v,g,b,y,_,c);if(x===void 0&&(x=p4e(i,e,t,n,r,s,f,v,g,b,y,_,c)),x!==void 0)return Math.max(d,x)};function k4e(i,e,t,n,r,s,a,o,l,c){if(a<=0)return;let u=Math.floor(i),d=Math.floor(e),f=Math.floor(t),v=n>0?1:n<0?-1:0,g=r>0?1:r<0?-1:0,b=s>0?1:s<0?-1:0,y=v!==0?Math.abs(1/n):1/0,_=g!==0?Math.abs(1/r):1/0,x=b!==0?Math.abs(1/s):1/0,w=v!==0?h9(i,n):1/0,S=g!==0?h9(e,r):1/0,A=b!==0?h9(t,s):1/0,T=(k,L,B)=>{if(!c(k,L,B))return;let U=WYe(i,e,t,n,r,s,k,L,B,a,o,l);if(!(U===void 0||U>a))return{distance:U,blockX:k,blockY:L,blockZ:B}},P=T(u,d,f);if(P)return P;let I=0;for(;I<=a&&(w<S?w<A?(u+=v,I=w,w+=y):(f+=b,I=A,A+=x):S<A?(d+=g,I=S,S+=_):(f+=b,I=A,A+=x),!(I>a));)if(P=T(u,d,f),P)return P}h();p();m();h();p();m();Lt();var m9={},T4e=!1;function jYe(){if(T4e)return;let i=globalThis.loadedData?.tints;if(i){for(let e of Object.keys(i))m9[e]=XYe(i[e]);T4e=!0}}function XYe(i){let e={},t=I4e(i.default??16777215);if(i.data)for(let n of i.data){let r=I4e(n.color);for(let s of n.keys)e[s]=r}return new Proxy(e,{get(n,r){return n[r]??t}})}function I4e(i){return[(i>>16&255)/255,(i>>8&255)/255,(i&255)/255]}function R4e(i,e){return jYe(),i==="grass_block"?[1,1,1]:i==="redstone_wire"?[1,1,1]:i==="birch_leaves"||i==="spruce_leaves"||i==="lily_pad"?m9.constant?.[i]??[1,1,1]:i.includes("leaves")||i==="vine"?m9.foliage?.[e]??[1,1,1]:["short_grass","tall_grass","fern","large_fern","sugar_cane","grass"].includes(i)?m9.grass?.[e]??[1,1,1]:[1,1,1]}var $Ye=512,LP=1/20,BP=class{constructor(e){this.worldRenderer=e}particles=[];sharedMaterial;enabled=!1;tickAccumulator=0;nextParticleIndex=0;enable(){this.enabled||(this.enabled=!0,this.ensureMaterial())}disable(){this.enabled&&(this.enabled=!1)}dispose(){for(let e of this.particles)e.active&&this.worldRenderer.sceneOrigin.removeAndUntrack(e.mesh),e.mesh.geometry.dispose();this.particles=[],this.sharedMaterial?.dispose(),this.sharedMaterial=void 0,this.nextParticleIndex=0}render=e=>{if(!this.enabled)return;for(this.tickAccumulator+=e;this.tickAccumulator>=LP;)this.tickAccumulator-=LP,this.tickPhysics();let t=this.tickAccumulator/LP;this.updateVisuals(t)};spawnBlockBreakParticles(e,t,n,r,s,a="plains"){if(!this.enabled)return;let o=this.resolveBlockTexture(r);if(!o)return;let l=R4e(r,a);for(let c=0;c<4;c++)for(let u=0;u<4;u++)for(let d=0;d<4;d++){let f=e+(c+.5)/4,v=t+(u+.5)/4,g=n+(d+.5)/4,b=f-e-.5,y=v-t-.5,_=g-n-.5;b+=(Math.random()*2-1)*.4,y+=(Math.random()*2-1)*.4,_+=(Math.random()*2-1)*.4;let x=(Math.random()+Math.random()+1)*.15,w=Math.sqrt(b*b+y*y+_*_),S=b/w*x*.4,A=y/w*x*.4+.1,T=_/w*x*.4,P=Math.floor(4/(Math.random()*.9+.1));this.createParticle(f,v,g,S,A,T,P,o,s,e,n,1,l)}}tickPhysics(){for(let e of this.particles){if(!e.active)continue;if(e.prevX=e.x,e.prevY=e.y,e.prevZ=e.z,e.age++,e.age>=e.maxAge){this.deactivateParticle(e);continue}e.yd-=.04,e.x+=e.xd,e.y+=e.yd,e.z+=e.zd;let t=this.getFloorY(e);e.y<=t?(e.y=t,e.yd=0,e.onGround=!0):e.onGround=!1,e.xd*=.98,e.yd*=.98,e.zd*=.98,e.onGround&&(e.xd*=.7,e.zd*=.7)}}updateVisuals(e){let t=this.worldRenderer.camera.position;for(let n of this.particles){if(!n.active)continue;let r=n.prevX+(n.x-n.prevX)*e,s=n.prevY+(n.y-n.prevY)*e,a=n.prevZ+(n.z-n.prevZ)*e;n.mesh.position.set(r,s,a),n.mesh.lookAt(t.x,t.y,t.z)}}spawnCrackParticle(e,t,n,r,s,a,o="plains"){if(!this.enabled)return;let l=this.resolveBlockTexture(s);if(!l)return;let c=R4e(s,o),u=e+Math.random()*.8+.1,d=t+Math.random()*.8+.1,f=n+Math.random()*.8+.1;switch(r){case 0:d=t-.1;break;case 1:d=t+1+.1;break;case 2:f=n-.1;break;case 3:f=n+1+.1;break;case 4:u=e-.1;break;case 5:u=e+1+.1;break}let v=(Math.random()*2-1)*.4*.2,g=(Math.random()*2-1)*.4*.2+.1*.2,b=(Math.random()*2-1)*.4*.2,y=Math.floor(4/(Math.random()*.9+.1));this.createParticle(u,d,f,v,g,b,y,l,a,e,n,.6,c)}createParticle(e,t,n,r,s,a,o,l,c,u,d,f=1,v=[1,1,1]){this.ensureMaterial();let g=this.findInactiveParticle();g||(this.particles.length<$Ye?g=this.allocateParticle():g=this.recycleOldest());let b=Math.floor(Math.random()*4),y=Math.floor(Math.random()*4),_=l.u+b/4*l.su,x=l.v+y/4*l.sv,w=l.su/4,S=l.sv/4;this.setGeometryUVs(g.mesh.geometry,_,x,w,S),g.active=!0,g.x=e,g.y=t,g.z=n,g.prevX=e,g.prevY=t,g.prevZ=n,g.xd=r,g.yd=s,g.zd=a,g.age=0,g.maxAge=o,g.onGround=!1,g.floorMap=c,g.blockX=Math.floor(u),g.blockZ=Math.floor(d);let A=.1*(.5+Math.random()*.5)*2*f;g.mesh.scale.set(A,A,A),g.mesh.position.set(e,t,n),g.mesh.visible=!0;let T=.6*v[0],P=.6*v[1],I=.6*v[2],k=new Float32Array([T,P,I,T,P,I,T,P,I,T,P,I]),L=g.mesh.geometry.getAttribute("color");L?(L.set(k),L.needsUpdate=!0):g.mesh.geometry.setAttribute("color",new Je(k,3)),this.worldRenderer.sceneOrigin.addAndTrack(g.mesh)}allocateParticle(){let e=new zn(1,1),t=new Ke(e,this.sharedMaterial);t.visible=!1;let n={mesh:t,active:!1,x:0,y:0,z:0,prevX:0,prevY:0,prevZ:0,xd:0,yd:0,zd:0,age:0,maxAge:0,onGround:!1,floorMap:[],blockX:0,blockZ:0};return this.particles.push(n),n}findInactiveParticle(){for(let e=0;e<this.particles.length;e++){let t=(this.nextParticleIndex+e)%this.particles.length;if(!this.particles[t].active)return this.nextParticleIndex=(t+1)%this.particles.length,this.particles[t]}}recycleOldest(){let e=this.particles[0];for(let t of this.particles)t.age>e.age&&(e=t);return this.deactivateParticle(e),e}deactivateParticle(e){e.active&&(e.active=!1,e.mesh.visible=!1,this.worldRenderer.sceneOrigin.removeAndUntrack(e.mesh))}getFloorY(e){let t=Math.floor(e.x)-e.blockX,n=Math.floor(e.z)-e.blockZ;return t=Math.max(-2,Math.min(2,t)),n=Math.max(-2,Math.min(2,n)),e.floorMap[(n+2)*5+(t+2)]}resolveBlockTexture(e){let t=this.worldRenderer.resourcesManager.currentResources;if(!t)return null;let n=t.blocksAtlasJson,r=n.textures;if(r[e])return this.extractUV(r[e],n);for(let s of["_side","_top","_front","_0",""]){let a=e+s;if(r[a])return this.extractUV(r[a],n)}for(let s of Object.keys(r))if(s.startsWith(e))return this.extractUV(r[s],n);return null}extractUV(e,t){return{u:e.u,v:e.v,su:e.su??t.suSv,sv:e.sv??t.suSv}}setGeometryUVs(e,t,n,r,s){let a=e.getAttribute("uv");a.setXY(0,t,n),a.setXY(1,t+r,n),a.setXY(2,t,n+s),a.setXY(3,t+r,n+s),a.needsUpdate=!0}ensureMaterial(){if(this.sharedMaterial)return;let e=this.worldRenderer.material.map;e&&(this.sharedMaterial=new _t({map:e,vertexColors:!0,transparent:!0,alphaTest:.1}))}},C4e={id:"blockBreakParticles",controller:BP,enabledDefault:!0,cannotBeDisabled:!0,requiresHeightmap:!1};h();p();m();var DP=class{constructor(e){this.worldRenderer=e}enabled=!1;lastBobWalkDist=0;lastBobTickTime=0;enable(){this.enabled=!0}disable(){this.enabled=!1,this.worldRenderer.cameraShake.setCameraBobInput(null);let{perspective:e}=this.worldRenderer.playerStateReactive;e==="first_person"&&this.worldRenderer.camera.position.set(0,0,0)}render=()=>{if(!this.enabled)return;let e=this.worldRenderer.displayOptions.inWorldRenderingConfig,{perspective:t}=this.worldRenderer.playerStateReactive;if(e.viewBobbing&&t==="first_person"&&!this.worldRenderer.playerStateUtils.isSpectator()){this.worldRenderer.playerStateReactive.walkDist!==this.lastBobWalkDist&&(this.lastBobTickTime=performance.now(),this.lastBobWalkDist=this.worldRenderer.playerStateReactive.walkDist);let r=Math.min((performance.now()-this.lastBobTickTime)/50,1);this.worldRenderer.cameraShake.setCameraBobInput({walkDist:this.worldRenderer.playerStateReactive.walkDist,prevWalkDist:this.worldRenderer.playerStateReactive.prevWalkDist,bob:this.worldRenderer.playerStateReactive.bob,prevBob:this.worldRenderer.playerStateReactive.prevBob,partialTick:r})}else this.worldRenderer.cameraShake.setCameraBobInput(null)};dispose(){this.disable()}},P4e={id:"cameraBobbing",controller:DP,enabledDefault:!0,cannotBeDisabled:!0};h();p();m();Lt();var OP=2e3,L4e=32,B4e=32,p9=12,D4e=24,v9=1.2,YYe=-5,NP=class{constructor(e){this.worldRenderer=e;this.configUnsubs.push(this.worldRenderer.onReactiveConfigUpdated("rainColor",()=>this.syncRainAppearance()),this.worldRenderer.onReactiveConfigUpdated("rainOpacity",()=>this.syncRainAppearance()))}instancedMesh;geometry;material;particles=[];enabled=!1;dummy=new Et;tempPosition=new X;tempQuaternion=new qt;tempScale=new X;configUnsubs=[];enable(){this.enabled||(this.enabled=!0,this.instancedMesh?(this.instancedMesh.visible=!0,this.syncRainAppearance()):this.createRain())}disable(){this.enabled&&(this.enabled=!1,this.instancedMesh&&(this.instancedMesh.visible=!1))}autoEnableCheck(){return this.worldRenderer.worldRendererConfig.isRaining===!0}render=e=>{if(!this.enabled||!this.instancedMesh||!this.material)return;let t=this.worldRenderer.getCameraPosition();this.instancedMesh.position.set(0,0,0);let n=this.worldRenderer.reactiveState.world.heightmaps,{dummy:r,tempPosition:s,tempQuaternion:a,tempScale:o}=this,l=NaN,c=NaN,u;for(let d=0;d<OP;d++){let f=this.particles[d];this.instancedMesh.getMatrixAt(d,r),r.decompose(s,a,o),s.addScaledVector(f.velocity,e);let v=s.y,g=Math.sqrt(s.x*s.x+s.z*s.z),b=t.x+s.x,y=t.y+s.y,_=t.z+s.z,x=Math.floor(b/16),w=Math.floor(_/16);(x!==l||w!==c)&&(u=n[`${x},${w}`],l=x,c=w);let S=(Math.floor(b)%16+16)%16,A=(Math.floor(_)%16+16)%16,T=u?.[A*16+S];if(g>L4e||T!==void 0&&T!==-32768&&y<=T+1+f.despawnOffset||v<YYe){this.respawnParticle(s);let I=p9+Math.random()*(D4e-p9);f.velocity.set((Math.random()-.5)*v9,-I,(Math.random()-.5)*v9),f.despawnOffset=Math.random()*.5}r.compose(s,a,o),this.instancedMesh.setMatrixAt(d,r)}this.instancedMesh.instanceMatrix.needsUpdate=!0};dispose(){for(let e of this.configUnsubs)e();this.configUnsubs.length=0,this.instancedMesh&&this.worldRenderer.scene.remove(this.instancedMesh),this.geometry?.dispose(),this.material?.dispose(),this.instancedMesh=void 0,this.geometry=void 0,this.material=void 0,this.particles=[]}syncRainAppearance(){if(!this.material)return;let{rainColor:e,rainOpacity:t}=this.worldRenderer.worldRendererConfig;this.material.color.set(e),this.material.opacity=Math.max(0,Math.min(1,t)),this.material.needsUpdate=!0}createRain(){let{rainColor:e,rainOpacity:t}=this.worldRenderer.worldRendererConfig;this.geometry=new Sn(.03,.3,.03),this.material=new _t({color:e,transparent:!0,opacity:Math.max(0,Math.min(1,t)),depthWrite:!0,fog:!1}),this.instancedMesh=new cl(this.geometry,this.material,OP),this.instancedMesh.name="rain-particles",this.instancedMesh.frustumCulled=!1;let n=new Et,r=new X;for(let s=0;s<OP;s++){this.respawnParticle(r),r.y=Math.random()*B4e,n.setPosition(r),this.instancedMesh.setMatrixAt(s,n);let a=p9+Math.random()*(D4e-p9);this.particles.push({velocity:new X((Math.random()-.5)*v9,-a,(Math.random()-.5)*v9),age:0,despawnOffset:Math.random()*.5})}this.instancedMesh.instanceMatrix.needsUpdate=!0,this.worldRenderer.scene.add(this.instancedMesh)}respawnParticle(e){let t=Math.random()*Math.PI*2,n=Math.random()*L4e;e.set(Math.cos(t)*n,B4e,Math.sin(t)*n)}},O4e={id:"rain",controller:NP,enabledDefault:!1,requiresHeightmap:!0};h();p();m();Lt();var N4e=new We(13/255,234/255,238/255),JYe=9,KYe=12e3,ZYe=1500,QYe=1e4,eJe=350,tJe=650,U4e=120,F4e=280,UP=class{constructor(e){this.worldRenderer=e;e.worldRendererConfig.futuristicReveal!==!0&&(this.enabled=!1)}enabled=!0;sections=new Map;completed=new Set;globalWaveStarted=!1;globalWaveStartMs=0;finishedChunkCount=0;firstQueuedMs=null;pulseTime=0;wireframeMaterial=new Pn({color:N4e,transparent:!0,opacity:1,blending:es,depthWrite:!1});wireframeGlowMaterial=new Pn({color:N4e,transparent:!0,opacity:.55,blending:es,depthWrite:!1});autoEnableCheck(){return this.worldRenderer.worldRendererConfig.futuristicReveal===!0}enable(){this.autoEnableCheck()&&this.setEnabled(!0)}disable(){this.setEnabled(!1)}dispose(){this.reset(),this.wireframeMaterial.dispose(),this.wireframeGlowMaterial.dispose()}shouldDeferSectionGeometry(e){return this.enabled&&!this.completed.has(e)}onSectionMeshed(e,t,n){let r=n.children.find(s=>s.name==="mesh");r instanceof Ke&&this.onSectionMeshedMesh(e,t,r)}onChunkFinished(){this.enabled&&(this.finishedChunkCount++,this.tryStartGlobalWave(performance.now()))}onSectionRemoved(e){this.cancelSection(e,!0),this.completed.delete(e)}onWorldSwitched(){this.reset()}tick(e,t=performance.now()){if(!this.enabled||(this.tryStartGlobalWave(t),!this.globalWaveStarted&&this.firstQueuedMs!==null&&this.sections.size>0&&t-this.firstQueuedMs>=KYe&&this.startGlobalWave(t),this.sections.size===0))return;this.pulseTime+=e*.001;let n=[];for(let r of this.sections.values()){if(t-r.phaseStartMs>QYe){n.push(r);continue}if(r.phase==="queued"){this.globalWaveStarted&&t>=r.revealAtMs&&this.beginWireframe(r,t);continue}let s=t-r.phaseStartMs;if(r.phase==="wireframe"){this.animateWireframe(r,s),s>=r.wireframeMs&&this.beginFade(r,t);continue}if(r.phase==="fade"){let a=Math.min(1,s/r.fadeMs);this.animateFade(r,a),a>=1&&n.push(r)}}for(let r of n)this.finishSection(r)}setEnabled(e){e!==this.enabled&&(this.enabled=e,e||this.forceFinishAll())}onSectionMeshedMesh(e,t,n){if(!this.enabled||!t.positions?.length||this.completed.has(e))return;let r=this.sections.get(e);if(r){r.mesh=n,r.geometry=t,(r.phase==="wireframe"||r.phase==="fade")&&this.finishSection(r);return}let s=performance.now();this.firstQueuedMs===null&&(this.firstQueuedMs=s);let a=this.globalWaveStarted;this.sections.set(e,{key:e,geometry:t,phase:"queued",phaseStartMs:s,revealAtMs:this.globalWaveStarted?s:0,wireframeMs:a?U4e:eJe,fadeMs:a?F4e:tJe,wireframeGroup:null,mesh:n,savedMaterial:null,pulseOffset:Math.random()*Math.PI*2}),n.visible=!1,this.setShaderMeshesVisible(e,!1),this.tryStartGlobalWave(s)}reset(){this.forceFinishAll(),this.sections.clear(),this.completed.clear(),this.globalWaveStarted=!1,this.globalWaveStartMs=0,this.finishedChunkCount=0,this.firstQueuedMs=null,this.pulseTime=0}forceFinishAll(){for(let e of[...this.sections.values()])this.finishSection(e);this.sections.clear(),this.unhideAllSectionMeshes()}tryStartGlobalWave(e){if(!this.globalWaveStarted&&this.sections.size!==0){if(this.finishedChunkCount>=JYe){this.startGlobalWave(e);return}this.worldRenderer.allChunksFinished&&this.startGlobalWave(e)}}startGlobalWave(e){if(this.globalWaveStarted)return;this.globalWaveStarted=!0,this.globalWaveStartMs=e;let t=this.worldRenderer.getCameraPosition(),n=1,r=new Map;for(let[s,a]of this.sections){if(a.phase!=="queued")continue;let{sx:o,sy:l,sz:c}=a.geometry,u=Math.hypot(o-t.x,l-t.y,c-t.z);r.set(s,u),n=Math.max(n,u)}for(let[,s]of this.sections){if(s.phase!=="queued")continue;let a=r.get(s.key)??0;s.revealAtMs=e+a/n*ZYe,s.wireframeMs=U4e,s.fadeMs=F4e}}beginWireframe(e,t){let n=e.mesh??this.getSectionMesh(e.key);if(e.mesh=n,!n){this.sections.delete(e.key);return}let r=this.createWireframeGeometry(e.geometry),s=new Kn(r,this.wireframeMaterial.clone());this.worldRenderer.sceneOrigin.track(s),s.position.set(e.geometry.sx,e.geometry.sy,e.geometry.sz),s.name="scifi-wireframe",s.renderOrder=1e3;let a=new Kn(r.clone(),this.wireframeGlowMaterial.clone());this.worldRenderer.sceneOrigin.track(a),a.position.copy(s.position),a.scale.setScalar(1.02),a.name="scifi-glow",a.renderOrder=999;let o=new bt;o.name="scifi-reveal-group",o.add(s,a),this.worldRenderer.realScene.add(o),n.visible=!1,this.setShaderMeshesVisible(e.key,!1),e.wireframeGroup=o,e.phase="wireframe",e.phaseStartMs=t}beginFade(e,t){let n=e.mesh??this.getSectionMesh(e.key);if(e.mesh=n,n){n.visible=!0;let r=n.material;if(!Array.isArray(r)&&r&&typeof r.clone=="function"){e.savedMaterial=r;let s=r.clone();s.transparent=!0,s.opacity=0,s.needsUpdate=!0,n.material=s}}this.setShaderMeshesVisible(e.key,!0),e.phase="fade",e.phaseStartMs=t}animateWireframe(e,t){if(!e.wireframeGroup)return;let n=e.wireframeGroup.children[0],r=e.wireframeGroup.children[1],s=.6+.4*Math.sin(this.pulseTime*4+e.pulseOffset);if(n?.material){let a=n.material;a.opacity=s;let o=.85+.15*Math.sin(this.pulseTime*6+t*.002);a.color.setRGB(13/255*o,234/255*o,238/255*o)}r?.material&&(r.material.opacity=s*.4)}animateFade(e,t){let n=1-(1-t)**3;if(e.wireframeGroup){let s=e.wireframeGroup.children[0],a=e.wireframeGroup.children[1];s?.material&&(s.material.opacity=1-n),a?.material&&(a.material.opacity=(1-n)*.55)}let r=e.mesh;r&&e.savedMaterial&&!Array.isArray(r.material)&&(r.material.opacity=n),this.setShaderMeshesVisible(e.key,n>.001)}finishSection(e){let t=e.mesh??this.getSectionMesh(e.key);if(t){if(e.savedMaterial){let r=t.material;t.material=e.savedMaterial,r.dispose(),e.savedMaterial=null}t.visible=!0}this.setShaderMeshesVisible(e.key,!0);let{chunkMeshManager:n}=this.worldRenderer;n.migrateDeferredShaderToGlobal(e.key),n.migrateDeferredLegacyToGlobal(e.key),e.wireframeGroup&&(this.disposeWireframeGroup(e.wireframeGroup),e.wireframeGroup=null),this.sections.delete(e.key),this.completed.add(e.key)}cancelSection(e,t){let n=this.sections.get(e);if(n){if(n.wireframeGroup&&this.disposeWireframeGroup(n.wireframeGroup),t){let r=n.mesh??this.getSectionMesh(e);if(r){if(n.savedMaterial){let s=r.material;r.material=n.savedMaterial,s.dispose()}r.visible=!0}this.setShaderMeshesVisible(e,!0)}this.sections.delete(e)}}getSectionMesh(e){let t=this.worldRenderer.chunkMeshManager.sectionObjects[e];if(!t)return null;let n=t.children.find(r=>r.name==="mesh");return n instanceof Ke?n:null}getShaderMesh(e){let t=this.worldRenderer.chunkMeshManager.sectionObjects[e];if(!t)return null;let n=t.children.find(r=>r.name==="shaderMesh");return n instanceof Ke?n:null}setShaderMeshesVisible(e,t){let n=this.getShaderMesh(e);n&&(n.visible=t)}unhideAllSectionMeshes(){for(let e of Object.values(this.worldRenderer.chunkMeshManager.sectionObjects))e&&e.traverse(t=>{t instanceof Ke&&(t.name==="mesh"||t.name==="shaderMesh")&&(t.visible=!0)})}disposeWireframeGroup(e){this.worldRenderer.sceneOrigin.removeAndUntrackAll(e),this.worldRenderer.realScene.remove(e),e.traverse(t=>{let n=t;n.geometry?.dispose();let r=n.material;Array.isArray(r)?r.forEach(s=>s.dispose()):r?.dispose()}),e.clear()}createWireframeGeometry(e){let t=e.positions,n=e.indices,r=[],s=new Set;for(let o=0;o<n.length;o+=3){let l=n[o],c=n[o+1],u=n[o+2];this.addEdge(t,l,c,r,s),this.addEdge(t,c,u,r,s),this.addEdge(t,u,l,r,s)}let a=new dt;return a.setAttribute("position",new Je(r,3)),a}addEdge(e,t,n,r,s){let a=Math.min(t,n),o=Math.max(t,n),l=`${a}-${o}`;s.has(l)||(s.add(l),r.push(e[t*3],e[t*3+1],e[t*3+2],e[n*3],e[n*3+1],e[n*3+2]))}},V4e={id:"futuristicReveal",controller:UP,enabledDefault:!0};h();p();m();Lt();var nJe=parseInt(Ma.replaceAll(/\D+/g,""),10),FP=class extends Xn{constructor(){super({uniforms:{time:{value:0}},vertexShader:`
29562
29562
  uniform float time;
29563
29563
  attribute float size;
29564
29564
  varying vec3 vColor;
@@ -29570,17 +29570,13 @@ void main() {
29570
29570
  gl_Position = projectionMatrix * mvPosition;
29571
29571
  }`,fragmentShader:`
29572
29572
  uniform sampler2D pointTexture;
29573
- uniform float fade;
29574
29573
  varying vec3 vColor;
29575
29574
  void main() {
29576
- // fade scales star brightness (0 = invisible). With additive blending this is
29577
- // the only way to dim stars \u2014 scene fog never reaches this shader. Driven by the
29578
- // rain state so stars disappear in rain like in vanilla.
29579
- gl_FragColor = vec4(vColor * fade, 1.0);
29575
+ gl_FragColor = vec4(vColor, 1.0);
29580
29576
 
29581
29577
  #include <tonemapping_fragment>
29582
29578
  #include <${nJe>=154?"colorspace_fragment":"encodings_fragment"}>
29583
- }`})}},VP=class{constructor(e){this.worldRenderer=e}points;timer=new Hs;enabled=!1;currentTime;fade=1;enable(){this.enabled||(this.enabled=!0,this.updateVisibility())}disable(){this.enabled&&(this.enabled=!1,this.removeStars())}toggle(){return this.enabled?this.disable():this.enable(),this.enabled}enablementCheck=()=>this.currentTime?this.currentTime>13500&&this.currentTime<23e3:!1;render=e=>{if(!this.points)return;this.points.position.set(0,0,0);let t=this.points.material;this.timer.update(performance.now()),t.uniforms.time.value=this.timer.getElapsed()*.2;let n=this.worldRenderer.worldRendererConfig.isRaining?0:1,r=Math.min(1,e*2);this.fade+=(n-this.fade)*r,t.uniforms.fade.value=this.fade};updateTimeOfDay(e){this.currentTime=e,this.enabled&&this.updateVisibility()}updateVisibility(){if(!this.enabled)return;let e=this.enablementCheck?.()??!1;e&&!this.points?this.createStars():!e&&this.points&&this.removeStars()}createStars(){if(this.points)return;let e=80,t=50,n=7e3,r=7,s=10,a=new dt,o=b=>new X().setFromSpherical(new Jf(b,Math.acos(1-Math.random()*2),Math.random()*2*Math.PI)),l=[],c=[],u=Array.from({length:n},()=>(.5+.5*Math.random())*r),d=new We,f=e+t,v=t/n;for(let b=0;b<n;b++)f-=v*Math.random(),l.push(...o(f).toArray()),d.setHSL(b/n,s,.9),c.push(d.r,d.g,d.b);a.setAttribute("position",new Je(l,3)),a.setAttribute("color",new Je(c,3)),a.setAttribute("size",new Je(u,1));let g=new FP;g.blending=es,g.depthTest=!0,g.depthWrite=!1,g.transparent=!0,this.points=new gr(a,g),this.points.renderOrder=-1,this.worldRenderer.scene.add(this.points)}dispose(){this.removeStars()}removeStars(){this.points&&(this.points.geometry.dispose(),this.points.material.dispose(),this.worldRenderer.scene.remove(this.points),this.points=void 0)}},z4e={id:"starfield",controller:VP,enabledDefault:!0,cannotBeDisabled:!0};var H4e={starfield:z4e,futuristicReveal:V4e,rain:O4e,cameraBobbing:P4e,blockBreakParticles:C4e};h();p();m();h();p();m();var zP=()=>({longRenderTime:!1,constantLongRenderTime:!1,tooManyEntities:!1,tooManyTextures:!1,unknownReason:!1});h();p();m();h();p();m();var hg=class{constructor(e){this.factors=e}renderTimeHistory=[];onFrame(e){this.pushRenderTime(e.totalMs),this.recompute(e)}pushRenderTime(e){this.renderTimeHistory.push(e),this.renderTimeHistory.length>24&&this.renderTimeHistory.shift()}recompute(e){let t=e.fps>0&&e.fps<=45,n=Math.max(0,e.totalMs-e.entitiesMs),r=e.totalMs>=30,s=this.renderTimeHistory.length,a=this.renderTimeHistory.filter(f=>f>=30).length,o=s>=8&&a/s>=.65,l=e.loadedTextureCount>=100,c=t&&e.entitiesMs>=8&&n<=20,d=t&&!(r||o||c||l);this.factors.longRenderTime=r,this.factors.constantLongRenderTime=o,this.factors.tooManyEntities=c,this.factors.tooManyTextures=l,this.factors.unknownReason=d}reset(){this.renderTimeHistory.length=0,this.factors.longRenderTime=!1,this.factors.constantLongRenderTime=!1,this.factors.tooManyEntities=!1,this.factors.tooManyTextures=!1,this.factors.unknownReason=!1}};h();p();m();var lJe=[{key:"longRenderTime",code:"LR"},{key:"constantLongRenderTime",code:"CLR"},{key:"tooManyEntities",code:"ENT"},{key:"tooManyTextures",code:"TEX"},{key:"unknownReason",code:"UNK"}];function qP(i){let e=lJe.filter(({key:t})=>i[t]).map(({code:t})=>t);return e.length>0?e.join("+"):""}var ia=class ia extends Ry{constructor(t,n,r){if(!r.resourcesManager)throw new Error("resourcesManager is required in displayOptions");super(r.resourcesManager,r,n);this.renderer=t;this.initOptions=n;this.displayOptions=r;this.performanceMonitor=new hg(this.reactiveState.world.instabilityFactors),this.renderer=t;let s=ia.getRendererInfo(t)??"...";r.rendererState.renderer=s,this.chunkMeshManager=new fg(this,this.scene,this.material,this.worldSizeParams.worldHeight,this.viewDistance),this.onRenderDistanceChanged=a=>{this.chunkMeshManager.updateViewDistance(a)},typeof window<"u"&&(window.setBlockLightmap=a=>{this.chunkMeshManager.setBlockLightmapParams(a)}),this.syncSkyLevelFromTime(this.timeOfTheDay),this.cursorBlock=new Bb(this),this.holdingBlock=sg(this),this.holdingBlockLeft=sg(this,!0);for(let a of Object.values(H4e))this.registerModule(a);this.skyboxRenderer=new qb(this.realScene,!1,null),this.skyboxRenderer.init(),this.addDebugOverlay(),this.resetScene(),this.init(),this.soundSystem=new Ob(this),this.cameraShake=new Nb(this,this.onRender),this.media=new Ub(this),this.fireworksLegacy=new zb(this),this.waypoints=new Vb(this),this.cinimaticScript=new Hb(this,(a,o,l)=>this.setCinimaticCamera(a,o,l),a=>this.setCinimaticFov(a),()=>({position:new kt(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),yaw:this.cameraShake.getBaseRotation().yaw,pitch:this.cameraShake.getBaseRotation().pitch,fov:this.camera.fov})),this.fireworks=new Gb(this.realScene,this.sceneOrigin),this.renderUpdateEmitter.on("chunkFinished",a=>{this.finishChunk(a)}),this.worldSwitchActions(),this.initializeModules()}outputFormat="threeJs";isShaderCubeBlocksEnabled(){return this.worldRendererConfig.shaderCubeBlocks===!0&&!!this.renderer?.capabilities?.isWebGL2}chunkMeshManager;get sectionObjects(){return this.chunkMeshManager.sectionObjects}cameraSectionPos=new kt(0,0,0);holdingBlock;holdingBlockLeft;scene=new Rr;get realScene(){return this.scene}ambientLight=new wa(13421772,ia.LEGACY_TO_PHYSICAL_LIGHT);directionalLight=new Ss(16777215,.5*ia.LEGACY_TO_PHYSICAL_LIGHT);entities=new Lb(this,globalThis.mcData);performanceMonitor;cameraGroupVr;material=new _t({vertexColors:!0,transparent:!0,alphaTest:.1});itemsTexture;cursorBlock;onRender=[];lastRenderTime=0;lastSciFiTickMs=0;animatedFov=0;lastFovAnimTime=0;cameraShake;cameraContainer;media;get waitingChunksToDisplay(){return this.chunkMeshManager.waitingChunksToDisplay}waypoints;cinimaticScript;camera;renderTimeAvg=0;pendingSectionUpdates=new Map;pendingSectionBufferStartTimes=new Map;get estimatedMemoryUsage(){return this.chunkMeshManager.getEstimatedMemoryUsage().total}modules={};sectionsOffsetsAnimations={};fountains=[];fireworksLegacy;DEBUG_RAYCAST=!1;skyboxRenderer;fireworks;sceneOrigin=new Wb(this.scene);cameraWorldPos={x:0,y:0,z:0};_cameraPositionAccessWarned=!1;_tmpCameraPos=new X;currentPosTween;currentRotTween;_tpDirection=new X;_tpPitchQuat=new qt;_tpYawQuat=new qt;_tpFinalQuat=new qt;_tpScenePos=new X;_tpAxisX=new X(1,0,0);_tpAxisY=new X(0,1,0);_tpChunkWorldPos=new X;get tilesRendered(){return this.chunkMeshManager.getTotalTiles()}get blocksRendered(){return this.chunkMeshManager.getTotalBlocks()}registerModule(t){if(t.id in this.modules){console.warn(`Module ${t.id} is already registered`);return}let n=new t.controller(this),r={manifest:t,controller:n,enabled:!1,toggle:()=>this.toggleModule(t.id)};this.modules[t.id]=r,t.enabledDefault&&this.toggleModule(t.id,!0)}enableModule(t){let n=this.modules[t];if(!n){console.warn(`Module ${t} not found`);return}n.enabled||(n.enabled=!0,n.controller.enable(),n.controller.render&&this.onRender.push(n.controller.render))}disableModule(t){let n=this.modules[t];if(!n){console.warn(`Module ${t} not found`);return}if(n.manifest.cannotBeDisabled){console.warn(`Module ${t} cannot be disabled`);return}if(n.enabled&&(n.enabled=!1,n.controller.disable(),n.controller.render)){let r=this.onRender.indexOf(n.controller.render);r>-1&&this.onRender.splice(r,1)}}toggleModule(t,n){let r=this.modules[t];if(!r)return console.warn(`Module ${t} not found`),!1;let s=n!==void 0?n:!r.enabled;if(s===r.enabled)return r.enabled;if(!s&&r.manifest.cannotBeDisabled)return console.warn(`Module ${t} cannot be disabled`),!0;if(r.enabled=s,s)r.controller.enable(),r.controller.render&&!this.onRender.includes(r.controller.render)&&this.onRender.push(r.controller.render);else if(r.controller.disable(),r.controller.render){let a=this.onRender.indexOf(r.controller.render);a>-1&&this.onRender.splice(a,1)}return s}setRain(t){this.worldRendererConfig.isRaining=t,this.toggleModule("rain",t)}disposeModules(){for(let t of Object.values(this.modules))t.controller.dispose();this.modules={}}initializeModules(){this.updateModulesFromConfig()}getModule(t){return this.modules[t]?.controller}anyModuleRequiresHeightmap(){return Object.values(this.modules).some(t=>t.enabled&&t.manifest.requiresHeightmap)}get cameraObject(){return this.cameraGroupVr??this.cameraContainer}_wrapCameraPositionWithWarning(){let t=this.camera.position,n=this,r=20,s=(l,c,u)=>Math.abs(l)>r||Math.abs(c)>r||Math.abs(u)>r,a=()=>{!n._cameraPositionAccessWarned&&typeof process<"u"},o=new Proxy(t,{set(l,c,u){return(c==="x"||c==="y"||c==="z")&&typeof u=="number"&&Math.abs(u)>r&&a(),l[c]=u,!0},get(l,c,u){let d=l[c];return c==="set"?function(f,v,g){return s(f,v,g)&&a(),l.set(f,v,g)}:c==="setX"||c==="setY"||c==="setZ"?function(f){return Math.abs(f)>r&&a(),l[c](f)}:c==="copy"?function(f){return s(f.x,f.y,f.z)&&a(),l.copy(f)}:typeof d=="function"?d.bind(l):d}});Object.defineProperty(this.camera,"position",{value:o,configurable:!0,enumerable:!0})}worldSwitchActions(){this.onWorldSwitched.push(()=>{this.getModule("futuristicReveal")?.onWorldSwitched?.(),this.protocolCustomBlocks.clear(),this.sectionsOffsetsAnimations={},this.waypoints.clear(),this.cinimaticScript.stopScript(),this.fireworks.clear(),this.syncSkyLevelFromTime(this.timeOfTheDay)})}downloadWorldGeometry(){MP(this,new X(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),this.cameraShake.getBaseRotation(),"world-geometry.json")}updateEntity(t,n=!1){let r={rotation:{head:{x:t.headPitch??t.pitch,y:t.headYaw,z:0}}};n?this.entities.updateEntityPosition(t,!1,r):this.entities.update(t,r)}updatePlayerEntity(t){this.entities.handlePlayerEntity(t)}resetScene(){this.sceneOrigin.update(0,0,0),this.cameraWorldPos.x=0,this.cameraWorldPos.y=0,this.cameraWorldPos.z=0,this.scene.matrixAutoUpdate=!1,this.scene.background=new We(this.initOptions.config.sceneBackground),this.scene.add(this.ambientLight),this.directionalLight.position.set(1,1,.5).normalize(),this.directionalLight.castShadow=!0,this.scene.add(this.directionalLight);let t=this.renderer.getSize(new ze);this.camera=new fn(75,t.x/t.y,.1,1e3),this._wrapCameraPositionWithWarning(),this.cameraContainer=new Ut,this.cameraContainer.add(this.camera),this.scene.add(this.cameraContainer)}watchReactivePlayerState(){super.watchReactivePlayerState(),this.onReactivePlayerStateUpdated("inWater",t=>{this.skyboxRenderer.updateWaterState(t,this.playerStateReactive.waterBreathing)}),this.onReactivePlayerStateUpdated("waterBreathing",t=>{this.skyboxRenderer.updateWaterState(this.playerStateReactive.inWater,t)}),this.onReactivePlayerStateUpdated("ambientLight",t=>{t&&(this.ambientLight.intensity=t*ia.LEGACY_TO_PHYSICAL_LIGHT)}),this.onReactivePlayerStateUpdated("directionalLight",t=>{t&&(this.directionalLight.intensity=t*ia.LEGACY_TO_PHYSICAL_LIGHT)}),this.onReactivePlayerStateUpdated("lookingAtBlock",t=>{this.cursorBlock.setHighlightCursorBlock(t?new kt(t.x,t.y,t.z):null,t?.shapes)}),this.onReactivePlayerStateUpdated("diggingBlock",t=>{this.cursorBlock.updateBreakAnimation(t?{x:t.x,y:t.y,z:t.z}:void 0,t?.stage??null,t?.mergedShape)}),this.onReactivePlayerStateUpdated("perspective",t=>{let n=new kt(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z);this.updateCamera(n,this.cameraShake.getBaseRotation().yaw,this.cameraShake.getBaseRotation().pitch)})}watchReactiveConfig(){super.watchReactiveConfig(),this.onReactiveConfigUpdated("showChunkBorders",r=>{this.updateShowChunksBorder(r)}),this.onReactiveConfigUpdated("defaultSkybox",r=>{this.skyboxRenderer.updateDefaultSkybox(r)}),this.onReactiveConfigUpdated("shaderCubeDebugMode",()=>{this.chunkMeshManager.syncCubeShaderUniforms(),this.chunkMeshManager.syncLegacyShaderUniforms()});let t=()=>{let r=this.worldRendererConfig;this.chunkMeshManager.setShadingTheme(r.shadingTheme,r.cardinalLight)};this.onReactiveConfigUpdated("shadingTheme",t),this.onReactiveConfigUpdated("cardinalLight",t),this.onReactiveConfigUpdated("futuristicReveal",()=>{this.updateModulesFromConfig()});let n=this.displayOptions.inWorldRenderingConfig.handRenderer;this.onReactiveConfigUpdated("handRenderer",r=>{if(r===n)return;n=r;let s=this.holdingBlock.ready,a=this.holdingBlockLeft.ready;this.holdingBlock.dispose(),this.holdingBlockLeft.dispose(),this.holdingBlock=sg(this),this.holdingBlockLeft=sg(this,!0),s&&(this.holdingBlock.ready=!0,this.holdingBlock.updateItem()),a&&(this.holdingBlockLeft.ready=!0,this.holdingBlockLeft.updateItem())}),this.onReactiveConfigUpdated("*",()=>{this.updateModulesFromConfig()}),this.updateModulesFromConfig()}updateModulesFromConfig(){let{moduleStates:t}=this.worldRendererConfig;for(let[n,r]of Object.entries(this.modules)){let s=t[n];if(s==="enabled"){r.enabled||this.toggleModule(n,!0);continue}if(s==="disabled"){r.enabled&&!r.manifest.cannotBeDisabled&&this.toggleModule(n,!1);continue}if(s==="auto"||s===void 0)if(r.controller.autoEnableCheck){let a=r.controller.autoEnableCheck();a&&!r.enabled?this.toggleModule(n,!0):!a&&r.enabled&&!r.manifest.cannotBeDisabled&&this.toggleModule(n,!1)}else{let a=r.manifest.enabledDefault??!1;a&&!r.enabled?this.toggleModule(n,!0):!a&&r.enabled&&!r.manifest.cannotBeDisabled&&this.toggleModule(n,!1)}}}changeHandSwingingState(t,n=!1){let r=n?this.holdingBlockLeft:this.holdingBlock;t?r.startSwing():r.stopSwing()}async updateAssetsData(){let t=this.resourcesManager.currentResources,n=this.material.map,r=this.itemsTexture,s=cc(t.blocksAtlasImage);s.needsUpdate=!0,s.flipY=!1,this.material.map=s,this.chunkMeshManager.syncCubeShaderUniforms(),this.chunkMeshManager.syncLegacyShaderUniforms();let a=cc(t.itemsAtlasImage);a.needsUpdate=!0,a.flipY=!1,this.itemsTexture=a,n&&n.dispose(),r&&r.dispose(),await super.updateAssetsData(),this.onAllTexturesLoaded(),Object.keys(this.loadedChunks).length>0&&(console.log("rerendering chunks because of texture update"),this.rerenderAllChunks())}onAllTexturesLoaded(){this.holdingBlock.ready=!0,this.holdingBlock.updateItem(),this.holdingBlockLeft.ready=!0,this.holdingBlockLeft.updateItem()}changeBackgroundColor(t){this.realScene.background=new We(t[0],t[1],t[2])}changeCardinalLight(t){this.worldRendererConfig.cardinalLight=t}timeUpdated(t){let n=this.getModule("starfield");n?.updateTimeOfDay&&n.updateTimeOfDay(t),this.skyboxRenderer.updateTime(t),this.syncSkyLevelFromTime(t)}syncSkyLevelFromTime(t){let n=Ml(t)/15;this.chunkMeshManager.setSkyLevel(n)}onDayCycleSkyLightChanged(t){}biomeUpdated(t){t?.temperature!==void 0&&this.skyboxRenderer.updateTemperature(t.temperature)}biomeReset(){this.skyboxRenderer.updateTemperature(vP)}getItemRenderData(t,n){return k_e(t,n,this.resourcesManager,this.playerStateReactive)}async demoModel(){let t=cursorBlockRel(0,1,0).position,n=await Pv();Sve(n,t);let r=new Ea(n,16776960);n.add(r),this.realScene.add(n)}demoItem(){let t=cursorBlockRel(0,1,0).position,{mesh:n}=this.entities.getItemMesh({itemId:541},{});n.position.set(t.x+.5,t.y+.5,t.z+.5);let r=new Ea(n,16776960);n.add(r),this.realScene.add(n)}debugOverlayAdded=!1;addDebugOverlay(){if(this.debugOverlayAdded)return;this.debugOverlayAdded=!0;let t=i4("debug-overlay",80,0,void 0,{className:r4});setInterval(()=>{if(t.setVisibility(this.displayAdvancedStats),this.displayAdvancedStats){let n=c=>new Intl.NumberFormat("en-US",{}).format(c),r=c=>new Intl.NumberFormat("en-US",{notation:"compact",maximumFractionDigits:1}).format(c),s="";s+=`TE: ${n(this.renderer.info.memory.textures)} `;let a=this.chunkMeshManager.getGlobalBufferStats();if(a.shaderFaces){let c=a.shaderFaces;s+=`CUBE: ${r(c.used)}/${r(c.capacity)}f `}if(a.legacyOpaque){let c=a.legacyOpaque;s+=`LEG-O: ${r(c.used)}/${r(c.capacity)}q `}if(a.legacyBlend){let c=a.legacyBlend;s+=`LEG-B: ${r(c.used)}/${r(c.capacity)}q `}s+=`MEM: ${this.chunkMeshManager.getEstimatedMemoryUsage().total} `;let o=this.cameraCollisionBlockCache.getAllocatedBytes();o>0&&(s+=`CAM: ${r(o)}b `);let l=qP(this.reactiveState.world.instabilityFactors);l&&(s+=`PF: ${l} `),t.updateText(s),this.backendInfoReport=s}},200)}updatePosDataChunk(t){let n=this.sectionObjects[t];if(!n)return;let[r,s,a]=t.split(",").map(u=>Math.floor(+u/16)),l=500-(Math.abs(r-this.cameraSectionPos.x)+Math.abs(s-this.cameraSectionPos.y)+Math.abs(a-this.cameraSectionPos.z)),c=n.mesh??n.shaderMesh??n.children.find(u=>u.name==="mesh"||u.name==="shaderMesh");c&&(c.renderOrder=l)}cameraSectionPositionUpdate(){for(let t in this.sectionObjects)this.sectionObjects[t]&&this.updatePosDataChunk(t)}getDir(t,n){return t===n?0:t<n?1:-1}finishChunk(t){this.chunkMeshManager.finishChunkDisplay(t),this.getModule("futuristicReveal")?.onChunkFinished?.()}applyPendingSectionUpdates(){if(this.pendingSectionUpdates.size===0)return;let t=performance.now(),n=this.getSectionHeight(),r=[];for(let s of this.pendingSectionUpdates.keys()){let a=this.pendingSectionBufferStartTimes.get(s)??t;if(t-a<ia.MAX_SECTION_UPDATE_BUFFER_MS){let[l,c,u]=s.split(",").map(Number),d=[`${l-16},${c},${u}`,`${l+16},${c},${u}`,`${l},${c-n},${u}`,`${l},${c+n},${u}`,`${l},${c},${u-16}`,`${l},${c},${u+16}`],f=!1;for(let v of d)if(this.sectionsWaiting.has(v)&&!this.pendingSectionUpdates.has(v)&&this.sectionObjects[v]){f=!0;break}if(f)continue}r.push(s)}if(r.length!==0)for(let s of r){let a=this.pendingSectionUpdates.get(s);this.pendingSectionUpdates.delete(s),this.pendingSectionBufferStartTimes.delete(s);let o=a.key.split(","),l=`${o[0]},${o[2]}`;if(!this.loadedChunks[l]||!this.active){this.chunkMeshManager.releaseSection(a.key);continue}if(!this.chunkMeshManager.sectionHasRenderableContent(a.geometry)){this.chunkMeshManager.releaseSection(a.key);continue}let c=this.chunkMeshManager.updateSection(a.key,a.geometry);this.updatePosDataChunk(a.key),c&&this.getModule("futuristicReveal")?.onSectionMeshed?.(a.key,a.geometry,c)}}clearPendingSectionUpdatesForChunk(t,n){for(let r of[...this.pendingSectionUpdates.keys()])r.startsWith(`${t},`)&&r.endsWith(`,${n}`)&&(this.pendingSectionUpdates.delete(r),this.pendingSectionBufferStartTimes.delete(r))}handleWorkerMessage(t){if(t.type==="geometry"){let n=t.key.split(","),r=`${n[0]},${n[2]}`;if(!this.loadedChunks[r]||!this.active){this.pendingSectionUpdates.delete(t.key),this.pendingSectionBufferStartTimes.delete(t.key);return}if(this.sectionObjects[t.key]){this.pendingSectionUpdates.set(t.key,t),this.pendingSectionBufferStartTimes.has(t.key)||this.pendingSectionBufferStartTimes.set(t.key,performance.now());return}if(!this.chunkMeshManager.sectionHasRenderableContent(t.geometry)){this.chunkMeshManager.releaseSection(t.key);return}let s=this.chunkMeshManager.updateSection(t.key,t.geometry);this.updatePosDataChunk(t.key),s&&this.getModule("futuristicReveal")?.onSectionMeshed?.(t.key,t.geometry,s)}}getCameraPosition(t){return(t??this._tmpCameraPos).set(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z)}getSectionCameraPosition(){let t=this.getCameraPosition();return new kt(Math.floor(t.x/16),Math.floor(t.y/16),Math.floor(t.z/16))}updateCameraSectionPos(){let t=this.getSectionCameraPosition();this.cameraSectionPos.equals(t)||(this.cameraSectionPos=t,this.cameraSectionPositionUpdate())}setFirstPersonCamera(t,n,r){let s=this.playerStateReactive.eyeHeight;this.updateCamera(t?.offset(0,s,0)??null,n,r),this.updateCameraSectionPos()}getThirdPersonCamera(t,n,r){t??=new X(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z);let s=this.playerStateReactive.perspective==="third_person_back",a=4,o=this._tpDirection.set(0,0,-1),l=this._tpPitchQuat.setFromAxisAngle(this._tpAxisX,r),c=this._tpYawQuat.setFromAxisAngle(this._tpAxisY,n),u=this._tpFinalQuat.multiplyQuaternions(c,l);o.applyQuaternion(u),s&&o.multiplyScalar(-1),this.DEBUG_RAYCAST&&this.debugRaycast(t,o,a);let d=.25,f=.05,v=.4,g=this.cameraCollisionBlockCache,b=k4e(t.x,t.y,t.z,o.x,o.y,o.z,a,d,f,(_,x,w)=>g.isSolidBlock(_,x,w)),y=a;return b!==void 0&&(y=Math.min(y,b.distance)),y<v&&(y=v),new kt(t.x+o.x*y,t.y+o.y*y,t.z+o.z*y)}debugRaycastHelper;debugHitPoint;debugRaycast(t,n,r){this.debugRaycastHelper&&(this.realScene.remove(this.debugRaycastHelper),this.debugRaycastHelper=void 0),this.debugHitPoint&&(this.realScene.remove(this.debugHitPoint),this.debugHitPoint=void 0);let s=new X(this.sceneOrigin.toSceneX(t.x),this.sceneOrigin.toSceneY(t.y),this.sceneOrigin.toSceneZ(t.z));this.debugRaycastHelper=new F0(n.clone().normalize(),s,r,16711680,r*.1,r*.05),this.realScene.add(this.debugRaycastHelper);let a=new xs(.2,8,8),o=new _t({color:65280});this.debugHitPoint=new Ke(a,o),this.debugHitPoint.position.copy(s).add(n.clone().multiplyScalar(r)),this.realScene.add(this.debugHitPoint)}prevFramePerspective=null;setCinimaticCamera(t,n,r){this.cameraWorldPos.x=t.x,this.cameraWorldPos.y=t.y,this.cameraWorldPos.z=t.z,this.sceneOrigin.update(t.x,t.y,t.z),this.cameraObject.position.set(0,0,0),this.cameraShake.setBaseRotation(r,n),this.updateCameraSectionPos()}setCinimaticFov(t){this.animatedFov=t,this.camera.fov=t,this.camera.updateProjectionMatrix()}updateSmoothFov(){if(this.cinimaticScript.running)return;let t=this.displayOptions.inWorldRenderingConfig.fov,n=this.playerStateReactive.fovMultiplier,r=t*(Number.isFinite(n)?n:1),s=performance.now();if(this.animatedFov===0&&(this.animatedFov=r),Math.abs(this.animatedFov-r)>=.01){let a=s-this.lastFovAnimTime,o=Math.min(a/ia.FOV_TRANSITION_MS,1),l=c=>1-(1-c)**3;this.animatedFov+=(r-this.animatedFov)*l(o),Math.abs(this.animatedFov-r)<.01&&(this.animatedFov=r)}else this.animatedFov=r;this.lastFovAnimTime=s,this.camera.fov!==this.animatedFov&&(this.camera.fov=this.animatedFov,this.camera.updateProjectionMatrix())}updateCamera(t,n,r){if(!this.cinimaticScript.running){if(t){this.renderer.xr.isPresenting&&(t.y-=this.camera.position.y),this.currentPosTween?.stop();let s=this.displayOptions.inWorldRenderingConfig.instantCameraUpdate?0:this.playerStateUtils.isSpectatingEntity()?150:50;this.currentPosTween=new jr(this.cameraWorldPos).to({x:t.x,y:t.y,z:t.z},s).onUpdate(()=>{this.sceneOrigin.update(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),this.cameraObject.position.set(0,0,0)}).start()}if(this.playerStateUtils.isSpectatingEntity()){let s=this.cameraShake.getBaseRotation(),a=0,o=Math.PI/2;s.yaw<o&&n>Math.PI+o?a=-Math.PI*2:n<o&&s.yaw>Math.PI+o&&(a=Math.PI*2),this.currentRotTween?.stop(),this.currentRotTween=new jr(s).to({pitch:r,yaw:n+a},100).onUpdate(l=>this.cameraShake.setBaseRotation(l.pitch,l.yaw-a)).start()}else{this.currentRotTween?.stop(),this.cameraShake.setBaseRotation(r,n);let{perspective:s}=this.playerStateReactive;if(s==="third_person_back"||s==="third_person_front"){let a=new X(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),o=this.getThirdPersonCamera(a,n,r),l=a.distanceTo(new X(o.x,o.y,o.z)),c=s==="third_person_back"?l:-l;this.camera.position.set(0,0,c),s==="third_person_front"?this.camera.rotation.set(0,Math.PI,0):this.camera.rotation.set(0,0,0)}else this.camera.position.z=0,this.camera.rotation.set(0,0,0),this.debugRaycastHelper&&(this.realScene.remove(this.debugRaycastHelper),this.debugRaycastHelper=void 0),this.debugHitPoint&&(this.realScene.remove(this.debugHitPoint),this.debugHitPoint=void 0)}this.updateCameraSectionPos()}}debugChunksVisibilityOverride(){let{chunksRenderAboveOverride:t,chunksRenderBelowOverride:n,chunksRenderDistanceOverride:r,chunksRenderAboveEnabled:s,chunksRenderBelowEnabled:a,chunksRenderDistanceEnabled:o}=this.reactiveDebugParams,l=this.getSectionHeight(),c=this.cameraSectionPos.y*l;if(this.displayOptions.inWorldRenderingConfig.enableDebugOverlay&&t!==void 0||n!==void 0||r!==void 0)for(let[u,d]of Object.entries(this.sectionObjects)){if(d._waitingForChunkDisplay)continue;let[f,v,g]=u.split(",").map(Number),b=s&&t!==void 0?v<=c+t:a&&n!==void 0?v>=c-n:o&&r!==void 0?Math.abs(v-c)<=r:!0;d.visible=b}else this.chunkMeshManager.updateSectionsVisibility()}render(t=!1){if(this.currentRenderedFrames++,this.reactiveDebugParams.stopRendering)return;this.debugChunksVisibilityOverride();let n=performance.now();this.lastRendered=performance.now();let r=this.lastRenderTime>0?Math.min(Math.max((n-this.lastRenderTime)/1e3,0),.1):1/60;this.lastRenderTime=n,this.cursorBlock.render(),this.updateSectionOffsets();let s=this.getCameraPosition();if(this.skyboxRenderer.update(s,this.viewDistance),this.updateSmoothFov(),t){let w=this.renderer.getSize(new ze);this.camera.aspect=w.width/w.height,this.camera.updateProjectionMatrix()}let a=0;if(!this.reactiveDebugParams.disableEntities){let w=performance.now();this.entities.render(),a=performance.now()-w}let o=this.cameraGroupVr instanceof bt?this.cameraGroupVr.children.find(w=>w instanceof fn):this.camera;this.applyPendingSectionUpdates();let l=performance.now(),c=l-this.lastSciFiTickMs;this.lastSciFiTickMs=l,this.getModule("futuristicReveal")?.tick?.(c,l);let u=this.cameraWorldPos.x,d=this.cameraWorldPos.y,f=this.cameraWorldPos.z;this.chunkMeshManager.maybeRebase({x:u,y:d,z:f});let v=this.chunkMeshManager.getRenderOrigin(),g=this.chunkMeshManager.globalBlockBuffer;g&&(g.setCameraOrigin(v,u,d,f),g.setDebugOverlay(this.displayOptions.inWorldRenderingConfig.enableDebugOverlay),g.compactStep(),g.hasPendingUploads()&&g.uploadDirtyRange(),g.suppressThreeDraw());let b=this.chunkMeshManager.globalLegacyBuffer;b&&(b.setDebugOverlay(this.displayOptions.inWorldRenderingConfig.enableDebugOverlay),b.compactStep(),b.hasPendingUploads()&&b.uploadDirtyRange(),b.suppressThreeDraw());let y=this.chunkMeshManager.globalLegacyBlendBuffer;y&&(y.setDebugOverlay(this.displayOptions.inWorldRenderingConfig.enableDebugOverlay),y.compactStep(),y.hasPendingUploads()&&y.uploadDirtyRange(),y.suppressThreeDraw()),this.chunkMeshManager.markCullDirtyIfBufferStateChanged(),this.chunkMeshManager.setLegacyCameraOrigin(u,d,f),this.chunkMeshManager.updateCullDirtyFromCamera(o,u,d,f),this.chunkMeshManager.cullDirty&&(this.chunkMeshManager.updateSectionCullAndSort(o,this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),this.chunkMeshManager.clearCullDirty()),this.renderer.render(this.scene,o),this.displayOptions.inWorldRenderingConfig.showHand&&this.playerStateReactive.gameMode!=="spectator"&&this.playerStateReactive.perspective==="first_person"&&!this.renderer.xr.isPresenting&&(this.holdingBlock.render(this.camera,this.renderer,this.ambientLight,this.directionalLight),this.holdingBlockLeft.render(this.camera,this.renderer,this.ambientLight,this.directionalLight));for(let w of this.fountains)this.sectionObjects[w.sectionId]&&!this.sectionObjects[w.sectionId].foutain&&(w.createParticles(this.sectionObjects[w.sectionId]),this.sectionObjects[w.sectionId].foutain=!0),w.render();this.waypoints.render(),this.fireworks.update();for(let w of this.onRender)w(r);let x=performance.now()-n;this.worldRendererConfig.autoLowerRenderDistance&&this.chunkMeshManager.recordRenderTime(x),this.renderTimeAvgCount++,this.renderTimeAvg=(this.renderTimeAvg*(this.renderTimeAvgCount-1)+x)/this.renderTimeAvgCount,this.renderTimeMax=Math.max(this.renderTimeMax,x),this.performanceMonitor.onFrame({totalMs:x,entitiesMs:a,loadedTextureCount:this.renderer.info.memory.textures,fps:this.lastFps})}renderHead(t,n,r,s){let a;if(s.SkullOwner?a=s.SkullOwner.Properties?.textures?.[0]?.Value:a=s.profile?.properties?.find(o=>o.name==="textures")?.value,!!a)try{let l=JSON.parse(Buffer.from(a,"base64").toString()).textures?.SKIN?.url,{skinTexturesProxy:c}=this.worldRendererConfig;c&&(l=l?.replace("http://textures.minecraft.net/",c).replace("https://textures.minecraft.net/",c));let u=$c(this,l,Yc.head),d=new bt;return r&&u.position.set(0,.3125,.3125),u.position.y-=23/16,d.add(u),this.sceneOrigin.track(d),d.position.set(t.x+.5,t.y+.045,t.z+.5),d.rotation.set(0,-Ot.degToRad(n*(r?90:45/2)),0),d.scale.set(.8,.8,.8),d}catch(o){console.error("Error decoding player texture:",o)}}lightUpdate(t,n){for(let r=this.worldSizeParams.minY;r<this.worldSizeParams.worldHeight;r+=16)this.setSectionDirty(new kt(t,r,n))}rerenderAllChunks(){for(let t of Object.keys(this.sectionObjects)){let[n,r,s]=t.split(",").map(Number);this.setSectionDirty(new kt(n,r,s))}}updateShowChunksBorder(t){this.chunkMeshManager.updateAllBoxHelpers(t)}resetWorld(){super.resetWorld(),this.pendingSectionUpdates.clear(),this.pendingSectionBufferStartTimes.clear(),this.chunkMeshManager.dispose(),this.chunkMeshManager=new fg(this,this.scene,this.material,this.worldSizeParams.worldHeight,this.viewDistance),this.debugRaycastHelper&&(this.realScene.remove(this.debugRaycastHelper),this.debugRaycastHelper=void 0),this.debugHitPoint&&(this.realScene.remove(this.debugHitPoint),this.debugHitPoint=void 0)}getLoadedChunksRelative(t,n=!1){let[r,s,a]=NE(t);return Object.fromEntries(Object.entries(this.sectionObjects).map(([o,l])=>{let[c,u,d]=o.split(",").map(Number),[f,v,g]=NE({x:c,y:u,z:d});return[n?`${f-r},${v-s},${g-a}`:`${f-r},${g-a}`,l]}))}readdChunks(){for(let t of Object.keys(this.sectionObjects))this.scene.remove(this.sectionObjects[t]);setTimeout(()=>{for(let t of Object.keys(this.sectionObjects))this.scene.add(this.sectionObjects[t])},500)}disableUpdates(t=this.scene.children){for(let n of t)n.matrixWorldNeedsUpdate=!1,this.disableUpdates(n.children??[])}removeColumn(t,n){super.removeColumn(t,n),this.clearPendingSectionUpdatesForChunk(t,n);let r=this.getSectionHeight(),s=this.worldMinYRender;for(let a=s;a<this.worldSizeParams.worldHeight;a+=r){let o=`${t},${a},${n}`;this.chunkMeshManager.sectionObjects[o]&&this.chunkMeshManager.releaseSection(o)}this.chunkMeshManager.onChunkRemovedFromGate(`${t},${n}`)}updateViewerPosition(t){super.updateViewerPosition(t),this.chunkMeshManager.pendingNearReveal.size>0&&this.chunkMeshManager.tryRevealPending()}onViewerChunkPositionChanged(){this.chunkMeshManager.tryRevealPending()}setSectionDirty(...t){super.setSectionDirty(...t)}static getRendererInfo(t){try{let n=t.getContext();return`${n.getParameter(n.getExtension("WEBGL_debug_renderer_info").UNMASKED_RENDERER_WEBGL)}`}catch(n){console.warn("Failed to get renderer info",n)}}worldStop(){this.media.onWorldStop()}destroy(){this.performanceMonitor?.reset(),this.pendingSectionUpdates.clear(),this.pendingSectionBufferStartTimes.clear(),this.chunkMeshManager.dispose(),this.disposeModules(),this.fireworksLegacy.destroy(),super.destroy(),this.skyboxRenderer.dispose(),this.fireworks.dispose()}shouldObjectVisible(t){let r=this.getSectionHeight(),s,a,o,l=this.sceneOrigin.getWorldPosition(t);l?(s=l.x,a=l.y,o=l.z):(s=this.sceneOrigin.toWorldX(t.position.x),a=this.sceneOrigin.toWorldY(t.position.y),o=this.sceneOrigin.toWorldZ(t.position.z));let c=Math.floor(s/16)*16,u=Math.floor(o/16)*16,d=Math.floor(a/r)*r,f=`${c},${u}`,v=`${c},${d},${u}`;return!!this.finishedChunks[f]||!!this.sectionObjects[v]}handleUserClick(t){this.media.handleUserClick(t)}updateSectionOffsets(){let t=performance.now();for(let[n,r]of Object.entries(this.sectionsOffsetsAnimations)){let s=(t-r.time)/1e3;r.time=t,r.currentOffsetX+=r.speedX*s,r.currentOffsetY+=r.speedY*s,r.currentOffsetZ+=r.speedZ*s,r.limitX!==void 0&&(r.speedX>0?r.currentOffsetX=Math.min(r.currentOffsetX,r.limitX):r.currentOffsetX=Math.max(r.currentOffsetX,r.limitX)),r.limitY!==void 0&&(r.speedY>0?r.currentOffsetY=Math.min(r.currentOffsetY,r.limitY):r.currentOffsetY=Math.max(r.currentOffsetY,r.limitY)),r.limitZ!==void 0&&(r.speedZ>0?r.currentOffsetZ=Math.min(r.currentOffsetZ,r.limitZ):r.currentOffsetZ=Math.max(r.currentOffsetZ,r.limitZ));let a=this.sectionObjects[n];a&&(a.position.set(r.currentOffsetX,r.currentOffsetY,r.currentOffsetZ),a.updateMatrix())}}reloadWorld(){this.entities.reloadEntities()}};Wn(ia,"LEGACY_TO_PHYSICAL_LIGHT",Math.PI),Wn(ia,"FOV_TRANSITION_MS",200),Wn(ia,"MAX_SECTION_UPDATE_BUFFER_MS",500);var Yd=ia;h();p();m();h();p();m();var mg="1.21.4";h();p();m();function Jd(i,e){i.aspect=e.width/e.height,i.updateProjectionMatrix()}h();p();m();h();p();m();var u0={mode:"v2",minecraftTextures:!0,v2Scene:"light",v2Camera:"dive",v2BlockGroup:"stainedGlass",v2CameraSpeedPercent:80,v2BlockSpeedPercent:40},GP=i=>i/100,g9={camera:GP(u0.v2CameraSpeedPercent),block:GP(u0.v2BlockSpeedPercent)};function WP(i,e=!1){return i?.mode?i.mode:e?"worldBlocks":u0.mode}h();p();m();Lt();h();p();m();var jP={};function XP(...i){let e=i.filter(n=>n.length>0).join("/"),t=typeof globalThis.location<"u"&&globalThis.location.href?globalThis.location.href:typeof jP<"u"&&jP.url?jP.url:`/${e}`;try{return new URL(e,t).href}catch{return`/${e}`}}var $P=new Date,W4e=$P.getMonth()===11&&$P.getDate()>=24&&$P.getDate()<=26,cJe=["panorama_3.webp","panorama_1.webp","panorama_4.webp","panorama_5.webp","panorama_0.webp","panorama_2.webp"],uJe=200,pg=class{constructor(e){this.documentRenderer=e;this.scene=new Rr,this.scene.background=new We(3294568);let t=new wa(13421772);this.scene.add(t);let n=new Ss(16777215,.5);n.position.set(1,1,.5).normalize(),n.castShadow=!0,this.scene.add(n),this.camera=new fn(85,e.canvas.width/e.canvas.height,.05,1e3),this.camera.position.set(0,0,0),this.camera.rotation.set(0,0,0)}scene;camera;startTimes=new Map;time=0;panoramaGroup=null;async init(){this.buildCubemap()}update(e,t){t&&Jd(this.camera,this.documentRenderer.canvas)}dispose(){this.scene.clear(),this.panoramaGroup=null,this.startTimes.clear()}buildCubemap(){let e=new Sn(1e3,1e3,1e3),t=[];for(let s of cJe)(async()=>{let o=XP("background",W4e?"christmas":"",s),l=await qu(o),c=cc(l);c.matrixAutoUpdate=!1,c.matrix.set(-1,0,1,0,1,0,0,0,1),c.wrapS=jn,c.wrapT=jn,c.minFilter=$t,c.magFilter=$t;let u=new _t({map:c,transparent:!0,side:In,depthWrite:!1,opacity:0});this.startTimes.set(u,Date.now()),t.push(u)})().catch(o=>{console.warn("[ClassicMenuBackground] Failed to load panorama face:",s,o)});let n=new Ke(e,t);n.onBeforeRender=()=>{this.time+=.01,n.rotation.y=Math.PI+this.time*.01,n.rotation.z=Math.sin(-this.time*.001)*.001;for(let s of t){let a=this.startTimes.get(s);if(a){let o=Date.now()-a;s.opacity=Math.min(1,o/uJe)}}};let r=new Ut;if(r.add(n),!W4e)for(let s=0;s<20;s++){let a=new o0("1.16.4","squid").mesh;a.position.set(Math.random()*30-15,Math.random()*20-10,Math.random()*10-17),a.rotation.set(0,Math.PI+Math.random(),-Math.PI/4,"ZYX");let o=Math.random()*.01;a.children[0].onBeforeRender=()=>{a.rotation.y+=o,a.rotation.z=Math.cos(n.rotation.y*3)*Math.PI/4-Math.PI/2},r.add(a)}this.scene.add(r),this.panoramaGroup=r}async debugImageInFrontOfCamera(){let e=await qu(XP("background","panorama_0.webp")),t=cc(e),n=new Ke(new zn(1e3,1e3),new _t({map:t}));n.position.set(0,0,-500),this.scene.add(n)}};h();p();m();Lt();h();p();m();var q5=["galaxy","nether","end","cyber","light"],G5=["cruise","barrel","dive","orbit","snake"],_9={galaxy:"Galaxy",nether:"Nether",end:"The End",cyber:"Cyber",light:"Light Space"},y9={cruise:"Cruise",barrel:"Barrel",dive:"Dive",orbit:"Orbit",snake:"Snake"},W5=["mixed","stainedGlass","wool","construction","glow","world"],b9={mixed:"Mixed",stainedGlass:"Stained glass",wool:"Wool",construction:"Construction",glow:"Glow",world:"World (grass & ores)"};var j4e=.1,Y4e={mixed:["white_wool","cyan_wool","blue_wool","purple_wool","white_stained_glass","cyan_stained_glass","blue_stained_glass","purple_stained_glass","glowstone","sea_lantern","amethyst_block","copper_block","gold_block","diamond_block"],stainedGlass:["white_stained_glass","orange_stained_glass","magenta_stained_glass","light_blue_stained_glass","yellow_stained_glass","lime_stained_glass","pink_stained_glass","gray_stained_glass","light_gray_stained_glass","cyan_stained_glass","purple_stained_glass","blue_stained_glass","brown_stained_glass","green_stained_glass","red_stained_glass","black_stained_glass"],wool:["white_wool","orange_wool","magenta_wool","light_blue_wool","yellow_wool","lime_wool","pink_wool","gray_wool","light_gray_wool","cyan_wool","purple_wool","blue_wool","brown_wool","green_wool","red_wool","black_wool"],construction:["copper_block","exposed_copper","weathered_copper","oxidized_copper","cut_copper","exposed_cut_copper","weathered_cut_copper","oxidized_cut_copper","iron_block","gold_block","diamond_block","emerald_block","netherite_block","lapis_block","redstone_block","coal_block","quartz_block","amethyst_block","bricks","stone_bricks","deepslate_bricks","polished_blackstone"],glow:["glowstone","sea_lantern","shroomlight","ochre_froglight","verdant_froglight","pearlescent_froglight","redstone_lamp","beacon"],world:["grass_block","podzol","mycelium","dirt","coarse_dirt","rooted_dirt","mud","clay","stone","cobblestone","mossy_cobblestone","deepslate","cobbled_deepslate","tuff","calcite","sand","red_sand","gravel","snow_block","coal_ore","deepslate_coal_ore","iron_ore","deepslate_iron_ore","copper_ore","deepslate_copper_ore","gold_ore","deepslate_gold_ore","diamond_ore","deepslate_diamond_ore","emerald_ore","deepslate_emerald_ore","lapis_ore","deepslate_lapis_ore","redstone_ore","deepslate_redstone_ore","nether_gold_ore","ancient_debris","oak_log","birch_log","spruce_log","jungle_log","acacia_log","dark_oak_log","mangrove_log","cherry_log","netherrack","soul_sand","basalt","end_stone"]},X4e={galaxy:{bg:132114,fog:132114,fogD:.011,blocks:[61695,54527,47359,59647,2280703,43263],emit:[13158,8789,6724],nebula:[4403,1114146,4386],galFn:i=>new We(i*.05,i*.2,i),ambient:264216,dir:3368703,pt1:43775,pt2:16729343,name:"GALAXY"},nether:{bg:917760,fog:917760,fogD:.016,blocks:[16720384,16737792,16750848,13373696,16729122,16755200],emit:[2230272,1114112,3346688],nebula:[1704960,851968,1705984],galFn:i=>new We(i,i*.15,0),ambient:1573376,dir:16724736,pt1:16729088,pt2:16755200,name:"NETHER"},end:{bg:0,fog:0,fogD:.009,blocks:[7807658,11158732,5570679,14527231,3342421,12299007],emit:[655381,1572901,327696],nebula:[524312,851989,262158],galFn:i=>new We(i*.4,0,i),ambient:393232,dir:10040319,pt1:11158783,pt2:4456618,name:"THE END"},cyber:{bg:792610,fog:792610,fogD:.008,blocks:[65535,4521932,11206468,6741503,8978278,65450],emit:[666163,668450,665656],nebula:[1192e3,1587240,1323588],galFn:i=>new We(i*.15,i*.85,i*.95),ambient:1716288,dir:6750156,pt1:4521966,pt2:10092356,name:"CYBER",starColor:13431039,starOpacity:.75,galaxyOpacity:.62,nebulaOpacity:.36,edgeLineColor:4521949,blockOpacity:[.38,.54]},light:{bg:8951984,fog:7899296,fogD:.006,gradientBg:{top:14214392,mid:10531016,bottom:6846608,radial:!0},blocks:[15266559,13691135,12114175,10537208,8960240,7383272,10012927,12640511,15792383,7909608,14216447,14739711],emit:[6854864,8958176,11061488,12638456],nebula:[9480392,11059424,12637420,14215416,7901360],galFn:i=>{let e=new We;return i<.4?e.lerpColors(new We(16054527),new We(14215423),i/.4):i<.75?e.lerpColors(new We(14215423),new We(11061488),(i-.4)/.35):e.lerpColors(new We(11061488),new We(9482464),(i-.75)/.25),e},ambient:7899296,dir:13688040,pt1:11061503,pt2:13162751,name:"LIGHT",starColor:15266047,starOpacity:.5,galaxyOpacity:.7,nebulaOpacity:.32,edgeLineColor:10010856,blockOpacity:[.42,.56]}},dJe={cruise:{pos:(i,e,t)=>({x:Math.sin(i*.28)*18+Math.cos(i*.11)*7+e*10,y:Math.sin(i*.19)*6+Math.cos(i*.31)*3+t*6,z:0}),look:(i,e,t)=>({x:Math.sin((i+.18)*.28)*18+e*8,y:Math.sin((i+.18)*.19)*6+t*4,z:-25}),roll:(i,e=0)=>e*.05+Math.sin(i*.22)*.015,spd:.18},barrel:{pos:(i,e,t)=>{let r=i*2.4;return{x:Math.cos(r)*10+e*4,y:Math.sin(r)*10+t*4,z:Math.sin(i*.4)*8}},look:i=>({x:Math.sin(i*.5)*5,y:Math.cos(i*.5)*5,z:-30}),roll:i=>i*2.4+Math.PI*.5,spd:.24},dive:{pos:(i,e,t)=>({x:Math.sin(i*.6)*30+e*8,y:Math.cos(i*.4)*18+t*6,z:Math.sin(i*.3)*12}),look:(i,e,t)=>({x:Math.sin(i*.6+.2)*30+e*6,y:Math.cos(i*.4+.2)*18-8+t*4,z:-35}),roll:(i,e=0)=>e*.08+Math.sin(i*.6)*.12,spd:.3},orbit:{pos:(i,e,t)=>({x:Math.cos(i*.5)*20+e*5,y:Math.sin(i*.25)*10+t*5,z:Math.sin(i*.5)*20}),look:()=>({x:0,y:0,z:-60}),roll:i=>Math.sin(i*.5)*.08,spd:.15},snake:{pos:(i,e,t)=>({x:Math.sin(i*1.1)*22+Math.sin(i*.37)*8+e*10,y:Math.sin(i*.7)*10+e*4+t*8,z:0}),look:(i,e,t)=>{let n=i+.12;return{x:Math.sin(n*1.1)*22+Math.sin(n*.37)*8+e*8,y:Math.sin(n*.7)*10+t*6,z:-22}},roll:(i,e=0)=>e*.1+Math.sin(i*1.1)*.06,spd:.22}},fJe={cruise:1,barrel:1.6,dive:2.2,orbit:.7,snake:1.4},hJe=250,x9=1e4,w9=3e3,j5=i=>i[Math.floor(Math.random()*i.length)],YP=i=>"#"+i.toString(16).padStart(6,"0"),$4e=i=>{if(typeof document>"u")return null;let e=document.createElement("canvas");e.width=4,e.height=512;let t=e.getContext("2d");if(!t)return null;let n=e.width,r=e.height,s=i.radial?t.createRadialGradient(n/2,r*.32,0,n/2,r*.32,r*.85):t.createLinearGradient(0,0,0,r);s.addColorStop(0,YP(i.top)),i.mid!=null&&s.addColorStop(.45,YP(i.mid)),s.addColorStop(1,YP(i.bottom)),t.fillStyle=s,t.fillRect(0,0,n,r);let a=new On(e);return a.needsUpdate=!0,a},X5=class{constructor(e,t={},n){this.documentRenderer=e;this.abortSignal=n;let r=u0;this.curScene=t.initialScene??r.v2Scene,this.curCam=t.initialCamera??r.v2Camera,this.blockGroup=t.initialBlockGroup??r.v2BlockGroup,this.cameraSpeed=t.initialCameraSpeed??g9.camera,this.blockSpeed=t.initialBlockSpeed??g9.block,this.useMinecraftTextures=t.useMinecraftTextures??r.minecraftTextures,this.resourcesManager=t.resourcesManager;let s=X4e[this.curScene];this.scene=new Rr,this.scene.fog=new C0(s.fog,s.fogD),this.applyScenePalette(s),this.camera=new fn(80,this.documentRenderer.canvas.width/this.documentRenderer.canvas.height,.1,700),this.ambient=new wa(s.ambient,2.5),this.scene.add(this.ambient),this.dir=new Ss(s.dir,4),this.dir.position.set(1,1,0),this.scene.add(this.dir),this.pt1=new yo(s.pt1,5,100),this.scene.add(this.pt1),this.pt2=new yo(s.pt2,4,80),this.pt2.position.set(30,20,-30),this.scene.add(this.pt2);for(let f=0;f<hJe;f++)this.spawnBlock(s,!0);if(!this.useMinecraftTextures){let f=s.edgeLineColor??62975;for(let v=0;v<40;v++){let g=new Pn({color:f,transparent:!0,opacity:.25});j5(this.blocks).mesh.add(new Kn(this.eGeo,g))}}this.scene.add(this.bGroup);let a=new dt,o=new Float32Array(5e3*3);for(let f=0;f<5e3*3;f++)o[f]=(Math.random()-.5)*500;a.setAttribute("position",new Mt(o,3)),this.stars=new gr(a,new Jr({color:s.starColor??16777215,size:.3,transparent:!0,opacity:s.starOpacity??.7,sizeAttenuation:!0})),this.scene.add(this.stars),this.galGeo=new dt;let l=new Float32Array(x9*3),c=new Float32Array(x9*3);for(let f=0;f<x9;f++){let v=f%3,g=Math.random(),b=v/3*Math.PI*2+g*Math.PI*5,y=g*90+Math.random()*10,_=(1-g)*18;l[f*3]=Math.cos(b)*y+(Math.random()-.5)*_,l[f*3+1]=(Math.random()-.5)*7,l[f*3+2]=Math.sin(b)*y+(Math.random()-.5)*_-180;let x=.2+g*.8,w=s.galFn(x);c[f*3]=w.r,c[f*3+1]=w.g,c[f*3+2]=w.b}this.galGeo.setAttribute("position",new Mt(l,3)),this.galGeo.setAttribute("color",new Mt(c,3)),this.galaxy=new gr(this.galGeo,new Jr({size:.9,vertexColors:!0,transparent:!0,opacity:s.galaxyOpacity??.55,sizeAttenuation:!0})),this.scene.add(this.galaxy),this.nebGeo=new dt;let u=new Float32Array(w9*3),d=new Float32Array(w9*3);for(let f=0;f<w9;f++){let v=25+Math.random()*110,g=Math.random()*Math.PI*2,b=(Math.random()-.5)*Math.PI*.5;u[f*3]=v*Math.cos(g)*Math.cos(b),u[f*3+1]=v*Math.sin(b)*.6,u[f*3+2]=v*Math.sin(g)*Math.cos(b)-80;let y=new We(j5(s.nebula));d[f*3]=y.r,d[f*3+1]=y.g,d[f*3+2]=y.b}this.nebGeo.setAttribute("position",new Mt(u,3)),this.nebGeo.setAttribute("color",new Mt(d,3)),this.nebula=new gr(this.nebGeo,new Jr({size:3,vertexColors:!0,transparent:!0,opacity:s.nebulaOpacity??.3,sizeAttenuation:!0})),this.scene.add(this.nebula),this.addBackgroundTextPlane(),this.setupMouseTracking()}scene;camera;ambient;dir;pt1;pt2;blocks=[];bGroup=new bt;galaxy;nebula;stars;galGeo;nebGeo;bGeo=new Sn(1,1,1);eGeo=new dl(this.bGeo);curScene;curCam;blockGroup;cameraSpeed;blockSpeed;camT=0;mx=0;my=0;tmx=0;tmy=0;transitioning=!1;useMinecraftTextures=!1;resourcesManager;atlasTexture=null;blockMaterialPool=new Map;gradientSky=null;gradientSkyTexture=null;disposed=!1;animTime=0;texturesApplied=!1;textureLoadInProgress=!1;onAssetsTexturesUpdated;async init(){this.useMinecraftTextures&&this.scheduleMinecraftTextureLoad()}scheduleMinecraftTextureLoad(){!this.useMinecraftTextures||this.disposed||this.texturesApplied||this.textureLoadInProgress||this.tryApplyMinecraftTextures()}attachAssetsListener(){let e=this.resourcesManager;!e||this.onAssetsTexturesUpdated||(this.onAssetsTexturesUpdated=()=>this.scheduleMinecraftTextureLoad(),e.on("assetsTexturesUpdated",this.onAssetsTexturesUpdated))}detachAssetsListener(){let e=this.resourcesManager;!e||!this.onAssetsTexturesUpdated||(e.off("assetsTexturesUpdated",this.onAssetsTexturesUpdated),this.onAssetsTexturesUpdated=void 0)}hasBlockAtlas(e){let t=e.currentResources;return!!(t?.blocksAtlasImage&&t.blocksAtlasJson)}async ensureAtlasReady(e){if(await this.ensureMcDataLoaded(),this.hasBlockAtlas(e))return!0;if(typeof document>"u"&&e!==this.resourcesManager)return!1;e.currentConfig={...e.currentConfig,version:mg,noInventoryGui:!0};try{await e.updateAssetsData?.({})}catch{return!1}return this.hasBlockAtlas(e)}async tryApplyMinecraftTextures(){if(!(this.disposed||!this.useMinecraftTextures||this.texturesApplied)){this.textureLoadInProgress=!0;try{let e=this.resourcesManager??new lc;if(!await this.ensureAtlasReady(e)){this.resourcesManager&&this.attachAssetsListener();return}if(this.disposed)return;this.applyMinecraftTexturesFromAtlas(e),this.texturesApplied=!0,this.detachAssetsListener()}catch(e){console.warn("[V2MenuBackground] Failed to load Minecraft textures, using solid colors:",e),this.useMinecraftTextures=!1,this.detachAssetsListener()}finally{this.textureLoadInProgress=!1}}}applyScenePalette(e){if(this.documentRenderer.renderer.setClearColor(e.bg),e.gradientBg)if(this.scene.background=null,this.gradientSky){if(this.gradientSky.visible=!0,this.gradientSkyTexture&&e.gradientBg){let s=$4e(e.gradientBg);s&&(this.gradientSkyTexture.dispose(),this.gradientSkyTexture=s,this.gradientSky.material.map=s,this.gradientSky.material.needsUpdate=!0)}}else{let s=$4e(e.gradientBg);s?(this.gradientSkyTexture=s,this.gradientSky=new Ke(new zn(900,700),new _t({map:s,depthWrite:!1,side:In})),this.gradientSky.position.set(0,0,-280),this.gradientSky.renderOrder=-1e3,this.scene.add(this.gradientSky)):this.scene.background=new We(e.bg)}else this.scene.background=new We(e.bg),this.gradientSky&&(this.gradientSky.visible=!1);this.scene.fog instanceof C0&&(this.scene.fog.color.set(e.fog),this.scene.fog.density=e.fogD);let t=this.stars?.material;t&&(t.color.set(e.starColor??16777215),t.opacity=e.starOpacity??.7);let n=this.galaxy?.material;n&&(n.opacity=e.galaxyOpacity??.55);let r=this.nebula?.material;r&&(r.opacity=e.nebulaOpacity??.3)}setupMouseTracking(){let e=n=>{let r=typeof window<"u"?window.innerWidth:this.documentRenderer.canvas.width,s=typeof window<"u"?window.innerHeight:this.documentRenderer.canvas.height;this.tmx=(n.clientX/r-.5)*2,this.tmy=-(n.clientY/s-.5)*2};(typeof document<"u"?document:void 0)?.addEventListener("mousemove",e,{signal:this.abortSignal})}addBackgroundTextPlane(){let n=typeof document<"u"?document.createElement("canvas"):null;if(!n)return;n.width=2048,n.height=768;let r=n.getContext("2d");if(!r)return;r.clearRect(0,0,2048,768),r.save(),r.font="bold 560px Orbitron, sans-serif",r.textAlign="center",r.textBaseline="middle",r.shadowColor="rgba(0,200,255,0.35)",r.shadowBlur=80,r.fillStyle="rgba(255,255,255,0.055)",r.fillText("V2",2048*.28,768*.5),r.restore(),r.save(),r.font="bold 148px Orbitron, sans-serif",r.textAlign="center",r.textBaseline="middle",r.shadowColor="rgba(0,200,255,0.2)",r.shadowBlur=40,r.fillStyle="rgba(255,255,255,0.038)",r.fillText("by ZARDOY",2048*.72,768*.52),r.restore();let s=new On(n),a=new Ke(new zn(280,105),new _t({map:s,transparent:!0,opacity:1,depthWrite:!1,side:In,blending:es}));a.position.set(8,4,-320),this.scene.add(a)}spawnBlock(e,t,n){let r=this.createBlockMaterial(e,n),s=new Ke(this.bGeo,r),a=.3+Math.random()*3;s.scale.setScalar(a),s.position.set((Math.random()-.5)*140,(Math.random()-.5)*70,t?-(Math.random()*140):-155-Math.random()*30),s.rotation.set(Math.random()*Math.PI*2,Math.random()*Math.PI*2,Math.random()*Math.PI*2);let o={mesh:s,spd:.04+Math.random()*.12,dx:(Math.random()-.5)*.012,dy:(Math.random()-.5)*.008,rx:(Math.random()-.5)*.012,ry:(Math.random()-.5)*.012,rz:(Math.random()-.5)*.01,minecraftBlockName:n};this.blocks.push(o),this.bGroup.add(s)}createBlockMaterial(e,t){if(this.useMinecraftTextures&&t){let s=this.blockMaterialPool.get(t);if(s)return s.clone()}let[n,r]=e.blockOpacity??[.32,.46];return new _t({color:j5(e.blocks),transparent:!0,opacity:n+Math.random()*(r-n),depthWrite:!1,blending:es})}removeBlockEdgeLines(){for(let e of this.blocks){let t=e.mesh.children.filter(n=>n instanceof Kn);for(let n of t){e.mesh.remove(n),n.geometry?.dispose();let r=n.material;Array.isArray(r)?r.forEach(s=>s.dispose()):r.dispose()}}}async ensureMcDataLoaded(){let e=globalThis._LOAD_MC_DATA;e&&await e()}resolveBlockAtlasUv(e,t,n){let r=s=>{let a=t[s];return a?{u:a.u,v:a.v,su:a.su??n.suSv,sv:a.sv??n.suSv}:null};if(t[e])return r(e);for(let s of["_top","_side","_front","_0"]){let a=r(`${e}${s}`);if(a)return a}for(let s of Object.keys(t))if(s.startsWith(e))return r(s);return null}applyMinecraftTexturesFromAtlas(e){let t=e.currentResources;if(!t?.blocksAtlasImage||!t.blocksAtlasJson)throw new Error("Block atlas not available");let n=t.blocksAtlasJson,r=n.textures;this.atlasTexture=cc(t.blocksAtlasImage),this.atlasTexture.flipY=!1,this.atlasTexture.needsUpdate=!0;for(let s of Y4e[this.blockGroup]){let a=this.resolveBlockAtlasUv(s,r,n);if(!a)continue;let o=this.atlasTexture.clone();o.flipY=!1,o.offset.set(a.u,a.v),o.repeat.set(a.su,a.sv),o.needsUpdate=!0;let l=s.includes("glass"),c=new _t({map:o,side:In,transparent:l,opacity:l?.85:1,alphaTest:l?.08:0,depthWrite:!0,toneMapped:!1});this.blockMaterialPool.set(s,c)}if(this.blockMaterialPool.size===0)throw new Error("No block textures resolved from atlas (check block names vs atlas keys)");this.removeBlockEdgeLines();for(let s of this.blocks){let a=j5([...this.blockMaterialPool.keys()]);s.minecraftBlockName=a,s.mesh.material=this.blockMaterialPool.get(a).clone()}}setScene(e){if(!q5.includes(e)||e===this.curScene||this.transitioning)return;this.transitioning=!0,this.curScene=e;let t=X4e[e];setTimeout(()=>{if(this.disposed)return;this.applyScenePalette(t),this.ambient.color.set(t.ambient),this.dir.color.set(t.dir),this.pt1.color.set(t.pt1),this.pt2.color.set(t.pt2);for(let s of this.blocks)this.useMinecraftTextures&&s.minecraftBlockName||s.mesh.material instanceof _t&&s.mesh.material.color.set(j5(t.blocks));let n=this.nebGeo.attributes.color;for(let s=0;s<w9;s++){let a=new We(j5(t.nebula));n.setXYZ(s,a.r,a.g,a.b)}n.needsUpdate=!0;let r=this.galGeo.attributes.color;for(let s=0;s<x9;s++){let a=.2+Math.random()*.8,o=t.galFn(a);r.setXYZ(s,o.r,o.g,o.b)}r.needsUpdate=!0,this.transitioning=!1},150)}setCamera(e){G5.includes(e)&&(this.curCam=e)}setCameraSpeed(e){this.cameraSpeed=Math.max(0,e)}setBlockSpeed(e){this.blockSpeed=Math.max(0,e)}async setBlockGroup(e){if(W5.includes(e)&&e!==this.blockGroup&&(this.blockGroup=e,!(!this.useMinecraftTextures||this.disposed))){for(let t of this.blockMaterialPool.values())t.map?.dispose(),t.dispose();this.blockMaterialPool.clear(),this.texturesApplied=!1,this.scheduleMinecraftTextureLoad()}}getSceneId(){return this.curScene}getCameraId(){return this.curCam}getBlockGroupId(){return this.blockGroup}update(e,t){t&&Jd(this.camera,this.documentRenderer.canvas);let n=dJe[this.curCam],r=this.cameraSpeed,s=this.blockSpeed;this.camT+=e*n.spd*r,this.mx+=(this.tmx-this.mx)*.05,this.my+=(this.tmy-this.my)*.05;let a=this.mx*j4e,o=this.my*j4e,l=n.pos(this.camT,a,o),c=n.look(this.camT,a,o);this.camera.position.set(l.x,l.y,l.z),this.camera.lookAt(c.x,c.y,c.z),this.camera.rotation.z=n.roll(this.camT,a);let u=fJe[this.curCam]*s;this.animTime+=e*1e3*s;for(let d of this.blocks){if(d.mesh.position.z+=d.spd*u*60*e,d.mesh.position.x+=d.dx*60*e*s,d.mesh.position.y+=d.dy*60*e*s,d.mesh.rotation.x+=d.rx*u,d.mesh.rotation.y+=d.ry*u,d.mesh.rotation.z+=d.rz,!this.useMinecraftTextures&&d.mesh.material instanceof _t){let f=d.mesh.userData.baseOpacity??.38;d.mesh.userData.baseOpacity==null&&(d.mesh.userData.baseOpacity=f);let v=.88+Math.abs(Math.sin(this.animTime*8e-4+d.mesh.position.x*.3))*.12;d.mesh.material.opacity=f*v}d.mesh.position.z>this.camera.position.z+15&&d.mesh.position.set((Math.random()-.5)*140,(Math.random()-.5)*70,this.camera.position.z-155-Math.random()*30)}this.pt1.position.set(Math.sin(this.camT*.8)*25+this.camera.position.x,Math.cos(this.camT*.6)*12+this.camera.position.y,this.camera.position.z-18),this.pt2.position.set(Math.cos(this.camT*.5)*20+this.camera.position.x,Math.sin(this.camT*.9)*15+this.camera.position.y,this.camera.position.z-30),this.galaxy.rotation.y+=e*.006*s,this.nebula.rotation.y-=e*.003*s,this.stars.rotation.y+=e*4e-4*s}dispose(){this.disposed=!0,this.detachAssetsListener(),this.scene.clear(),this.bGeo.dispose(),this.eGeo.dispose(),this.galGeo.dispose(),this.nebGeo.dispose(),this.gradientSkyTexture?.dispose(),this.atlasTexture?.dispose();for(let e of this.blockMaterialPool.values())e.map?.dispose(),e.dispose();this.blockMaterialPool.clear()}};h();p();m();Lt();h();p();m();var r8e=Yr(n8e(),1),i8e=Yr(CI(),1);var s8e=i=>{let e=(0,r8e.default)(i),t=(0,i8e.default)(i),n=new e(i).sync,r=xJe(n);for(let s of r)if(s.startsWith("set")&&s!=="setColumn"){let a=n[s].bind(n);n[s]=(...o)=>{let l=o[0];l.x!==void 0&&!n.getColumnAt(l)&&n.setColumn(Math.floor(l.x/16),Math.floor(l.z/16),new t(void 0)),a(...o)}}return n};function xJe(i){let e=new Set,t=i;do for(let n of Object.getOwnPropertyNames(t))typeof i[n]=="function"&&n!=="constructor"&&e.add(n);while(t=Object.getPrototypeOf(t));return[...e]}h();p();m();var a8e={paused:!1,showChunkBorders:!1,enableDebugOverlay:!1,debugWasmPerf:!1,debugModelVariant:void 0,futuristicReveal:!1,wasmMesher:!0,shaderCubeBlocks:!1,shaderCubeDebugMode:0,mesherWorkers:1,addChunksBatchWaitTime:200,_experimentalSmoothChunkLoading:!0,_renderByChunks:!1,autoLowerRenderDistance:!1,disableMesherConversionCache:!1,dedicatedChangeWorker:!1,shadingTheme:"high-contrast",cardinalLight:"default",dayCycle:!0,smoothLighting:!0,enableLighting:!0,starfield:!0,defaultSkybox:!0,renderEntities:!0,extraBlockRenderers:!0,foreground:!0,fov:75,volume:1,showHand:!1,viewBobbing:!1,handRenderer:"vanilla",renderEars:!0,highlightBlockColor:"blue",fetchPlayerSkins:!0,skinTexturesProxy:void 0,vrSupport:!0,vrPageGameRendering:!0,clipWorldBelowY:void 0,isPlayground:!1,instantCameraUpdate:!1,isRaining:!1,rainColor:"rgb(118, 148, 226)",rainOpacity:.5,moduleStates:{}};var nL=()=>({reactive:_l({world:{chunksLoaded:{},heightmaps:{},allChunksLoaded:!1,mesherWork:!1,instabilityFactors:zP(),intersectMedia:null},renderer:"...",preventEscapeMenu:!1}),nonReactive:{fps:0,worstRenderTime:0,avgRenderTime:0,world:{chunksLoadedCount:0,chunksTotalNumber:0,chunksFullInfo:"-"},renderer:{timeline:{live:[],frozen:[],lastSecond:[]}}}});h();p();m();h();p();m();h();p();m();Ia();var yg=i=>[Math.floor(i.x/16),Math.floor(i.z/16)];var wJe=async(i,e,t,n=1)=>{for(let r=0;r<i.length;r+=n)e&&await new Promise(s=>setTimeout(s,e)),await t(i[r],r)},$5=new WeakMap,bg=class bg extends W0{static restoreTransferred(e,t){let n=new bg;if(!t)return n;let r=$5.get(t);if(r)r.activeWorldView=n;else{let s=({data:a})=>{let l=$5.get(t)?.activeWorldView;!l||a?.class!==bg.restorerName||a.type==="event"&&l.emit(a.eventName,...a.args)};t.addEventListener("message",s),r={activeWorldView:n,handler:s},$5.set(t,r)}return n}static clearWorkerBridgeForTest(e){let t=$5.get(e);t&&(e.removeEventListener("message",t.handler),$5.delete(e))}static getWorkerBridgeListenerCountForTest(e){return $5.has(e)?1:0}};Wn(bg,"restorerName","WorldViewWorker");var Y5=bg,M9=class extends W0{constructor(t,n,r=new kt(0,0,0)){super();this.world=t;this.viewDistance=n;this.lastPos=new kt(0,0,0).update(r)}spiralNumber=0;gotPanicLastTime=!1;panicChunksReload=()=>{};loadedChunks={};inLoading=!1;chunkReceiveTimes=[];lastChunkReceiveTime=0;lastChunkReceiveTimeAvg=0;panicTimeout;lastPos;eventListeners={};debugChunksInfo={};waitingSpiralChunksLoad={};addWaitTime=1;keepChunksDistance=0;isPlayground=!1;allowPositionUpdate=!0;prepareForTransfer(t){if(t){let n=this.emit.bind(this);this.emit=(r,...s)=>{n(r,...s),t.postMessage({class:Y5.restorerName,type:"event",eventName:r,args:e4(s)})}}return{__restorer:Y5.restorerName}}setBlockStateId(t,n){let r=this.world.setBlockStateId(t,n);if(r&&typeof r.then=="function")throw new Error("setBlockStateId returned promise (not supported)");this.emit("blockUpdate",{pos:t,stateId:n})}updateViewDistance(t){this.viewDistance=t,this.emit("renderDistance",t)}async init(t,n){console.log("WorldView init"),this.updateViewDistance(this.viewDistance),this.emit("chunkPosUpdate",{pos:t}),n?.time?.timeOfDay!==void 0&&this.emit("time",n.time.timeOfDay),n?.entity&&this.emit("playerEntity",n.entity),this.emitterGotConnected(n);let[r,s]=yg(t),a=C3(this.viewDistance).map(([o,l])=>new kt((r+o)*16,0,(s+l)*16));this.lastPos.update(t),await this._loadChunks(a,t)}chunkProgress(){if(this.panicTimeout&&clearTimeout(this.panicTimeout),this.chunkReceiveTimes.length>=5){let t=this.chunkReceiveTimes.reduce((r,s)=>r+s,0)/this.chunkReceiveTimes.length;this.lastChunkReceiveTimeAvg=t;let n=t*2+1e3;this.panicTimeout&&clearTimeout(this.panicTimeout),this.panicTimeout=setTimeout(()=>{!this.gotPanicLastTime&&this.inLoading&&(console.warn("Chunk loading seems stuck, triggering panic reload"),this.gotPanicLastTime=!0,this.panicChunksReload())},n)}}async _loadChunks(t,n){this.spiralNumber++;let{spiralNumber:r}=this;for(let a of Object.keys(this.waitingSpiralChunksLoad))this.waitingSpiralChunksLoad[a](!1),delete this.waitingSpiralChunksLoad[a];let s=!0;this.inLoading=!0,await wJe(t,this.addWaitTime,async a=>{!s||this.loadedChunks[`${a.x},${a.z}`]||(this.world.getColumnAt(a)||(s=await new Promise(o=>{this.waitingSpiralChunksLoad[`${a.x},${a.z}`]=o})),s&&(await this.loadChunk(a,void 0,`spiral ${r} from ${n.x},${n.z}`),this.chunkProgress()))}),r===this.spiralNumber&&(this.panicTimeout&&clearTimeout(this.panicTimeout),this.inLoading=!1,this.gotPanicLastTime=!1,this.chunkReceiveTimes=[],this.lastChunkReceiveTime=0)}async loadChunk(t,n=!1,r="spiral"){let[s,a]=yg(this.lastPos),o=Math.abs(s-Math.floor(t.x/16)),l=Math.abs(a-Math.floor(t.z/16));if(o<=this.viewDistance&&l<=this.viewDistance){let c=await this.world.getColumnAt(t.y!==void 0?t:new kt(t.x,0,t.z));if(c){let u=c.toJson(),d={minY:c.minY??0,worldHeight:c.worldHeight??256};this.emit("loadChunk",{x:t.x,z:t.z,chunk:u,blockEntities:c.blockEntities,worldConfig:d,isLightUpdate:n}),this.loadedChunks[`${t.x},${t.z}`]=!0,this.debugChunksInfo[`${t.x},${t.z}`]??={loads:[]},this.debugChunksInfo[`${t.x},${t.z}`].loads.push({dataLength:u.length,reason:r,time:Date.now()})}else this.isPlayground&&this.emit("markAsLoaded",{x:t.x,z:t.z})}}async reloadLoadedChunks(){let t=Object.keys(this.loadedChunks);for(let n of t){let[r,s]=n.split(",").map(Number);await this.loadChunk({x:r,z:s},!1,"mesher-reconfigure")}}unloadAllChunks(){for(let t of Object.keys(this.loadedChunks)){let[n,r]=t.split(",").map(Number);this.unloadChunk({x:n,z:r})}}unloadChunk(t){this.emit("unloadChunk",{x:t.x,z:t.z}),delete this.loadedChunks[`${t.x},${t.z}`],delete this.debugChunksInfo[`${t.x},${t.z}`]}emitterGotConnected(t){typeof globalThis.WorkerGlobalScope<"u"&&globalThis instanceof globalThis.WorkerGlobalScope||!t||this.emit("blockEntities",new Proxy({},{get(r,s,a){if(typeof s!="string")return;let[o,l,c]=s.split(",").map(Number);return t.world.getBlock(new kt(o,l,c))?.entity}}))}lastBiomeId=null;updateBiome(t){try{if(!this.world.getBiome)return;let n=this.world.getBiome(t);n!==this.lastBiomeId&&(this.lastBiomeId=n,this.emit("biomeReset"))}catch(n){console.error("error updating biome",n)}}lastPosCheck=null;async updatePosition(t,n=!1){if(!this.allowPositionUpdate)return;let r=t.floored();if(!n&&this.lastPosCheck&&this.lastPosCheck.equals(r))return;this.lastPosCheck=r,this.updateBiome(t);let[s,a]=yg(this.lastPos),[o,l]=yg(t);if(s!==o||a!==l||n){this.emit("chunkPosUpdate",{pos:t});let c=[],u=n?this.viewDistance:this.viewDistance+this.keepChunksDistance;for(let f of Object.keys(this.loadedChunks)){let[v,g]=f.split(",").map(Number),b=new kt(v,0,g),[y,_]=yg(b),x=Math.abs(o-y),w=Math.abs(l-_);(x>u||w>u)&&c.push(b)}for(let f of c)this.unloadChunk(f);let d=C3(this.viewDistance).map(([f,v])=>{let g=new kt((o+f)*16,0,(l+v)*16);if(!this.loadedChunks[`${g.x},${g.z}`])return g}).filter(f=>!!f);this.lastPos.update(t),this._loadChunks(d,t)}else this.emit("chunkPosUpdate",{pos:t}),this.lastPos.update(t)}};var xg=class{constructor(e,t,n){this.documentRenderer=e;this.options=t;this.abortSignal=n;this._scene=new Rr,this._scene.background=new We(3294568),this._camera=new fn(85,e.canvas.width/e.canvas.height,.05,1e3),this.camera.position.set(0,0,0),this.camera.rotation.set(0,0,0)}_scene;_camera;get scene(){return this._scene}get camera(){return this._camera}worldRenderer;WorldRendererClass=Yd;async init(){let e=mg,t=new lc;if(t.currentConfig={version:e,noInventoryGui:!0},await t.updateAssetsData?.({}),this.abortSignal.aborted)return;console.time("load menu background scene");let n=s8e(e),s=Si()(e),o=globalThis.mcData.blocksArray.filter(v=>{if(!v.name.includes("stained_glass"))return!1;let g=s.fromStateId(v.defaultState,0);if(g.shapes?.length!==1)return!1;let b=g.shapes[0];return b[0]===0&&b[1]===0&&b[2]===0&&b[3]===1&&b[4]===1&&b[5]===1}),l=-15,c=100,u=100;for(let v=-c;v<c;v++)for(let g=-u;g<u;g++){let b=o[Math.floor(Math.random()*o.length)];n.setBlockStateId(new kt(v,g,l),b.defaultState)}this._camera.updateProjectionMatrix(),this._camera.position.set(.5,u/2+.5,.5),this._camera.rotation.set(0,0,0);let d=new kt(...this._camera.position.toArray()),f=new M9(n,2,d);this.abortSignal.aborted||(this.worldRenderer=new this.WorldRendererClass(this.documentRenderer.renderer,this.options,{version:e,worldView:f,inWorldRenderingConfig:a8e,playerStateReactive:Y0e().reactive,rendererState:nL().reactive,nonReactiveState:nL().nonReactive,resourcesManager:t}),this.worldRenderer instanceof Yd&&(this._scene=this.worldRenderer.realScene,this._camera=this.worldRenderer.camera),f.init(d),await this.worldRenderer.waitForChunksToRender(),!this.abortSignal.aborted&&(this.setupMouseParallax(),console.timeEnd("load menu background scene")))}update(e,t){t&&Jd(this.camera,this.documentRenderer.canvas)}dispose(){this.worldRenderer?.destroy(),this.worldRenderer=void 0,this._scene.clear()}setupMouseParallax(){let e=this._camera,t=e.position.x,n=e.position.y,r;document.body.addEventListener("pointermove",s=>{if(s.pointerType!=="mouse")return;let a=.2,o=s.clientX/window.innerWidth-.5,l=-(s.clientY/window.innerHeight-.5);r?.stop(),r=new jr(e.position).to({x:t+o*a,y:n+l*a},0),r.start(),e.updateProjectionMatrix()},{signal:this.abortSignal})}};h();p();m();Lt();var wg=class{constructor(e,t,n={},r=!1){this.documentRenderer=e;this.options=t;this.mode=WP(n,r)}active;abortController=new AbortController;mode;lastFrameTime=0;get v2(){return this.active instanceof X5?this.active:void 0}get scene(){return this.active?.scene}get camera(){return this.active?.camera}async start(e={}){this.active=this.createImplementation(e),await this.active.init(),this.active.scene.background instanceof We&&this.documentRenderer.renderer.setClearColor(this.active.scene.background),this.lastFrameTime=performance.now(),this.documentRenderer.render=(t=!1)=>{let n=performance.now(),r=Math.min((n-this.lastFrameTime)/1e3,.05);this.lastFrameTime=n;let s=this.active;s&&(s.update(r,t),this.documentRenderer.renderer.render(s.scene,s.camera))}}createImplementation(e){switch(this.mode){case"v2":return new X5(this.documentRenderer,{useMinecraftTextures:e.useMinecraftTextures,initialScene:e.v2Scene,initialCamera:e.v2Camera,initialBlockGroup:e.v2BlockGroup,initialCameraSpeed:e.v2CameraSpeed,initialBlockSpeed:e.v2BlockSpeed,resourcesManager:e.resourcesManager},this.abortController.signal);case"worldBlocks":return new xg(this.documentRenderer,this.options,this.abortController.signal);default:return new pg(this.documentRenderer)}}dispose(){this.active?.dispose(),this.active=void 0,this.abortController.abort()}};h();p();m();var Kd=u0,SJe={rendererWorldPerformance:"normal",rendererMeshersCountOverride:null,starfieldRendering:!0,defaultSkybox:!0,menuBackgroundMode:Kd.mode,menuBackgroundMinecraftTextures:Kd.minecraftTextures,menuBackgroundV2Scene:Kd.v2Scene,menuBackgroundV2Camera:Kd.v2Camera,menuBackgroundV2BlockGroup:Kd.v2BlockGroup,menuBackgroundV2CameraSpeed:Kd.v2CameraSpeedPercent,menuBackgroundV2BlockSpeed:Kd.v2BlockSpeedPercent,rendererFuturisticReveal:!1,rendererPerfDebugOverlay:!1,disableBlockEntityTextures:!1,rendererMesher:"wasm",rendererShaderCubeDebugMode:"off",showChunkBorders:!1,renderEntities:!0,renderDebug:"basic",frameLimit:!1,backgroundRendering:"20fps",vanillaLook:!1,smoothLighting:!0,newVersionsLighting:!1,vrSupport:!0,vrPageGameRendering:!1,clipWorldBelowY:void 0,highlightBlockColor:"auto",loadPlayerSkins:!0,renderEars:!0,showHand:!0,viewBobbing:!0,dayCycleAndLighting:!0,keepChunksDistance:1,gpuPreference:"default",fov:75};var EJe={menuBackgroundMode:{possibleValues:[["classic","Classic"],["v2","V2"]],requiresRestart:!0},menuBackgroundMinecraftTextures:{text:"Minecraft block textures",tooltip:"Use block atlas on V2 menu cubes (loads assets on menu)"},menuBackgroundV2Scene:{possibleValues:q5.map(i=>[i,_9[i]])},menuBackgroundV2Camera:{possibleValues:G5.map(i=>[i,y9[i]])},menuBackgroundV2BlockGroup:{possibleValues:W5.map(i=>[i,b9[i]]),text:"Block pool",tooltip:"Block set for textured menu cubes (requires Minecraft textures)"},menuBackgroundV2CameraSpeed:{text:"Camera speed",tooltip:"Orbit / fly-through camera path speed. 0 freezes the path; mouse parallax still works.",min:0,max:200,unit:"%"},menuBackgroundV2BlockSpeed:{text:"Block speed",tooltip:"Floating blocks and sky rotation. Independent of camera path speed.",min:0,max:200,unit:"%"},rendererWorldPerformance:{text:"World performance",tooltip:"Background workers for chunk geometry. Recreates mesher workers and reloads chunks.",requiresChunksReload:!0,possibleValues:[["low-energy","Low Energy"],["normal","Normal"],["maximum","Maximum"]]},starfieldRendering:{text:"Starfield"},defaultSkybox:{text:"Default skybox"},rendererFuturisticReveal:{text:"Futuristic world reveal"},rendererPerfDebugOverlay:{text:"Performance debug overlay"},disableBlockEntityTextures:{text:"Disable block entity textures",tooltip:"Skips signs, banners, heads, maps, etc."},rendererMesher:{possibleValues:[["wasm","WASM"],["legacy-js","Legacy JS"]],text:"Mesher pipeline",tooltip:"Browser technology for processing world geometry before render. WASM is the fastest; if you see a dead tab icon, reloads, or other errors, switch to Legacy JS.",requiresChunksReload:!0},rendererShaderCubeDebugMode:{text:"Shader cube debug",tooltip:"Instanced cube path visualization (requires shader cubes enabled).",possibleValues:[["off","Off"],["holes","Hole test (red)"],["texIndex","Tile index colors"],["faces","Face id colors"],["atlasAlpha","Atlas alpha"]]},showChunkBorders:{text:"Chunk borders"},renderEntities:{text:"Render entities"},renderDebug:{possibleValues:["advanced","basic","none"]},frameLimit:{text:"Frame limit",tooltip:"false = VSync / unlimited when focused"},backgroundRendering:{text:"Background FPS limit",possibleValues:[["full","NO"],["5fps","5 FPS"],["20fps","20 FPS"]]},vanillaLook:{text:"Vanilla shading",tooltip:"On: Minecraft-style face shading. Off: higher-contrast client shading."},smoothLighting:{},newVersionsLighting:{text:"Lighting in newer versions"},vrSupport:{text:"VR support",tooltip:"Shows VR entry; does not force VR on."},vrPageGameRendering:{text:"VR page game rendering"},clipWorldBelowY:{text:"Clip world below Y"},highlightBlockColor:{possibleValues:[["auto","Auto"],["blue","Blue"],["classic","Classic"]]},loadPlayerSkins:{},renderEars:{tooltip:"Deadmau5 ears when the skin texture includes them"},showHand:{},viewBobbing:{},dayCycleAndLighting:{text:"Day cycle"},keepChunksDistance:{text:"Keep chunks distance",tooltip:"Extra distance before unloading chunks",max:5,unit:""},fov:{min:30,max:110,unit:"\xB0",text:"FOV"},gpuPreference:{text:"GPU preference",tooltip:"WebGL power preference. Requires reload / backend restart to apply.",requiresRestart:!0,possibleValues:[["default","Auto"],["high-performance","Dedicated"],["low-power","Low power"]]}};Ht.enabled=!1;globalThis.THREE=Gt;var o8e=i=>({updateMap:i.entities.updateMap.bind(i.entities),updateCustomBlock:i.updateCustomBlock.bind(i),getBlockInfo:i.getBlockInfo.bind(i),playEntityAnimation:i.entities.playAnimation.bind(i.entities),damageEntity:i.entities.handleDamageEvent.bind(i.entities),updatePlayerSkin:i.entities.updatePlayerSkin.bind(i.entities),applyTemporaryPlayerSkinOverride:i.entities.applyTemporaryPlayerSkinOverride.bind(i.entities),changeHandSwingingState:i.changeHandSwingingState.bind(i),getHighestBlocks:i.getHighestBlocks.bind(i),reloadWorld:i.reloadWorld.bind(i),updateEntityModel:i.entities.updateEntityModel.bind(i.entities),playEntityModelAnimation:i.entities.playEntityModelAnimation.bind(i.entities),addMedia:i.media.addMedia.bind(i.media),destroyMedia:i.media.destroyMedia.bind(i.media),setControlMode:i.media.setControlMode.bind(i.media),setVideoPlaying:i.media.setVideoPlaying.bind(i.media),setVideoSeeking:i.media.setVideoSeeking.bind(i.media),setVideoVolume:i.media.setVideoVolume.bind(i.media),setVideoSpeed:i.media.setVideoSpeed.bind(i.media),handleUserClick:i.media.handleUserClick.bind(i.media),addSectionAnimation(e,t){i.sectionsOffsetsAnimations[e]=t},removeSectionAnimation(e){delete i.sectionsOffsetsAnimations[e]},shakeFromDamage:i.cameraShake.shakeFromDamage.bind(i.cameraShake),onPageInteraction:i.media.onPageInteraction.bind(i.media),downloadMesherLog:i.downloadMesherLog.bind(i),explodeFirework:i.fireworksLegacy.explode.bind(i.fireworksLegacy),explodeFireworkFacingCamera:i.fireworksLegacy.explodeFacingCamera.bind(i.fireworksLegacy),addWaypoint:i.waypoints.addWaypoint.bind(i.waypoints),removeWaypoint:i.waypoints.removeWaypoint.bind(i.waypoints),startCinimaticScript:i.cinimaticScript.startScript.bind(i.cinimaticScript),stopCinimaticScript:i.cinimaticScript.stopScript.bind(i.cinimaticScript),launchFirework:i.fireworks.launchFirework.bind(i.fireworks),setSkyboxImage:i.skyboxRenderer.setSkyboxImage.bind(i.skyboxRenderer),setRain:i.setRain.bind(i),spawnBlockBreakParticles(e,t,n,r,s,a){i.getModule("blockBreakParticles")?.spawnBlockBreakParticles(e,t,n,r,s,a)},spawnBlockCrackParticle(e,t,n,r,s,a,o){i.getModule("blockBreakParticles")?.spawnCrackParticle(e,t,n,r,s,a,o)},async loadGeometryExport(e){let{applyWorldGeometryExport:t}=await Promise.resolve().then(()=>(AP(),j_e));return t(i,e)},feedChunkPacket(e){let{kind:t,...n}=e,r={type:t,...n};for(let s of i.workers)s.postMessage(r)},getChunksDebugState(){let e={};for(let t of Object.keys(i.sectionObjects)){let[n,,r]=t.split(",").map(Number);e[`${n},${r}`]=!0}return{loadedSectionsChunks:e,loadedChunks:{...i.loadedChunks},finishedChunks:{...i.finishedChunks}}}}),MJe=[],A9=(i,...e)=>{for(let t of Object.values(globalThis.loadedMods??{}))try{t.threeJsBackendModule?.[i]?.(...e)}catch(n){let r=`[mod three.js] Error calling ${i} on ${t.name}: ${n}`;throw new Error(r)}},l8e=()=>{let i,e=null,t=null,n=null,r=null,s=(u,d)=>{u.hello&&console.log("Thanks for using minecraft-renderer project: one of the most performant Minecraft world renderers for the web!"),Ln?i=u2(u,MJe,globalThis):i=u,e=new Q_(i,d?.canvas),globalThis.renderer=e.renderer,globalThis.documentRenderer=e,globalThis.threeJsBackend=c,A9("default",c)},a=async u=>{if(!e)throw new Error("Document renderer not initialized");n&&(n.destroy(),n=null,r=null,globalThis.world=void 0,globalThis.frameTimingCollector=void 0),t&&(t.dispose(),t=null);let d={...i.config.menuBackground,...u};t=new wg(e,{...i},d,!!process.env.SINGLE_FILE_BUILD_MODE),A9("menuBackgroundCreated",t),await t.start(d),A9("menuBackgroundReady",t)},o=async u=>{if(!e)throw new Error("Document renderer not initialized");t&&(t.dispose(),t=null),n&&(n.destroy(),n=null,r=null,globalThis.world=void 0,globalThis.frameTimingCollector=void 0);let f=Ln?u2(u,[lc,Y5],globalThis):u;e.nonReactiveState=f.nonReactiveState,globalThis.resourcesManager=f.resourcesManager,n=new Yd(e.renderer,i,f),await n.worldReadyPromise,r=f.inWorldRenderingConfig.enableDebugOverlay?new n4(f.nonReactiveState):null,globalThis.frameTimingCollector=r;let v=e.render;e.render=function(g){v.call(this,g),r?.markFrameStart(),f.inWorldRenderingConfig.paused||n?.render(g),r?.markFrameEnd(),r?.markFrameDisplay()},e.inWorldRenderingConfig=f.inWorldRenderingConfig,globalThis.world=n,A9("worldReady",n)},l=()=>{t&&(t.dispose(),t=null),e&&e.dispose(),n&&(n.destroy(),n=null)},c={id:"threejs",displayName:`three.js ${Ma}`,startMenuBackground:a,startWorld:o,disconnect:l,setRendering(u){e.setPaused(!u),n&&(n.renderingActive=u)},getMenuBackground:()=>t??void 0,getDebugOverlay:()=>({get entitiesString(){return n?.entities.getDebugString()},get left(){return{"Geo Memory":n?.chunkMeshManager.getEstimatedMemoryUsage().total??"-"}}}),updateCamera(u,d,f){r?.markCameraUpdate(!u),n?.setFirstPersonCamera(u,d,f)},get soundSystem(){return n?.soundSystem},get backendMethods(){if(n)return o8e(n)}};return{main:{init:s,backend:c},workerProxy(){return SN({init(u,d){s(u,{canvas:d})},updateSizeExternal(u,d,f){e?.updateSizeExternal(u,d,f)},startMenuBackground:a,startWorld:o,disconnect:l,setRendering:c.setRendering,updateCamera(u,d,f){let v=u?new kt(u.x,u.y,u.z):null;r?.markCameraUpdate(!v),c.updateCamera(v,d,f)},async callBackendMethod(u,...d){if(!n)throw new Error("World renderer not initialized");let v=o8e(n)[u];if(!v)throw new Error(`Backend method ${String(u)} is unavailable`);return v(...d)}})}}};globalThis.structuredClone??=i=>JSON.parse(JSON.stringify(i));var c8e=i=>{TB(i);let e=globalThis;e.mcData=i,e.loadedData=i,self.postMessage({type:"mcDataApplied"})};self.addEventListener("message",i=>{let e=i.data;if(e.type==="mcData"){c8e(e.mcData),console.log("data loaded");return}Array.isArray(e)&&e.forEach(t=>{t.type==="mcData"&&c8e(t.mcData)})});var AJe=l8e();AJe.workerProxy();})();
29579
+ }`})}},VP=class{constructor(e){this.worldRenderer=e}points;timer=new Hs;enabled=!1;currentTime;enable(){this.enabled||(this.enabled=!0,this.updateVisibility())}disable(){this.enabled&&(this.enabled=!1,this.removeStars())}toggle(){return this.enabled?this.disable():this.enable(),this.enabled}enablementCheck=()=>this.currentTime?this.currentTime>13500&&this.currentTime<23e3:!1;render=()=>{if(!this.points)return;this.points.position.set(0,0,0);let e=this.points.material;this.timer.update(performance.now()),e.uniforms.time.value=this.timer.getElapsed()*.2};updateTimeOfDay(e){this.currentTime=e,this.enabled&&this.updateVisibility()}updateVisibility(){if(!this.enabled)return;let e=this.enablementCheck?.()??!1;e&&!this.points?this.createStars():!e&&this.points&&this.removeStars()}createStars(){if(this.points)return;let e=80,t=50,n=7e3,r=7,s=10,a=new dt,o=b=>new X().setFromSpherical(new Jf(b,Math.acos(1-Math.random()*2),Math.random()*2*Math.PI)),l=[],c=[],u=Array.from({length:n},()=>(.5+.5*Math.random())*r),d=new We,f=e+t,v=t/n;for(let b=0;b<n;b++)f-=v*Math.random(),l.push(...o(f).toArray()),d.setHSL(b/n,s,.9),c.push(d.r,d.g,d.b);a.setAttribute("position",new Je(l,3)),a.setAttribute("color",new Je(c,3)),a.setAttribute("size",new Je(u,1));let g=new FP;g.blending=es,g.depthTest=!0,g.depthWrite=!1,g.transparent=!0,this.points=new gr(a,g),this.points.renderOrder=-1,this.worldRenderer.scene.add(this.points)}dispose(){this.removeStars()}removeStars(){this.points&&(this.points.geometry.dispose(),this.points.material.dispose(),this.worldRenderer.scene.remove(this.points),this.points=void 0)}},z4e={id:"starfield",controller:VP,enabledDefault:!0,cannotBeDisabled:!0};var H4e={starfield:z4e,futuristicReveal:V4e,rain:O4e,cameraBobbing:P4e,blockBreakParticles:C4e};h();p();m();h();p();m();var zP=()=>({longRenderTime:!1,constantLongRenderTime:!1,tooManyEntities:!1,tooManyTextures:!1,unknownReason:!1});h();p();m();h();p();m();var hg=class{constructor(e){this.factors=e}renderTimeHistory=[];onFrame(e){this.pushRenderTime(e.totalMs),this.recompute(e)}pushRenderTime(e){this.renderTimeHistory.push(e),this.renderTimeHistory.length>24&&this.renderTimeHistory.shift()}recompute(e){let t=e.fps>0&&e.fps<=45,n=Math.max(0,e.totalMs-e.entitiesMs),r=e.totalMs>=30,s=this.renderTimeHistory.length,a=this.renderTimeHistory.filter(f=>f>=30).length,o=s>=8&&a/s>=.65,l=e.loadedTextureCount>=100,c=t&&e.entitiesMs>=8&&n<=20,d=t&&!(r||o||c||l);this.factors.longRenderTime=r,this.factors.constantLongRenderTime=o,this.factors.tooManyEntities=c,this.factors.tooManyTextures=l,this.factors.unknownReason=d}reset(){this.renderTimeHistory.length=0,this.factors.longRenderTime=!1,this.factors.constantLongRenderTime=!1,this.factors.tooManyEntities=!1,this.factors.tooManyTextures=!1,this.factors.unknownReason=!1}};h();p();m();var lJe=[{key:"longRenderTime",code:"LR"},{key:"constantLongRenderTime",code:"CLR"},{key:"tooManyEntities",code:"ENT"},{key:"tooManyTextures",code:"TEX"},{key:"unknownReason",code:"UNK"}];function qP(i){let e=lJe.filter(({key:t})=>i[t]).map(({code:t})=>t);return e.length>0?e.join("+"):""}var ia=class ia extends Ry{constructor(t,n,r){if(!r.resourcesManager)throw new Error("resourcesManager is required in displayOptions");super(r.resourcesManager,r,n);this.renderer=t;this.initOptions=n;this.displayOptions=r;this.performanceMonitor=new hg(this.reactiveState.world.instabilityFactors),this.renderer=t;let s=ia.getRendererInfo(t)??"...";r.rendererState.renderer=s,this.chunkMeshManager=new fg(this,this.scene,this.material,this.worldSizeParams.worldHeight,this.viewDistance),this.onRenderDistanceChanged=a=>{this.chunkMeshManager.updateViewDistance(a)},typeof window<"u"&&(window.setBlockLightmap=a=>{this.chunkMeshManager.setBlockLightmapParams(a)}),this.syncSkyLevelFromTime(this.timeOfTheDay),this.cursorBlock=new Bb(this),this.holdingBlock=sg(this),this.holdingBlockLeft=sg(this,!0);for(let a of Object.values(H4e))this.registerModule(a);this.skyboxRenderer=new qb(this.realScene,!1,null),this.skyboxRenderer.init(),this.addDebugOverlay(),this.resetScene(),this.init(),this.soundSystem=new Ob(this),this.cameraShake=new Nb(this,this.onRender),this.media=new Ub(this),this.fireworksLegacy=new zb(this),this.waypoints=new Vb(this),this.cinimaticScript=new Hb(this,(a,o,l)=>this.setCinimaticCamera(a,o,l),a=>this.setCinimaticFov(a),()=>({position:new kt(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),yaw:this.cameraShake.getBaseRotation().yaw,pitch:this.cameraShake.getBaseRotation().pitch,fov:this.camera.fov})),this.fireworks=new Gb(this.realScene,this.sceneOrigin),this.renderUpdateEmitter.on("chunkFinished",a=>{this.finishChunk(a)}),this.worldSwitchActions(),this.initializeModules()}outputFormat="threeJs";isShaderCubeBlocksEnabled(){return this.worldRendererConfig.shaderCubeBlocks===!0&&!!this.renderer?.capabilities?.isWebGL2}chunkMeshManager;get sectionObjects(){return this.chunkMeshManager.sectionObjects}cameraSectionPos=new kt(0,0,0);holdingBlock;holdingBlockLeft;scene=new Rr;get realScene(){return this.scene}ambientLight=new wa(13421772,ia.LEGACY_TO_PHYSICAL_LIGHT);directionalLight=new Ss(16777215,.5*ia.LEGACY_TO_PHYSICAL_LIGHT);entities=new Lb(this,globalThis.mcData);performanceMonitor;cameraGroupVr;material=new _t({vertexColors:!0,transparent:!0,alphaTest:.1});itemsTexture;cursorBlock;onRender=[];lastRenderTime=0;lastSciFiTickMs=0;animatedFov=0;lastFovAnimTime=0;cameraShake;cameraContainer;media;get waitingChunksToDisplay(){return this.chunkMeshManager.waitingChunksToDisplay}waypoints;cinimaticScript;camera;renderTimeAvg=0;pendingSectionUpdates=new Map;pendingSectionBufferStartTimes=new Map;get estimatedMemoryUsage(){return this.chunkMeshManager.getEstimatedMemoryUsage().total}modules={};sectionsOffsetsAnimations={};fountains=[];fireworksLegacy;DEBUG_RAYCAST=!1;skyboxRenderer;fireworks;sceneOrigin=new Wb(this.scene);cameraWorldPos={x:0,y:0,z:0};_cameraPositionAccessWarned=!1;_tmpCameraPos=new X;currentPosTween;currentRotTween;_tpDirection=new X;_tpPitchQuat=new qt;_tpYawQuat=new qt;_tpFinalQuat=new qt;_tpScenePos=new X;_tpAxisX=new X(1,0,0);_tpAxisY=new X(0,1,0);_tpChunkWorldPos=new X;get tilesRendered(){return this.chunkMeshManager.getTotalTiles()}get blocksRendered(){return this.chunkMeshManager.getTotalBlocks()}registerModule(t){if(t.id in this.modules){console.warn(`Module ${t.id} is already registered`);return}let n=new t.controller(this),r={manifest:t,controller:n,enabled:!1,toggle:()=>this.toggleModule(t.id)};this.modules[t.id]=r,t.enabledDefault&&this.toggleModule(t.id,!0)}enableModule(t){let n=this.modules[t];if(!n){console.warn(`Module ${t} not found`);return}n.enabled||(n.enabled=!0,n.controller.enable(),n.controller.render&&this.onRender.push(n.controller.render))}disableModule(t){let n=this.modules[t];if(!n){console.warn(`Module ${t} not found`);return}if(n.manifest.cannotBeDisabled){console.warn(`Module ${t} cannot be disabled`);return}if(n.enabled&&(n.enabled=!1,n.controller.disable(),n.controller.render)){let r=this.onRender.indexOf(n.controller.render);r>-1&&this.onRender.splice(r,1)}}toggleModule(t,n){let r=this.modules[t];if(!r)return console.warn(`Module ${t} not found`),!1;let s=n!==void 0?n:!r.enabled;if(s===r.enabled)return r.enabled;if(!s&&r.manifest.cannotBeDisabled)return console.warn(`Module ${t} cannot be disabled`),!0;if(r.enabled=s,s)r.controller.enable(),r.controller.render&&!this.onRender.includes(r.controller.render)&&this.onRender.push(r.controller.render);else if(r.controller.disable(),r.controller.render){let a=this.onRender.indexOf(r.controller.render);a>-1&&this.onRender.splice(a,1)}return s}setRain(t){this.worldRendererConfig.isRaining=t,this.toggleModule("rain",t)}disposeModules(){for(let t of Object.values(this.modules))t.controller.dispose();this.modules={}}initializeModules(){this.updateModulesFromConfig()}getModule(t){return this.modules[t]?.controller}anyModuleRequiresHeightmap(){return Object.values(this.modules).some(t=>t.enabled&&t.manifest.requiresHeightmap)}get cameraObject(){return this.cameraGroupVr??this.cameraContainer}_wrapCameraPositionWithWarning(){let t=this.camera.position,n=this,r=20,s=(l,c,u)=>Math.abs(l)>r||Math.abs(c)>r||Math.abs(u)>r,a=()=>{!n._cameraPositionAccessWarned&&typeof process<"u"},o=new Proxy(t,{set(l,c,u){return(c==="x"||c==="y"||c==="z")&&typeof u=="number"&&Math.abs(u)>r&&a(),l[c]=u,!0},get(l,c,u){let d=l[c];return c==="set"?function(f,v,g){return s(f,v,g)&&a(),l.set(f,v,g)}:c==="setX"||c==="setY"||c==="setZ"?function(f){return Math.abs(f)>r&&a(),l[c](f)}:c==="copy"?function(f){return s(f.x,f.y,f.z)&&a(),l.copy(f)}:typeof d=="function"?d.bind(l):d}});Object.defineProperty(this.camera,"position",{value:o,configurable:!0,enumerable:!0})}worldSwitchActions(){this.onWorldSwitched.push(()=>{this.getModule("futuristicReveal")?.onWorldSwitched?.(),this.protocolCustomBlocks.clear(),this.sectionsOffsetsAnimations={},this.waypoints.clear(),this.cinimaticScript.stopScript(),this.fireworks.clear(),this.syncSkyLevelFromTime(this.timeOfTheDay)})}downloadWorldGeometry(){MP(this,new X(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),this.cameraShake.getBaseRotation(),"world-geometry.json")}updateEntity(t,n=!1){let r={rotation:{head:{x:t.headPitch??t.pitch,y:t.headYaw,z:0}}};n?this.entities.updateEntityPosition(t,!1,r):this.entities.update(t,r)}updatePlayerEntity(t){this.entities.handlePlayerEntity(t)}resetScene(){this.sceneOrigin.update(0,0,0),this.cameraWorldPos.x=0,this.cameraWorldPos.y=0,this.cameraWorldPos.z=0,this.scene.matrixAutoUpdate=!1,this.scene.background=new We(this.initOptions.config.sceneBackground),this.scene.add(this.ambientLight),this.directionalLight.position.set(1,1,.5).normalize(),this.directionalLight.castShadow=!0,this.scene.add(this.directionalLight);let t=this.renderer.getSize(new ze);this.camera=new fn(75,t.x/t.y,.1,1e3),this._wrapCameraPositionWithWarning(),this.cameraContainer=new Ut,this.cameraContainer.add(this.camera),this.scene.add(this.cameraContainer)}watchReactivePlayerState(){super.watchReactivePlayerState(),this.onReactivePlayerStateUpdated("inWater",t=>{this.skyboxRenderer.updateWaterState(t,this.playerStateReactive.waterBreathing)}),this.onReactivePlayerStateUpdated("waterBreathing",t=>{this.skyboxRenderer.updateWaterState(this.playerStateReactive.inWater,t)}),this.onReactivePlayerStateUpdated("ambientLight",t=>{t&&(this.ambientLight.intensity=t*ia.LEGACY_TO_PHYSICAL_LIGHT)}),this.onReactivePlayerStateUpdated("directionalLight",t=>{t&&(this.directionalLight.intensity=t*ia.LEGACY_TO_PHYSICAL_LIGHT)}),this.onReactivePlayerStateUpdated("lookingAtBlock",t=>{this.cursorBlock.setHighlightCursorBlock(t?new kt(t.x,t.y,t.z):null,t?.shapes)}),this.onReactivePlayerStateUpdated("diggingBlock",t=>{this.cursorBlock.updateBreakAnimation(t?{x:t.x,y:t.y,z:t.z}:void 0,t?.stage??null,t?.mergedShape)}),this.onReactivePlayerStateUpdated("perspective",t=>{let n=new kt(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z);this.updateCamera(n,this.cameraShake.getBaseRotation().yaw,this.cameraShake.getBaseRotation().pitch)})}watchReactiveConfig(){super.watchReactiveConfig(),this.onReactiveConfigUpdated("showChunkBorders",r=>{this.updateShowChunksBorder(r)}),this.onReactiveConfigUpdated("defaultSkybox",r=>{this.skyboxRenderer.updateDefaultSkybox(r)}),this.onReactiveConfigUpdated("shaderCubeDebugMode",()=>{this.chunkMeshManager.syncCubeShaderUniforms(),this.chunkMeshManager.syncLegacyShaderUniforms()});let t=()=>{let r=this.worldRendererConfig;this.chunkMeshManager.setShadingTheme(r.shadingTheme,r.cardinalLight)};this.onReactiveConfigUpdated("shadingTheme",t),this.onReactiveConfigUpdated("cardinalLight",t),this.onReactiveConfigUpdated("futuristicReveal",()=>{this.updateModulesFromConfig()});let n=this.displayOptions.inWorldRenderingConfig.handRenderer;this.onReactiveConfigUpdated("handRenderer",r=>{if(r===n)return;n=r;let s=this.holdingBlock.ready,a=this.holdingBlockLeft.ready;this.holdingBlock.dispose(),this.holdingBlockLeft.dispose(),this.holdingBlock=sg(this),this.holdingBlockLeft=sg(this,!0),s&&(this.holdingBlock.ready=!0,this.holdingBlock.updateItem()),a&&(this.holdingBlockLeft.ready=!0,this.holdingBlockLeft.updateItem())}),this.onReactiveConfigUpdated("*",()=>{this.updateModulesFromConfig()}),this.updateModulesFromConfig()}updateModulesFromConfig(){let{moduleStates:t}=this.worldRendererConfig;for(let[n,r]of Object.entries(this.modules)){let s=t[n];if(s==="enabled"){r.enabled||this.toggleModule(n,!0);continue}if(s==="disabled"){r.enabled&&!r.manifest.cannotBeDisabled&&this.toggleModule(n,!1);continue}if(s==="auto"||s===void 0)if(r.controller.autoEnableCheck){let a=r.controller.autoEnableCheck();a&&!r.enabled?this.toggleModule(n,!0):!a&&r.enabled&&!r.manifest.cannotBeDisabled&&this.toggleModule(n,!1)}else{let a=r.manifest.enabledDefault??!1;a&&!r.enabled?this.toggleModule(n,!0):!a&&r.enabled&&!r.manifest.cannotBeDisabled&&this.toggleModule(n,!1)}}}changeHandSwingingState(t,n=!1){let r=n?this.holdingBlockLeft:this.holdingBlock;t?r.startSwing():r.stopSwing()}async updateAssetsData(){let t=this.resourcesManager.currentResources,n=this.material.map,r=this.itemsTexture,s=cc(t.blocksAtlasImage);s.needsUpdate=!0,s.flipY=!1,this.material.map=s,this.chunkMeshManager.syncCubeShaderUniforms(),this.chunkMeshManager.syncLegacyShaderUniforms();let a=cc(t.itemsAtlasImage);a.needsUpdate=!0,a.flipY=!1,this.itemsTexture=a,n&&n.dispose(),r&&r.dispose(),await super.updateAssetsData(),this.onAllTexturesLoaded(),Object.keys(this.loadedChunks).length>0&&(console.log("rerendering chunks because of texture update"),this.rerenderAllChunks())}onAllTexturesLoaded(){this.holdingBlock.ready=!0,this.holdingBlock.updateItem(),this.holdingBlockLeft.ready=!0,this.holdingBlockLeft.updateItem()}changeBackgroundColor(t){this.realScene.background=new We(t[0],t[1],t[2])}changeCardinalLight(t){this.worldRendererConfig.cardinalLight=t}timeUpdated(t){let n=this.getModule("starfield");n?.updateTimeOfDay&&n.updateTimeOfDay(t),this.skyboxRenderer.updateTime(t),this.syncSkyLevelFromTime(t)}syncSkyLevelFromTime(t){let n=Ml(t)/15;this.chunkMeshManager.setSkyLevel(n)}onDayCycleSkyLightChanged(t){}biomeUpdated(t){t?.temperature!==void 0&&this.skyboxRenderer.updateTemperature(t.temperature)}biomeReset(){this.skyboxRenderer.updateTemperature(vP)}getItemRenderData(t,n){return k_e(t,n,this.resourcesManager,this.playerStateReactive)}async demoModel(){let t=cursorBlockRel(0,1,0).position,n=await Pv();Sve(n,t);let r=new Ea(n,16776960);n.add(r),this.realScene.add(n)}demoItem(){let t=cursorBlockRel(0,1,0).position,{mesh:n}=this.entities.getItemMesh({itemId:541},{});n.position.set(t.x+.5,t.y+.5,t.z+.5);let r=new Ea(n,16776960);n.add(r),this.realScene.add(n)}debugOverlayAdded=!1;addDebugOverlay(){if(this.debugOverlayAdded)return;this.debugOverlayAdded=!0;let t=i4("debug-overlay",80,0,void 0,{className:r4});setInterval(()=>{if(t.setVisibility(this.displayAdvancedStats),this.displayAdvancedStats){let n=c=>new Intl.NumberFormat("en-US",{}).format(c),r=c=>new Intl.NumberFormat("en-US",{notation:"compact",maximumFractionDigits:1}).format(c),s="";s+=`TE: ${n(this.renderer.info.memory.textures)} `;let a=this.chunkMeshManager.getGlobalBufferStats();if(a.shaderFaces){let c=a.shaderFaces;s+=`CUBE: ${r(c.used)}/${r(c.capacity)}f `}if(a.legacyOpaque){let c=a.legacyOpaque;s+=`LEG-O: ${r(c.used)}/${r(c.capacity)}q `}if(a.legacyBlend){let c=a.legacyBlend;s+=`LEG-B: ${r(c.used)}/${r(c.capacity)}q `}s+=`MEM: ${this.chunkMeshManager.getEstimatedMemoryUsage().total} `;let o=this.cameraCollisionBlockCache.getAllocatedBytes();o>0&&(s+=`CAM: ${r(o)}b `);let l=qP(this.reactiveState.world.instabilityFactors);l&&(s+=`PF: ${l} `),t.updateText(s),this.backendInfoReport=s}},200)}updatePosDataChunk(t){let n=this.sectionObjects[t];if(!n)return;let[r,s,a]=t.split(",").map(u=>Math.floor(+u/16)),l=500-(Math.abs(r-this.cameraSectionPos.x)+Math.abs(s-this.cameraSectionPos.y)+Math.abs(a-this.cameraSectionPos.z)),c=n.mesh??n.shaderMesh??n.children.find(u=>u.name==="mesh"||u.name==="shaderMesh");c&&(c.renderOrder=l)}cameraSectionPositionUpdate(){for(let t in this.sectionObjects)this.sectionObjects[t]&&this.updatePosDataChunk(t)}getDir(t,n){return t===n?0:t<n?1:-1}finishChunk(t){this.chunkMeshManager.finishChunkDisplay(t),this.getModule("futuristicReveal")?.onChunkFinished?.()}applyPendingSectionUpdates(){if(this.pendingSectionUpdates.size===0)return;let t=performance.now(),n=this.getSectionHeight(),r=[];for(let s of this.pendingSectionUpdates.keys()){let a=this.pendingSectionBufferStartTimes.get(s)??t;if(t-a<ia.MAX_SECTION_UPDATE_BUFFER_MS){let[l,c,u]=s.split(",").map(Number),d=[`${l-16},${c},${u}`,`${l+16},${c},${u}`,`${l},${c-n},${u}`,`${l},${c+n},${u}`,`${l},${c},${u-16}`,`${l},${c},${u+16}`],f=!1;for(let v of d)if(this.sectionsWaiting.has(v)&&!this.pendingSectionUpdates.has(v)&&this.sectionObjects[v]){f=!0;break}if(f)continue}r.push(s)}if(r.length!==0)for(let s of r){let a=this.pendingSectionUpdates.get(s);this.pendingSectionUpdates.delete(s),this.pendingSectionBufferStartTimes.delete(s);let o=a.key.split(","),l=`${o[0]},${o[2]}`;if(!this.loadedChunks[l]||!this.active){this.chunkMeshManager.releaseSection(a.key);continue}if(!this.chunkMeshManager.sectionHasRenderableContent(a.geometry)){this.chunkMeshManager.releaseSection(a.key);continue}let c=this.chunkMeshManager.updateSection(a.key,a.geometry);this.updatePosDataChunk(a.key),c&&this.getModule("futuristicReveal")?.onSectionMeshed?.(a.key,a.geometry,c)}}clearPendingSectionUpdatesForChunk(t,n){for(let r of[...this.pendingSectionUpdates.keys()])r.startsWith(`${t},`)&&r.endsWith(`,${n}`)&&(this.pendingSectionUpdates.delete(r),this.pendingSectionBufferStartTimes.delete(r))}handleWorkerMessage(t){if(t.type==="geometry"){let n=t.key.split(","),r=`${n[0]},${n[2]}`;if(!this.loadedChunks[r]||!this.active){this.pendingSectionUpdates.delete(t.key),this.pendingSectionBufferStartTimes.delete(t.key);return}if(this.sectionObjects[t.key]){this.pendingSectionUpdates.set(t.key,t),this.pendingSectionBufferStartTimes.has(t.key)||this.pendingSectionBufferStartTimes.set(t.key,performance.now());return}if(!this.chunkMeshManager.sectionHasRenderableContent(t.geometry)){this.chunkMeshManager.releaseSection(t.key);return}let s=this.chunkMeshManager.updateSection(t.key,t.geometry);this.updatePosDataChunk(t.key),s&&this.getModule("futuristicReveal")?.onSectionMeshed?.(t.key,t.geometry,s)}}getCameraPosition(t){return(t??this._tmpCameraPos).set(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z)}getSectionCameraPosition(){let t=this.getCameraPosition();return new kt(Math.floor(t.x/16),Math.floor(t.y/16),Math.floor(t.z/16))}updateCameraSectionPos(){let t=this.getSectionCameraPosition();this.cameraSectionPos.equals(t)||(this.cameraSectionPos=t,this.cameraSectionPositionUpdate())}setFirstPersonCamera(t,n,r){let s=this.playerStateReactive.eyeHeight;this.updateCamera(t?.offset(0,s,0)??null,n,r),this.updateCameraSectionPos()}getThirdPersonCamera(t,n,r){t??=new X(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z);let s=this.playerStateReactive.perspective==="third_person_back",a=4,o=this._tpDirection.set(0,0,-1),l=this._tpPitchQuat.setFromAxisAngle(this._tpAxisX,r),c=this._tpYawQuat.setFromAxisAngle(this._tpAxisY,n),u=this._tpFinalQuat.multiplyQuaternions(c,l);o.applyQuaternion(u),s&&o.multiplyScalar(-1),this.DEBUG_RAYCAST&&this.debugRaycast(t,o,a);let d=.25,f=.05,v=.4,g=this.cameraCollisionBlockCache,b=k4e(t.x,t.y,t.z,o.x,o.y,o.z,a,d,f,(_,x,w)=>g.isSolidBlock(_,x,w)),y=a;return b!==void 0&&(y=Math.min(y,b.distance)),y<v&&(y=v),new kt(t.x+o.x*y,t.y+o.y*y,t.z+o.z*y)}debugRaycastHelper;debugHitPoint;debugRaycast(t,n,r){this.debugRaycastHelper&&(this.realScene.remove(this.debugRaycastHelper),this.debugRaycastHelper=void 0),this.debugHitPoint&&(this.realScene.remove(this.debugHitPoint),this.debugHitPoint=void 0);let s=new X(this.sceneOrigin.toSceneX(t.x),this.sceneOrigin.toSceneY(t.y),this.sceneOrigin.toSceneZ(t.z));this.debugRaycastHelper=new F0(n.clone().normalize(),s,r,16711680,r*.1,r*.05),this.realScene.add(this.debugRaycastHelper);let a=new xs(.2,8,8),o=new _t({color:65280});this.debugHitPoint=new Ke(a,o),this.debugHitPoint.position.copy(s).add(n.clone().multiplyScalar(r)),this.realScene.add(this.debugHitPoint)}prevFramePerspective=null;setCinimaticCamera(t,n,r){this.cameraWorldPos.x=t.x,this.cameraWorldPos.y=t.y,this.cameraWorldPos.z=t.z,this.sceneOrigin.update(t.x,t.y,t.z),this.cameraObject.position.set(0,0,0),this.cameraShake.setBaseRotation(r,n),this.updateCameraSectionPos()}setCinimaticFov(t){this.animatedFov=t,this.camera.fov=t,this.camera.updateProjectionMatrix()}updateSmoothFov(){if(this.cinimaticScript.running)return;let t=this.displayOptions.inWorldRenderingConfig.fov,n=this.playerStateReactive.fovMultiplier,r=t*(Number.isFinite(n)?n:1),s=performance.now();if(this.animatedFov===0&&(this.animatedFov=r),Math.abs(this.animatedFov-r)>=.01){let a=s-this.lastFovAnimTime,o=Math.min(a/ia.FOV_TRANSITION_MS,1),l=c=>1-(1-c)**3;this.animatedFov+=(r-this.animatedFov)*l(o),Math.abs(this.animatedFov-r)<.01&&(this.animatedFov=r)}else this.animatedFov=r;this.lastFovAnimTime=s,this.camera.fov!==this.animatedFov&&(this.camera.fov=this.animatedFov,this.camera.updateProjectionMatrix())}updateCamera(t,n,r){if(!this.cinimaticScript.running){if(t){this.renderer.xr.isPresenting&&(t.y-=this.camera.position.y),this.currentPosTween?.stop();let s=this.displayOptions.inWorldRenderingConfig.instantCameraUpdate?0:this.playerStateUtils.isSpectatingEntity()?150:50;this.currentPosTween=new jr(this.cameraWorldPos).to({x:t.x,y:t.y,z:t.z},s).onUpdate(()=>{this.sceneOrigin.update(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),this.cameraObject.position.set(0,0,0)}).start()}if(this.playerStateUtils.isSpectatingEntity()){let s=this.cameraShake.getBaseRotation(),a=0,o=Math.PI/2;s.yaw<o&&n>Math.PI+o?a=-Math.PI*2:n<o&&s.yaw>Math.PI+o&&(a=Math.PI*2),this.currentRotTween?.stop(),this.currentRotTween=new jr(s).to({pitch:r,yaw:n+a},100).onUpdate(l=>this.cameraShake.setBaseRotation(l.pitch,l.yaw-a)).start()}else{this.currentRotTween?.stop(),this.cameraShake.setBaseRotation(r,n);let{perspective:s}=this.playerStateReactive;if(s==="third_person_back"||s==="third_person_front"){let a=new X(this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),o=this.getThirdPersonCamera(a,n,r),l=a.distanceTo(new X(o.x,o.y,o.z)),c=s==="third_person_back"?l:-l;this.camera.position.set(0,0,c),s==="third_person_front"?this.camera.rotation.set(0,Math.PI,0):this.camera.rotation.set(0,0,0)}else this.camera.position.z=0,this.camera.rotation.set(0,0,0),this.debugRaycastHelper&&(this.realScene.remove(this.debugRaycastHelper),this.debugRaycastHelper=void 0),this.debugHitPoint&&(this.realScene.remove(this.debugHitPoint),this.debugHitPoint=void 0)}this.updateCameraSectionPos()}}debugChunksVisibilityOverride(){let{chunksRenderAboveOverride:t,chunksRenderBelowOverride:n,chunksRenderDistanceOverride:r,chunksRenderAboveEnabled:s,chunksRenderBelowEnabled:a,chunksRenderDistanceEnabled:o}=this.reactiveDebugParams,l=this.getSectionHeight(),c=this.cameraSectionPos.y*l;if(this.displayOptions.inWorldRenderingConfig.enableDebugOverlay&&t!==void 0||n!==void 0||r!==void 0)for(let[u,d]of Object.entries(this.sectionObjects)){if(d._waitingForChunkDisplay)continue;let[f,v,g]=u.split(",").map(Number),b=s&&t!==void 0?v<=c+t:a&&n!==void 0?v>=c-n:o&&r!==void 0?Math.abs(v-c)<=r:!0;d.visible=b}else this.chunkMeshManager.updateSectionsVisibility()}render(t=!1){if(this.currentRenderedFrames++,this.reactiveDebugParams.stopRendering)return;this.debugChunksVisibilityOverride();let n=performance.now();this.lastRendered=performance.now();let r=this.lastRenderTime>0?Math.min(Math.max((n-this.lastRenderTime)/1e3,0),.1):1/60;this.lastRenderTime=n,this.cursorBlock.render(),this.updateSectionOffsets();let s=this.getCameraPosition();if(this.skyboxRenderer.update(s,this.viewDistance),this.updateSmoothFov(),t){let w=this.renderer.getSize(new ze);this.camera.aspect=w.width/w.height,this.camera.updateProjectionMatrix()}let a=0;if(!this.reactiveDebugParams.disableEntities){let w=performance.now();this.entities.render(),a=performance.now()-w}let o=this.cameraGroupVr instanceof bt?this.cameraGroupVr.children.find(w=>w instanceof fn):this.camera;this.applyPendingSectionUpdates();let l=performance.now(),c=l-this.lastSciFiTickMs;this.lastSciFiTickMs=l,this.getModule("futuristicReveal")?.tick?.(c,l);let u=this.cameraWorldPos.x,d=this.cameraWorldPos.y,f=this.cameraWorldPos.z;this.chunkMeshManager.maybeRebase({x:u,y:d,z:f});let v=this.chunkMeshManager.getRenderOrigin(),g=this.chunkMeshManager.globalBlockBuffer;g&&(g.setCameraOrigin(v,u,d,f),g.setDebugOverlay(this.displayOptions.inWorldRenderingConfig.enableDebugOverlay),g.compactStep(),g.hasPendingUploads()&&g.uploadDirtyRange(),g.suppressThreeDraw());let b=this.chunkMeshManager.globalLegacyBuffer;b&&(b.setDebugOverlay(this.displayOptions.inWorldRenderingConfig.enableDebugOverlay),b.compactStep(),b.hasPendingUploads()&&b.uploadDirtyRange(),b.suppressThreeDraw());let y=this.chunkMeshManager.globalLegacyBlendBuffer;y&&(y.setDebugOverlay(this.displayOptions.inWorldRenderingConfig.enableDebugOverlay),y.compactStep(),y.hasPendingUploads()&&y.uploadDirtyRange(),y.suppressThreeDraw()),this.chunkMeshManager.markCullDirtyIfBufferStateChanged(),this.chunkMeshManager.setLegacyCameraOrigin(u,d,f),this.chunkMeshManager.updateCullDirtyFromCamera(o,u,d,f),this.chunkMeshManager.cullDirty&&(this.chunkMeshManager.updateSectionCullAndSort(o,this.cameraWorldPos.x,this.cameraWorldPos.y,this.cameraWorldPos.z),this.chunkMeshManager.clearCullDirty()),this.renderer.render(this.scene,o),this.displayOptions.inWorldRenderingConfig.showHand&&this.playerStateReactive.gameMode!=="spectator"&&this.playerStateReactive.perspective==="first_person"&&!this.renderer.xr.isPresenting&&(this.holdingBlock.render(this.camera,this.renderer,this.ambientLight,this.directionalLight),this.holdingBlockLeft.render(this.camera,this.renderer,this.ambientLight,this.directionalLight));for(let w of this.fountains)this.sectionObjects[w.sectionId]&&!this.sectionObjects[w.sectionId].foutain&&(w.createParticles(this.sectionObjects[w.sectionId]),this.sectionObjects[w.sectionId].foutain=!0),w.render();this.waypoints.render(),this.fireworks.update();for(let w of this.onRender)w(r);let x=performance.now()-n;this.worldRendererConfig.autoLowerRenderDistance&&this.chunkMeshManager.recordRenderTime(x),this.renderTimeAvgCount++,this.renderTimeAvg=(this.renderTimeAvg*(this.renderTimeAvgCount-1)+x)/this.renderTimeAvgCount,this.renderTimeMax=Math.max(this.renderTimeMax,x),this.performanceMonitor.onFrame({totalMs:x,entitiesMs:a,loadedTextureCount:this.renderer.info.memory.textures,fps:this.lastFps})}renderHead(t,n,r,s){let a;if(s.SkullOwner?a=s.SkullOwner.Properties?.textures?.[0]?.Value:a=s.profile?.properties?.find(o=>o.name==="textures")?.value,!!a)try{let l=JSON.parse(Buffer.from(a,"base64").toString()).textures?.SKIN?.url,{skinTexturesProxy:c}=this.worldRendererConfig;c&&(l=l?.replace("http://textures.minecraft.net/",c).replace("https://textures.minecraft.net/",c));let u=$c(this,l,Yc.head),d=new bt;return r&&u.position.set(0,.3125,.3125),u.position.y-=23/16,d.add(u),this.sceneOrigin.track(d),d.position.set(t.x+.5,t.y+.045,t.z+.5),d.rotation.set(0,-Ot.degToRad(n*(r?90:45/2)),0),d.scale.set(.8,.8,.8),d}catch(o){console.error("Error decoding player texture:",o)}}lightUpdate(t,n){for(let r=this.worldSizeParams.minY;r<this.worldSizeParams.worldHeight;r+=16)this.setSectionDirty(new kt(t,r,n))}rerenderAllChunks(){for(let t of Object.keys(this.sectionObjects)){let[n,r,s]=t.split(",").map(Number);this.setSectionDirty(new kt(n,r,s))}}updateShowChunksBorder(t){this.chunkMeshManager.updateAllBoxHelpers(t)}resetWorld(){super.resetWorld(),this.pendingSectionUpdates.clear(),this.pendingSectionBufferStartTimes.clear(),this.chunkMeshManager.dispose(),this.chunkMeshManager=new fg(this,this.scene,this.material,this.worldSizeParams.worldHeight,this.viewDistance),this.debugRaycastHelper&&(this.realScene.remove(this.debugRaycastHelper),this.debugRaycastHelper=void 0),this.debugHitPoint&&(this.realScene.remove(this.debugHitPoint),this.debugHitPoint=void 0)}getLoadedChunksRelative(t,n=!1){let[r,s,a]=NE(t);return Object.fromEntries(Object.entries(this.sectionObjects).map(([o,l])=>{let[c,u,d]=o.split(",").map(Number),[f,v,g]=NE({x:c,y:u,z:d});return[n?`${f-r},${v-s},${g-a}`:`${f-r},${g-a}`,l]}))}readdChunks(){for(let t of Object.keys(this.sectionObjects))this.scene.remove(this.sectionObjects[t]);setTimeout(()=>{for(let t of Object.keys(this.sectionObjects))this.scene.add(this.sectionObjects[t])},500)}disableUpdates(t=this.scene.children){for(let n of t)n.matrixWorldNeedsUpdate=!1,this.disableUpdates(n.children??[])}removeColumn(t,n){super.removeColumn(t,n),this.clearPendingSectionUpdatesForChunk(t,n);let r=this.getSectionHeight(),s=this.worldMinYRender;for(let a=s;a<this.worldSizeParams.worldHeight;a+=r){let o=`${t},${a},${n}`;this.chunkMeshManager.sectionObjects[o]&&this.chunkMeshManager.releaseSection(o)}this.chunkMeshManager.onChunkRemovedFromGate(`${t},${n}`)}updateViewerPosition(t){super.updateViewerPosition(t),this.chunkMeshManager.pendingNearReveal.size>0&&this.chunkMeshManager.tryRevealPending()}onViewerChunkPositionChanged(){this.chunkMeshManager.tryRevealPending()}setSectionDirty(...t){super.setSectionDirty(...t)}static getRendererInfo(t){try{let n=t.getContext();return`${n.getParameter(n.getExtension("WEBGL_debug_renderer_info").UNMASKED_RENDERER_WEBGL)}`}catch(n){console.warn("Failed to get renderer info",n)}}worldStop(){this.media.onWorldStop()}destroy(){this.performanceMonitor?.reset(),this.pendingSectionUpdates.clear(),this.pendingSectionBufferStartTimes.clear(),this.chunkMeshManager.dispose(),this.disposeModules(),this.fireworksLegacy.destroy(),super.destroy(),this.skyboxRenderer.dispose(),this.fireworks.dispose()}shouldObjectVisible(t){let r=this.getSectionHeight(),s,a,o,l=this.sceneOrigin.getWorldPosition(t);l?(s=l.x,a=l.y,o=l.z):(s=this.sceneOrigin.toWorldX(t.position.x),a=this.sceneOrigin.toWorldY(t.position.y),o=this.sceneOrigin.toWorldZ(t.position.z));let c=Math.floor(s/16)*16,u=Math.floor(o/16)*16,d=Math.floor(a/r)*r,f=`${c},${u}`,v=`${c},${d},${u}`;return!!this.finishedChunks[f]||!!this.sectionObjects[v]}handleUserClick(t){this.media.handleUserClick(t)}updateSectionOffsets(){let t=performance.now();for(let[n,r]of Object.entries(this.sectionsOffsetsAnimations)){let s=(t-r.time)/1e3;r.time=t,r.currentOffsetX+=r.speedX*s,r.currentOffsetY+=r.speedY*s,r.currentOffsetZ+=r.speedZ*s,r.limitX!==void 0&&(r.speedX>0?r.currentOffsetX=Math.min(r.currentOffsetX,r.limitX):r.currentOffsetX=Math.max(r.currentOffsetX,r.limitX)),r.limitY!==void 0&&(r.speedY>0?r.currentOffsetY=Math.min(r.currentOffsetY,r.limitY):r.currentOffsetY=Math.max(r.currentOffsetY,r.limitY)),r.limitZ!==void 0&&(r.speedZ>0?r.currentOffsetZ=Math.min(r.currentOffsetZ,r.limitZ):r.currentOffsetZ=Math.max(r.currentOffsetZ,r.limitZ));let a=this.sectionObjects[n];a&&(a.position.set(r.currentOffsetX,r.currentOffsetY,r.currentOffsetZ),a.updateMatrix())}}reloadWorld(){this.entities.reloadEntities()}};Wn(ia,"LEGACY_TO_PHYSICAL_LIGHT",Math.PI),Wn(ia,"FOV_TRANSITION_MS",200),Wn(ia,"MAX_SECTION_UPDATE_BUFFER_MS",500);var Yd=ia;h();p();m();h();p();m();var mg="1.21.4";h();p();m();function Jd(i,e){i.aspect=e.width/e.height,i.updateProjectionMatrix()}h();p();m();h();p();m();var u0={mode:"v2",minecraftTextures:!0,v2Scene:"light",v2Camera:"dive",v2BlockGroup:"stainedGlass",v2CameraSpeedPercent:80,v2BlockSpeedPercent:40},GP=i=>i/100,g9={camera:GP(u0.v2CameraSpeedPercent),block:GP(u0.v2BlockSpeedPercent)};function WP(i,e=!1){return i?.mode?i.mode:e?"worldBlocks":u0.mode}h();p();m();Lt();h();p();m();var jP={};function XP(...i){let e=i.filter(n=>n.length>0).join("/"),t=typeof globalThis.location<"u"&&globalThis.location.href?globalThis.location.href:typeof jP<"u"&&jP.url?jP.url:`/${e}`;try{return new URL(e,t).href}catch{return`/${e}`}}var $P=new Date,W4e=$P.getMonth()===11&&$P.getDate()>=24&&$P.getDate()<=26,cJe=["panorama_3.webp","panorama_1.webp","panorama_4.webp","panorama_5.webp","panorama_0.webp","panorama_2.webp"],uJe=200,pg=class{constructor(e){this.documentRenderer=e;this.scene=new Rr,this.scene.background=new We(3294568);let t=new wa(13421772);this.scene.add(t);let n=new Ss(16777215,.5);n.position.set(1,1,.5).normalize(),n.castShadow=!0,this.scene.add(n),this.camera=new fn(85,e.canvas.width/e.canvas.height,.05,1e3),this.camera.position.set(0,0,0),this.camera.rotation.set(0,0,0)}scene;camera;startTimes=new Map;time=0;panoramaGroup=null;async init(){this.buildCubemap()}update(e,t){t&&Jd(this.camera,this.documentRenderer.canvas)}dispose(){this.scene.clear(),this.panoramaGroup=null,this.startTimes.clear()}buildCubemap(){let e=new Sn(1e3,1e3,1e3),t=[];for(let s of cJe)(async()=>{let o=XP("background",W4e?"christmas":"",s),l=await qu(o),c=cc(l);c.matrixAutoUpdate=!1,c.matrix.set(-1,0,1,0,1,0,0,0,1),c.wrapS=jn,c.wrapT=jn,c.minFilter=$t,c.magFilter=$t;let u=new _t({map:c,transparent:!0,side:In,depthWrite:!1,opacity:0});this.startTimes.set(u,Date.now()),t.push(u)})().catch(o=>{console.warn("[ClassicMenuBackground] Failed to load panorama face:",s,o)});let n=new Ke(e,t);n.onBeforeRender=()=>{this.time+=.01,n.rotation.y=Math.PI+this.time*.01,n.rotation.z=Math.sin(-this.time*.001)*.001;for(let s of t){let a=this.startTimes.get(s);if(a){let o=Date.now()-a;s.opacity=Math.min(1,o/uJe)}}};let r=new Ut;if(r.add(n),!W4e)for(let s=0;s<20;s++){let a=new o0("1.16.4","squid").mesh;a.position.set(Math.random()*30-15,Math.random()*20-10,Math.random()*10-17),a.rotation.set(0,Math.PI+Math.random(),-Math.PI/4,"ZYX");let o=Math.random()*.01;a.children[0].onBeforeRender=()=>{a.rotation.y+=o,a.rotation.z=Math.cos(n.rotation.y*3)*Math.PI/4-Math.PI/2},r.add(a)}this.scene.add(r),this.panoramaGroup=r}async debugImageInFrontOfCamera(){let e=await qu(XP("background","panorama_0.webp")),t=cc(e),n=new Ke(new zn(1e3,1e3),new _t({map:t}));n.position.set(0,0,-500),this.scene.add(n)}};h();p();m();Lt();h();p();m();var q5=["galaxy","nether","end","cyber","light"],G5=["cruise","barrel","dive","orbit","snake"],_9={galaxy:"Galaxy",nether:"Nether",end:"The End",cyber:"Cyber",light:"Light Space"},y9={cruise:"Cruise",barrel:"Barrel",dive:"Dive",orbit:"Orbit",snake:"Snake"},W5=["mixed","stainedGlass","wool","construction","glow","world"],b9={mixed:"Mixed",stainedGlass:"Stained glass",wool:"Wool",construction:"Construction",glow:"Glow",world:"World (grass & ores)"};var j4e=.1,Y4e={mixed:["white_wool","cyan_wool","blue_wool","purple_wool","white_stained_glass","cyan_stained_glass","blue_stained_glass","purple_stained_glass","glowstone","sea_lantern","amethyst_block","copper_block","gold_block","diamond_block"],stainedGlass:["white_stained_glass","orange_stained_glass","magenta_stained_glass","light_blue_stained_glass","yellow_stained_glass","lime_stained_glass","pink_stained_glass","gray_stained_glass","light_gray_stained_glass","cyan_stained_glass","purple_stained_glass","blue_stained_glass","brown_stained_glass","green_stained_glass","red_stained_glass","black_stained_glass"],wool:["white_wool","orange_wool","magenta_wool","light_blue_wool","yellow_wool","lime_wool","pink_wool","gray_wool","light_gray_wool","cyan_wool","purple_wool","blue_wool","brown_wool","green_wool","red_wool","black_wool"],construction:["copper_block","exposed_copper","weathered_copper","oxidized_copper","cut_copper","exposed_cut_copper","weathered_cut_copper","oxidized_cut_copper","iron_block","gold_block","diamond_block","emerald_block","netherite_block","lapis_block","redstone_block","coal_block","quartz_block","amethyst_block","bricks","stone_bricks","deepslate_bricks","polished_blackstone"],glow:["glowstone","sea_lantern","shroomlight","ochre_froglight","verdant_froglight","pearlescent_froglight","redstone_lamp","beacon"],world:["grass_block","podzol","mycelium","dirt","coarse_dirt","rooted_dirt","mud","clay","stone","cobblestone","mossy_cobblestone","deepslate","cobbled_deepslate","tuff","calcite","sand","red_sand","gravel","snow_block","coal_ore","deepslate_coal_ore","iron_ore","deepslate_iron_ore","copper_ore","deepslate_copper_ore","gold_ore","deepslate_gold_ore","diamond_ore","deepslate_diamond_ore","emerald_ore","deepslate_emerald_ore","lapis_ore","deepslate_lapis_ore","redstone_ore","deepslate_redstone_ore","nether_gold_ore","ancient_debris","oak_log","birch_log","spruce_log","jungle_log","acacia_log","dark_oak_log","mangrove_log","cherry_log","netherrack","soul_sand","basalt","end_stone"]},X4e={galaxy:{bg:132114,fog:132114,fogD:.011,blocks:[61695,54527,47359,59647,2280703,43263],emit:[13158,8789,6724],nebula:[4403,1114146,4386],galFn:i=>new We(i*.05,i*.2,i),ambient:264216,dir:3368703,pt1:43775,pt2:16729343,name:"GALAXY"},nether:{bg:917760,fog:917760,fogD:.016,blocks:[16720384,16737792,16750848,13373696,16729122,16755200],emit:[2230272,1114112,3346688],nebula:[1704960,851968,1705984],galFn:i=>new We(i,i*.15,0),ambient:1573376,dir:16724736,pt1:16729088,pt2:16755200,name:"NETHER"},end:{bg:0,fog:0,fogD:.009,blocks:[7807658,11158732,5570679,14527231,3342421,12299007],emit:[655381,1572901,327696],nebula:[524312,851989,262158],galFn:i=>new We(i*.4,0,i),ambient:393232,dir:10040319,pt1:11158783,pt2:4456618,name:"THE END"},cyber:{bg:792610,fog:792610,fogD:.008,blocks:[65535,4521932,11206468,6741503,8978278,65450],emit:[666163,668450,665656],nebula:[1192e3,1587240,1323588],galFn:i=>new We(i*.15,i*.85,i*.95),ambient:1716288,dir:6750156,pt1:4521966,pt2:10092356,name:"CYBER",starColor:13431039,starOpacity:.75,galaxyOpacity:.62,nebulaOpacity:.36,edgeLineColor:4521949,blockOpacity:[.38,.54]},light:{bg:8951984,fog:7899296,fogD:.006,gradientBg:{top:14214392,mid:10531016,bottom:6846608,radial:!0},blocks:[15266559,13691135,12114175,10537208,8960240,7383272,10012927,12640511,15792383,7909608,14216447,14739711],emit:[6854864,8958176,11061488,12638456],nebula:[9480392,11059424,12637420,14215416,7901360],galFn:i=>{let e=new We;return i<.4?e.lerpColors(new We(16054527),new We(14215423),i/.4):i<.75?e.lerpColors(new We(14215423),new We(11061488),(i-.4)/.35):e.lerpColors(new We(11061488),new We(9482464),(i-.75)/.25),e},ambient:7899296,dir:13688040,pt1:11061503,pt2:13162751,name:"LIGHT",starColor:15266047,starOpacity:.5,galaxyOpacity:.7,nebulaOpacity:.32,edgeLineColor:10010856,blockOpacity:[.42,.56]}},dJe={cruise:{pos:(i,e,t)=>({x:Math.sin(i*.28)*18+Math.cos(i*.11)*7+e*10,y:Math.sin(i*.19)*6+Math.cos(i*.31)*3+t*6,z:0}),look:(i,e,t)=>({x:Math.sin((i+.18)*.28)*18+e*8,y:Math.sin((i+.18)*.19)*6+t*4,z:-25}),roll:(i,e=0)=>e*.05+Math.sin(i*.22)*.015,spd:.18},barrel:{pos:(i,e,t)=>{let r=i*2.4;return{x:Math.cos(r)*10+e*4,y:Math.sin(r)*10+t*4,z:Math.sin(i*.4)*8}},look:i=>({x:Math.sin(i*.5)*5,y:Math.cos(i*.5)*5,z:-30}),roll:i=>i*2.4+Math.PI*.5,spd:.24},dive:{pos:(i,e,t)=>({x:Math.sin(i*.6)*30+e*8,y:Math.cos(i*.4)*18+t*6,z:Math.sin(i*.3)*12}),look:(i,e,t)=>({x:Math.sin(i*.6+.2)*30+e*6,y:Math.cos(i*.4+.2)*18-8+t*4,z:-35}),roll:(i,e=0)=>e*.08+Math.sin(i*.6)*.12,spd:.3},orbit:{pos:(i,e,t)=>({x:Math.cos(i*.5)*20+e*5,y:Math.sin(i*.25)*10+t*5,z:Math.sin(i*.5)*20}),look:()=>({x:0,y:0,z:-60}),roll:i=>Math.sin(i*.5)*.08,spd:.15},snake:{pos:(i,e,t)=>({x:Math.sin(i*1.1)*22+Math.sin(i*.37)*8+e*10,y:Math.sin(i*.7)*10+e*4+t*8,z:0}),look:(i,e,t)=>{let n=i+.12;return{x:Math.sin(n*1.1)*22+Math.sin(n*.37)*8+e*8,y:Math.sin(n*.7)*10+t*6,z:-22}},roll:(i,e=0)=>e*.1+Math.sin(i*1.1)*.06,spd:.22}},fJe={cruise:1,barrel:1.6,dive:2.2,orbit:.7,snake:1.4},hJe=250,x9=1e4,w9=3e3,j5=i=>i[Math.floor(Math.random()*i.length)],YP=i=>"#"+i.toString(16).padStart(6,"0"),$4e=i=>{if(typeof document>"u")return null;let e=document.createElement("canvas");e.width=4,e.height=512;let t=e.getContext("2d");if(!t)return null;let n=e.width,r=e.height,s=i.radial?t.createRadialGradient(n/2,r*.32,0,n/2,r*.32,r*.85):t.createLinearGradient(0,0,0,r);s.addColorStop(0,YP(i.top)),i.mid!=null&&s.addColorStop(.45,YP(i.mid)),s.addColorStop(1,YP(i.bottom)),t.fillStyle=s,t.fillRect(0,0,n,r);let a=new On(e);return a.needsUpdate=!0,a},X5=class{constructor(e,t={},n){this.documentRenderer=e;this.abortSignal=n;let r=u0;this.curScene=t.initialScene??r.v2Scene,this.curCam=t.initialCamera??r.v2Camera,this.blockGroup=t.initialBlockGroup??r.v2BlockGroup,this.cameraSpeed=t.initialCameraSpeed??g9.camera,this.blockSpeed=t.initialBlockSpeed??g9.block,this.useMinecraftTextures=t.useMinecraftTextures??r.minecraftTextures,this.resourcesManager=t.resourcesManager;let s=X4e[this.curScene];this.scene=new Rr,this.scene.fog=new C0(s.fog,s.fogD),this.applyScenePalette(s),this.camera=new fn(80,this.documentRenderer.canvas.width/this.documentRenderer.canvas.height,.1,700),this.ambient=new wa(s.ambient,2.5),this.scene.add(this.ambient),this.dir=new Ss(s.dir,4),this.dir.position.set(1,1,0),this.scene.add(this.dir),this.pt1=new yo(s.pt1,5,100),this.scene.add(this.pt1),this.pt2=new yo(s.pt2,4,80),this.pt2.position.set(30,20,-30),this.scene.add(this.pt2);for(let f=0;f<hJe;f++)this.spawnBlock(s,!0);if(!this.useMinecraftTextures){let f=s.edgeLineColor??62975;for(let v=0;v<40;v++){let g=new Pn({color:f,transparent:!0,opacity:.25});j5(this.blocks).mesh.add(new Kn(this.eGeo,g))}}this.scene.add(this.bGroup);let a=new dt,o=new Float32Array(5e3*3);for(let f=0;f<5e3*3;f++)o[f]=(Math.random()-.5)*500;a.setAttribute("position",new Mt(o,3)),this.stars=new gr(a,new Jr({color:s.starColor??16777215,size:.3,transparent:!0,opacity:s.starOpacity??.7,sizeAttenuation:!0})),this.scene.add(this.stars),this.galGeo=new dt;let l=new Float32Array(x9*3),c=new Float32Array(x9*3);for(let f=0;f<x9;f++){let v=f%3,g=Math.random(),b=v/3*Math.PI*2+g*Math.PI*5,y=g*90+Math.random()*10,_=(1-g)*18;l[f*3]=Math.cos(b)*y+(Math.random()-.5)*_,l[f*3+1]=(Math.random()-.5)*7,l[f*3+2]=Math.sin(b)*y+(Math.random()-.5)*_-180;let x=.2+g*.8,w=s.galFn(x);c[f*3]=w.r,c[f*3+1]=w.g,c[f*3+2]=w.b}this.galGeo.setAttribute("position",new Mt(l,3)),this.galGeo.setAttribute("color",new Mt(c,3)),this.galaxy=new gr(this.galGeo,new Jr({size:.9,vertexColors:!0,transparent:!0,opacity:s.galaxyOpacity??.55,sizeAttenuation:!0})),this.scene.add(this.galaxy),this.nebGeo=new dt;let u=new Float32Array(w9*3),d=new Float32Array(w9*3);for(let f=0;f<w9;f++){let v=25+Math.random()*110,g=Math.random()*Math.PI*2,b=(Math.random()-.5)*Math.PI*.5;u[f*3]=v*Math.cos(g)*Math.cos(b),u[f*3+1]=v*Math.sin(b)*.6,u[f*3+2]=v*Math.sin(g)*Math.cos(b)-80;let y=new We(j5(s.nebula));d[f*3]=y.r,d[f*3+1]=y.g,d[f*3+2]=y.b}this.nebGeo.setAttribute("position",new Mt(u,3)),this.nebGeo.setAttribute("color",new Mt(d,3)),this.nebula=new gr(this.nebGeo,new Jr({size:3,vertexColors:!0,transparent:!0,opacity:s.nebulaOpacity??.3,sizeAttenuation:!0})),this.scene.add(this.nebula),this.addBackgroundTextPlane(),this.setupMouseTracking()}scene;camera;ambient;dir;pt1;pt2;blocks=[];bGroup=new bt;galaxy;nebula;stars;galGeo;nebGeo;bGeo=new Sn(1,1,1);eGeo=new dl(this.bGeo);curScene;curCam;blockGroup;cameraSpeed;blockSpeed;camT=0;mx=0;my=0;tmx=0;tmy=0;transitioning=!1;useMinecraftTextures=!1;resourcesManager;atlasTexture=null;blockMaterialPool=new Map;gradientSky=null;gradientSkyTexture=null;disposed=!1;animTime=0;texturesApplied=!1;textureLoadInProgress=!1;onAssetsTexturesUpdated;async init(){this.useMinecraftTextures&&this.scheduleMinecraftTextureLoad()}scheduleMinecraftTextureLoad(){!this.useMinecraftTextures||this.disposed||this.texturesApplied||this.textureLoadInProgress||this.tryApplyMinecraftTextures()}attachAssetsListener(){let e=this.resourcesManager;!e||this.onAssetsTexturesUpdated||(this.onAssetsTexturesUpdated=()=>this.scheduleMinecraftTextureLoad(),e.on("assetsTexturesUpdated",this.onAssetsTexturesUpdated))}detachAssetsListener(){let e=this.resourcesManager;!e||!this.onAssetsTexturesUpdated||(e.off("assetsTexturesUpdated",this.onAssetsTexturesUpdated),this.onAssetsTexturesUpdated=void 0)}hasBlockAtlas(e){let t=e.currentResources;return!!(t?.blocksAtlasImage&&t.blocksAtlasJson)}async ensureAtlasReady(e){if(await this.ensureMcDataLoaded(),this.hasBlockAtlas(e))return!0;if(typeof document>"u"&&e!==this.resourcesManager)return!1;e.currentConfig={...e.currentConfig,version:mg,noInventoryGui:!0};try{await e.updateAssetsData?.({})}catch{return!1}return this.hasBlockAtlas(e)}async tryApplyMinecraftTextures(){if(!(this.disposed||!this.useMinecraftTextures||this.texturesApplied)){this.textureLoadInProgress=!0;try{let e=this.resourcesManager??new lc;if(!await this.ensureAtlasReady(e)){this.resourcesManager&&this.attachAssetsListener();return}if(this.disposed)return;this.applyMinecraftTexturesFromAtlas(e),this.texturesApplied=!0,this.detachAssetsListener()}catch(e){console.warn("[V2MenuBackground] Failed to load Minecraft textures, using solid colors:",e),this.useMinecraftTextures=!1,this.detachAssetsListener()}finally{this.textureLoadInProgress=!1}}}applyScenePalette(e){if(this.documentRenderer.renderer.setClearColor(e.bg),e.gradientBg)if(this.scene.background=null,this.gradientSky){if(this.gradientSky.visible=!0,this.gradientSkyTexture&&e.gradientBg){let s=$4e(e.gradientBg);s&&(this.gradientSkyTexture.dispose(),this.gradientSkyTexture=s,this.gradientSky.material.map=s,this.gradientSky.material.needsUpdate=!0)}}else{let s=$4e(e.gradientBg);s?(this.gradientSkyTexture=s,this.gradientSky=new Ke(new zn(900,700),new _t({map:s,depthWrite:!1,side:In})),this.gradientSky.position.set(0,0,-280),this.gradientSky.renderOrder=-1e3,this.scene.add(this.gradientSky)):this.scene.background=new We(e.bg)}else this.scene.background=new We(e.bg),this.gradientSky&&(this.gradientSky.visible=!1);this.scene.fog instanceof C0&&(this.scene.fog.color.set(e.fog),this.scene.fog.density=e.fogD);let t=this.stars?.material;t&&(t.color.set(e.starColor??16777215),t.opacity=e.starOpacity??.7);let n=this.galaxy?.material;n&&(n.opacity=e.galaxyOpacity??.55);let r=this.nebula?.material;r&&(r.opacity=e.nebulaOpacity??.3)}setupMouseTracking(){let e=n=>{let r=typeof window<"u"?window.innerWidth:this.documentRenderer.canvas.width,s=typeof window<"u"?window.innerHeight:this.documentRenderer.canvas.height;this.tmx=(n.clientX/r-.5)*2,this.tmy=-(n.clientY/s-.5)*2};(typeof document<"u"?document:void 0)?.addEventListener("mousemove",e,{signal:this.abortSignal})}addBackgroundTextPlane(){let n=typeof document<"u"?document.createElement("canvas"):null;if(!n)return;n.width=2048,n.height=768;let r=n.getContext("2d");if(!r)return;r.clearRect(0,0,2048,768),r.save(),r.font="bold 560px Orbitron, sans-serif",r.textAlign="center",r.textBaseline="middle",r.shadowColor="rgba(0,200,255,0.35)",r.shadowBlur=80,r.fillStyle="rgba(255,255,255,0.055)",r.fillText("V2",2048*.28,768*.5),r.restore(),r.save(),r.font="bold 148px Orbitron, sans-serif",r.textAlign="center",r.textBaseline="middle",r.shadowColor="rgba(0,200,255,0.2)",r.shadowBlur=40,r.fillStyle="rgba(255,255,255,0.038)",r.fillText("by ZARDOY",2048*.72,768*.52),r.restore();let s=new On(n),a=new Ke(new zn(280,105),new _t({map:s,transparent:!0,opacity:1,depthWrite:!1,side:In,blending:es}));a.position.set(8,4,-320),this.scene.add(a)}spawnBlock(e,t,n){let r=this.createBlockMaterial(e,n),s=new Ke(this.bGeo,r),a=.3+Math.random()*3;s.scale.setScalar(a),s.position.set((Math.random()-.5)*140,(Math.random()-.5)*70,t?-(Math.random()*140):-155-Math.random()*30),s.rotation.set(Math.random()*Math.PI*2,Math.random()*Math.PI*2,Math.random()*Math.PI*2);let o={mesh:s,spd:.04+Math.random()*.12,dx:(Math.random()-.5)*.012,dy:(Math.random()-.5)*.008,rx:(Math.random()-.5)*.012,ry:(Math.random()-.5)*.012,rz:(Math.random()-.5)*.01,minecraftBlockName:n};this.blocks.push(o),this.bGroup.add(s)}createBlockMaterial(e,t){if(this.useMinecraftTextures&&t){let s=this.blockMaterialPool.get(t);if(s)return s.clone()}let[n,r]=e.blockOpacity??[.32,.46];return new _t({color:j5(e.blocks),transparent:!0,opacity:n+Math.random()*(r-n),depthWrite:!1,blending:es})}removeBlockEdgeLines(){for(let e of this.blocks){let t=e.mesh.children.filter(n=>n instanceof Kn);for(let n of t){e.mesh.remove(n),n.geometry?.dispose();let r=n.material;Array.isArray(r)?r.forEach(s=>s.dispose()):r.dispose()}}}async ensureMcDataLoaded(){let e=globalThis._LOAD_MC_DATA;e&&await e()}resolveBlockAtlasUv(e,t,n){let r=s=>{let a=t[s];return a?{u:a.u,v:a.v,su:a.su??n.suSv,sv:a.sv??n.suSv}:null};if(t[e])return r(e);for(let s of["_top","_side","_front","_0"]){let a=r(`${e}${s}`);if(a)return a}for(let s of Object.keys(t))if(s.startsWith(e))return r(s);return null}applyMinecraftTexturesFromAtlas(e){let t=e.currentResources;if(!t?.blocksAtlasImage||!t.blocksAtlasJson)throw new Error("Block atlas not available");let n=t.blocksAtlasJson,r=n.textures;this.atlasTexture=cc(t.blocksAtlasImage),this.atlasTexture.flipY=!1,this.atlasTexture.needsUpdate=!0;for(let s of Y4e[this.blockGroup]){let a=this.resolveBlockAtlasUv(s,r,n);if(!a)continue;let o=this.atlasTexture.clone();o.flipY=!1,o.offset.set(a.u,a.v),o.repeat.set(a.su,a.sv),o.needsUpdate=!0;let l=s.includes("glass"),c=new _t({map:o,side:In,transparent:l,opacity:l?.85:1,alphaTest:l?.08:0,depthWrite:!0,toneMapped:!1});this.blockMaterialPool.set(s,c)}if(this.blockMaterialPool.size===0)throw new Error("No block textures resolved from atlas (check block names vs atlas keys)");this.removeBlockEdgeLines();for(let s of this.blocks){let a=j5([...this.blockMaterialPool.keys()]);s.minecraftBlockName=a,s.mesh.material=this.blockMaterialPool.get(a).clone()}}setScene(e){if(!q5.includes(e)||e===this.curScene||this.transitioning)return;this.transitioning=!0,this.curScene=e;let t=X4e[e];setTimeout(()=>{if(this.disposed)return;this.applyScenePalette(t),this.ambient.color.set(t.ambient),this.dir.color.set(t.dir),this.pt1.color.set(t.pt1),this.pt2.color.set(t.pt2);for(let s of this.blocks)this.useMinecraftTextures&&s.minecraftBlockName||s.mesh.material instanceof _t&&s.mesh.material.color.set(j5(t.blocks));let n=this.nebGeo.attributes.color;for(let s=0;s<w9;s++){let a=new We(j5(t.nebula));n.setXYZ(s,a.r,a.g,a.b)}n.needsUpdate=!0;let r=this.galGeo.attributes.color;for(let s=0;s<x9;s++){let a=.2+Math.random()*.8,o=t.galFn(a);r.setXYZ(s,o.r,o.g,o.b)}r.needsUpdate=!0,this.transitioning=!1},150)}setCamera(e){G5.includes(e)&&(this.curCam=e)}setCameraSpeed(e){this.cameraSpeed=Math.max(0,e)}setBlockSpeed(e){this.blockSpeed=Math.max(0,e)}async setBlockGroup(e){if(W5.includes(e)&&e!==this.blockGroup&&(this.blockGroup=e,!(!this.useMinecraftTextures||this.disposed))){for(let t of this.blockMaterialPool.values())t.map?.dispose(),t.dispose();this.blockMaterialPool.clear(),this.texturesApplied=!1,this.scheduleMinecraftTextureLoad()}}getSceneId(){return this.curScene}getCameraId(){return this.curCam}getBlockGroupId(){return this.blockGroup}update(e,t){t&&Jd(this.camera,this.documentRenderer.canvas);let n=dJe[this.curCam],r=this.cameraSpeed,s=this.blockSpeed;this.camT+=e*n.spd*r,this.mx+=(this.tmx-this.mx)*.05,this.my+=(this.tmy-this.my)*.05;let a=this.mx*j4e,o=this.my*j4e,l=n.pos(this.camT,a,o),c=n.look(this.camT,a,o);this.camera.position.set(l.x,l.y,l.z),this.camera.lookAt(c.x,c.y,c.z),this.camera.rotation.z=n.roll(this.camT,a);let u=fJe[this.curCam]*s;this.animTime+=e*1e3*s;for(let d of this.blocks){if(d.mesh.position.z+=d.spd*u*60*e,d.mesh.position.x+=d.dx*60*e*s,d.mesh.position.y+=d.dy*60*e*s,d.mesh.rotation.x+=d.rx*u,d.mesh.rotation.y+=d.ry*u,d.mesh.rotation.z+=d.rz,!this.useMinecraftTextures&&d.mesh.material instanceof _t){let f=d.mesh.userData.baseOpacity??.38;d.mesh.userData.baseOpacity==null&&(d.mesh.userData.baseOpacity=f);let v=.88+Math.abs(Math.sin(this.animTime*8e-4+d.mesh.position.x*.3))*.12;d.mesh.material.opacity=f*v}d.mesh.position.z>this.camera.position.z+15&&d.mesh.position.set((Math.random()-.5)*140,(Math.random()-.5)*70,this.camera.position.z-155-Math.random()*30)}this.pt1.position.set(Math.sin(this.camT*.8)*25+this.camera.position.x,Math.cos(this.camT*.6)*12+this.camera.position.y,this.camera.position.z-18),this.pt2.position.set(Math.cos(this.camT*.5)*20+this.camera.position.x,Math.sin(this.camT*.9)*15+this.camera.position.y,this.camera.position.z-30),this.galaxy.rotation.y+=e*.006*s,this.nebula.rotation.y-=e*.003*s,this.stars.rotation.y+=e*4e-4*s}dispose(){this.disposed=!0,this.detachAssetsListener(),this.scene.clear(),this.bGeo.dispose(),this.eGeo.dispose(),this.galGeo.dispose(),this.nebGeo.dispose(),this.gradientSkyTexture?.dispose(),this.atlasTexture?.dispose();for(let e of this.blockMaterialPool.values())e.map?.dispose(),e.dispose();this.blockMaterialPool.clear()}};h();p();m();Lt();h();p();m();var r8e=Yr(n8e(),1),i8e=Yr(CI(),1);var s8e=i=>{let e=(0,r8e.default)(i),t=(0,i8e.default)(i),n=new e(i).sync,r=xJe(n);for(let s of r)if(s.startsWith("set")&&s!=="setColumn"){let a=n[s].bind(n);n[s]=(...o)=>{let l=o[0];l.x!==void 0&&!n.getColumnAt(l)&&n.setColumn(Math.floor(l.x/16),Math.floor(l.z/16),new t(void 0)),a(...o)}}return n};function xJe(i){let e=new Set,t=i;do for(let n of Object.getOwnPropertyNames(t))typeof i[n]=="function"&&n!=="constructor"&&e.add(n);while(t=Object.getPrototypeOf(t));return[...e]}h();p();m();var a8e={paused:!1,showChunkBorders:!1,enableDebugOverlay:!1,debugWasmPerf:!1,debugModelVariant:void 0,futuristicReveal:!1,wasmMesher:!0,shaderCubeBlocks:!1,shaderCubeDebugMode:0,mesherWorkers:1,addChunksBatchWaitTime:200,_experimentalSmoothChunkLoading:!0,_renderByChunks:!1,autoLowerRenderDistance:!1,disableMesherConversionCache:!1,dedicatedChangeWorker:!1,shadingTheme:"high-contrast",cardinalLight:"default",dayCycle:!0,smoothLighting:!0,enableLighting:!0,starfield:!0,defaultSkybox:!0,renderEntities:!0,extraBlockRenderers:!0,foreground:!0,fov:75,volume:1,showHand:!1,viewBobbing:!1,handRenderer:"vanilla",renderEars:!0,highlightBlockColor:"blue",fetchPlayerSkins:!0,skinTexturesProxy:void 0,vrSupport:!0,vrPageGameRendering:!0,clipWorldBelowY:void 0,isPlayground:!1,instantCameraUpdate:!1,isRaining:!1,rainColor:"rgb(118, 148, 226)",rainOpacity:.5,moduleStates:{}};var nL=()=>({reactive:_l({world:{chunksLoaded:{},heightmaps:{},allChunksLoaded:!1,mesherWork:!1,instabilityFactors:zP(),intersectMedia:null},renderer:"...",preventEscapeMenu:!1}),nonReactive:{fps:0,worstRenderTime:0,avgRenderTime:0,world:{chunksLoadedCount:0,chunksTotalNumber:0,chunksFullInfo:"-"},renderer:{timeline:{live:[],frozen:[],lastSecond:[]}}}});h();p();m();h();p();m();h();p();m();Ia();var yg=i=>[Math.floor(i.x/16),Math.floor(i.z/16)];var wJe=async(i,e,t,n=1)=>{for(let r=0;r<i.length;r+=n)e&&await new Promise(s=>setTimeout(s,e)),await t(i[r],r)},$5=new WeakMap,bg=class bg extends W0{static restoreTransferred(e,t){let n=new bg;if(!t)return n;let r=$5.get(t);if(r)r.activeWorldView=n;else{let s=({data:a})=>{let l=$5.get(t)?.activeWorldView;!l||a?.class!==bg.restorerName||a.type==="event"&&l.emit(a.eventName,...a.args)};t.addEventListener("message",s),r={activeWorldView:n,handler:s},$5.set(t,r)}return n}static clearWorkerBridgeForTest(e){let t=$5.get(e);t&&(e.removeEventListener("message",t.handler),$5.delete(e))}static getWorkerBridgeListenerCountForTest(e){return $5.has(e)?1:0}};Wn(bg,"restorerName","WorldViewWorker");var Y5=bg,M9=class extends W0{constructor(t,n,r=new kt(0,0,0)){super();this.world=t;this.viewDistance=n;this.lastPos=new kt(0,0,0).update(r)}spiralNumber=0;gotPanicLastTime=!1;panicChunksReload=()=>{};loadedChunks={};inLoading=!1;chunkReceiveTimes=[];lastChunkReceiveTime=0;lastChunkReceiveTimeAvg=0;panicTimeout;lastPos;eventListeners={};debugChunksInfo={};waitingSpiralChunksLoad={};addWaitTime=1;keepChunksDistance=0;isPlayground=!1;allowPositionUpdate=!0;prepareForTransfer(t){if(t){let n=this.emit.bind(this);this.emit=(r,...s)=>{n(r,...s),t.postMessage({class:Y5.restorerName,type:"event",eventName:r,args:e4(s)})}}return{__restorer:Y5.restorerName}}setBlockStateId(t,n){let r=this.world.setBlockStateId(t,n);if(r&&typeof r.then=="function")throw new Error("setBlockStateId returned promise (not supported)");this.emit("blockUpdate",{pos:t,stateId:n})}updateViewDistance(t){this.viewDistance=t,this.emit("renderDistance",t)}async init(t,n){console.log("WorldView init"),this.updateViewDistance(this.viewDistance),this.emit("chunkPosUpdate",{pos:t}),n?.time?.timeOfDay!==void 0&&this.emit("time",n.time.timeOfDay),n?.entity&&this.emit("playerEntity",n.entity),this.emitterGotConnected(n);let[r,s]=yg(t),a=C3(this.viewDistance).map(([o,l])=>new kt((r+o)*16,0,(s+l)*16));this.lastPos.update(t),await this._loadChunks(a,t)}chunkProgress(){if(this.panicTimeout&&clearTimeout(this.panicTimeout),this.chunkReceiveTimes.length>=5){let t=this.chunkReceiveTimes.reduce((r,s)=>r+s,0)/this.chunkReceiveTimes.length;this.lastChunkReceiveTimeAvg=t;let n=t*2+1e3;this.panicTimeout&&clearTimeout(this.panicTimeout),this.panicTimeout=setTimeout(()=>{!this.gotPanicLastTime&&this.inLoading&&(console.warn("Chunk loading seems stuck, triggering panic reload"),this.gotPanicLastTime=!0,this.panicChunksReload())},n)}}async _loadChunks(t,n){this.spiralNumber++;let{spiralNumber:r}=this;for(let a of Object.keys(this.waitingSpiralChunksLoad))this.waitingSpiralChunksLoad[a](!1),delete this.waitingSpiralChunksLoad[a];let s=!0;this.inLoading=!0,await wJe(t,this.addWaitTime,async a=>{!s||this.loadedChunks[`${a.x},${a.z}`]||(this.world.getColumnAt(a)||(s=await new Promise(o=>{this.waitingSpiralChunksLoad[`${a.x},${a.z}`]=o})),s&&(await this.loadChunk(a,void 0,`spiral ${r} from ${n.x},${n.z}`),this.chunkProgress()))}),r===this.spiralNumber&&(this.panicTimeout&&clearTimeout(this.panicTimeout),this.inLoading=!1,this.gotPanicLastTime=!1,this.chunkReceiveTimes=[],this.lastChunkReceiveTime=0)}async loadChunk(t,n=!1,r="spiral"){let[s,a]=yg(this.lastPos),o=Math.abs(s-Math.floor(t.x/16)),l=Math.abs(a-Math.floor(t.z/16));if(o<=this.viewDistance&&l<=this.viewDistance){let c=await this.world.getColumnAt(t.y!==void 0?t:new kt(t.x,0,t.z));if(c){let u=c.toJson(),d={minY:c.minY??0,worldHeight:c.worldHeight??256};this.emit("loadChunk",{x:t.x,z:t.z,chunk:u,blockEntities:c.blockEntities,worldConfig:d,isLightUpdate:n}),this.loadedChunks[`${t.x},${t.z}`]=!0,this.debugChunksInfo[`${t.x},${t.z}`]??={loads:[]},this.debugChunksInfo[`${t.x},${t.z}`].loads.push({dataLength:u.length,reason:r,time:Date.now()})}else this.isPlayground&&this.emit("markAsLoaded",{x:t.x,z:t.z})}}async reloadLoadedChunks(){let t=Object.keys(this.loadedChunks);for(let n of t){let[r,s]=n.split(",").map(Number);await this.loadChunk({x:r,z:s},!1,"mesher-reconfigure")}}unloadAllChunks(){for(let t of Object.keys(this.loadedChunks)){let[n,r]=t.split(",").map(Number);this.unloadChunk({x:n,z:r})}}unloadChunk(t){this.emit("unloadChunk",{x:t.x,z:t.z}),delete this.loadedChunks[`${t.x},${t.z}`],delete this.debugChunksInfo[`${t.x},${t.z}`]}emitterGotConnected(t){typeof globalThis.WorkerGlobalScope<"u"&&globalThis instanceof globalThis.WorkerGlobalScope||!t||this.emit("blockEntities",new Proxy({},{get(r,s,a){if(typeof s!="string")return;let[o,l,c]=s.split(",").map(Number);return t.world.getBlock(new kt(o,l,c))?.entity}}))}lastBiomeId=null;updateBiome(t){try{if(!this.world.getBiome)return;let n=this.world.getBiome(t);n!==this.lastBiomeId&&(this.lastBiomeId=n,this.emit("biomeReset"))}catch(n){console.error("error updating biome",n)}}lastPosCheck=null;async updatePosition(t,n=!1){if(!this.allowPositionUpdate)return;let r=t.floored();if(!n&&this.lastPosCheck&&this.lastPosCheck.equals(r))return;this.lastPosCheck=r,this.updateBiome(t);let[s,a]=yg(this.lastPos),[o,l]=yg(t);if(s!==o||a!==l||n){this.emit("chunkPosUpdate",{pos:t});let c=[],u=n?this.viewDistance:this.viewDistance+this.keepChunksDistance;for(let f of Object.keys(this.loadedChunks)){let[v,g]=f.split(",").map(Number),b=new kt(v,0,g),[y,_]=yg(b),x=Math.abs(o-y),w=Math.abs(l-_);(x>u||w>u)&&c.push(b)}for(let f of c)this.unloadChunk(f);let d=C3(this.viewDistance).map(([f,v])=>{let g=new kt((o+f)*16,0,(l+v)*16);if(!this.loadedChunks[`${g.x},${g.z}`])return g}).filter(f=>!!f);this.lastPos.update(t),this._loadChunks(d,t)}else this.emit("chunkPosUpdate",{pos:t}),this.lastPos.update(t)}};var xg=class{constructor(e,t,n){this.documentRenderer=e;this.options=t;this.abortSignal=n;this._scene=new Rr,this._scene.background=new We(3294568),this._camera=new fn(85,e.canvas.width/e.canvas.height,.05,1e3),this.camera.position.set(0,0,0),this.camera.rotation.set(0,0,0)}_scene;_camera;get scene(){return this._scene}get camera(){return this._camera}worldRenderer;WorldRendererClass=Yd;async init(){let e=mg,t=new lc;if(t.currentConfig={version:e,noInventoryGui:!0},await t.updateAssetsData?.({}),this.abortSignal.aborted)return;console.time("load menu background scene");let n=s8e(e),s=Si()(e),o=globalThis.mcData.blocksArray.filter(v=>{if(!v.name.includes("stained_glass"))return!1;let g=s.fromStateId(v.defaultState,0);if(g.shapes?.length!==1)return!1;let b=g.shapes[0];return b[0]===0&&b[1]===0&&b[2]===0&&b[3]===1&&b[4]===1&&b[5]===1}),l=-15,c=100,u=100;for(let v=-c;v<c;v++)for(let g=-u;g<u;g++){let b=o[Math.floor(Math.random()*o.length)];n.setBlockStateId(new kt(v,g,l),b.defaultState)}this._camera.updateProjectionMatrix(),this._camera.position.set(.5,u/2+.5,.5),this._camera.rotation.set(0,0,0);let d=new kt(...this._camera.position.toArray()),f=new M9(n,2,d);this.abortSignal.aborted||(this.worldRenderer=new this.WorldRendererClass(this.documentRenderer.renderer,this.options,{version:e,worldView:f,inWorldRenderingConfig:a8e,playerStateReactive:Y0e().reactive,rendererState:nL().reactive,nonReactiveState:nL().nonReactive,resourcesManager:t}),this.worldRenderer instanceof Yd&&(this._scene=this.worldRenderer.realScene,this._camera=this.worldRenderer.camera),f.init(d),await this.worldRenderer.waitForChunksToRender(),!this.abortSignal.aborted&&(this.setupMouseParallax(),console.timeEnd("load menu background scene")))}update(e,t){t&&Jd(this.camera,this.documentRenderer.canvas)}dispose(){this.worldRenderer?.destroy(),this.worldRenderer=void 0,this._scene.clear()}setupMouseParallax(){let e=this._camera,t=e.position.x,n=e.position.y,r;document.body.addEventListener("pointermove",s=>{if(s.pointerType!=="mouse")return;let a=.2,o=s.clientX/window.innerWidth-.5,l=-(s.clientY/window.innerHeight-.5);r?.stop(),r=new jr(e.position).to({x:t+o*a,y:n+l*a},0),r.start(),e.updateProjectionMatrix()},{signal:this.abortSignal})}};h();p();m();Lt();var wg=class{constructor(e,t,n={},r=!1){this.documentRenderer=e;this.options=t;this.mode=WP(n,r)}active;abortController=new AbortController;mode;lastFrameTime=0;get v2(){return this.active instanceof X5?this.active:void 0}get scene(){return this.active?.scene}get camera(){return this.active?.camera}async start(e={}){this.active=this.createImplementation(e),await this.active.init(),this.active.scene.background instanceof We&&this.documentRenderer.renderer.setClearColor(this.active.scene.background),this.lastFrameTime=performance.now(),this.documentRenderer.render=(t=!1)=>{let n=performance.now(),r=Math.min((n-this.lastFrameTime)/1e3,.05);this.lastFrameTime=n;let s=this.active;s&&(s.update(r,t),this.documentRenderer.renderer.render(s.scene,s.camera))}}createImplementation(e){switch(this.mode){case"v2":return new X5(this.documentRenderer,{useMinecraftTextures:e.useMinecraftTextures,initialScene:e.v2Scene,initialCamera:e.v2Camera,initialBlockGroup:e.v2BlockGroup,initialCameraSpeed:e.v2CameraSpeed,initialBlockSpeed:e.v2BlockSpeed,resourcesManager:e.resourcesManager},this.abortController.signal);case"worldBlocks":return new xg(this.documentRenderer,this.options,this.abortController.signal);default:return new pg(this.documentRenderer)}}dispose(){this.active?.dispose(),this.active=void 0,this.abortController.abort()}};h();p();m();var Kd=u0,SJe={rendererWorldPerformance:"normal",rendererMeshersCountOverride:null,starfieldRendering:!0,defaultSkybox:!0,menuBackgroundMode:Kd.mode,menuBackgroundMinecraftTextures:Kd.minecraftTextures,menuBackgroundV2Scene:Kd.v2Scene,menuBackgroundV2Camera:Kd.v2Camera,menuBackgroundV2BlockGroup:Kd.v2BlockGroup,menuBackgroundV2CameraSpeed:Kd.v2CameraSpeedPercent,menuBackgroundV2BlockSpeed:Kd.v2BlockSpeedPercent,rendererFuturisticReveal:!1,rendererPerfDebugOverlay:!1,disableBlockEntityTextures:!1,rendererMesher:"wasm",rendererShaderCubeDebugMode:"off",showChunkBorders:!1,renderEntities:!0,renderDebug:"basic",frameLimit:!1,backgroundRendering:"20fps",vanillaLook:!1,smoothLighting:!0,newVersionsLighting:!1,vrSupport:!0,vrPageGameRendering:!1,clipWorldBelowY:void 0,highlightBlockColor:"auto",loadPlayerSkins:!0,renderEars:!0,showHand:!0,viewBobbing:!0,dayCycleAndLighting:!0,keepChunksDistance:1,gpuPreference:"default",fov:75};var EJe={menuBackgroundMode:{possibleValues:[["classic","Classic"],["v2","V2"]],requiresRestart:!0},menuBackgroundMinecraftTextures:{text:"Minecraft block textures",tooltip:"Use block atlas on V2 menu cubes (loads assets on menu)"},menuBackgroundV2Scene:{possibleValues:q5.map(i=>[i,_9[i]])},menuBackgroundV2Camera:{possibleValues:G5.map(i=>[i,y9[i]])},menuBackgroundV2BlockGroup:{possibleValues:W5.map(i=>[i,b9[i]]),text:"Block pool",tooltip:"Block set for textured menu cubes (requires Minecraft textures)"},menuBackgroundV2CameraSpeed:{text:"Camera speed",tooltip:"Orbit / fly-through camera path speed. 0 freezes the path; mouse parallax still works.",min:0,max:200,unit:"%"},menuBackgroundV2BlockSpeed:{text:"Block speed",tooltip:"Floating blocks and sky rotation. Independent of camera path speed.",min:0,max:200,unit:"%"},rendererWorldPerformance:{text:"World performance",tooltip:"Background workers for chunk geometry. Recreates mesher workers and reloads chunks.",requiresChunksReload:!0,possibleValues:[["low-energy","Low Energy"],["normal","Normal"],["maximum","Maximum"]]},starfieldRendering:{text:"Starfield"},defaultSkybox:{text:"Default skybox"},rendererFuturisticReveal:{text:"Futuristic world reveal"},rendererPerfDebugOverlay:{text:"Performance debug overlay"},disableBlockEntityTextures:{text:"Disable block entity textures",tooltip:"Skips signs, banners, heads, maps, etc."},rendererMesher:{possibleValues:[["wasm","WASM"],["legacy-js","Legacy JS"]],text:"Mesher pipeline",tooltip:"Browser technology for processing world geometry before render. WASM is the fastest; if you see a dead tab icon, reloads, or other errors, switch to Legacy JS.",requiresChunksReload:!0},rendererShaderCubeDebugMode:{text:"Shader cube debug",tooltip:"Instanced cube path visualization (requires shader cubes enabled).",possibleValues:[["off","Off"],["holes","Hole test (red)"],["texIndex","Tile index colors"],["faces","Face id colors"],["atlasAlpha","Atlas alpha"]]},showChunkBorders:{text:"Chunk borders"},renderEntities:{text:"Render entities"},renderDebug:{possibleValues:["advanced","basic","none"]},frameLimit:{text:"Frame limit",tooltip:"false = VSync / unlimited when focused"},backgroundRendering:{text:"Background FPS limit",possibleValues:[["full","NO"],["5fps","5 FPS"],["20fps","20 FPS"]]},vanillaLook:{text:"Vanilla shading",tooltip:"On: Minecraft-style face shading. Off: higher-contrast client shading."},smoothLighting:{},newVersionsLighting:{text:"Lighting in newer versions"},vrSupport:{text:"VR support",tooltip:"Shows VR entry; does not force VR on."},vrPageGameRendering:{text:"VR page game rendering"},clipWorldBelowY:{text:"Clip world below Y"},highlightBlockColor:{possibleValues:[["auto","Auto"],["blue","Blue"],["classic","Classic"]]},loadPlayerSkins:{},renderEars:{tooltip:"Deadmau5 ears when the skin texture includes them"},showHand:{},viewBobbing:{},dayCycleAndLighting:{text:"Day cycle"},keepChunksDistance:{text:"Keep chunks distance",tooltip:"Extra distance before unloading chunks",max:5,unit:""},fov:{min:30,max:110,unit:"\xB0",text:"FOV"},gpuPreference:{text:"GPU preference",tooltip:"WebGL power preference. Requires reload / backend restart to apply.",requiresRestart:!0,possibleValues:[["default","Auto"],["high-performance","Dedicated"],["low-power","Low power"]]}};Ht.enabled=!1;globalThis.THREE=Gt;var o8e=i=>({updateMap:i.entities.updateMap.bind(i.entities),updateCustomBlock:i.updateCustomBlock.bind(i),getBlockInfo:i.getBlockInfo.bind(i),playEntityAnimation:i.entities.playAnimation.bind(i.entities),damageEntity:i.entities.handleDamageEvent.bind(i.entities),updatePlayerSkin:i.entities.updatePlayerSkin.bind(i.entities),applyTemporaryPlayerSkinOverride:i.entities.applyTemporaryPlayerSkinOverride.bind(i.entities),changeHandSwingingState:i.changeHandSwingingState.bind(i),getHighestBlocks:i.getHighestBlocks.bind(i),reloadWorld:i.reloadWorld.bind(i),updateEntityModel:i.entities.updateEntityModel.bind(i.entities),playEntityModelAnimation:i.entities.playEntityModelAnimation.bind(i.entities),addMedia:i.media.addMedia.bind(i.media),destroyMedia:i.media.destroyMedia.bind(i.media),setControlMode:i.media.setControlMode.bind(i.media),setVideoPlaying:i.media.setVideoPlaying.bind(i.media),setVideoSeeking:i.media.setVideoSeeking.bind(i.media),setVideoVolume:i.media.setVideoVolume.bind(i.media),setVideoSpeed:i.media.setVideoSpeed.bind(i.media),handleUserClick:i.media.handleUserClick.bind(i.media),addSectionAnimation(e,t){i.sectionsOffsetsAnimations[e]=t},removeSectionAnimation(e){delete i.sectionsOffsetsAnimations[e]},shakeFromDamage:i.cameraShake.shakeFromDamage.bind(i.cameraShake),onPageInteraction:i.media.onPageInteraction.bind(i.media),downloadMesherLog:i.downloadMesherLog.bind(i),explodeFirework:i.fireworksLegacy.explode.bind(i.fireworksLegacy),explodeFireworkFacingCamera:i.fireworksLegacy.explodeFacingCamera.bind(i.fireworksLegacy),addWaypoint:i.waypoints.addWaypoint.bind(i.waypoints),removeWaypoint:i.waypoints.removeWaypoint.bind(i.waypoints),startCinimaticScript:i.cinimaticScript.startScript.bind(i.cinimaticScript),stopCinimaticScript:i.cinimaticScript.stopScript.bind(i.cinimaticScript),launchFirework:i.fireworks.launchFirework.bind(i.fireworks),setSkyboxImage:i.skyboxRenderer.setSkyboxImage.bind(i.skyboxRenderer),setRain:i.setRain.bind(i),spawnBlockBreakParticles(e,t,n,r,s,a){i.getModule("blockBreakParticles")?.spawnBlockBreakParticles(e,t,n,r,s,a)},spawnBlockCrackParticle(e,t,n,r,s,a,o){i.getModule("blockBreakParticles")?.spawnCrackParticle(e,t,n,r,s,a,o)},async loadGeometryExport(e){let{applyWorldGeometryExport:t}=await Promise.resolve().then(()=>(AP(),j_e));return t(i,e)},feedChunkPacket(e){let{kind:t,...n}=e,r={type:t,...n};for(let s of i.workers)s.postMessage(r)},getChunksDebugState(){let e={};for(let t of Object.keys(i.sectionObjects)){let[n,,r]=t.split(",").map(Number);e[`${n},${r}`]=!0}return{loadedSectionsChunks:e,loadedChunks:{...i.loadedChunks},finishedChunks:{...i.finishedChunks}}}}),MJe=[],A9=(i,...e)=>{for(let t of Object.values(globalThis.loadedMods??{}))try{t.threeJsBackendModule?.[i]?.(...e)}catch(n){let r=`[mod three.js] Error calling ${i} on ${t.name}: ${n}`;throw new Error(r)}},l8e=()=>{let i,e=null,t=null,n=null,r=null,s=(u,d)=>{u.hello&&console.log("Thanks for using minecraft-renderer project: one of the most performant Minecraft world renderers for the web!"),Ln?i=u2(u,MJe,globalThis):i=u,e=new Q_(i,d?.canvas),globalThis.renderer=e.renderer,globalThis.documentRenderer=e,globalThis.threeJsBackend=c,A9("default",c)},a=async u=>{if(!e)throw new Error("Document renderer not initialized");n&&(n.destroy(),n=null,r=null,globalThis.world=void 0,globalThis.frameTimingCollector=void 0),t&&(t.dispose(),t=null);let d={...i.config.menuBackground,...u};t=new wg(e,{...i},d,!!process.env.SINGLE_FILE_BUILD_MODE),A9("menuBackgroundCreated",t),await t.start(d),A9("menuBackgroundReady",t)},o=async u=>{if(!e)throw new Error("Document renderer not initialized");t&&(t.dispose(),t=null),n&&(n.destroy(),n=null,r=null,globalThis.world=void 0,globalThis.frameTimingCollector=void 0);let f=Ln?u2(u,[lc,Y5],globalThis):u;e.nonReactiveState=f.nonReactiveState,globalThis.resourcesManager=f.resourcesManager,n=new Yd(e.renderer,i,f),await n.worldReadyPromise,r=f.inWorldRenderingConfig.enableDebugOverlay?new n4(f.nonReactiveState):null,globalThis.frameTimingCollector=r;let v=e.render;e.render=function(g){v.call(this,g),r?.markFrameStart(),f.inWorldRenderingConfig.paused||n?.render(g),r?.markFrameEnd(),r?.markFrameDisplay()},e.inWorldRenderingConfig=f.inWorldRenderingConfig,globalThis.world=n,A9("worldReady",n)},l=()=>{t&&(t.dispose(),t=null),e&&e.dispose(),n&&(n.destroy(),n=null)},c={id:"threejs",displayName:`three.js ${Ma}`,startMenuBackground:a,startWorld:o,disconnect:l,setRendering(u){e.setPaused(!u),n&&(n.renderingActive=u)},getMenuBackground:()=>t??void 0,getDebugOverlay:()=>({get entitiesString(){return n?.entities.getDebugString()},get left(){return{"Geo Memory":n?.chunkMeshManager.getEstimatedMemoryUsage().total??"-"}}}),updateCamera(u,d,f){r?.markCameraUpdate(!u),n?.setFirstPersonCamera(u,d,f)},get soundSystem(){return n?.soundSystem},get backendMethods(){if(n)return o8e(n)}};return{main:{init:s,backend:c},workerProxy(){return SN({init(u,d){s(u,{canvas:d})},updateSizeExternal(u,d,f){e?.updateSizeExternal(u,d,f)},startMenuBackground:a,startWorld:o,disconnect:l,setRendering:c.setRendering,updateCamera(u,d,f){let v=u?new kt(u.x,u.y,u.z):null;r?.markCameraUpdate(!v),c.updateCamera(v,d,f)},async callBackendMethod(u,...d){if(!n)throw new Error("World renderer not initialized");let v=o8e(n)[u];if(!v)throw new Error(`Backend method ${String(u)} is unavailable`);return v(...d)}})}}};globalThis.structuredClone??=i=>JSON.parse(JSON.stringify(i));var c8e=i=>{TB(i);let e=globalThis;e.mcData=i,e.loadedData=i,self.postMessage({type:"mcDataApplied"})};self.addEventListener("message",i=>{let e=i.data;if(e.type==="mcData"){c8e(e.mcData),console.log("data loaded");return}Array.isArray(e)&&e.forEach(t=>{t.type==="mcData"&&c8e(t.mcData)})});var AJe=l8e();AJe.workerProxy();})();
29584
29580
  /*! Bundled license information:
29585
29581
 
29586
29582
  @jspm/core/nodelibs/browser/chunk-DtuTasat.js: