minerender 2.1.0-alpha.86 → 2.1.0-alpha.87

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3156,6 +3156,41 @@ declare class AnvilParser {
3156
3156
  private static unpack;
3157
3157
  }
3158
3158
 
3159
+ /** Loads chunk columns at absolute integer chunk coordinates. */
3160
+ interface WorldChunkSource {
3161
+ /** Returns the requested column, or `undefined` if absent. Honor signal to cancel discarded reads. */
3162
+ getChunk(x: number, z: number, signal?: AbortSignal): Promise<AnvilChunk | undefined>;
3163
+ }
3164
+
3165
+ /**
3166
+ * Reads `r.<x>.<z>.mca` at integer region coordinates, or returns `undefined` when absent.
3167
+ * Forward `signal` to file or network I/O; it aborts when every caller waiting for the region cancels.
3168
+ */
3169
+ type AnvilRegionReader = (x: number, z: number, signal?: AbortSignal) => Promise<Uint8Array | ArrayBuffer | undefined>;
3170
+ /** Cache limits passed to `new AnvilWorldSource(readRegion, options)`. */
3171
+ interface AnvilWorldSourceOptions {
3172
+ /** Maximum cached regions, including missing regions. Defaults to 4; 0 disables caching. */
3173
+ maxCachedRegions?: number;
3174
+ /** Maximum retained region bytes. Defaults to 64 MiB; larger regions are read without caching. */
3175
+ maxCachedBytes?: number;
3176
+ }
3177
+ /** Reads selected Java Anvil chunk columns and caches raw regions within count and byte limits. */
3178
+ declare class AnvilWorldSource implements WorldChunkSource {
3179
+ private readonly readRegion;
3180
+ private readonly regions;
3181
+ private readonly pending;
3182
+ private readonly maxCachedRegions;
3183
+ private readonly maxCachedBytes;
3184
+ private cachedBytes;
3185
+ constructor(readRegion: AnvilRegionReader, options?: AnvilWorldSourceOptions);
3186
+ /** Decodes one column at absolute chunk coordinates. Aborting a caller leaves other shared readers active. */
3187
+ getChunk(x: number, z: number, signal?: AbortSignal): Promise<AnvilChunk | undefined>;
3188
+ /** Releases cached regions. Reads already in progress finish without repopulating this cache. */
3189
+ clearCache(): void;
3190
+ private getRegion;
3191
+ private cacheRegion;
3192
+ }
3193
+
3159
3194
  /** A placed block's data snapshot and optional render object, returned by world and chunk accessors. */
