From 677ad8115a054b98da86fd40842b8059c136d12c Mon Sep 17 00:00:00 2001 From: Paula Date: Sun, 27 Sep 2026 23:45:07 -0300 Subject: [PATCH] Region file format --- .gitignore | 3 +- desktop/main.ts | 2 +- server/game/game_server.ts | 65 +++--- server/game/host_protocol.ts | 6 +- server/game/load_mods.ts | 3 +- server/game/saves.ts | 107 +++++++++ server/game/worker.ts | 8 +- server/game/world.ts | 146 ++++++++++-- server/host.ts | 98 +++++--- server/main.ts | 2 +- server/regions.ts | 171 ++++++++++++++ tests/base_game_test.ts | 38 +-- tests/bmod_test.ts | 6 +- tests/client_updates_test.ts | 2 +- tests/fixtures/world_v2.json | 436 ----------------------------------- tests/helpers.ts | 3 +- tests/server_scripts_test.ts | 3 +- tests/world_save_test.ts | 134 +++++++++++ 18 files changed, 666 insertions(+), 567 deletions(-) create mode 100644 server/game/saves.ts create mode 100644 server/regions.ts delete mode 100644 tests/fixtures/world_v2.json create mode 100644 tests/world_save_test.ts diff --git a/.gitignore b/.gitignore index 2dda3bd..caa9837 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,4 @@ build/ -world.json -world.json.tmp +world/ server_mods/ dist/ diff --git a/desktop/main.ts b/desktop/main.ts index af31ea7..6639510 100644 --- a/desktop/main.ts +++ b/desktop/main.ts @@ -50,7 +50,7 @@ function singleplayer_host(): Promise { return await start_host({ build_dir: BUILD_DIR, server_mods_dir: join(ROOT, "server_mods"), - world_file: join(worlds, "world.json"), + world_dir: join(worlds, "world"), on_fatal(message) { console.error(message); alert(`The singleplayer world stopped: ${message}`); diff --git a/server/game/game_server.ts b/server/game/game_server.ts index 82f902f..eabafda 100644 --- a/server/game/game_server.ts +++ b/server/game/game_server.ts @@ -14,7 +14,6 @@ import { BlockRegistry, EverythingRegistry, ItemRegistry } from "$/common/everyt import { can_take_output, click_slot, Container, ItemData, ItemStack, take_output } from "$/common/inventory.ts"; import { AIR_ID, - BlockChange, ClientMessage, ContainerKey, CRAFTING_RESULT_SLOT, @@ -45,6 +44,7 @@ import { consume_recipe_items, update_crafting_result } from "./crafting.ts"; import { OpenScreen, SavedPlayer, ServerPlayer } from "./player.ts"; import { encode_skin, MAX_SKIN_BYTES, skin_problem } from "./skins.ts"; import { ServerWorld, Tile } from "./world.ts"; +import type { WorldSave } from "./saves.ts"; import { BLOCK_DROP_PICKUP_DELAY, DESPAWN_TICKS, @@ -91,20 +91,22 @@ export interface GameHost { download(url: string, max_bytes: number): Promise; } -export interface SavedWorld { - version: 3; +// level.json, everything saved but the blocks, which are in region files (see saves.ts) +export interface SavedLevel { + version: 4; seed: string; - // world time in ticks, 0 in saves from before the day and night cycle - time?: number; - changes: BlockChange[]; + // see ServerWorld.worldgen_fingerprint + worldgen: string; + // world time in ticks + time: number; tiles: SavedTile[]; // every ctx.containers container, by id - containers?: Record; + containers: Record; players: Record; // items on the ground - entities?: SavedItemEntity[]; + entities: SavedItemEntity[]; // ctx.storage of every mod, by mod id - mod_storage?: Record>; + mod_storage: Record>; } interface SavedTile { @@ -114,9 +116,6 @@ interface SavedTile { z: number; // what BlockRef.data holds mod_data?: unknown; - // version 2, when chests and furnaces were engine code: their fields and their items - data?: Record; - containers?: Record; } // the loaded mods, see load_mods.ts @@ -148,17 +147,21 @@ export class GameServer { // what runs tick(), for /tps. tests call tick() themselves loop?: GameLoop; - constructor(host: GameHost, save: string | undefined, default_seed: string, mods: GameMods) { + constructor(host: GameHost, save: WorldSave | undefined, default_seed: string, mods: GameMods) { this.#host = host; this.#mods = mods; this.mods = mods.runtime; this.recipes = mods.recipes; - // version 1 saves only had the seed and block changes - const saved: Partial | undefined = save ? JSON.parse(save) : undefined; + const saved: SavedLevel | undefined = save?.level ? JSON.parse(save.level) : undefined; + if (saved && saved.version !== 4) { + throw new Error(`The world was saved in format ${saved.version}, this server only loads format 4`); + } this.world = new ServerWorld(saved?.seed ?? default_seed, mods.worldgen); this.mods.storage = saved?.mod_storage ?? {}; - this.world.load_changes(saved?.changes ?? []); + if (saved) { + this.world.load_chunks(save?.chunks ?? [], saved.worldgen); + } this.world.time = saved?.time ?? 0; this.#day = this.world.day; for (const [id, items] of Object.entries(saved?.containers ?? {})) { @@ -167,14 +170,15 @@ export class GameServer { this.containers.set(id, container); } for (const tile of saved?.tiles ?? []) { - this.world.add_tile({ id: tile.id, x: tile.x, y: tile.y, z: tile.z, mod_data: this.#upgrade_tile(tile) }); + this.world.add_tile({ id: tile.id, x: tile.x, y: tile.y, z: tile.z, mod_data: tile.mod_data }); } for (const entity of saved?.entities ?? []) { const item = ItemEntity.load(this.#new_entity_id(), entity); this.#entities.set(item.id, item); } this.#saved_players = saved?.players ?? {}; - this.world.dirty = saved?.version !== 3; + // a new world is saved straight away, and a loaded one when load_chunks had to save chunks again + this.world.dirty = !saved || this.world.has_unsaved_chunks(); this.#register_commands(); this.world.on_block_change = (x, y, z, id, state) => @@ -273,15 +277,16 @@ export class GameServer { } } - save(): string { + // level.json and the chunks changed since the last save + save(): Required { for (const player of this.#players.values()) { this.#saved_players[player.name] = player.save(); } - const saved: SavedWorld = { - version: 3, + const level: SavedLevel = { + version: 4, seed: this.world.seed, + worldgen: this.world.worldgen_fingerprint(), time: this.world.time, - changes: this.world.all_changes(), tiles: [...this.world.tiles.values()].map((tile) => ({ id: tile.id, x: tile.x, @@ -297,7 +302,7 @@ export class GameServer { mod_storage: this.mods.storage, }; this.world.dirty = false; - return JSON.stringify(saved); + return { level: JSON.stringify(level), chunks: this.world.save_chunks() }; } // used by block behaviors and mods @@ -540,20 +545,6 @@ export class GameServer { // version 2 saves had chests and furnaces in the engine, with their fields in data and their items in // containers.main. the components keep those fields and put the items in a ctx.containers container - #upgrade_tile(tile: SavedTile): unknown { - if (tile.mod_data !== undefined || (!tile.data && !tile.containers)) { - return tile.mod_data; - } - const data: Record = { ...tile.data }; - const items = tile.containers?.main; - if (items) { - const { id, container } = this.create_container(items.length); - container.load(items); - data.container = id; - } - return data; - } - // messages // hello -> welcome, then ready -> join. see "Delivery to clients" in MODS.md diff --git a/server/game/host_protocol.ts b/server/game/host_protocol.ts index 08380fe..6552797 100644 --- a/server/game/host_protocol.ts +++ b/server/game/host_protocol.ts @@ -1,11 +1,12 @@ import type { ModData, ModListing } from "$/common/mod_loader.ts"; +import type { WorldSave } from "./saves.ts"; // messages between server/main.ts (the host) and the game server worker export type HostToGame = | { type: "init"; - save: string | undefined; + save: WorldSave; default_seed: string; // in load order, with the scripts' code since the worker can't read files mods: { listing: ModListing; data: ModData; server_code?: string; worldgen_code?: string }[]; @@ -23,6 +24,7 @@ export type GameToHost = | { type: "failed"; error: string } | { type: "send"; conn: number; data: string } | { type: "close"; conn: number } - | { type: "save"; data: string; final: boolean } + // level.json and the chunks that changed + | { type: "save"; save: Required; final: boolean } // the worker can't use the network, so the host fetches urls for it, like skins | { type: "download"; id: number; url: string; max_bytes: number }; diff --git a/server/game/load_mods.ts b/server/game/load_mods.ts index 1cf9c60..b1d9870 100644 --- a/server/game/load_mods.ts +++ b/server/game/load_mods.ts @@ -4,6 +4,7 @@ import { register_mod_data } from "$/common/mod_loader.ts"; import type { ModData, ModListing } from "$/common/mod_loader.ts"; import { load_worldgen } from "$/common/worldgen_loader.ts"; import { GameHost, GameServer } from "./game_server.ts"; +import type { WorldSave } from "./saves.ts"; import { ModRuntime } from "./mod_runtime.ts"; export interface ServerModSource { @@ -16,7 +17,7 @@ export interface ServerModSource { export async function start_game( host: GameHost, - save: string | undefined, + save: WorldSave | undefined, default_seed: string, mods: ServerModSource[], ): Promise { diff --git a/server/game/saves.ts b/server/game/saves.ts new file mode 100644 index 0000000..c7201d1 --- /dev/null +++ b/server/game/saves.ts @@ -0,0 +1,107 @@ +// what a world is saved as, apart from the files: level.json's text and each chunk's blocks. server/regions.ts puts +// the chunks into region files, this is what's inside one chunk's entry before it's compressed: +// +// u8 format, CHUNK_FORMAT +// u32 palette size, then each entry: u8 id length, the id as utf-8, u16 state bits +// the palette index of every block, in ServerWorld's order (y, then z, then x): u8 each for up to 256 entries, +// u16 each for more +// a bit per block, set where it isn't what world generation makes there, like a block a player placed +// +// numbers are big-endian. blocks are saved by their string ids, so mods can come and go without a save's numbers +// meaning other blocks +import { CHUNK_AREA, CHUNK_HEIGHT } from "$/common/constants.ts"; + +export const CHUNK_FORMAT = 1; +export const CHUNK_VOLUME = CHUNK_AREA * CHUNK_HEIGHT; + +export interface SavedChunk { + x: number; + z: number; + data: Uint8Array; +} + +// a world as the host reads it and the game saves it. the game only saves the chunks that changed since it last did +export interface WorldSave { + // level.json, without it the world is new + level?: string; + chunks: SavedChunk[]; +} + +export interface ChunkBlocks { + // an id and its state bits + palette: [string, number][]; + // the palette index of each block + blocks: Uint16Array; + // CHUNK_VOLUME bits, see is_changed + changed: Uint8Array; +} + +export function is_changed(chunk: ChunkBlocks, index: number) { + return (chunk.changed[index >> 3] & (1 << (index & 7))) !== 0; +} + +export function encode_chunk(chunk: ChunkBlocks): Uint8Array { + const ids = chunk.palette.map(([id]) => new TextEncoder().encode(id)); + if (ids.some((id) => id.length > 255)) throw new Error("A block id is too long to save"); + const wide = chunk.palette.length > 256; + const size = 1 + 4 + ids.reduce((sum, id) => sum + 1 + id.length + 2, 0) + + CHUNK_VOLUME * (wide ? 2 : 1) + CHUNK_VOLUME / 8; + const bytes = new Uint8Array(size); + const view = new DataView(bytes.buffer); + let offset = 0; + view.setUint8(offset++, CHUNK_FORMAT); + view.setUint32(offset, chunk.palette.length); + offset += 4; + chunk.palette.forEach(([, state], i) => { + view.setUint8(offset++, ids[i].length); + bytes.set(ids[i], offset); + offset += ids[i].length; + view.setUint16(offset, state); + offset += 2; + }); + for (let i = 0; i < CHUNK_VOLUME; i++) { + if (wide) { + view.setUint16(offset, chunk.blocks[i]); + offset += 2; + } else { + bytes[offset++] = chunk.blocks[i]; + } + } + bytes.set(chunk.changed, offset); + return bytes; +} + +// throws when the bytes aren't a chunk this can read +export function decode_chunk(bytes: Uint8Array): ChunkBlocks { + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + let offset = 0; + const format = view.getUint8(offset++); + if (format !== CHUNK_FORMAT) throw new Error(`Unknown chunk format ${format}`); + const palette_size = view.getUint32(offset); + offset += 4; + if (palette_size > CHUNK_VOLUME) throw new Error("Bad palette"); + const palette: [string, number][] = []; + for (let i = 0; i < palette_size; i++) { + const length = view.getUint8(offset++); + const id = new TextDecoder().decode(bytes.subarray(offset, offset + length)); + offset += length; + palette.push([id, view.getUint16(offset)]); + offset += 2; + } + const wide = palette_size > 256; + if (bytes.length !== offset + CHUNK_VOLUME * (wide ? 2 : 1) + CHUNK_VOLUME / 8) { + throw new Error("Wrong size"); + } + const blocks = new Uint16Array(CHUNK_VOLUME); + for (let i = 0; i < CHUNK_VOLUME; i++) { + if (wide) { + blocks[i] = view.getUint16(offset); + offset += 2; + } else { + blocks[i] = bytes[offset++]; + } + if (blocks[i] >= palette_size) throw new Error("Bad palette index"); + } + const changed = bytes.slice(offset, offset + CHUNK_VOLUME / 8); + return { palette, blocks, changed }; +} diff --git a/server/game/worker.ts b/server/game/worker.ts index 596bb39..bf8674f 100644 --- a/server/game/worker.ts +++ b/server/game/worker.ts @@ -15,7 +15,9 @@ const downloads = new Map void; reject let next_download = 1; function post(message: GameToHost) { - self.postMessage(message); + // the chunks are moved to the host, not copied + const transfer = message.type === "save" ? message.save.chunks.map((chunk) => chunk.data.buffer) : []; + self.postMessage(message, transfer); } self.onmessage = async (event: MessageEvent) => { @@ -53,7 +55,7 @@ self.onmessage = async (event: MessageEvent) => { game.on_disconnect(message.conn); break; case "shutdown": - post({ type: "save", data: game.save(), final: true }); + post({ type: "save", save: game.save(), final: true }); break; } }; @@ -92,7 +94,7 @@ async function init(message: Extract) { setInterval(() => { if (game!.world.dirty) { - post({ type: "save", data: game!.save(), final: false }); + post({ type: "save", save: game!.save(), final: false }); } }, SAVE_INTERVAL_MS); diff --git a/server/game/world.ts b/server/game/world.ts index 641fbe6..4d68243 100644 --- a/server/game/world.ts +++ b/server/game/world.ts @@ -5,12 +5,15 @@ import { AIR_ID, BlockChange } from "$/common/protocol.ts"; import { block_value, chunk_key, default_block_value } from "$/common/utils.ts"; import { LruMap } from "./lru.ts"; import { CYCLE_TICKS } from "$/common/time.ts"; +import { CHUNK_VOLUME, ChunkBlocks, decode_chunk, encode_chunk, is_changed, SavedChunk } from "./saves.ts"; // generation only, rebuilt when needed. 256 KB each const RAW_CACHE_SIZE = 128; const CHUNK_CACHE_SIZE = 256; // how far from the middle of the world to look for dry land to spawn on, in chunks const SPAWN_SEARCH_CHUNKS = 32; +// generated for worldgen_fingerprint, spread out so most changes to world generation touch at least one +const FINGERPRINT_CHUNKS = [[0, 0], [7, -3], [-45, 18], [130, -80], [-310, 260], [1000, -1000]]; // a block with data the server keeps, like where a chest's items are. never sent to clients export interface Tile { @@ -38,8 +41,10 @@ export class ServerWorld { #raw = new LruMap(RAW_CACHE_SIZE); #chunks = new LruMap(CHUNK_CACHE_SIZE); - // changes from generated terrain, per chunk. these and the tiles are what gets saved + // changes from generated terrain, per chunk, which is also what clients get sent. saved as whole chunks #changes = new Map>(); + // chunks changed since they were last saved, by chunk_key + #unsaved = new Map(); tiles = new Map(); // ticks since 06:00 of day 1, see common/time.ts @@ -159,10 +164,120 @@ export class ServerWorld { return all; } - load_changes(changes: BlockChange[]) { - for (const [x, y, z, id, state] of changes) { - this.#record_change(x, y, z, id, state ?? 0); + #fingerprint: string | undefined; + + // a hash of some generated chunks, saved with the world: when it's different world generation changed, like a mod + // update, and saved chunks can't be trusted to say which of their blocks generation made + worldgen_fingerprint(): string { + if (this.#fingerprint === undefined) { + // fnv-1a + let hash = 0x811c9dc5; + const add = (values: ArrayLike) => { + for (let i = 0; i < values.length; i++) { + hash = Math.imul(hash ^ values[i], 0x01000193) >>> 0; + } + }; + for (const [x, z] of FINGERPRINT_CHUNKS) { + const raw = this.#get_raw(x, z); + add(raw.blocks); + add(raw.spills); + } + this.#fingerprint = hash.toString(16).padStart(8, "0"); } + return this.#fingerprint; + } + + // chunks from a save. with a different fingerprint every block is compared with what generation makes now, so the + // saved terrain stays as it was and only chunks never saved get the new generation, like minecraft + load_chunks(chunks: SavedChunk[], fingerprint: string | undefined) { + const regenerate = chunks.length > 0 && fingerprint !== this.worldgen_fingerprint(); + if (regenerate) { + console.log(`World generation changed, comparing ${chunks.length} saved chunks with it`); + } + for (const { x: chunk_x, z: chunk_z, data } of chunks) { + let chunk: ChunkBlocks; + try { + chunk = decode_chunk(data); + } catch (e) { + console.error(`Couldn't load chunk ${chunk_x}, ${chunk_z}: ${(e as Error).message}`); + continue; + } + const generated = regenerate ? this.#generate_chunk(chunk_x, chunk_z) : undefined; + // unknown ids, from mods that are gone, stay as changes so they come back with the mod + const values = chunk.palette.map(([id, state]) => { + const nid = id === AIR_ID ? AIR : this.block_ids[id]; + return nid === undefined ? -1 : block_value(nid, state); + }); + for (let i = 0; i < CHUNK_VOLUME; i++) { + const block = chunk.blocks[i]; + if (generated ? generated[i] === values[block] : !is_changed(chunk, i)) { + continue; + } + const [id, state] = chunk.palette[block]; + const x = chunk_x * CHUNK_SIZE + (i % CHUNK_SIZE); + const z = chunk_z * CHUNK_SIZE + Math.floor(i / CHUNK_SIZE) % CHUNK_SIZE; + this.#record_change(x, Math.floor(i / CHUNK_AREA), z, id, state); + } + if (regenerate) { + this.#unsaved.set(chunk_key(chunk_x, chunk_z), [chunk_x, chunk_z]); + this.dirty = true; + } else { + this.#unsaved.delete(chunk_key(chunk_x, chunk_z)); + } + } + } + + has_unsaved_chunks() { + return this.#unsaved.size > 0; + } + + // every chunk changed since the last call, as saved chunks + save_chunks(): SavedChunk[] { + const saved = [...this.#unsaved.values()].map(([x, z]) => ({ + x, + z, + data: encode_chunk(this.#chunk_blocks(x, z)), + })); + this.#unsaved.clear(); + return saved; + } + + #chunk_blocks(chunk_x: number, chunk_z: number): ChunkBlocks { + 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 blocks = new Uint16Array(CHUNK_VOLUME); + const by_value = new Map(); + this.#get_chunk(chunk_x, chunk_z).forEach((value, i) => { + 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); + } + blocks[i] = index; + }); + + // the changes, which also keeps blocks of mods that are gone + const changed = new Uint8Array(CHUNK_VOLUME / 8); + for (const [x, y, z, id, state] of this.#changes.get(chunk_key(chunk_x, chunk_z))?.values() ?? []) { + const i = index_in_chunk(x, y, z, chunk_x, chunk_z); + blocks[i] = index_of(id, state ?? 0); + changed[i >> 3] |= 1 << (i & 7); + } + return { palette, blocks, changed }; } get_tile(x: number, y: number, z: number) { @@ -187,6 +302,7 @@ export class ServerWorld { this.#changes.set(key, chunk_changes); } chunk_changes.set(position_key(x, y, z), state ? [x, y, z, id, state] : [x, y, z, id]); + this.#unsaved.set(key, [Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE)]); } #get_raw(chunk_x: number, chunk_z: number) { @@ -209,8 +325,20 @@ export class ServerWorld { return blocks; } - // same rules as the client: own blocks, then neighbors' leaves only into air, then player changes + // same rules as the client: what generation makes, then player changes #build_chunk(chunk_x: number, chunk_z: number) { + const blocks = this.#generate_chunk(chunk_x, chunk_z); + for (const [x, y, z, id, state] of this.#changes.get(chunk_key(chunk_x, chunk_z))?.values() ?? []) { + const nid = id === AIR_ID ? AIR : this.block_ids[id]; + if (nid !== undefined) { + blocks[index_in_chunk(x, y, z, chunk_x, chunk_z)] = block_value(nid, state ?? 0); + } + } + return blocks; + } + + // own blocks, then neighbors' leaves only into air + #generate_chunk(chunk_x: number, chunk_z: number) { const blocks = this.#get_raw(chunk_x, chunk_z).blocks.slice(); for (let dx = -1; dx <= 1; dx++) { @@ -231,14 +359,6 @@ export class ServerWorld { } } } - - for (const [x, y, z, id, state] of this.#changes.get(chunk_key(chunk_x, chunk_z))?.values() ?? []) { - const nid = id === AIR_ID ? AIR : this.block_ids[id]; - if (nid !== undefined) { - blocks[index_in_chunk(x, y, z, chunk_x, chunk_z)] = block_value(nid, state ?? 0); - } - } - return blocks; } } diff --git a/server/host.ts b/server/host.ts index 7cc37e8..f0d5a62 100644 --- a/server/host.ts +++ b/server/host.ts @@ -4,6 +4,8 @@ import { serveDir } from "@std/http/file-server"; import { join } from "@std/path"; import { GameToHost, HostToGame } from "./game/host_protocol.ts"; import { load_bmods } from "./load_bmods.ts"; +import { read_regions, write_chunks } from "./regions.ts"; +import type { SavedChunk, WorldSave } from "./game/saves.ts"; const MAX_MESSAGE_SIZE = 4096; // in build/, see build.ts @@ -16,7 +18,8 @@ export interface HostOptions { build_dir: string; // the .bmod files to load server_mods_dir: string; - world_file: string; + // the world's folder: level.json, and the blocks in region/ + world_dir: string; seed?: string; // the game can't go on, like the worker crashing on_fatal(message: string): void; @@ -43,13 +46,17 @@ export async function start_host(options: HostOptions): Promise { const sockets = new Map(); let next_conn = 1; - let on_final_save: (() => void) | undefined; + let on_final_save: ((error?: Error) => void) | undefined; + // saves are written one after another, in order + let saving = Promise.resolve(); + // chunks from saves that couldn't be written, tried again with the next one + let unwritten = new Map(); game.onmessage = (event: MessageEvent) => { const message = event.data; switch (message.type) { case "ready": - console.log(`World ${options.world_file} ready, seed ${message.seed}`); + console.log(`World ${options.world_dir} ready, seed ${message.seed}`); break; case "failed": options.on_fatal(`Couldn't start the game: ${message.error}`); @@ -64,13 +71,27 @@ export async function start_host(options: HostOptions): Promise { case "close": sockets.get(message.conn)?.close(); break; - case "save": - write_world(options.world_file, message.data); - if (message.final) { - console.log("World saved"); - on_final_save?.(); - } + case "save": { + const { save, final } = message; + saving = saving.then(async () => { + const chunks = new Map(unwritten); + for (const chunk of save.chunks) chunks.set(`${chunk.x},${chunk.z}`, chunk); + try { + await write_world(options.world_dir, { level: save.level, chunks: [...chunks.values()] }); + unwritten = new Map(); + } catch (e) { + unwritten = chunks; + console.error(`Couldn't save the world: ${(e as Error).message}`); + if (final) on_final_save?.(e as Error); + return; + } + if (final) { + console.log("World saved"); + on_final_save?.(); + } + }); break; + } case "download": download(message.url, message.max_bytes).then( (bytes) => post({ type: "downloaded", id: message.id, bytes }), @@ -85,17 +106,21 @@ export async function start_host(options: HostOptions): Promise { options.on_fatal(`Game server crashed: ${event.message}`); }; - post({ - type: "init", - save: read_world(options.world_file), - default_seed: options.seed ?? crypto.randomUUID(), - mods: mods.map(({ listing, bmod }) => ({ - listing, - data: bmod.data, - server_code: bmod.scripts.server, - worldgen_code: bmod.scripts.worldgen, - })), - }); + const save = await read_world(options.world_dir); + game.postMessage( + { + type: "init", + save, + default_seed: options.seed ?? crypto.randomUUID(), + mods: mods.map(({ listing, bmod }) => ({ + listing, + data: bmod.data, + server_code: bmod.scripts.server, + worldgen_code: bmod.scripts.worldgen, + })), + } satisfies HostToGame, + save.chunks.map((chunk) => chunk.data.buffer), + ); function handle_socket(socket: WebSocket) { const conn = next_conn++; @@ -154,10 +179,14 @@ export async function start_host(options: HostOptions): Promise { () => reject(new Error("Game server didn't save in time")), SHUTDOWN_TIMEOUT_MS, ); - on_final_save = () => { + on_final_save = (error) => { clearTimeout(timeout); game.terminate(); - resolve(); + if (error) { + reject(error); + } else { + resolve(); + } }; post({ type: "shutdown" }); }); @@ -219,21 +248,28 @@ async function download(url: string, max_bytes: number): Promise { return bytes; } -function read_world(file: string): string | undefined { +const LEVEL_FILE = "level.json"; +const REGION_DIR = "region"; + +// a folder that isn't there is a new world +async function read_world(dir: string): Promise { + let level: string | undefined; try { - return Deno.readTextFileSync(file); + level = Deno.readTextFileSync(join(dir, LEVEL_FILE)); } catch (e) { - if (e instanceof Deno.errors.NotFound) { - return undefined; - } - throw e; + if (!(e instanceof Deno.errors.NotFound)) throw e; } + return { level, chunks: level ? await read_regions(join(dir, REGION_DIR)) : [] }; } -function write_world(file: string, data: string) { +// the chunks first, level.json says which world generation they were saved with +async function write_world(dir: string, save: Required) { + await write_chunks(join(dir, REGION_DIR), save.chunks); + Deno.mkdirSync(dir, { recursive: true }); // write then rename so a crash mid write doesnt eat the world - Deno.writeTextFileSync(`${file}.tmp`, data); - Deno.renameSync(`${file}.tmp`, file); + const level = join(dir, LEVEL_FILE); + Deno.writeTextFileSync(`${level}.tmp`, save.level); + Deno.renameSync(`${level}.tmp`, level); } // the engine's textures, listed by the build next to the client's assets. engine:missing is drawn by code diff --git a/server/main.ts b/server/main.ts index b67b7d3..7c10fa4 100644 --- a/server/main.ts +++ b/server/main.ts @@ -8,7 +8,7 @@ try { host = await start_host({ build_dir: Deno.env.get("BUILD_DIR") ?? "build", server_mods_dir: Deno.env.get("SERVER_MODS_DIR") ?? "server_mods", - world_file: Deno.env.get("WORLD_FILE") ?? "world.json", + world_dir: Deno.env.get("WORLD_DIR") ?? "world", seed: Deno.env.get("SEED"), on_fatal(message) { console.error(message); diff --git a/server/regions.ts b/server/regions.ts new file mode 100644 index 0000000..3c2e900 --- /dev/null +++ b/server/regions.ts @@ -0,0 +1,171 @@ +// region files, laid out like minecraft's since mcregion (a mod, part of the game from beta 1.3): the chunks of a +// 32 by 32 chunk square in one file, so saving writes only the chunks that changed. the file is 4 KiB sectors, the +// first two are the header: +// +// 1024 locations, one per chunk: u24 first sector, u8 how many sectors. 0 and 0 where there's no chunk +// 1024 timestamps: u32 seconds, when the chunk was last written +// +// a chunk's place in those is (x & 31) + (z & 31) * 32. its sectors start with u32 the length of what follows, u8 +// the compression (2, zlib like minecraft's default), then the compressed chunk from server/game/saves.ts. +// big-endian. a chunk saved again goes into sectors nothing uses and the header is written last, so a crash while +// saving leaves the chunks as they were instead of half written +import { join } from "@std/path"; +import type { SavedChunk } from "./game/saves.ts"; + +const SECTOR = 4096; +const REGION_CHUNKS = 32; +const CHUNKS_PER_REGION = REGION_CHUNKS * REGION_CHUNKS; +const HEADER_SECTORS = 2; +const HEADER_SIZE = HEADER_SECTORS * SECTOR; +const ZLIB = 2; +// what fits in a location's sector count, 1 MB +const MAX_CHUNK_SECTORS = 255; +const REGION_FILE = /^r\.(-?\d+)\.(-?\d+)\.bwr$/; + +export function region_file(region_x: number, region_z: number) { + return `r.${region_x}.${region_z}.bwr`; +} + +// every chunk in the folder's region files, uncompressed. chunks that can't be read are skipped, saying so +export async function read_regions(dir: string): Promise { + let entries: Deno.DirEntry[]; + try { + entries = [...Deno.readDirSync(dir)]; + } catch (e) { + if (e instanceof Deno.errors.NotFound) return []; + throw e; + } + const chunks: SavedChunk[] = []; + for (const entry of entries) { + const match = entry.isFile && REGION_FILE.exec(entry.name); + if (!match) continue; + const [region_x, region_z] = [Number(match[1]), Number(match[2])]; + const bytes = await Deno.readFile(join(dir, entry.name)); + if (bytes.length < HEADER_SIZE) { + console.error(`${entry.name} is too short to be a region file`); + continue; + } + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + for (let i = 0; i < CHUNKS_PER_REGION; i++) { + const location = view.getUint32(i * 4); + if (location === 0) continue; + const x = region_x * REGION_CHUNKS + (i % REGION_CHUNKS); + const z = region_z * REGION_CHUNKS + Math.floor(i / REGION_CHUNKS); + try { + const start = (location >>> 8) * SECTOR; + const length = view.getUint32(start); + const compression = view.getUint8(start + 4); + if (compression !== ZLIB) throw new Error(`unknown compression ${compression}`); + if (length < 1 || start + 4 + length > bytes.length) { + throw new Error("it goes past the end of the file"); + } + chunks.push({ x, z, data: await inflate(bytes.subarray(start + 5, start + 4 + length)) }); + } catch (e) { + console.error(`Couldn't read chunk ${x}, ${z} from ${entry.name}: ${(e as Error).message}`); + } + } + } + return chunks; +} + +// saves the chunks into their region files, making them and the folder when needed +export async function write_chunks(dir: string, chunks: SavedChunk[]) { + const regions = new Map(); + for (const chunk of chunks) { + const name = region_file(Math.floor(chunk.x / REGION_CHUNKS), Math.floor(chunk.z / REGION_CHUNKS)); + regions.set(name, [...regions.get(name) ?? [], chunk]); + } + if (regions.size) Deno.mkdirSync(dir, { recursive: true }); + for (const [name, region_chunks] of regions) { + await write_region(join(dir, name), region_chunks); + } +} + +async function write_region(path: string, chunks: SavedChunk[]) { + const compressed = await Promise.all(chunks.map((chunk) => deflate(chunk.data))); + using file = await Deno.open(path, { read: true, write: true, create: true }); + + const header = new Uint8Array(HEADER_SIZE); + await read_at(file, 0, header); + const view = new DataView(header.buffer); + + // the sectors the header points at now, which stay untouched until the new header is written + const used: boolean[] = []; + for (let i = 0; i < HEADER_SECTORS; i++) used[i] = true; + for (let i = 0; i < CHUNKS_PER_REGION; i++) { + const location = view.getUint32(i * 4); + const [first, count] = [location >>> 8, location & 0xFF]; + for (let sector = first; sector < first + count; sector++) used[sector] = true; + } + + const now = Math.floor(Date.now() / 1000); + for (const [i, chunk] of chunks.entries()) { + const data = compressed[i]; + const sectors = Math.ceil((5 + data.length) / SECTOR); + if (sectors > MAX_CHUNK_SECTORS) { + throw new Error(`Chunk ${chunk.x}, ${chunk.z} is too big to save (${data.length} bytes)`); + } + const first = free_sectors(used, sectors); + for (let sector = first; sector < first + sectors; sector++) used[sector] = true; + + const bytes = new Uint8Array(sectors * SECTOR); + const chunk_view = new DataView(bytes.buffer); + chunk_view.setUint32(0, data.length + 1); + chunk_view.setUint8(4, ZLIB); + bytes.set(data, 5); + await write_at(file, first * SECTOR, bytes); + + const index = (chunk.x & (REGION_CHUNKS - 1)) + (chunk.z & (REGION_CHUNKS - 1)) * REGION_CHUNKS; + view.setUint32(index * 4, (first << 8) | sectors); + view.setUint32(SECTOR + index * 4, now); + } + + // the chunks are on disk before the header points at them + await file.syncData(); + await write_at(file, 0, header); +} + +// the first of the first run of that many sectors nothing uses, which can be past the end of the file +function free_sectors(used: boolean[], count: number) { + let start = HEADER_SECTORS; + for (let sector = HEADER_SECTORS; sector < used.length; sector++) { + if (used[sector]) { + start = sector + 1; + } else if (sector - start + 1 === count) { + return start; + } + } + return start; +} + +// reads as much of bytes as the file has there, a new file reads as zeros +async function read_at(file: Deno.FsFile, offset: number, bytes: Uint8Array) { + await file.seek(offset, Deno.SeekMode.Start); + let read = 0; + while (read < bytes.length) { + const n = await file.read(bytes.subarray(read)); + if (n === null) break; + read += n; + } +} + +async function write_at(file: Deno.FsFile, offset: number, bytes: Uint8Array) { + await file.seek(offset, Deno.SeekMode.Start); + let written = 0; + while (written < bytes.length) { + written += await file.write(bytes.subarray(written)); + } +} + +// "deflate" is zlib's format, what minecraft calls compression 2 +function deflate(bytes: Uint8Array) { + return transform(bytes, new CompressionStream("deflate")); +} + +function inflate(bytes: Uint8Array) { + return transform(bytes, new DecompressionStream("deflate")); +} + +async function transform(bytes: Uint8Array, stream: CompressionStream | DecompressionStream) { + return new Uint8Array(await new Response(new Blob([bytes]).stream().pipeThrough(stream)).arrayBuffer()); +} diff --git a/tests/base_game_test.ts b/tests/base_game_test.ts index 12f3955..7aa96bb 100644 --- a/tests/base_game_test.ts +++ b/tests/base_game_test.ts @@ -165,11 +165,13 @@ Deno.test("a new watering can starts empty, and players are told so in its lore" assertEquals(can.lore, "Water: 0/32"); // lore is worked out for players, it isn't saved - const saved = JSON.parse(t.game.save()); + const saved = JSON.parse(t.game.save().level); const saved_can = saved.players.alice?.inventory?.find((i: Msg) => i?.id === "bworld:watering_can"); assert(!saved_can || saved_can.lore === undefined); t.game.on_disconnect(1); - const after = JSON.parse(t.game.save()).players.alice.inventory.find((i: Msg) => i?.id === "bworld:watering_can"); + const after = JSON.parse(t.game.save().level).players.alice.inventory.find((i: Msg) => + i?.id === "bworld:watering_can" + ); assertEquals(after.lore, undefined); }); @@ -182,38 +184,6 @@ Deno.test("items are called by their name, or by one made from their id", async assertEquals(display_name("test:thing"), "A Thing"); }); -Deno.test("chests and furnaces from a world saved before they were mod code keep their items and keep smelting", async () => { - const t = await test_game("mods", Deno.readTextFileSync("tests/fixtures/world_v2.json"), "fixture-seed"); - t.join(1, "alice"); - - t.send(1, { type: "use_block", x: 1, y: 100, z: 0, face: "top" }); - const chest = last_container(t.take(1), "screen"); - assertEquals(chest.length, 27); - assertEquals(chest[4], { id: "bworld:coal", count: 6 }); - t.send(1, { type: "close_screen" }); - - t.send(1, { type: "use_block", x: 2, y: 100, z: 0, face: "top" }); - let messages = t.take(1); - assertEquals(last_container(messages, "screen"), [ - { id: "bworld:iron_ore", count: 2 }, - { id: "bworld:coal", count: 2 }, - { id: "bworld:iron_ingot", count: 1 }, - ]); - const properties = messages.filter((m) => m.type === "screen_properties").at(-1).properties; - assertEquals(properties, { progress: 50, progress_max: 200, fuel: 751, fuel_max: 1000 }); - - // 150 more ticks finish the second ingot - for (let i = 0; i < 150; i++) t.game.tick(); - messages = t.take(1); - assertEquals(last_container(messages, "screen")[2], { id: "bworld:iron_ingot", count: 2 }); - - // saved in the new format, nothing lost - const saved = JSON.parse(t.game.save()); - assertEquals(saved.version, 3); - assert(saved.tiles.every((tile: Msg) => tile.data === undefined && tile.containers === undefined)); - assertEquals(Object.keys(saved.containers).length, 2); -}); - Deno.test("a smithing table upgrades a wooden pickaxe with 5 stone, using up exactly that", async () => { const t = await setup([["bworld:wood_pickaxe", 1], ["bworld:stone", 7]]); t.game.set_block(1, 100, 0, "bworld:smithing_table"); diff --git a/tests/bmod_test.ts b/tests/bmod_test.ts index 9b9d5ce..d08f3ed 100644 --- a/tests/bmod_test.ts +++ b/tests/bmod_test.ts @@ -133,12 +133,12 @@ Deno.test("the host serves each mod's player copy by its hash, and a game made f `${build}/assets/textures/index.json`, JSON.stringify(ENGINE_TEXTURES.slice(1).map((id) => id.split(":")[1])), ); - const world = `${build}/world.json`; + const world = `${build}/world`; const host = await start_host({ build_dir: build, server_mods_dir: folder, - world_file: world, + world_dir: world, seed: "bmod-seed", on_fatal: (message) => { throw new Error(message); @@ -156,7 +156,7 @@ Deno.test("the host serves each mod's player copy by its hash, and a game made f // the game worker loaded both mods, including the template's server script, and saves await host.shutdown(); - const saved = JSON.parse(Deno.readTextFileSync(world)); + const saved = JSON.parse(Deno.readTextFileSync(`${world}/level.json`)); assertEquals(saved.seed, "bmod-seed"); for (const dir of [sources, folder, build]) Deno.removeSync(dir, { recursive: true }); diff --git a/tests/client_updates_test.ts b/tests/client_updates_test.ts index a82382d..a097a34 100644 --- a/tests/client_updates_test.ts +++ b/tests/client_updates_test.ts @@ -1,4 +1,4 @@ -import { assert, assertEquals } from "@std/assert"; +import { assertEquals } from "@std/assert"; import { join } from "@std/path"; import { CLIENT_MANIFEST, client_manifest, sha256, update_client } from "$/desktop/client_updates.ts"; diff --git a/tests/fixtures/world_v2.json b/tests/fixtures/world_v2.json deleted file mode 100644 index 1dc9fc7..0000000 --- a/tests/fixtures/world_v2.json +++ /dev/null @@ -1,436 +0,0 @@ -{ - "version": 2, - "seed": "fixture-seed", - "changes": [ - [ - -3, - 99, - -3, - "bworld:stone" - ], - [ - -3, - 99, - -2, - "bworld:stone" - ], - [ - -3, - 99, - -1, - "bworld:stone" - ], - [ - -2, - 99, - -3, - "bworld:stone" - ], - [ - -2, - 99, - -2, - "bworld:stone" - ], - [ - -2, - 99, - -1, - "bworld:stone" - ], - [ - -1, - 99, - -3, - "bworld:stone" - ], - [ - -1, - 99, - -2, - "bworld:stone" - ], - [ - -1, - 99, - -1, - "bworld:stone" - ], - [ - -3, - 99, - 0, - "bworld:stone" - ], - [ - -3, - 99, - 1, - "bworld:stone" - ], - [ - -3, - 99, - 2, - "bworld:stone" - ], - [ - -3, - 99, - 3, - "bworld:stone" - ], - [ - -2, - 99, - 0, - "bworld:stone" - ], - [ - -2, - 99, - 1, - "bworld:stone" - ], - [ - -2, - 99, - 2, - "bworld:stone" - ], - [ - -2, - 99, - 3, - "bworld:stone" - ], - [ - -1, - 99, - 0, - "bworld:stone" - ], - [ - -1, - 99, - 1, - "bworld:stone" - ], - [ - -1, - 99, - 2, - "bworld:stone" - ], - [ - -1, - 99, - 3, - "bworld:stone" - ], - [ - 0, - 99, - -3, - "bworld:stone" - ], - [ - 0, - 99, - -2, - "bworld:stone" - ], - [ - 0, - 99, - -1, - "bworld:stone" - ], - [ - 1, - 99, - -3, - "bworld:stone" - ], - [ - 1, - 99, - -2, - "bworld:stone" - ], - [ - 1, - 99, - -1, - "bworld:stone" - ], - [ - 2, - 99, - -3, - "bworld:stone" - ], - [ - 2, - 99, - -2, - "bworld:stone" - ], - [ - 2, - 99, - -1, - "bworld:stone" - ], - [ - 3, - 99, - -3, - "bworld:stone" - ], - [ - 3, - 99, - -2, - "bworld:stone" - ], - [ - 3, - 99, - -1, - "bworld:stone" - ], - [ - 0, - 99, - 0, - "bworld:stone" - ], - [ - 0, - 99, - 1, - "bworld:stone" - ], - [ - 0, - 99, - 2, - "bworld:stone" - ], - [ - 0, - 99, - 3, - "bworld:stone" - ], - [ - 1, - 99, - 0, - "bworld:stone" - ], - [ - 1, - 99, - 1, - "bworld:stone" - ], - [ - 1, - 99, - 2, - "bworld:stone" - ], - [ - 1, - 99, - 3, - "bworld:stone" - ], - [ - 2, - 99, - 0, - "bworld:stone" - ], - [ - 2, - 99, - 1, - "bworld:stone" - ], - [ - 2, - 99, - 2, - "bworld:stone" - ], - [ - 2, - 99, - 3, - "bworld:stone" - ], - [ - 3, - 99, - 0, - "bworld:stone" - ], - [ - 3, - 99, - 1, - "bworld:stone" - ], - [ - 3, - 99, - 2, - "bworld:stone" - ], - [ - 3, - 99, - 3, - "bworld:stone" - ], - [ - 1, - 100, - 0, - "bworld:chest" - ], - [ - 2, - 100, - 0, - "bworld:furnace" - ] - ], - "tiles": [ - { - "id": "bworld:chest", - "x": 1, - "y": 100, - "z": 0, - "data": {}, - "containers": { - "main": [ - null, - null, - null, - null, - { - "id": "bworld:coal", - "count": 6 - }, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null - ] - } - }, - { - "id": "bworld:furnace", - "x": 2, - "y": 100, - "z": 0, - "data": { - "progress": 50, - "progress_max": 200, - "fuel": 751, - "fuel_max": 1000 - }, - "containers": { - "main": [ - { - "id": "bworld:iron_ore", - "count": 2 - }, - { - "id": "bworld:coal", - "count": 2 - }, - { - "id": "bworld:iron_ingot", - "count": 1 - } - ] - } - } - ], - "players": { - "alice": { - "x": 0.5, - "y": 100, - "z": 0.5, - "yaw": 0, - "pitch": 0, - "selected_slot": 0, - "inventory": [ - { - "id": "bworld:coal", - "count": 2 - }, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null - ] - } - }, - "entities": [], - "mod_storage": {} -} diff --git a/tests/helpers.ts b/tests/helpers.ts index e116a7b..90a22f2 100644 --- a/tests/helpers.ts +++ b/tests/helpers.ts @@ -5,6 +5,7 @@ import type { ServerModSource } from "$/server/game/load_mods.ts"; import { GameServer } from "$/server/game/game_server.ts"; import { start_game } from "$/server/game/load_mods.ts"; import { PROTOCOL_VERSION } from "$/common/protocol.ts"; +import type { WorldSave } from "$/server/game/saves.ts"; // mods straight from their source folders, skipping the build: scripts are imported as typescript export function mod_sources(mods_dir: string): ServerModSource[] { @@ -37,7 +38,7 @@ export function mod_sources(mods_dir: string): ServerModSource[] { } // a game with an in memory host that remembers what it sent to each connection -export async function test_game(mods_dir: string, save?: string, seed = "test-seed") { +export async function test_game(mods_dir: string, save?: WorldSave, seed = "test-seed") { EverythingRegistry.clear(); const outbox = new Map(); const closed = new Set(); diff --git a/tests/server_scripts_test.ts b/tests/server_scripts_test.ts index 5cc7339..d53477c 100644 --- a/tests/server_scripts_test.ts +++ b/tests/server_scripts_test.ts @@ -1,5 +1,6 @@ import { assert, assertEquals } from "@std/assert"; import { copy_dir, test_game } from "./helpers.ts"; +import type { WorldSave } from "$/server/game/saves.ts"; // a mod that uses every part of the server api worth testing, and writes down what happened in its storage const SERVER_SCRIPT = ` @@ -151,7 +152,7 @@ function test_mods() { return dir; } -async function setup(save?: string) { +async function setup(save?: WorldSave) { const dir = test_mods(); const game = await test_game(dir, save); game.join(1, "alice"); diff --git a/tests/world_save_test.ts b/tests/world_save_test.ts new file mode 100644 index 0000000..e65a3db --- /dev/null +++ b/tests/world_save_test.ts @@ -0,0 +1,134 @@ +import { assert, assertEquals, assertNotEquals } from "@std/assert"; +import { AIR_ID } from "$/common/protocol.ts"; +import { CHUNK_VOLUME, decode_chunk, encode_chunk, is_changed, SavedChunk } from "$/server/game/saves.ts"; +import { read_regions, region_file, write_chunks } from "$/server/regions.ts"; +import { test_game } from "./helpers.ts"; + +function chunk_data(seed: number, palette_size = 3) { + const palette: [string, number][] = []; + for (let i = 0; i < palette_size; i++) palette.push([`test:block_${i}`, i % 5]); + const blocks = new Uint16Array(CHUNK_VOLUME).map((_, i) => (i * seed) % palette_size); + const changed = new Uint8Array(CHUNK_VOLUME / 8).map((_, i) => (i * seed) & 0xFF); + return { palette, blocks, changed }; +} + +Deno.test("a chunk's blocks come back as they were saved, with more than 256 kinds too", () => { + for (const palette_size of [1, 3, 256, 300]) { + const chunk = chunk_data(7, palette_size); + const decoded = decode_chunk(encode_chunk(chunk)); + assertEquals(decoded.palette, chunk.palette); + assertEquals(decoded.blocks, chunk.blocks); + assertEquals(decoded.changed, chunk.changed); + } + // a byte a block when that's enough + assert(encode_chunk(chunk_data(7, 256)).length < encode_chunk(chunk_data(7, 257)).length - CHUNK_VOLUME / 2); +}); + +Deno.test("region files keep chunks, including negative ones, and saving one again doesn't touch the others", async () => { + const dir = Deno.makeTempDirSync(); + const chunk = (x: number, z: number, seed: number): SavedChunk => ({ + x, + z, + data: encode_chunk(chunk_data(seed)), + }); + const by_position = (chunks: SavedChunk[]) => + Object.fromEntries(chunks.map((c) => [`${c.x},${c.z}`, decode_chunk(c.data).blocks[5]])); + + await write_chunks(dir, [chunk(0, 0, 1), chunk(31, 31, 2), chunk(-1, -1, 3), chunk(-33, 40, 4)]); + assertEquals( + [...Deno.readDirSync(dir)].map((e) => e.name).sort(), + [region_file(-1, -1), region_file(-2, 1), region_file(0, 0)].sort(), + ); + assertEquals(by_position(await read_regions(dir)), { "0,0": 2, "31,31": 1, "-1,-1": 0, "-33,40": 2 }); + + // saved again, over and over: the file doesn't keep growing, sectors let go of get used again + const path = `${dir}/${region_file(0, 0)}`; + await write_chunks(dir, [chunk(0, 0, 2)]); + const size = Deno.statSync(path).size; + for (let i = 0; i < 5; i++) await write_chunks(dir, [chunk(0, 0, 2 + (i % 2))]); + assert(Deno.statSync(path).size <= size + 4096 * 2); + assertEquals(by_position(await read_regions(dir)), { "0,0": 1, "31,31": 1, "-1,-1": 0, "-33,40": 2 }); + + assertEquals(await read_regions(`${dir}/nothing`), []); + Deno.removeSync(dir, { recursive: true }); +}); + +Deno.test("changed blocks are saved as whole chunks, and only chunks that changed are saved again", async () => { + const { game } = await test_game("mods"); + game.set_block(3, 120, 5, "bworld:stone"); + game.set_block(-20, 120, 40, "bworld:planks"); + game.world.set_block(-20, 121, 40, "bworld:furnace", 1); + const saved = game.save(); + assertEquals(saved.chunks.map((c) => [c.x, c.z]).sort(), [[-2, 2], [0, 0]]); + + // the chunk has every block, and marks the ones generation didn't make + const chunk = decode_chunk(saved.chunks.find((c) => c.x === 0)!.data); + const index = 120 * 256 + 5 * 16 + 3; + assertEquals(chunk.palette[chunk.blocks[index]], ["bworld:stone", 0]); + assert(is_changed(chunk, index)); + assert(chunk.palette.some(([id]) => id === "bworld:bedrock" || id === "bworld:stone")); + assertEquals(chunk.changed.reduce((sum, byte) => sum + byte.toString(2).split("1").length - 1, 0), 1); + + assertEquals(game.save().chunks, []); + game.set_block(4, 120, 5, "bworld:stone"); + assertEquals(game.save().chunks.map((c) => [c.x, c.z]), [[0, 0]]); + + const loaded = await test_game("mods", saved); + assertEquals(loaded.game.world.get_block_id(3, 120, 5), "bworld:stone"); + assertEquals(loaded.game.world.get_block_id(-20, 120, 40), "bworld:planks"); + assertEquals(loaded.game.world.get_block_value(-20, 121, 40) >>> 16, 1); + // players get the changes, not the whole chunks + const join = loaded.join(1, "alice"); + assertEquals(join.changes.length, 3); + // nothing to save again after loading + assertEquals(loaded.game.save().chunks, []); +}); + +// a saved chunk with a block that isn't marked changed and isn't what generation makes: what's saved from a world +// generation that's since changed +async function saved_with_old_terrain() { + const { game } = await test_game("mods"); + game.set_block(3, 120, 5, "bworld:stone"); + const saved = game.save(); + const chunk = decode_chunk(saved.chunks[0].data); + const index = 121 * 256 + 5 * 16 + 3; + assertEquals(chunk.palette[chunk.blocks[index]][0], AIR_ID); + chunk.blocks[index] = chunk.blocks[120 * 256 + 5 * 16 + 3]; + saved.chunks[0].data = encode_chunk(chunk); + return { saved, level: JSON.parse(saved.level) }; +} + +Deno.test("when world generation is the same, blocks it made come from it", async () => { + const { saved } = await saved_with_old_terrain(); + const { game } = await test_game("mods", saved); + assertEquals(game.world.get_block_id(3, 121, 5), AIR_ID); + assertEquals(game.save().chunks, []); +}); + +Deno.test("when world generation changed, saved chunks keep their terrain and are saved again", async () => { + const { saved, level } = await saved_with_old_terrain(); + saved.level = JSON.stringify({ ...level, worldgen: "older" }); + const { game, join } = await test_game("mods", saved); + assertEquals(game.world.get_block_id(3, 121, 5), "bworld:stone"); + assertEquals(game.world.get_block_id(3, 120, 5), "bworld:stone"); + assertEquals(join(1, "alice").changes.length, 2); + + const again = game.save(); + assertNotEquals(JSON.parse(again.level).worldgen, "older"); + const chunk = decode_chunk(again.chunks[0].data); + assert(is_changed(chunk, 121 * 256 + 5 * 16 + 3)); +}); + +Deno.test("blocks of a mod that's gone are kept in the save", async () => { + const { saved } = await saved_with_old_terrain(); + const chunk = decode_chunk(saved.chunks[0].data); + chunk.palette[chunk.blocks[120 * 256 + 5 * 16 + 3]] = ["gone:thing", 2]; + saved.chunks[0].data = encode_chunk(chunk); + + const { game } = await test_game("mods", saved); + // generation's block stands in for it + assertNotEquals(game.world.get_block_id(3, 120, 5), "gone:thing"); + game.set_block(0, 120, 0, "bworld:stone"); + const again = decode_chunk(game.save().chunks[0].data); + assertEquals(again.palette[again.blocks[120 * 256 + 5 * 16 + 3]], ["gone:thing", 2]); +});