// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later import { AIR, CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts"; import { SECTION_HEIGHT, type WorldShape } from "@/common/world_shape.ts"; import { biome_in, ChunkColumn, column_heights, type ColumnBiomes, Section, SECTION_VOLUME } from "@/common/section.ts"; import { BlockRegistry, EverythingRegistry, light_tables } from "@/common/everything_registry.ts"; import { generate_raw_chunk, RawChunk, WorldgenSetup } from "@/common/generation.ts"; import { AIR_ID } from "@/common/protocol.ts"; import { block_value, chunk_key } from "@/common/utils.ts"; import { block_numbering } from "@/common/worldgen_bundle.ts"; import { LruMap } from "./lru.ts"; import { collision_shape_at, EMPTY_SHAPE, type Shape } from "@/common/block_shapes.ts"; import { farming_day } from "@/common/time.ts"; import { encode_level_chunk } from "@/common/chunk_streaming.ts"; import { ChunkBlocks, decode_chunk, encode_chunk, SavedChunk, SavedChunks } from "./saves.ts"; // generation only, rebuilt when needed. 16 KB for each section that isn't all one block, about 7 of a 256 tall // chunk's 16. with a worldgen pool, it holds what the pool made until the // chunks are built, a few dozen chunks ahead of what players are sent const RAW_CACHE_SIZE = 256; const CHUNK_CACHE_SIZE = 256; // a raw chunk's spills and biomes, a few KB each, kept longer than its blocks: building a chunk needs its own raw // blocks and only its neighbors' spills const SPILL_CACHE_SIZE = 4096; // surface and sky heights, 1 KB each const COLUMN_CACHE_SIZE = 1024; // light reaches at most this far, see light_at const LIGHT_REACH = 15; const LIGHT_BOX = LIGHT_REACH * 2 + 1; // how far from the middle of the world to look for dry land to spawn on, in chunks const SPAWN_SEARCH_CHUNKS = 32; // the chunks around the middle the spawn search usually finds land in, with their neighbors, worth generating ahead export const SPAWN_AREA_CHUNKS = 3; // a block with data the server keeps, like where a chest's items are. only client_data is sent to clients export interface Tile { id: string; x: number; y: number; z: number; // what BlockRef.data holds mod_data?: unknown; // the fields clients see, see BlockRef.set_client_data. only set through set_tile_client_data, which replaces the // object, so a saved copy of the tile never changes under the save client_data?: Record; // false when its components turned ticking off for it, see GameServer.set_tile_ticking ticking?: false; } // some of the tiles, kept by chunk so a chunk's are found without going through every tile in the world class ChunkTiles { #chunks = new Map>(); get empty() { return this.#chunks.size === 0; } // adds or removes it set(tile: Tile, has: boolean) { const key = tile_chunk_key(tile); let tiles = this.#chunks.get(key); if (has) { if (!tiles) { tiles = new Set(); this.#chunks.set(key, tiles); } tiles.add(tile); } else if (tiles?.delete(tile) && tiles.size === 0) { this.#chunks.delete(key); } } has(tile: Tile) { return this.#chunks.get(tile_chunk_key(tile))?.has(tile) ?? false; } in_chunk(chunk_x: number, chunk_z: number): Iterable { return this.#chunks.get(chunk_key(chunk_x, chunk_z)) ?? []; } } function tile_chunk_key(tile: Tile) { return chunk_key(Math.floor(tile.x / CHUNK_SIZE), Math.floor(tile.z / CHUNK_SIZE)); } // a chunk as it is now, loaded from the save or generated interface LoadedChunk { column: ChunkColumn; // saved blocks of mods that are gone, by index in the chunk (see #index). air in column, and saved again until // replaced unknown?: Map; } export function position_key(x: number, y: number, z: number) { return `${x},${y},${z}`; } // the authoritative world: chunks from the save, and generated ones where there's nothing saved yet export class ServerWorld { readonly seed: string; readonly block_ids: Record = {}; readonly worldgen: WorldgenSetup; // the dimension's height and sky light, chunks hold all of it readonly shape: WorldShape; // what a freshly placed or generated block stores, by numeric id: the id with its default states readonly default_values: number[] = []; // for light_at, by numeric id #opacity: Uint8Array; #emission: Uint8Array; // what generation made, and the chunks as they are, with neighbors' leaves and player changes. unsaved chunks // that are forgotten are kept in #evicted until they're saved #raw = new LruMap(RAW_CACHE_SIZE); #chunks = new LruMap(CHUNK_CACHE_SIZE, (key, chunk) => this.#evict(key, chunk)); // what generation decided each column's biome is, and what it put in neighbors, kept for longer than the rest #biomes = new LruMap(SPILL_CACHE_SIZE); #spills = new LruMap(SPILL_CACHE_SIZE); // raw chunks generated on this thread because nothing had made them yet: with a worldgen pool, what still waits // on generation. see GameServer's /tps fallbacks = 0; // what called for them, by the caller's place in the code, when set. for finding what to move off the fallback fallback_callers?: Map; // per column of a chunk, the highest block that isn't air, then the lowest y that sees the sky. see #columns_of #columns = new LruMap(COLUMN_CACHE_SIZE); // where saved chunks are read from, and which there are, by chunk_key. chunks saved this session are added #saved_chunks: SavedChunks | undefined; #saved = new Set(); // chunks generated or changed since they were last saved, by chunk_key #unsaved = new Map(); // unsaved chunks #chunks forgot, ready to save, by chunk_key #evicted = new Map(); tiles = new Map(); // the tiles with client data, to send with their chunk #client_tiles = new ChunkTiles(); // the tiles that tick, which the game decides, see GameServer.set_tile_ticking #ticking_tiles = new ChunkTiles(); // ticks since 06:00 of day 1, see common/time.ts time = 0; // days since the world started, see farming_day in common/time.ts get day() { return farming_day(this.time); } // set when anything that gets saved changes dirty = false; on_block_change?: (x: number, y: number, z: number, id: string, state: number) => void; // the fields that changed, null for the ones that are gone on_client_data_change?: (x: number, y: number, z: number, changed: Record) => void; constructor(seed: string, worldgen: WorldgenSetup) { this.seed = seed; this.worldgen = worldgen; this.shape = worldgen.shape; // numbered the same way as generation in a worker numbers them, see common/worldgen_bundle.ts const { block_ids, default_values } = block_numbering(); Object.assign(this.block_ids, block_ids); this.default_values.push(...default_values); const tables = light_tables(EverythingRegistry.get_registry("blocks")); this.#opacity = tables.opacity; this.#emission = tables.emission; } #spawn: { x: number; y: number; z: number } | undefined; // where new players start: the ground closest to the middle of the world, like minecraft's world spawn. ground is // a column whose top block has collision, so not water or a plant spawn_point() { if (!this.#spawn) { this.#spawn = this.#find_spawn(); } return this.#spawn; } #find_spawn() { const { min_y, max_y } = this.shape; // chunks in rings around the middle, one column each for (let radius = 0; radius <= SPAWN_SEARCH_CHUNKS; radius++) { for (let cz = -radius; cz <= radius; cz++) { for (let cx = -radius; cx <= radius; cx++) { if (Math.max(Math.abs(cx), Math.abs(cz)) !== radius) continue; const x = cx * CHUNK_SIZE + CHUNK_SIZE / 2; const z = cz * CHUNK_SIZE + CHUNK_SIZE / 2; let y = max_y - 1; while (y > min_y && this.get_block_nid(x, y, z) === AIR) y--; if (y > min_y && this.get_block_info(x, y, z)?.has_collision) { return { x: x + 0.5, y: y + 1, z: z + 0.5 }; } } } } return { x: 0.5, y: max_y - 1, z: 0.5 }; } get_block_id(x: number, y: number, z: number): string { const nid = this.get_block_nid(x, y, z); return nid === AIR ? AIR_ID : EverythingRegistry.get_by_id("blocks", nid)?.id ?? AIR_ID; } get_block_nid(x: number, y: number, z: number): number { if (!this.shape.contains(y)) { return AIR; } const chunk_x = Math.floor(x / CHUNK_SIZE); const chunk_z = Math.floor(z / CHUNK_SIZE); return this.#get_chunk(chunk_x, chunk_z).get(x, y, z) & ID_MASK; } // the id with its state bits get_block_value(x: number, y: number, z: number): number { if (!this.shape.contains(y)) { return AIR; } const chunk_x = Math.floor(x / CHUNK_SIZE); const chunk_z = Math.floor(z / CHUNK_SIZE); return this.#get_chunk(chunk_x, chunk_z).get(x, y, z); } // whether entities bump into the block there, water and other blocks with "collision": false don't has_collision(x: number, y: number, z: number) { return this.get_block_info(x, y, z)?.has_collision ?? false; } // what entities bump into there, see common/physics.ts collision_shape(x: number, y: number, z: number): Shape { const value = this.get_block_value(x, y, z); const nid = value & ID_MASK; const block = nid === AIR ? undefined : EverythingRegistry.get_by_id("blocks", nid); return block ? collision_shape_at(block, value) : EMPTY_SHAPE; } get_block_info(x: number, y: number, z: number): BlockRegistry | undefined { const nid = this.get_block_nid(x, y, z); return nid === AIR ? undefined : EverythingRegistry.get_by_id("blocks", nid); } // the highest y in a column where it's this biome without generating its chunk, a little off near coasts and // cliffs, see NoiseTerrain.locate_biome locate_biome(biome: string, x: number, z: number): number | undefined { return this.worldgen.generator.for_seed(this.seed).locate_biome(biome, x, z, this.shape.min_y); } // like "bworld:plains", what generation decided. one per block across and every 4 blocks up, see ChunkColumn biome_at(x: number, y: number, z: number): string { const chunk_x = Math.floor(x / CHUNK_SIZE); const chunk_z = Math.floor(z / CHUNK_SIZE); return biome_in(this.#chunk_biomes(chunk_x, chunk_z), this.shape, x, y, z); } // a saved chunk's are the ones saved with it, which loads it. other chunks' come from generation without building // them #chunk_biomes(chunk_x: number, chunk_z: number) { const key = chunk_key(chunk_x, chunk_z); const chunk = this.#chunks.get(key); if (chunk) return chunk.column.biomes; if (this.#is_saved(key)) return this.#get_loaded(chunk_x, chunk_z).column.biomes; return this.#biomes.get(key) ?? this.#get_raw(chunk_x, chunk_z).column.biomes; } // builds the chunk now if it isn't, generating what it needs on this thread build(chunk_x: number, chunk_z: number) { this.#get_chunk(chunk_x, chunk_z); } // whether the chunk is built and kept, like a loaded chunk in minecraft. nothing builds one by asking has_chunk(chunk_x: number, chunk_z: number) { return this.#chunks.has(chunk_key(chunk_x, chunk_z)); } // whether the chunk was ever generated: it's kept, or saved, so reading it generates nothing. it may not be in // memory, then reading it decodes it from the save is_generated(chunk_x: number, chunk_z: number) { const key = chunk_key(chunk_x, chunk_z); return this.#chunks.has(key) || this.#is_saved(key); } // counts as using the chunk so it's kept longer, if it's there. returns whether it is, see has_chunk keep_chunk(chunk_x: number, chunk_z: number) { return this.#chunks.get(chunk_key(chunk_x, chunk_z)) !== undefined; } // where in a kept chunk (see has_chunk) the blocks are whose numeric id is set in wanted, as x, y, z. nothing when // the chunk isn't kept. sections that are all a block that isn't wanted are passed over find_blocks(chunk_x: number, chunk_z: number, wanted: Uint8Array): [number, number, number][] { const column = this.#chunks.get(chunk_key(chunk_x, chunk_z))?.column; if (!column) return []; const found: [number, number, number][] = []; column.sections.forEach((section, s) => { if (section.blocks === null && !wanted[section.value & ID_MASK]) return; for (let i = 0; i < SECTION_VOLUME; i++) { if (!wanted[section.get(i) & ID_MASK]) continue; found.push([ chunk_x * CHUNK_SIZE + (i & 15), this.shape.min_y + s * 16 + (i >> 8), chunk_z * CHUNK_SIZE + ((i >> 4) & 15), ]); } }); return found; } // what generation makes in a chunk, neighbors' spills included, without what players changed. built again every // call, for comparing generation (tests/worldgen_golden_test.ts) generated_blocks(chunk_x: number, chunk_z: number): ChunkColumn { return this.#generate_chunk(chunk_x, chunk_z); } // whether every chunk within radius blocks of x, z is, see has_chunk has_chunks_around(x: number, z: number, radius: number) { for (let cx = Math.floor((x - radius) / CHUNK_SIZE); cx <= Math.floor((x + radius) / CHUNK_SIZE); cx++) { for (let cz = Math.floor((z - radius) / CHUNK_SIZE); cz <= Math.floor((z + radius) / CHUNK_SIZE); cz++) { if (!this.has_chunk(cx, cz)) return false; } } return true; } // how much light going through the block there loses, 0-15 light_opacity(x: number, y: number, z: number) { return this.#opacity[this.get_block_nid(x, y, z)]; } // the highest block that isn't air, min_y - 1 for an empty column. minecraft's WORLD_SURFACE heightmap surface_height(x: number, z: number): number { return this.#columns_of(x, z)[column_index(x, z)]; } // the lowest y with nothing above it that stops light, where sky light is 15 sky_height(x: number, z: number): number { return this.#columns_of(x, z)[CHUNK_AREA + column_index(x, z)]; } // the sky and block light there, 0-15, the same as clients work out (see client/workers/lighting.ts) but for one // position: searching out from it, cheapest first, for the brightest place light could come from. light loses // max(1, opacity) for every block it goes into, and never gets further than 15 blocks. no sky light at all in a // dimension without it light_at(x: number, y: number, z: number): { sky: number; block: number } { const { min_y, max_y, sky_light } = this.shape; if (y >= max_y) return { sky: sky_light ? 15 : 0, block: 0 }; if (y < min_y) return { sky: 0, block: 0 }; // the box around it, 3x3 chunks at most, fetched once each. blocks are in it by their offset from the start const first_x = Math.floor((x - LIGHT_REACH) / CHUNK_SIZE); const first_z = Math.floor((z - LIGHT_REACH) / CHUNK_SIZE); const chunks: (ChunkColumn | undefined)[] = []; const skies: (Int16Array | undefined)[] = []; const box_index = (dx: number, dy: number, dz: number) => ((dy + LIGHT_REACH) * LIGHT_BOX + dz + LIGHT_REACH) * LIGHT_BOX + dx + LIGHT_REACH; // what light loses on its way from a block to the start. 255 is not reached yet const cost = new Uint8Array(LIGHT_BOX ** 3).fill(255); const queues: number[][] = Array.from({ length: LIGHT_REACH }, () => []); let next = 0; const reach = (dx: number, dy: number, dz: number) => { if (y + dy < min_y || y + dy >= max_y) return; const at = box_index(dx, dy, dz); if (cost[at] <= next) return; cost[at] = next; queues[next].push(dx, dy, dz); }; reach(0, 0, 0); let sky = 0; let block = 0; for (let lost = 0; lost < LIGHT_REACH; lost++) { // nothing further away can be brighter than what's been found if (LIGHT_REACH - lost <= sky && LIGHT_REACH - lost <= block) break; const queue = queues[lost]; for (let i = 0; i < queue.length; i += 3) { const dx = queue[i], dy = queue[i + 1], dz = queue[i + 2]; if (cost[box_index(dx, dy, dz)] !== lost) continue; const bx = x + dx, by = y + dy, bz = z + dz; const chunk_x = Math.floor(bx / CHUNK_SIZE); const chunk_z = Math.floor(bz / CHUNK_SIZE); const which = (chunk_z - first_z) * 3 + chunk_x - first_x; const blocks = chunks[which] ??= this.#get_chunk(chunk_x, chunk_z); const column = (bz - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + bx - chunk_x * CHUNK_SIZE; const nid = blocks.get(bx, by, bz) & ID_MASK; if (sky_light) { const columns = skies[which] ??= this.#columns_of(bx, bz); if (by >= columns[CHUNK_AREA + column]) sky = Math.max(sky, LIGHT_REACH - lost); } block = Math.max(block, this.#emission[nid] - lost); // light comes to this block from its neighbors, losing what going into it costs next = lost + Math.max(1, this.#opacity[nid]); if (next >= LIGHT_REACH) continue; reach(dx, dy - 1, dz); reach(dx, dy + 1, dz); reach(dx - 1, dy, dz); reach(dx + 1, dy, dz); reach(dx, dy, dz - 1); reach(dx, dy, dz + 1); } } return { sky, block }; } #columns_of(x: number, z: number) { const chunk_x = Math.floor(x / CHUNK_SIZE); const chunk_z = Math.floor(z / CHUNK_SIZE); const key = chunk_key(chunk_x, chunk_z); let columns = this.#columns.get(key); if (!columns) { columns = column_heights(this.#get_chunk(chunk_x, chunk_z), this.#opacity); this.#columns.set(key, columns); } return columns; } // only changes the block, the game server runs behaviors and tiles. state bits default to the block's defaults set_block(x: number, y: number, z: number, id: string, state?: number) { if (!this.shape.contains(y)) { return; } const nid = id === AIR_ID ? AIR : this.block_ids[id]; if (nid === undefined) { throw new Error(`Unknown block ${id}`); } const value = state === undefined ? this.default_values[nid] ?? nid : block_value(nid, state); const chunk_x = Math.floor(x / CHUNK_SIZE); const chunk_z = Math.floor(z / CHUNK_SIZE); const chunk = this.#get_loaded(chunk_x, chunk_z); chunk.column.set(x, y, z, value); chunk.unknown?.delete(this.#index(x, y, z, chunk_x, chunk_z)); this.#columns.delete(chunk_key(chunk_x, chunk_z)); this.#mark_unsaved(chunk_x, chunk_z); const state_bits = value >>> 16; this.on_block_change?.(x, y, z, id, state_bits); } // what clients are sent, the whole chunk as it is now. block values use this world's numeric ids, see block_table level_chunk(chunk_x: number, chunk_z: number): Uint8Array { return encode_level_chunk(this.#get_loaded(chunk_x, chunk_z).column); } // the block id of each numeric id, for clients to read level_chunk with block_table(): string[] { const table: string[] = []; for (const [id, nid] of Object.entries(this.block_ids)) { table[nid] = id; } table[AIR] = AIR_ID; return table; } // where to read saved chunks from. they're read when they're needed use_saved_chunks(chunks: SavedChunks) { this.#saved_chunks = chunks; for (const [x, z] of chunks.list) this.#saved.add(chunk_key(x, z)); } // every chunk generated or changed since the last call, as saved chunks save_chunks(): SavedChunk[] { const saved = [...this.#unsaved].map(([key, [x, z]]) => { const chunk = this.#chunks.peek(key); this.#saved.add(key); return chunk ? { x, z, data: encode_chunk(this.#chunk_blocks(chunk)) } : this.#evicted.get(key)!; }); this.#unsaved.clear(); this.#evicted.clear(); return saved; } #chunk_blocks(chunk: LoadedChunk): Required { const palette: [string, number][] = []; const palette_index = new Map(); const index_of = (id: string, state: number) => { const key = `${id} ${state}`; let index = palette_index.get(key); if (index === undefined) { index = palette.push([id, state]) - 1; palette_index.set(key, index); } return index; }; const by_value = new Map(); const value_index = (value: number) => { let index = by_value.get(value); if (index === undefined) { const nid = value & ID_MASK; const id = nid === AIR ? AIR_ID : EverythingRegistry.get_by_id("blocks", nid)?.id ?? AIR_ID; index = index_of(id, value >>> 16); by_value.set(value, index); } return index; }; const { sections, biomes } = chunk.column; const saved = sections.map((section) => { if (section.blocks === null) return new Section(value_index(section.value)); const indexes = new Uint32Array(SECTION_VOLUME); // runs of the same block are common, like air above the ground and stone below let last_value = -1; let last_index = 0; for (let i = 0; i < SECTION_VOLUME; i++) { const value = section.blocks[i]; if (value !== last_value) { last_value = value; last_index = value_index(value); } indexes[i] = last_index; } return new Section(indexes); }); for (const [i, [id, state]] of chunk.unknown ?? []) { saved[Math.floor(i / SECTION_VOLUME)].set(i % SECTION_VOLUME, index_of(id, state)); } return { palette, min_y: this.shape.min_y, sections: saved, biomes }; } get_tile(x: number, y: number, z: number) { return this.tiles.get(position_key(x, y, z)); } add_tile(tile: Tile) { this.tiles.set(position_key(tile.x, tile.y, tile.z), tile); this.#client_tiles.set(tile, tile.client_data !== undefined); this.dirty = true; } // clients drop its client data with it remove_tile(x: number, y: number, z: number) { const tile = this.get_tile(x, y, z); if (!tile) return; if (tile.client_data) { this.#client_tiles.set(tile, false); const gone = Object.fromEntries(Object.keys(tile.client_data).map((field) => [field, null])); this.on_client_data_change?.(x, y, z, gone); } this.#ticking_tiles.set(tile, false); this.tiles.delete(position_key(x, y, z)); this.dirty = true; } // one field of what clients see of it, any json value. undefined removes it. setting what it already is sends // nothing set_tile_client_data(tile: Tile, field: string, value: unknown) { if (JSON.stringify(tile.client_data?.[field]) === JSON.stringify(value)) return; const { [field]: _, ...data } = tile.client_data ?? {}; if (value !== undefined) data[field] = value; if (Object.keys(data).length > 0) tile.client_data = data; else delete tile.client_data; this.#client_tiles.set(tile, tile.client_data !== undefined); this.dirty = true; this.on_client_data_change?.(tile.x, tile.y, tile.z, { [field]: value ?? null }); } // the tiles in a chunk that have client data client_tiles(chunk_x: number, chunk_z: number): Iterable { return this.#client_tiles.in_chunk(chunk_x, chunk_z); } // whether it runs its components' on_tick and on_second near players set_ticks(tile: Tile, ticks: boolean) { this.#ticking_tiles.set(tile, ticks); } ticks(tile: Tile) { return this.#ticking_tiles.has(tile); } // the tiles in a chunk that tick ticking_tiles(chunk_x: number, chunk_z: number): Iterable { return this.#ticking_tiles.in_chunk(chunk_x, chunk_z); } get has_ticking_tiles() { return !this.#ticking_tiles.empty; } #mark_unsaved(chunk_x: number, chunk_z: number) { this.#unsaved.set(chunk_key(chunk_x, chunk_z), [chunk_x, chunk_z]); this.dirty = true; } // whether there's a saved chunk there, which the game's thread reads instead of generating anything #is_saved(key: number) { return this.#saved.has(key) || this.#evicted.has(key); } #get_raw(chunk_x: number, chunk_z: number) { const key = chunk_key(chunk_x, chunk_z); let raw = this.#raw.get(key); if (!raw) { this.fallbacks += 1; if (this.fallback_callers) { const caller = fallback_caller(new Error().stack ?? ""); this.fallback_callers.set(caller, (this.fallback_callers.get(caller) ?? 0) + 1); } raw = generate_raw_chunk(chunk_x, chunk_z, this.seed, this.block_ids, this.worldgen, this.default_values); this.#keep_raw(key, raw); } return raw; } #keep_raw(key: number, raw: RawChunk) { this.#raw.set(key, raw); this.#biomes.set(key, raw.column.biomes); this.#spills.set(key, raw.spills); } // a raw chunk a worldgen worker made. generation is the same everywhere, so one made here first is kept add_raw(chunk_x: number, chunk_z: number, raw: RawChunk) { const key = chunk_key(chunk_x, chunk_z); if (!this.#raw.has(key)) this.#keep_raw(key, raw); } // whether the chunk is built, or can be without generating anything: it's saved, or its own raw blocks and its // neighbors' spills are here can_build(chunk_x: number, chunk_z: number) { return this.raws_needed(chunk_x, chunk_z).length === 0; } // the raw chunks building it would generate on this thread: none if it's built or saved, otherwise its own if its // blocks aren't here, and its neighbors' whose spills aren't raws_needed(chunk_x: number, chunk_z: number): [number, number][] { const key = chunk_key(chunk_x, chunk_z); if (this.#chunks.has(key) || this.#is_saved(key)) return []; const needed: [number, number][] = []; if (!this.#raw.has(chunk_key(chunk_x, chunk_z))) needed.push([chunk_x, chunk_z]); for (let dx = -1; dx <= 1; dx++) { for (let dz = -1; dz <= 1; dz++) { if ((dx !== 0 || dz !== 0) && !this.#spills.has(chunk_key(chunk_x + dx, chunk_z + dz))) { needed.push([chunk_x + dx, chunk_z + dz]); } } } return needed; } #spills_of(chunk_x: number, chunk_z: number) { return this.#spills.get(chunk_key(chunk_x, chunk_z)) ?? this.#get_raw(chunk_x, chunk_z).spills; } #get_chunk(chunk_x: number, chunk_z: number) { return this.#get_loaded(chunk_x, chunk_z).column; } #get_loaded(chunk_x: number, chunk_z: number) { const key = chunk_key(chunk_x, chunk_z); let chunk = this.#chunks.get(key); if (!chunk) { chunk = this.#load(chunk_x, chunk_z); this.#chunks.set(key, chunk); } return chunk; } // the saved chunk, or a new one from generation, which is saved from then on like minecraft's #load(chunk_x: number, chunk_z: number): LoadedChunk { const key = chunk_key(chunk_x, chunk_z); if (this.#is_saved(key)) { const evicted = this.#evicted.get(key); this.#evicted.delete(key); const data = evicted?.data ?? this.#saved_chunks?.read(chunk_x, chunk_z); try { if (!data) throw new Error("it couldn't be read"); return this.#from_saved(chunk_x, chunk_z, decode_chunk(data)); } catch (e) { console.error( `Couldn't load chunk ${chunk_x}, ${chunk_z}, generating it again: ${(e as Error).message}`, ); } } const column = this.#generate_chunk(chunk_x, chunk_z); this.#mark_unsaved(chunk_x, chunk_z); return { column }; } #from_saved(chunk_x: number, chunk_z: number, saved: ChunkBlocks): LoadedChunk { // ids of mods that are gone are air until they're back const values = saved.palette.map(([id, state]) => { const nid = id === AIR_ID ? AIR : this.block_ids[id]; return nid === undefined ? undefined : block_value(nid, state); }); let unknown: Map | undefined; // sections the save doesn't have are air, and ones the dimension doesn't have are left out const offset = (this.shape.min_y - saved.min_y) / SECTION_HEIGHT; const sections = Array.from({ length: this.shape.height / SECTION_HEIGHT }, (_, s) => { const section = saved.sections[offset + s]; if (!section) return new Section(AIR); const start = s * SECTION_VOLUME; const blocks = section.blocks; if (blocks === null) { const value = values[section.value]; if (value === undefined) { for (let i = 0; i < SECTION_VOLUME; i++) { (unknown ??= new Map()).set(start + i, saved.palette[section.value]); } } return new Section(value ?? AIR); } for (let i = 0; i < SECTION_VOLUME; i++) { const value = values[blocks[i]]; if (value === undefined) (unknown ??= new Map()).set(start + i, saved.palette[blocks[i]]); blocks[i] = value ?? AIR; } return section; }); let saved_biomes = saved.biomes; if (!saved_biomes) { // saved before chunks had them. saved again with them const key = chunk_key(chunk_x, chunk_z); saved_biomes = this.#biomes.get(key) ?? this.#get_raw(chunk_x, chunk_z).column.biomes; this.#mark_unsaved(chunk_x, chunk_z); } // past what the save has, its top or bottom section's go on const last = saved_biomes.sections.length - 1; const biomes = { palette: [...saved_biomes.palette], sections: sections.map((_, s) => saved_biomes.sections[Math.min(Math.max(offset + s, 0), last)]), }; return { column: new ChunkColumn(chunk_x, chunk_z, this.shape, sections, biomes), unknown }; } // an unsaved chunk is encoded to be saved, instead of being generated again or kept whole #evict(key: number, chunk: LoadedChunk) { const position = this.#unsaved.get(key); if (!position) return; const [x, z] = position; this.#evicted.set(key, { x, z, data: encode_chunk(this.#chunk_blocks(chunk)) }); } // a block's place in its chunk's blocks, from the bottom of the world. y has to be in the shape #index(x: number, y: number, z: number, chunk_x: number, chunk_z: number) { return (y - this.shape.min_y) * CHUNK_AREA + (z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE); } // own blocks, then neighbors' leaves only into air #generate_chunk(chunk_x: number, chunk_z: number) { const column = this.#get_raw(chunk_x, chunk_z).column.clone(); for (let dx = -1; dx <= 1; dx++) { for (let dz = -1; dz <= 1; dz++) { if (dx === 0 && dz === 0) { continue; } const spills = this.#spills_of(chunk_x + dx, chunk_z + dz); for (let i = 0; i < spills.length; i += 4) { const [x, y, z, nid] = [spills[i], spills[i + 1], spills[i + 2], spills[i + 3]]; if (Math.floor(x / CHUNK_SIZE) !== chunk_x || Math.floor(z / CHUNK_SIZE) !== chunk_z) { continue; } if (column.get(x, y, z) === AIR) { column.set(x, y, z, nid); } } } } return column; } } // where in the code a fallback came from: the first caller outside this file, as file:line function fallback_caller(stack: string) { const frames = stack.split("\n").slice(1).map((line) => line.trim()); const outside = frames.find((frame) => !frame.includes("/world.ts")) ?? frames[0] ?? "unknown"; const match = outside.match(/at (?:(\S+) )?\(?.*\/([^/]+:\d+):\d+\)?$/); return match ? `${match[1] ?? "?"} ${match[2]}` : outside; } // a column's place in its chunk, the same as its blocks' in a layer function column_index(x: number, z: number) { return (z - Math.floor(z / CHUNK_SIZE) * CHUNK_SIZE) * CHUNK_SIZE + x - Math.floor(x / CHUNK_SIZE) * CHUNK_SIZE; }