3160
3195
  interface BlockInfo<SectionMeshing extends boolean = false> {
3161
3196
  /** Detached block data; use world or chunk setters to update stored blocks. */
@@ -3315,6 +3350,73 @@ interface MineRenderWorldOptions<SectionMeshing extends boolean = boolean> {
3315
3350
  maxAtlasSize?: number;
3316
3351
  }
3317
3352
 
3353
+ interface WorldStreamerOptions {
3354
+ /** Loads a square of chunk columns around the center. Integer from 0 to 32; defaults to 2. */
3355
+ loadRadius?: number;
3356
+ /** Retains loaded columns within this radius. Defaults to loadRadius + 1, capped at 32. */
3357
+ unloadRadius?: number;
3358
+ }
3359
+ /**
3360
+ * Loads nearby chunk columns in distance order and unloads distant columns.
3361
+ * Updates coalesce to the latest center and serialize world mutations. Use a dedicated world:
3362
+ * the streamer replaces columns it loads, and callers must await disposal before editing that world.
3363
+ * The source remains caller-owned. Lighting, biome tint, and LOD are not added by streaming.
3364
+ */
3365
+ declare class WorldStreamer {
3366
+ private readonly world;
3367
+ private readonly source;
3368
+ private readonly loadRadius;
3369
+ private readonly unloadRadius;
3370
+ private readonly loaded;
3371
+ private readonly owned;
3372
+ private readonly missing;
3373
+ private readonly failed;
3374
+ private desired;
3375
+ private center?;
3376
+ private loading?;
3377
+ private running?;
3378
+ private disposal?;
3379
+ private disposed;
3380
+ constructor(world: Pick<MineRenderWorld<boolean>, "placeChunk" | "unloadChunkColumn">, source: WorldChunkSource, options?: WorldStreamerOptions);
3381
+ /** Returns absolute coordinates of successfully placed columns, including retained columns. */
3382
+ get loadedChunks(): readonly {
3383
+ x: number;
3384
+ z: number;
3385
+ }[];
3386
+ /** Returns source failures retained within the unload radius. Failed columns do not block other loads. */
3387
+ get failedChunks(): readonly {
3388
+ x: number;
3389
+ z: number;
3390
+ error: unknown;
3391
+ }[];
3392
+ /** Counts desired columns still waiting for a source read or placement, including the active column. */
3393
+ get pendingChunks(): number;
3394
+ /**
3395
+ * Updates the center in absolute chunk coordinates. Repeated calls share the active drain.
3396
+ * Source failures are recorded in failedChunks; other columns continue loading. Missing and failed
3397
+ * columns are remembered within the retention radius. Call retryFailedChunks to retry source failures.
3398
+ * Placement and unload failures reject the drain; call update again to retry those operations.
3399
+ * Reads outside the latest load radius receive an abort signal; placement finishes before unloading.
3400
+ * Sources should represent an unchanged world during streaming.
3401
+ */
3402
+ update(x: number, z: number): Promise<void>;
3403
+ /** Updates from a camera or view-center position in scene units. One chunk spans 256 scene units. */
3404
+ updatePosition(position: {
3405
+ x: number;
3406
+ z: number;
3407
+ }): Promise<void>;
3408
+ /** Forgets recorded source failures and retries desired columns at the latest center. */
3409
+ retryFailedChunks(): Promise<void>;
3410
+ /** Aborts source reads, waits for active work, then unloads owned columns. The world and source remain caller-owned. */
3411
+ dispose(): Promise<void>;
3412
+ private drain;
3413
+ private needsLoad;
3414
+ private unload;
3415
+ private validateChunk;
3416
+ private within;
3417
+ private key;
3418
+ }
3419
+
3318
3420
  /**
3319
3421
  * {@link EnvProvider} backed by the DOM. Uses nothing outside of standard browser APIs and
3320
3422
  * localforage, so it stays free of Node polyfills.
@@ -3352,4 +3454,4 @@ declare class BrowserCache extends PersistentCache<LocalForage> {
3352
3454
  */
3353
3455
  declare function probeImageSize(data: Uint8Array): ImageSizeInfo;
3354
3456
 
3355
- export { AXES, type AnimationFrame, type AnimationMeta, type AnimatorFunction, type AnvilChunk, AnvilParser, type AnvilRegion, ArchiveAssetSource, type ArchiveAssetSourceOptions, type ArchiveEntry, type ArchiveProxy, AssetKey, AssetLoadError, AssetLoader, AssetParser, AssetSource, type AssetType, Assets, Axis, BUILTIN_ENTITY, BUILTIN_GENERATED, type BannerPattern, type BannerPatternDraw, BannerPatterns, BasicAssetKey, type BasicMinecraftAsset, BatchedExecutor, type BedrockBone, type BedrockCube, type BedrockEntityDescription, type BedrockEntityFile, type BedrockGeometry, type BedrockGeometryFile, type BitmapFont, type BitmapGlyph, type Block, BlockEntities, type BlockEntityEntry, type BlockEntityIndex, type BlockEntityPart, type BlockEntityRotation, type BlockFluidState, type BlockInfo, type BlockModel, type BlockModelTextures, BlockObject, type BlockObjectOptions, type BlockState, type BlockStateMultipart, type BlockStateProperties, type BlockStateProperty, type BlockStatePropertyDefaults, type BlockStatePropertyValue, BlockStateResolver, type BlockStateVariant, type BlockStateVariants, BlockStates, BlockTints, type BoxGeometryKey, BrowserArchiveProxy, BrowserCache, BrowserEnv, CUBE_FACES, CUBE_FACE_OFFSETS, type CacheKey, Caching, type CameraOptions, CanvasImage, type CapeLayout, Chunk, ChunkData, Colormaps, type CompatCanvas, type CompatImage, type ComposerOptions, type ControlsOptions, CubeFace, CubeFaceIndex, DEFAULT_ELEMENTS, DEFAULT_NAMESPACE, DEFAULT_ROOT, DEFAULT_UV, DISPLAY_POSITIONS, DYE_COLORS, type DebugOptions, type DeepPartial, DefaultBlockStates, DisplayPosition, DisplayTransforms, type Disposable, type DoubleArray, type DyeColor, ENTITY_ANIMATION_CHANNELS, type ElementFace, type ElementRotation, Entities, type EntityAnimation, type EntityAnimationBone, type EntityAnimationChannel, type EntityAnimationFile, type EntityAnimationKeyframe, type EntityAnimationOptions, EntityAnimationPlayer, type EntityAnimationPose, type EntityLayer, type EntityModel, type EntityModelCube, type EntityModelFile, type EntityModelLayer, type EntityModelOptions, type EntityModelPart, type EntityModelPass, EntityObject, type EntityObjectOptions, type EntityRenderMode, type EntityTransformOp, Env, type EnvProvider, type ExtractableImageData, type FluidKind, FluidModelObject, type FluidSample, type FluidSampler, Fonts, type FrameCallback, type FromTo, GUI_CONTAINER_LAYOUTS, Geometries, type GuiBookButtonState, type GuiBookOptions, type GuiBossBarColor, type GuiBossBarOptions, type GuiContainerType, GuiHelper, type GuiItemLayer, type GuiLayer, GuiLight, GuiObject, type GuiObjectOptions, type GuiRecipe, type GuiRecipeIngredient, type GuiRecipeOptions, type GuiSpriteScaling, type GuiText, type GuiTextLayer, type GuiTextLayout, type GuiTextOptions, type GuiTextRun, type GuiTextStyle, type GuiTextureLayer, type GuiTooltipOptions, HostedAssetSource, type IModelTextures, ITEM_GENERATED, type ImageInfo, ImageLoader, type ImageSizeInfo, InstanceManager, InstanceReference, type Instanceable, type ItemModel, type ItemModelContext, type ItemModelTextures, type ItemTintColor, type ItemTintSource, ItemTints, type ListAsset, type LoadedSceneDocument, type LoadedSceneObject, MapControls, type MaterialKey, Materials, type Maybe, type MeshKey, Meshes, MineRenderError, MineRenderScene, type MineRenderSceneOptions, MineRenderWorld, type MineRenderWorldOptions, type MinecraftAsset, MinecraftCubeTexture, MinecraftFaceUV, type MinecraftTextureMeta, type Model, ModelCulling, type ModelDisplay, type ModelElement, type ModelFaces, ModelGenerator, ModelMerger, ModelObject, type ModelObjectOptions, ModelTextures, Models, type MultiBlockBlock, type MultiBlockEntity, type MultiBlockStructure, type MultipartCondition, type NBTAsset, NBTHelper, OrbitControls, type PackFormat, PackFormats, PackMetadata, PersistentCache, type PositionedGuiGlyph, type QuadArray, type RawImageKey, type RenderOptions, Renderer, type RendererFrame, type RendererOptions, type RequestConfig, RequestError, type RequestResponse, Requests, type ResolvedBlockEntity, type ResponseParser, SKIN_PARTS, type SceneBlockDefinition, type SceneDocument, SceneDocumentLoader, type SceneEntityDefinition, SceneExporter, type SceneGLTFExportOptions, type SceneGuiDefinition, type SceneGuiLayer, SceneInspector, type SceneModelDefinition, SceneObject, type SceneObjectDefinition, type SceneObjectDefinitionBase, type SceneObjectOptions, type SceneSkinDefinition, type SceneSkinPosePart, SceneStats, SceneStatsDisplay, SchematicParser, type SchematicParserOptions, SectionMesh, type SectionMeshEntry, type SectionMeshTemplate, SectionModels, type Serializable, type SkinGeometries, SkinImage, SkinObject, type SkinObjectOptions, SkinPart, type SkinTexture, type SkinTextureCoordinates, SkinTextures, Skins, type SpecialItemPart, type SpecialItemRenderer, SpecialItems, type StructureNBT, StructureParser, type TextureAsset, TextureAtlas, type TextureKey, TextureLoader, Textures, Ticker, type TickerFunction, TintColors, type Transformable, type TripleArray, UVMapper, type VideoExportOptions, VideoExporter, WrappedImage, addBox3WireframeToObject, addWireframeToMesh, addWireframeToObject, applyElementRotation, applyGenericRotation, axisToVec3, base64decode, base64encode, capeTextureSizes, captureException, changeEvent, clampRotationDegrees, classicSkinGeometries, classicSkinTextureCoordinates, computeMorphedAttributes, createCanvas, createFluidGeometry, createGuiTextGeometry, createGuiTextureGeometry, createImage, entityAnimationTime, estimateBytesUsed, getBlockFluidState, getFluidKind, interleaveAttributes, isAssetKey, isBasicAssetKey, isBlockObject, isDisposable, isDoubleArray, isEntityObject, isGuiObject, isInstanceManager, isInstanceReference, isInstanceable, isInstancedMesh, isMesh, isMineRenderScene, isModelObject, isObject3D, isOrthographicCamera, isPerspectiveCamera, isQuadArray, isSceneObject, isTransformable, isTripleArray, isVector3, layoutGuiText, md5, mergeBufferAttributes, mergeBufferGeometries, mergeVertices, parseSceneDocument, prefix, probeImageSize, registerBrowserEnv, sampleEntityAnimation, sampleEntityKeyframes, sampleFluid, serializeBoxGeometryKey, serializeImageKey, serializeMaterialKey, serializeMeshKey, serializeTextureKey, sha1, sha256, sha512, shutdown, sleep, slimSkinGeometries, slimSkinTextureCoordinates, timingEnd, timingStart, toDegrees, toRadians, toTrianglesDrawMode, trimCanvas };
3457
+ export { AXES, type AnimationFrame, type AnimationMeta, type AnimatorFunction, type AnvilChunk, AnvilParser, type AnvilRegion, type AnvilRegionReader, AnvilWorldSource, type AnvilWorldSourceOptions, ArchiveAssetSource, type ArchiveAssetSourceOptions, type ArchiveEntry, type ArchiveProxy, AssetKey, AssetLoadError, AssetLoader, AssetParser, AssetSource, type AssetType, Assets, Axis, BUILTIN_ENTITY, BUILTIN_GENERATED, type BannerPattern, type BannerPatternDraw, BannerPatterns, BasicAssetKey, type BasicMinecraftAsset, BatchedExecutor, type BedrockBone, type BedrockCube, type BedrockEntityDescription, type BedrockEntityFile, type BedrockGeometry, type BedrockGeometryFile, type BitmapFont, type BitmapGlyph, type Block, BlockEntities, type BlockEntityEntry, type BlockEntityIndex, type BlockEntityPart, type BlockEntityRotation, type BlockFluidState, type BlockInfo, type BlockModel, type BlockModelTextures, BlockObject, type BlockObjectOptions, type BlockState, type BlockStateMultipart, type BlockStateProperties, type BlockStateProperty, type BlockStatePropertyDefaults, type BlockStatePropertyValue, BlockStateResolver, type BlockStateVariant, type BlockStateVariants, BlockStates, BlockTints, type BoxGeometryKey, BrowserArchiveProxy, BrowserCache, BrowserEnv, CUBE_FACES, CUBE_FACE_OFFSETS, type CacheKey, Caching, type CameraOptions, CanvasImage, type CapeLayout, Chunk, ChunkData, Colormaps, type CompatCanvas, type CompatImage, type ComposerOptions, type ControlsOptions, CubeFace, CubeFaceIndex, DEFAULT_ELEMENTS, DEFAULT_NAMESPACE, DEFAULT_ROOT, DEFAULT_UV, DISPLAY_POSITIONS, DYE_COLORS, type DebugOptions, type DeepPartial, DefaultBlockStates, DisplayPosition, DisplayTransforms, type Disposable, type DoubleArray, type DyeColor, ENTITY_ANIMATION_CHANNELS, type ElementFace, type ElementRotation, Entities, type EntityAnimation, type EntityAnimationBone, type EntityAnimationChannel, type EntityAnimationFile, type EntityAnimationKeyframe, type EntityAnimationOptions, EntityAnimationPlayer, type EntityAnimationPose, type EntityLayer, type EntityModel, type EntityModelCube, type EntityModelFile, type EntityModelLayer, type EntityModelOptions, type EntityModelPart, type EntityModelPass, EntityObject, type EntityObjectOptions, type EntityRenderMode, type EntityTransformOp, Env, type EnvProvider, type ExtractableImageData, type FluidKind, FluidModelObject, type FluidSample, type FluidSampler, Fonts, type FrameCallback, type FromTo, GUI_CONTAINER_LAYOUTS, Geometries, type GuiBookButtonState, type GuiBookOptions, type GuiBossBarColor, type GuiBossBarOptions, type GuiContainerType, GuiHelper, type GuiItemLayer, type GuiLayer, GuiLight, GuiObject, type GuiObjectOptions, type GuiRecipe, type GuiRecipeIngredient, type GuiRecipeOptions, type GuiSpriteScaling, type GuiText, type GuiTextLayer, type GuiTextLayout, type GuiTextOptions, type GuiTextRun, type GuiTextStyle, type GuiTextureLayer, type GuiTooltipOptions, HostedAssetSource, type IModelTextures, ITEM_GENERATED, type ImageInfo, ImageLoader, type ImageSizeInfo, InstanceManager, InstanceReference, type Instanceable, type ItemModel, type ItemModelContext, type ItemModelTextures, type ItemTintColor, type ItemTintSource, ItemTints, type ListAsset, type LoadedSceneDocument, type LoadedSceneObject, MapControls, type MaterialKey, Materials, type Maybe, type MeshKey, Meshes, MineRenderError, MineRenderScene, type MineRenderSceneOptions, MineRenderWorld, type MineRenderWorldOptions, type MinecraftAsset, MinecraftCubeTexture, MinecraftFaceUV, type MinecraftTextureMeta, type Model, ModelCulling, type ModelDisplay, type ModelElement, type ModelFaces, ModelGenerator, ModelMerger, ModelObject, type ModelObjectOptions, ModelTextures, Models, type MultiBlockBlock, type MultiBlockEntity, type MultiBlockStructure, type MultipartCondition, type NBTAsset, NBTHelper, OrbitControls, type PackFormat, PackFormats, PackMetadata, PersistentCache, type PositionedGuiGlyph, type QuadArray, type RawImageKey, type RenderOptions, Renderer, type RendererFrame, type RendererOptions, type RequestConfig, RequestError, type RequestResponse, Requests, type ResolvedBlockEntity, type ResponseParser, SKIN_PARTS, type SceneBlockDefinition, type SceneDocument, SceneDocumentLoader, type SceneEntityDefinition, SceneExporter, type SceneGLTFExportOptions, type SceneGuiDefinition, type SceneGuiLayer, SceneInspector, type SceneModelDefinition, SceneObject, type SceneObjectDefinition, type SceneObjectDefinitionBase, type SceneObjectOptions, type SceneSkinDefinition, type SceneSkinPosePart, SceneStats, SceneStatsDisplay, SchematicParser, type SchematicParserOptions, SectionMesh, type SectionMeshEntry, type SectionMeshTemplate, SectionModels, type Serializable, type SkinGeometries, SkinImage, SkinObject, type SkinObjectOptions, SkinPart, type SkinTexture, type SkinTextureCoordinates, SkinTextures, Skins, type SpecialItemPart, type SpecialItemRenderer, SpecialItems, type StructureNBT, StructureParser, type TextureAsset, TextureAtlas, type TextureKey, TextureLoader, Textures, Ticker, type TickerFunction, TintColors, type Transformable, type TripleArray, UVMapper, type VideoExportOptions, VideoExporter, type WorldChunkSource, WorldStreamer, type WorldStreamerOptions, WrappedImage, addBox3WireframeToObject, addWireframeToMesh, addWireframeToObject, applyElementRotation, applyGenericRotation, axisToVec3, base64decode, base64encode, capeTextureSizes, captureException, changeEvent, clampRotationDegrees, classicSkinGeometries, classicSkinTextureCoordinates, computeMorphedAttributes, createCanvas, createFluidGeometry, createGuiTextGeometry, createGuiTextureGeometry, createImage, entityAnimationTime, estimateBytesUsed, getBlockFluidState, getFluidKind, interleaveAttributes, isAssetKey, isBasicAssetKey, isBlockObject, isDisposable, isDoubleArray, isEntityObject, isGuiObject, isInstanceManager, isInstanceReference, isInstanceable, isInstancedMesh, isMesh, isMineRenderScene, isModelObject, isObject3D, isOrthographicCamera, isPerspectiveCamera, isQuadArray, isSceneObject, isTransformable, isTripleArray, isVector3, layoutGuiText, md5, mergeBufferAttributes, mergeBufferGeometries, mergeVertices, parseSceneDocument, prefix, probeImageSize, registerBrowserEnv, sampleEntityAnimation, sampleEntityKeyframes, sampleFluid, serializeBoxGeometryKey, serializeImageKey, serializeMaterialKey, serializeMeshKey, serializeTextureKey, sha1, sha256, sha512, shutdown, sleep, slimSkinGeometries, slimSkinTextureCoordinates, timingEnd, timingStart, toDegrees, toRadians, toTrianglesDrawMode, trimCanvas };
@@ -3156,6 +3156,41 @@ declare class AnvilParser {
3156
3156
  private static unpack;
3157
3157
  }
3158
3158
 
3159
+ /** Loads chunk columns at absolute integer chunk coordinates. */
3160
+ interface WorldChunkSource {
3161
+ /** Returns the requested column, or `undefined` if absent. Honor signal to cancel discarded reads. */
3162
+ getChunk(x: number, z: number, signal?: AbortSignal): Promise<AnvilChunk | undefined>;
3163
+ }
3164
+
3165
+ /**
3166
+ * Reads `r.<x>.<z>.mca` at integer region coordinates, or returns `undefined` when absent.
3167
+ * Forward `signal` to file or network I/O; it aborts when every caller waiting for the region cancels.
3168
+ */
3169
+ type AnvilRegionReader = (x: number, z: number, signal?: AbortSignal) => Promise<Uint8Array | ArrayBuffer | undefined>;
3170
+ /** Cache limits passed to `new AnvilWorldSource(readRegion, options)`. */
3171
+ interface AnvilWorldSourceOptions {
3172
+ /** Maximum cached regions, including missing regions. Defaults to 4; 0 disables caching. */
3173
+ maxCachedRegions?: number;
3174
+ /** Maximum retained region bytes. Defaults to 64 MiB; larger regions are read without caching. */
3175
+ maxCachedBytes?: number;
3176
+ }
3177
+ /** Reads selected Java Anvil chunk columns and caches raw regions within count and byte limits. */
3178
+ declare class AnvilWorldSource implements WorldChunkSource {
3179
+ private readonly readRegion;
3180
+ private readonly regions;
3181
+ private readonly pending;
3182
+ private readonly maxCachedRegions;
3183
+ private readonly maxCachedBytes;
3184
+ private cachedBytes;
3185
+ constructor(readRegion: AnvilRegionReader, options?: AnvilWorldSourceOptions);
3186
+ /** Decodes one column at absolute chunk coordinates. Aborting a caller leaves other shared readers active. */
3187
+ getChunk(x: number, z: number, signal?: AbortSignal): Promise<AnvilChunk | undefined>;
3188
+ /** Releases cached regions. Reads already in progress finish without repopulating this cache. */
3189
+ clearCache(): void;
3190
+ private getRegion;
3191
+ private cacheRegion;
3192
+ }
3193
+
3159
3194
  /** A placed block's data snapshot and optional render object, returned by world and chunk accessors. */
3160
3195
  interface BlockInfo<SectionMeshing extends boolean = false> {
3161
3196
  /** Detached block data; use world or chunk setters to update stored blocks. */
@@ -3315,6 +3350,73 @@ interface MineRenderWorldOptions<SectionMeshing extends boolean = boolean> {
3315
3350
  maxAtlasSize?: number;
3316
3351
  }
3317
3352
 
3353
+ interface WorldStreamerOptions {
3354
+ /** Loads a square of chunk columns around the center. Integer from 0 to 32; defaults to 2. */
3355
+ loadRadius?: number;
3356
+ /** Retains loaded columns within this radius. Defaults to loadRadius + 1, capped at 32. */
3357
+ unloadRadius?: number;
3358
+ }
3359
+ /**
3360
+ * Loads nearby chunk columns in distance order and unloads distant columns.
3361
+ * Updates coalesce to the latest center and serialize world mutations. Use a dedicated world:
3362
+ * the streamer replaces columns it loads, and callers must await disposal before editing that world.
3363
+ * The source remains caller-owned. Lighting, biome tint, and LOD are not added by streaming.
3364
+ */
3365
+ declare class WorldStreamer {
3366
+ private readonly world;
3367
+ private readonly source;
3368
+ private readonly loadRadius;
3369
+ private readonly unloadRadius;
3370
+ private readonly loaded;
3371
+ private readonly owned;
3372
+ private readonly missing;
3373
+ private readonly failed;
3374
+ private desired;
3375
+ private center?;
3376
+ private loading?;
3377
+ private running?;
3378
+ private disposal?;
3379
+ private disposed;
3380
+ constructor(world: Pick<MineRenderWorld<boolean>, "placeChunk" | "unloadChunkColumn">, source: WorldChunkSource, options?: WorldStreamerOptions);
3381
+ /** Returns absolute coordinates of successfully placed columns, including retained columns. */
3382
+ get loadedChunks(): readonly {
3383
+ x: number;
3384
+ z: number;
3385
+ }[];
3386
+ /** Returns source failures retained within the unload radius. Failed columns do not block other loads. */
3387
+ get failedChunks(): readonly {
3388
+ x: number;
3389
+ z: number;
3390
+ error: unknown;
3391
+ }[];
3392
+ /** Counts desired columns still waiting for a source read or placement, including the active column. */
3393
+ get pendingChunks(): number;
3394
+ /**
3395
+ * Updates the center in absolute chunk coordinates. Repeated calls share the active drain.
3396
+ * Source failures are recorded in failedChunks; other columns continue loading. Missing and failed
3397
+ * columns are remembered within the retention radius. Call retryFailedChunks to retry source failures.
3398
+ * Placement and unload failures reject the drain; call update again to retry those operations.
3399
+ * Reads outside the latest load radius receive an abort signal; placement finishes before unloading.
3400
+ * Sources should represent an unchanged world during streaming.
3401
+ */
3402
+ update(x: number, z: number): Promise<void>;
3403
+ /** Updates from a camera or view-center position in scene units. One chunk spans 256 scene units. */
3404
+ updatePosition(position: {
3405
+ x: number;
3406
+ z: number;
3407
+ }): Promise<void>;
3408
+ /** Forgets recorded source failures and retries desired columns at the latest center. */
3409
+ retryFailedChunks(): Promise<void>;
3410
+ /** Aborts source reads, waits for active work, then unloads owned columns. The world and source remain caller-owned. */
3411
+ dispose(): Promise<void>;
3412
+ private drain;
3413
+ private needsLoad;
3414
+ private unload;
3415
+ private validateChunk;
3416
+ private within;
3417
+ private key;
3418
+ }
3419
+
3318
3420
  /**
3319
3421
  * {@link EnvProvider} backed by the DOM. Uses nothing outside of standard browser APIs and
3320
3422
  * localforage, so it stays free of Node polyfills.
@@ -3352,4 +3454,4 @@ declare class BrowserCache extends PersistentCache<LocalForage> {
3352
3454
  */
3353
3455
  declare function probeImageSize(data: Uint8Array): ImageSizeInfo;
3354
3456
 
3355
- export { AXES, type AnimationFrame, type AnimationMeta, type AnimatorFunction, type AnvilChunk, AnvilParser, type AnvilRegion, ArchiveAssetSource, type ArchiveAssetSourceOptions, type ArchiveEntry, type ArchiveProxy, AssetKey, AssetLoadError, AssetLoader, AssetParser, AssetSource, type AssetType, Assets, Axis, BUILTIN_ENTITY, BUILTIN_GENERATED, type BannerPattern, type BannerPatternDraw, BannerPatterns, BasicAssetKey, type BasicMinecraftAsset, BatchedExecutor, type BedrockBone, type BedrockCube, type BedrockEntityDescription, type BedrockEntityFile, type BedrockGeometry, type BedrockGeometryFile, type BitmapFont, type BitmapGlyph, type Block, BlockEntities, type BlockEntityEntry, type BlockEntityIndex, type BlockEntityPart, type BlockEntityRotation, type BlockFluidState, type BlockInfo, type BlockModel, type BlockModelTextures, BlockObject, type BlockObjectOptions, type BlockState, type BlockStateMultipart, type BlockStateProperties, type BlockStateProperty, type BlockStatePropertyDefaults, type BlockStatePropertyValue, BlockStateResolver, type BlockStateVariant, type BlockStateVariants, BlockStates, BlockTints, type BoxGeometryKey, BrowserArchiveProxy, BrowserCache, BrowserEnv, CUBE_FACES, CUBE_FACE_OFFSETS, type CacheKey, Caching, type CameraOptions, CanvasImage, type CapeLayout, Chunk, ChunkData, Colormaps, type CompatCanvas, type CompatImage, type ComposerOptions, type ControlsOptions, CubeFace, CubeFaceIndex, DEFAULT_ELEMENTS, DEFAULT_NAMESPACE, DEFAULT_ROOT, DEFAULT_UV, DISPLAY_POSITIONS, DYE_COLORS, type DebugOptions, type DeepPartial, DefaultBlockStates, DisplayPosition, DisplayTransforms, type Disposable, type DoubleArray, type DyeColor, ENTITY_ANIMATION_CHANNELS, type ElementFace, type ElementRotation, Entities, type EntityAnimation, type EntityAnimationBone, type EntityAnimationChannel, type EntityAnimationFile, type EntityAnimationKeyframe, type EntityAnimationOptions, EntityAnimationPlayer, type EntityAnimationPose, type EntityLayer, type EntityModel, type EntityModelCube, type EntityModelFile, type EntityModelLayer, type EntityModelOptions, type EntityModelPart, type EntityModelPass, EntityObject, type EntityObjectOptions, type EntityRenderMode, type EntityTransformOp, Env, type EnvProvider, type ExtractableImageData, type FluidKind, FluidModelObject, type FluidSample, type FluidSampler, Fonts, type FrameCallback, type FromTo, GUI_CONTAINER_LAYOUTS, Geometries, type GuiBookButtonState, type GuiBookOptions, type GuiBossBarColor, type GuiBossBarOptions, type GuiContainerType, GuiHelper, type GuiItemLayer, type GuiLayer, GuiLight, GuiObject, type GuiObjectOptions, type GuiRecipe, type GuiRecipeIngredient, type GuiRecipeOptions, type GuiSpriteScaling, type GuiText, type GuiTextLayer, type GuiTextLayout, type GuiTextOptions, type GuiTextRun, type GuiTextStyle, type GuiTextureLayer, type GuiTooltipOptions, HostedAssetSource, type IModelTextures, ITEM_GENERATED, type ImageInfo, ImageLoader, type ImageSizeInfo, InstanceManager, InstanceReference, type Instanceable, type ItemModel, type ItemModelContext, type ItemModelTextures, type ItemTintColor, type ItemTintSource, ItemTints, type ListAsset, type LoadedSceneDocument, type LoadedSceneObject, MapControls, type MaterialKey, Materials, type Maybe, type MeshKey, Meshes, MineRenderError, MineRenderScene, type MineRenderSceneOptions, MineRenderWorld, type MineRenderWorldOptions, type MinecraftAsset, MinecraftCubeTexture, MinecraftFaceUV, type MinecraftTextureMeta, type Model, ModelCulling, type ModelDisplay, type ModelElement, type ModelFaces, ModelGenerator, ModelMerger, ModelObject, type ModelObjectOptions, ModelTextures, Models, type MultiBlockBlock, type MultiBlockEntity, type MultiBlockStructure, type MultipartCondition, type NBTAsset, NBTHelper, OrbitControls, type PackFormat, PackFormats, PackMetadata, PersistentCache, type PositionedGuiGlyph, type QuadArray, type RawImageKey, type RenderOptions, Renderer, type RendererFrame, type RendererOptions, type RequestConfig, RequestError, type RequestResponse, Requests, type ResolvedBlockEntity, type ResponseParser, SKIN_PARTS, type SceneBlockDefinition, type SceneDocument, SceneDocumentLoader, type SceneEntityDefinition, SceneExporter, type SceneGLTFExportOptions, type SceneGuiDefinition, type SceneGuiLayer, SceneInspector, type SceneModelDefinition, SceneObject, type SceneObjectDefinition, type SceneObjectDefinitionBase, type SceneObjectOptions, type SceneSkinDefinition, type SceneSkinPosePart, SceneStats, SceneStatsDisplay, SchematicParser, type SchematicParserOptions, SectionMesh, type SectionMeshEntry, type SectionMeshTemplate, SectionModels, type Serializable, type SkinGeometries, SkinImage, SkinObject, type SkinObjectOptions, SkinPart, type SkinTexture, type SkinTextureCoordinates, SkinTextures, Skins, type SpecialItemPart, type SpecialItemRenderer, SpecialItems, type StructureNBT, StructureParser, type TextureAsset, TextureAtlas, type TextureKey, TextureLoader, Textures, Ticker, type TickerFunction, TintColors, type Transformable, type TripleArray, UVMapper, type VideoExportOptions, VideoExporter, WrappedImage, addBox3WireframeToObject, addWireframeToMesh, addWireframeToObject, applyElementRotation, applyGenericRotation, axisToVec3, base64decode, base64encode, capeTextureSizes, captureException, changeEvent, clampRotationDegrees, classicSkinGeometries, classicSkinTextureCoordinates, computeMorphedAttributes, createCanvas, createFluidGeometry, createGuiTextGeometry, createGuiTextureGeometry, createImage, entityAnimationTime, estimateBytesUsed, getBlockFluidState, getFluidKind, interleaveAttributes, isAssetKey, isBasicAssetKey, isBlockObject, isDisposable, isDoubleArray, isEntityObject, isGuiObject, isInstanceManager, isInstanceReference, isInstanceable, isInstancedMesh, isMesh, isMineRenderScene, isModelObject, isObject3D, isOrthographicCamera, isPerspectiveCamera, isQuadArray, isSceneObject, isTransformable, isTripleArray, isVector3, layoutGuiText, md5, mergeBufferAttributes, mergeBufferGeometries, mergeVertices, parseSceneDocument, prefix, probeImageSize, registerBrowserEnv, sampleEntityAnimation, sampleEntityKeyframes, sampleFluid, serializeBoxGeometryKey, serializeImageKey, serializeMaterialKey, serializeMeshKey, serializeTextureKey, sha1, sha256, sha512, shutdown, sleep, slimSkinGeometries, slimSkinTextureCoordinates, timingEnd, timingStart, toDegrees, toRadians, toTrianglesDrawMode, trimCanvas };
3457
+ export { AXES, type AnimationFrame, type AnimationMeta, type AnimatorFunction, type AnvilChunk, AnvilParser, type AnvilRegion, type AnvilRegionReader, AnvilWorldSource, type AnvilWorldSourceOptions, ArchiveAssetSource, type ArchiveAssetSourceOptions, type ArchiveEntry, type ArchiveProxy, AssetKey, AssetLoadError, AssetLoader, AssetParser, AssetSource, type AssetType, Assets, Axis, BUILTIN_ENTITY, BUILTIN_GENERATED, type BannerPattern, type BannerPatternDraw, BannerPatterns, BasicAssetKey, type BasicMinecraftAsset, BatchedExecutor, type BedrockBone, type BedrockCube, type BedrockEntityDescription, type BedrockEntityFile, type BedrockGeometry, type BedrockGeometryFile, type BitmapFont, type BitmapGlyph, type Block, BlockEntities, type BlockEntityEntry, type BlockEntityIndex, type BlockEntityPart, type BlockEntityRotation, type BlockFluidState, type BlockInfo, type BlockModel, type BlockModelTextures, BlockObject, type BlockObjectOptions, type BlockState, type BlockStateMultipart, type BlockStateProperties, type BlockStateProperty, type BlockStatePropertyDefaults, type BlockStatePropertyValue, BlockStateResolver, type BlockStateVariant, type BlockStateVariants, BlockStates, BlockTints, type BoxGeometryKey, BrowserArchiveProxy, BrowserCache, BrowserEnv, CUBE_FACES, CUBE_FACE_OFFSETS, type CacheKey, Caching, type CameraOptions, CanvasImage, type CapeLayout, Chunk, ChunkData, Colormaps, type CompatCanvas, type CompatImage, type ComposerOptions, type ControlsOptions, CubeFace, CubeFaceIndex, DEFAULT_ELEMENTS, DEFAULT_NAMESPACE, DEFAULT_ROOT, DEFAULT_UV, DISPLAY_POSITIONS, DYE_COLORS, type DebugOptions, type DeepPartial, DefaultBlockStates, DisplayPosition, DisplayTransforms, type Disposable, type DoubleArray, type DyeColor, ENTITY_ANIMATION_CHANNELS, type ElementFace, type ElementRotation, Entities, type EntityAnimation, type EntityAnimationBone, type EntityAnimationChannel, type EntityAnimationFile, type EntityAnimationKeyframe, type EntityAnimationOptions, EntityAnimationPlayer, type EntityAnimationPose, type EntityLayer, type EntityModel, type EntityModelCube, type EntityModelFile, type EntityModelLayer, type EntityModelOptions, type EntityModelPart, type EntityModelPass, EntityObject, type EntityObjectOptions, type EntityRenderMode, type EntityTransformOp, Env, type EnvProvider, type ExtractableImageData, type FluidKind, FluidModelObject, type FluidSample, type FluidSampler, Fonts, type FrameCallback, type FromTo, GUI_CONTAINER_LAYOUTS, Geometries, type GuiBookButtonState, type GuiBookOptions, type GuiBossBarColor, type GuiBossBarOptions, type GuiContainerType, GuiHelper, type GuiItemLayer, type GuiLayer, GuiLight, GuiObject, type GuiObjectOptions, type GuiRecipe, type GuiRecipeIngredient, type GuiRecipeOptions, type GuiSpriteScaling, type GuiText, type GuiTextLayer, type GuiTextLayout, type GuiTextOptions, type GuiTextRun, type GuiTextStyle, type GuiTextureLayer, type GuiTooltipOptions, HostedAssetSource, type IModelTextures, ITEM_GENERATED, type ImageInfo, ImageLoader, type ImageSizeInfo, InstanceManager, InstanceReference, type Instanceable, type ItemModel, type ItemModelContext, type ItemModelTextures, type ItemTintColor, type ItemTintSource, ItemTints, type ListAsset, type LoadedSceneDocument, type LoadedSceneObject, MapControls, type MaterialKey, Materials, type Maybe, type MeshKey, Meshes, MineRenderError, MineRenderScene, type MineRenderSceneOptions, MineRenderWorld, type MineRenderWorldOptions, type MinecraftAsset, MinecraftCubeTexture, MinecraftFaceUV, type MinecraftTextureMeta, type Model, ModelCulling, type ModelDisplay, type ModelElement, type ModelFaces, ModelGenerator, ModelMerger, ModelObject, type ModelObjectOptions, ModelTextures, Models, type MultiBlockBlock, type MultiBlockEntity, type MultiBlockStructure, type MultipartCondition, type NBTAsset, NBTHelper, OrbitControls, type PackFormat, PackFormats, PackMetadata, PersistentCache, type PositionedGuiGlyph, type QuadArray, type RawImageKey, type RenderOptions, Renderer, type RendererFrame, type RendererOptions, type RequestConfig, RequestError, type RequestResponse, Requests, type ResolvedBlockEntity, type ResponseParser, SKIN_PARTS, type SceneBlockDefinition, type SceneDocument, SceneDocumentLoader, type SceneEntityDefinition, SceneExporter, type SceneGLTFExportOptions, type SceneGuiDefinition, type SceneGuiLayer, SceneInspector, type SceneModelDefinition, SceneObject, type SceneObjectDefinition, type SceneObjectDefinitionBase, type SceneObjectOptions, type SceneSkinDefinition, type SceneSkinPosePart, SceneStats, SceneStatsDisplay, SchematicParser, type SchematicParserOptions, SectionMesh, type SectionMeshEntry, type SectionMeshTemplate, SectionModels, type Serializable, type SkinGeometries, SkinImage, SkinObject, type SkinObjectOptions, SkinPart, type SkinTexture, type SkinTextureCoordinates, SkinTextures, Skins, type SpecialItemPart, type SpecialItemRenderer, SpecialItems, type StructureNBT, StructureParser, type TextureAsset, TextureAtlas, type TextureKey, TextureLoader, Textures, Ticker, type TickerFunction, TintColors, type Transformable, type TripleArray, UVMapper, type VideoExportOptions, VideoExporter, type WorldChunkSource, WorldStreamer, type WorldStreamerOptions, WrappedImage, addBox3WireframeToObject, addWireframeToMesh, addWireframeToObject, applyElementRotation, applyGenericRotation, axisToVec3, base64decode, base64encode, capeTextureSizes, captureException, changeEvent, clampRotationDegrees, classicSkinGeometries, classicSkinTextureCoordinates, computeMorphedAttributes, createCanvas, createFluidGeometry, createGuiTextGeometry, createGuiTextureGeometry, createImage, entityAnimationTime, estimateBytesUsed, getBlockFluidState, getFluidKind, interleaveAttributes, isAssetKey, isBasicAssetKey, isBlockObject, isDisposable, isDoubleArray, isEntityObject, isGuiObject, isInstanceManager, isInstanceReference, isInstanceable, isInstancedMesh, isMesh, isMineRenderScene, isModelObject, isObject3D, isOrthographicCamera, isPerspectiveCamera, isQuadArray, isSceneObject, isTransformable, isTripleArray, isVector3, layoutGuiText, md5, mergeBufferAttributes, mergeBufferGeometries, mergeVertices, parseSceneDocument, prefix, probeImageSize, registerBrowserEnv, sampleEntityAnimation, sampleEntityKeyframes, sampleFluid, serializeBoxGeometryKey, serializeImageKey, serializeMaterialKey, serializeMeshKey, serializeTextureKey, sha1, sha256, sha512, shutdown, sleep, slimSkinGeometries, slimSkinTextureCoordinates, timingEnd, timingStart, toDegrees, toRadians, toTrianglesDrawMode, trimCanvas };
@@ -18688,6 +18688,7 @@ var index_browser_exports = {};
18688
18688
  __export(index_browser_exports, {
18689
18689
  AXES: () => AXES,
18690
18690
  AnvilParser: () => AnvilParser,
18691
+ AnvilWorldSource: () => AnvilWorldSource,
18691
18692
  ArchiveAssetSource: () => ArchiveAssetSource,
18692
18693
  AssetKey: () => AssetKey,
18693
18694
  AssetLoadError: () => AssetLoadError,
@@ -18791,6 +18792,7 @@ __export(index_browser_exports, {
18791
18792
  TintColors: () => TintColors,
18792
18793
  UVMapper: () => UVMapper,
18793
18794
  VideoExporter: () => VideoExporter,
18795
+ WorldStreamer: () => WorldStreamer,
18794
18796
  WrappedImage: () => WrappedImage,
18795
18797
  addBox3WireframeToObject: () => addBox3WireframeToObject,
18796
18798
  addWireframeToMesh: () => addWireframeToMesh,
@@ -28896,6 +28898,134 @@ var AnvilParser = class {
28896
28898
  }
28897
28899
  };
28898
28900
 
28901
+ // src/world/AnvilWorldSource.ts
28902
+ init_MineRenderError();
28903
+ async function abortable2(promise, signal) {
28904
+ if (!signal) return promise;
28905
+ let abort;
28906
+ const cancelled = new Promise((_, reject) => {
28907
+ abort = () => reject(signal.reason);
28908
+ signal.addEventListener("abort", abort, { once: true });
28909
+ if (signal.aborted) abort();
28910
+ });
28911
+ try {
28912
+ return await Promise.race([promise, cancelled]);
28913
+ } finally {
28914
+ signal.removeEventListener("abort", abort);
28915
+ }
28916
+ }
28917
+ var AnvilWorldSource = class {
28918
+ constructor(readRegion, options = {}) {
28919
+ this.readRegion = readRegion;
28920
+ this.regions = /* @__PURE__ */ new Map();
28921
+ this.pending = /* @__PURE__ */ new Map();
28922
+ this.cachedBytes = 0;
28923
+ this.maxCachedRegions = options.maxCachedRegions ?? 4;
28924
+ this.maxCachedBytes = options.maxCachedBytes ?? 64 * 1024 * 1024;
28925
+ for (const [name, value] of Object.entries({ maxCachedRegions: this.maxCachedRegions, maxCachedBytes: this.maxCachedBytes })) {
28926
+ if (!Number.isSafeInteger(value) || value < 0) throw new RangeError(`${name} must be a nonnegative safe integer`);
28927
+ }
28928
+ }
28929
+ /** Decodes one column at absolute chunk coordinates. Aborting a caller leaves other shared readers active. */
28930
+ async getChunk(x, z, signal) {
28931
+ if (!Number.isSafeInteger(x) || !Number.isSafeInteger(z)) {
28932
+ throw new RangeError("Chunk column coordinates must be safe integers");
28933
+ }
28934
+ const regionX = Math.floor(x / 32), regionZ = Math.floor(z / 32);
28935
+ const data = await this.getRegion(regionX, regionZ, signal);
28936
+ signal?.throwIfAborted();
28937
+ if (!data) return void 0;
28938
+ const chunk = await abortable2(AnvilParser.parseChunk(data, x - regionX * 32, z - regionZ * 32), signal);
28939
+ signal?.throwIfAborted();
28940
+ if (chunk && (chunk.x !== x || chunk.z !== z)) {
28941
+ throw new MineRenderError(`Anvil chunk coordinates ${chunk.x},${chunk.z} do not match requested column ${x},${z}`);
28942
+ }
28943
+ return chunk;
28944
+ }
28945
+ /** Releases cached regions. Reads already in progress finish without repopulating this cache. */
28946
+ clearCache() {
28947
+ this.regions.clear();
28948
+ this.pending.clear();
28949
+ this.cachedBytes = 0;
28950
+ }
28951
+ getRegion(x, z, signal) {
28952
+ signal?.throwIfAborted();
28953
+ const key = `${x},${z}`;
28954
+ const cached2 = this.regions.get(key);
28955
+ if (cached2) {
28956
+ this.regions.delete(key);
28957
+ this.regions.set(key, cached2);
28958
+ return Promise.resolve(cached2.data);
28959
+ }
28960
+ let loading = this.pending.get(key);
28961
+ if (!loading) {
28962
+ const controller = new AbortController();
28963
+ loading = {
28964
+ controller,
28965
+ waiters: 0,
28966
+ settled: false,
28967
+ promise: Promise.resolve().then(() => {
28968
+ controller.signal.throwIfAborted();
28969
+ return this.readRegion(x, z, controller.signal);
28970
+ }).then((data) => {
28971
+ controller.signal.throwIfAborted();
28972
+ let bytes = data instanceof Uint8Array ? data : data === void 0 ? void 0 : new Uint8Array(data);
28973
+ if (bytes && bytes.byteLength !== bytes.buffer.byteLength) bytes = new Uint8Array(bytes);
28974
+ if (bytes) AnvilParser.getChunkList(bytes);
28975
+ loading.settled = true;
28976
+ if (this.pending.get(key) === loading) this.cacheRegion(key, bytes);
28977
+ return bytes;
28978
+ }).finally(() => {
28979
+ loading.settled = true;
28980
+ if (this.pending.get(key) === loading) this.pending.delete(key);
28981
+ })
28982
+ };
28983
+ this.pending.set(key, loading);
28984
+ }
28985
+ const read = loading;
28986
+ read.waiters++;
28987
+ return new Promise((resolve, reject) => {
28988
+ let finished = false;
28989
+ const release = () => {
28990
+ if (finished) return false;
28991
+ finished = true;
28992
+ signal?.removeEventListener("abort", abort);
28993
+ read.waiters--;
28994
+ return true;
28995
+ };
28996
+ const abort = () => {
28997
+ if (!release()) return;
28998
+ if (!read.waiters && !read.settled) {
28999
+ if (this.pending.get(key) === read) this.pending.delete(key);
29000
+ read.controller.abort(signal.reason);
29001
+ }
29002
+ reject(signal.reason);
29003
+ };
29004
+ signal?.addEventListener("abort", abort, { once: true });
29005
+ read.promise.then(
29006
+ (data) => {
29007
+ if (release()) resolve(data);
29008
+ },
29009
+ (error) => {
29010
+ if (release()) reject(error);
29011
+ }
29012
+ );
29013
+ if (signal?.aborted) abort();
29014
+ });
29015
+ }
29016
+ cacheRegion(key, data) {
29017
+ const size = data?.byteLength ?? 0;
29018
+ if (!this.maxCachedRegions || size > this.maxCachedBytes) return;
29019
+ this.regions.set(key, { data, size });
29020
+ this.cachedBytes += size;
29021
+ while (this.regions.size > this.maxCachedRegions || this.cachedBytes > this.maxCachedBytes) {
29022
+ const oldest = this.regions.keys().next().value;
29023
+ this.cachedBytes -= this.regions.get(oldest).size;
29024
+ this.regions.delete(oldest);
29025
+ }
29026
+ }
29027
+ };
29028
+
28899
29029
  // src/world/Chunk.ts
28900
29030
  var import_three42 = require("three");
28901
29031
  init_BlockStates();
@@ -29570,4 +29700,178 @@ var Chunk = class _Chunk {
29570
29700
  );
29571
29701
  }
29572
29702
  };
29703
+
29704
+ // src/world/WorldStreamer.ts
29705
+ var WorldStreamer = class {
29706
+ constructor(world, source, options = {}) {
29707
+ this.world = world;
29708
+ this.source = source;
29709
+ this.loaded = /* @__PURE__ */ new Map();
29710
+ this.owned = /* @__PURE__ */ new Map();
29711
+ this.missing = /* @__PURE__ */ new Map();
29712
+ this.failed = /* @__PURE__ */ new Map();
29713
+ this.desired = [];
29714
+ this.disposed = false;
29715
+ this.loadRadius = options.loadRadius ?? 2;
29716
+ this.unloadRadius = options.unloadRadius ?? Math.min(32, this.loadRadius + 1);
29717
+ if (![this.loadRadius, this.unloadRadius].every((value) => Number.isInteger(value) && value >= 0 && value <= 32) || this.unloadRadius < this.loadRadius) {
29718
+ throw new RangeError("Chunk radii must be integers from 0 to 32, with unloadRadius at least loadRadius");
29719
+ }
29720
+ }
29721
+ /** Returns absolute coordinates of successfully placed columns, including retained columns. */
29722
+ get loadedChunks() {
29723
+ return [...this.loaded.values()].map((position) => ({ ...position }));
29724
+ }
29725
+ /** Returns source failures retained within the unload radius. Failed columns do not block other loads. */
29726
+ get failedChunks() {
29727
+ return [...this.failed.values()].map((failure) => ({ ...failure }));
29728
+ }
29729
+ /** Counts desired columns still waiting for a source read or placement, including the active column. */
29730
+ get pendingChunks() {
29731
+ return this.desired.filter((position) => this.needsLoad(position)).length;
29732
+ }
29733
+ /**
29734
+ * Updates the center in absolute chunk coordinates. Repeated calls share the active drain.
29735
+ * Source failures are recorded in failedChunks; other columns continue loading. Missing and failed
29736
+ * columns are remembered within the retention radius. Call retryFailedChunks to retry source failures.
29737
+ * Placement and unload failures reject the drain; call update again to retry those operations.
29738
+ * Reads outside the latest load radius receive an abort signal; placement finishes before unloading.
29739
+ * Sources should represent an unchanged world during streaming.
29740
+ */
29741
+ async update(x, z) {
29742
+ if (this.disposed) throw new Error("WorldStreamer is disposed");
29743
+ if (![x, z].every((value) => Number.isSafeInteger(value) && Number.isSafeInteger(value - this.unloadRadius) && Number.isSafeInteger(value + this.unloadRadius))) {
29744
+ throw new RangeError("Chunk coordinates must be safe integers within the streaming radius");
29745
+ }
29746
+ if (!this.center || this.center.x !== x || this.center.z !== z) {
29747
+ this.center = { x, z };
29748
+ this.desired = [];
29749
+ for (let dz = -this.loadRadius; dz <= this.loadRadius; dz++) {
29750
+ for (let dx = -this.loadRadius; dx <= this.loadRadius; dx++) {
29751
+ this.desired.push({ x: x + dx, z: z + dz });
29752
+ }
29753
+ }
29754
+ this.desired.sort((a, b) => (a.x - x) ** 2 + (a.z - z) ** 2 - (b.x - x) ** 2 - (b.z - z) ** 2);
29755
+ if (this.loading && !this.within(this.loading.position, this.loadRadius)) {
29756
+ this.loading.controller.abort();
29757
+ }
29758
+ }
29759
+ return this.running ?? (this.running = Promise.resolve().then(() => this.drain()));
29760
+ }
29761
+ /** Updates from a camera or view-center position in scene units. One chunk spans 256 scene units. */
29762
+ async updatePosition(position) {
29763
+ if (![position.x, position.z].every(Number.isFinite)) throw new RangeError("Scene coordinates must be finite");
29764
+ return this.update(Math.floor(position.x / 256), Math.floor(position.z / 256));
29765
+ }
29766
+ /** Forgets recorded source failures and retries desired columns at the latest center. */
29767
+ async retryFailedChunks() {
29768
+ if (this.disposed) throw new Error("WorldStreamer is disposed");
29769
+ this.failed.clear();
29770
+ if (this.center) await this.update(this.center.x, this.center.z);
29771
+ }
29772
+ /** Aborts source reads, waits for active work, then unloads owned columns. The world and source remain caller-owned. */
29773
+ dispose() {
29774
+ this.disposed = true;
29775
+ this.desired = [];
29776
+ this.center = void 0;
29777
+ this.loading?.controller.abort();
29778
+ return this.disposal ?? (this.disposal = Promise.resolve().then(async () => {
29779
+ await this.running?.catch(() => void 0);
29780
+ let failure;
29781
+ let failed = false;
29782
+ for (const position of this.owned.values()) {
29783
+ try {
29784
+ await this.unload(position);
29785
+ } catch (error) {
29786
+ failed = true;
29787
+ failure ?? (failure = error);
29788
+ }
29789
+ }
29790
+ this.missing.clear();
29791
+ this.failed.clear();
29792
+ if (failed) throw failure;
29793
+ }).catch((error) => {
29794
+ this.disposal = void 0;
29795
+ throw error;
29796
+ }));
29797
+ }
29798
+ async drain() {
29799
+ try {
29800
+ while (!this.disposed) {
29801
+ for (const [key, position2] of this.missing) {
29802
+ if (!this.within(position2, this.unloadRadius)) this.missing.delete(key);
29803
+ }
29804
+ for (const [key, position2] of this.failed) {
29805
+ if (!this.within(position2, this.unloadRadius)) this.failed.delete(key);
29806
+ }
29807
+ const obsolete = [...this.owned.values()].find((position2) => !this.loaded.has(this.key(position2)) || !this.within(position2, this.unloadRadius));
29808
+ if (obsolete) {
29809
+ await this.unload(obsolete);
29810
+ continue;
29811
+ }
29812
+ const position = this.desired.find((position2) => this.needsLoad(position2));
29813
+ if (!position) return;
29814
+ let chunk;
29815
+ const controller = new AbortController();
29816
+ this.loading = { position, controller };
29817
+ try {
29818
+ chunk = await this.source.getChunk(position.x, position.z, controller.signal);
29819
+ if (chunk) this.validateChunk(chunk, position);
29820
+ } catch (error) {
29821
+ if (!controller.signal.aborted && !this.disposed && this.within(position, this.loadRadius)) {
29822
+ this.failed.set(this.key(position), { ...position, error });
29823
+ }
29824
+ continue;
29825
+ } finally {
29826
+ this.loading = void 0;
29827
+ }
29828
+ if (controller.signal.aborted || this.disposed || !this.within(position, this.loadRadius)) continue;
29829
+ if (!chunk) {
29830
+ this.missing.set(this.key(position), position);
29831
+ continue;
29832
+ }
29833
+ this.owned.set(this.key(position), position);
29834
+ try {
29835
+ await this.world.placeChunk(chunk);
29836
+ this.loaded.set(this.key(position), position);
29837
+ } catch (error) {
29838
+ try {
29839
+ await this.unload(position);
29840
+ } catch (cleanupError) {
29841
+ const failure = error instanceof Error ? error : new Error(String(error));
29842
+ try {
29843
+ Object.defineProperty(failure, "cause", { value: cleanupError, configurable: true });
29844
+ } catch {
29845
+ throw Object.assign(new Error(failure.message), { cause: cleanupError });
29846
+ }
29847
+ throw failure;
29848
+ }
29849
+ throw error;
29850
+ }
29851
+ }
29852
+ } finally {
29853
+ this.running = void 0;
29854
+ }
29855
+ }
29856
+ needsLoad(position) {
29857
+ const key = this.key(position);
29858
+ return !this.loaded.has(key) && !this.missing.has(key) && !this.failed.has(key);
29859
+ }
29860
+ async unload(position) {
29861
+ await this.world.unloadChunkColumn(position.x, position.z);
29862
+ this.owned.delete(this.key(position));
29863
+ this.loaded.delete(this.key(position));
29864
+ }
29865
+ validateChunk(chunk, position) {
29866
+ if (chunk.x !== position.x || chunk.z !== position.z) {
29867
+ throw new Error(`World source returned chunk ${chunk.x},${chunk.z} for ${position.x},${position.z}`);
29868
+ }
29869
+ }
29870
+ within(position, radius) {
29871
+ return !!this.center && Math.abs(position.x - this.center.x) <= radius && Math.abs(position.z - this.center.z) <= radius;
29872
+ }
29873
+ key(position) {
29874
+ return `${position.x},${position.z}`;
29875
+ }
29876
+ };
29573
29877
  //# sourceMappingURL=index.js.map