Save all generated chunks instead of only chunks that were changed

This commit is contained in:
2026-10-11 02:02:01 -03:00
parent 44a39bf8ec
commit 5a59a63862
17 changed files with 644 additions and 314 deletions
+11 -10
View File
@@ -12,19 +12,20 @@ What world generation has today (see [World Generation](docs/modding/worldgen/in
- **The server generates every chunk** (`server/game/world.ts`, `common/generation.ts`). Players only get finished
chunks, so generation code and data never have to reach clients.
- **Three passes per chunk:** terrain (data, see [GENERATION.md](GENERATION.md)), then ores (`worldgen/ores.json`), then
features, code or data, by step. The base game's trees are a code feature in `vegetal_decoration`.
- **Three passes per chunk:** terrain (data, see [terrain.md](docs/modding/worldgen/terrain.md)), then ores
(`worldgen/ores.json`), then features, code or data, by step. The base game's trees are a code feature in
`vegetal_decoration`.
- **Chunks generate alone.** A feature may write up to one chunk away. Those writes are "spills" that only fill air in
the neighbor, so the result doesn't depend on which chunk generates first.
- **Determinism is the rule everything rests on.** A save only keeps player changes. Untouched terrain is generated
again on every load, and when generation changes, a fingerprint makes the server compare saved chunks against the new
output (`ServerWorld.load_chunks`).
- **Determinism matters at chunk borders.** Every chunk generated is saved whole, like Minecraft, so a change to
generation only shows in chunks never generated before. A chunk generated next to a saved one still takes the saved
one's spills from generation, so features cross the border the same way only when generation hasn't changed.
- **Heights and biomes for any column**, without generating its chunk: `OverworldTerrain.column` and `estimate_biome`.
The biome is exact away from coasts and cliffs. The height is the height before 3D noise, so it isn't the real
surface.
- **Blocks:** numeric states (up to 16 bits), `variants`, `parts`, shapes, tile data, containers, components and shared
rules. Tags exist for blocks, items and entities. Biomes are a registry of data (`worldgen/biomes/` in a mod), but
which one a column gets is data too, a biome source's rules (see [GENERATION.md](GENERATION.md)).
which one a column gets is data too, a biome source's rules (see [biomes.md](docs/modding/worldgen/biomes.md)).
- **Loot:** a block's `drops` is one item id. There are no loot tables.
What's missing for structures:
@@ -507,10 +508,10 @@ the same hook later.
### Determinism and Saves
- Starts and pieces are recomputed whenever needed and never saved, following the [modding plan's](docs/modding_plan.md)
rule that a save only keeps changes.
- Adding or removing a mod with structures changes untouched terrain in existing worlds, the same as features do now.
The worldgen fingerprint already detects it and keeps saved chunks as they were.
- Starts and pieces are recomputed whenever needed and never saved: a chunk with a piece in it is saved with its blocks
like any other, and pieces reaching into chunks not generated yet need the same start.
- Adding or removing a mod with structures changes only chunks not generated yet, the same as features do now. Saved
chunks stay as they were, so there can be seams.
- Tests generate the same chunks in different orders and compare every block. A golden test records a few chunks with
structures in them, so changes to generation show up.
+6 -5
View File
@@ -5,16 +5,17 @@ with ores (data) and features (a worldgen script).
## Determinism
A save only keeps what players changed on top of the generated terrain. Everything else is generated again whenever a
chunk loads, so a chunk has to come out **exactly the same every time**. If it doesn't, blocks players broke reappear
and their builds end up half buried.
Every chunk is saved whole once it's generated, like Minecraft, so a saved chunk never changes when generation does.
Generation still has to come out **exactly the same every time**: a chunk is generated more than once, since what a
feature writes into a neighbor is generated again when that neighbor is (even years later, next to a saved chunk). If it
isn't the same, trees are cut off at chunk borders.
- **Never use `Math.random`, `Date`, `performance.now` or anything else that changes between runs.** Use the chunk's
`rng` and noise helpers, which are seeded from the world's seed.
- Don't keep state between chunks. Chunks generate in any order, and in several worldgen workers at once, each with its
own copy of the worldgen scripts (and the game generates a few itself).
- Adding or removing a mod's features is safe for chunks that haven't been generated yet, but changes existing worlds'
untouched terrain the next time it loads.
- Adding or removing a mod's features only changes chunks that haven't been generated yet, with seams where they meet
saved ones.
## The Passes
+2 -2
View File
@@ -247,8 +247,8 @@ filler down to its `filler_depth`. Everything else is stone.
## Changing the Base Game's Terrain
A mod can add biomes to it, but can't replace its files yet: an id defined by two mods is an error. Anything that
changes the terrain changes untouched land in existing worlds, the same as adding a [feature](index.md#features). The
worldgen fingerprint keeps chunks players changed as they were.
changes the terrain changes land not generated yet in existing worlds, the same as adding a
[feature](index.md#features). Every chunk generated is saved, so what's been generated stays as it was.
[Engine access](../misc/engine.md) mods can hook `engine.common.OverworldTerrain`, whose `density` and `cave` are called
for every cell corner.
+7 -7
View File
@@ -289,11 +289,11 @@ engine assets in `assets/`.
### Rules That Keep Existing Worlds Working
1. **Ids don't change.** Saves store blocks and items by string id, including inventories and chest contents.
2. **Terrain is identical, block for block.** A save only stores what players changed on top of generated terrain. If
the generator's output changes at all, every existing world silently changes with it. `tests/worldgen_golden_test.ts`
hashes 64 chunks for each of 3 seeds against `tests/fixtures/worldgen_golden.json`. A change meant to change
generation records it again (`deno test -A tests/worldgen_golden_test.ts -- --update`), and the worldgen fingerprint
(`ServerWorld.worldgen_fingerprint`) keeps chunks players saved as they were.
2. **Terrain doesn't change by accident.** Every chunk generated is saved whole, like Minecraft, so a change to
generation only shows in chunks not generated yet, with seams where they meet saved ones.
`tests/worldgen_golden_test.ts` hashes 64 chunks for each of 3 seeds against `tests/fixtures/worldgen_golden.json`,
so it's never a surprise. A change meant to change generation records it again
(`deno test -A tests/worldgen_golden_test.ts -- --update`).
3. **Old saves are upgraded when loading.** The save format can change, as long as older saves load into the new shape.
`tests/fixtures/` keeps a save from each version.
4. **The protocol can change, with `PROTOCOL_VERSION`.** Clients on another version are turned away before anything else
@@ -387,5 +387,5 @@ and a world saved before any of this plays exactly the same.
a goal for now.
- **Generation's loose ends.** The packaged desktop build hasn't been tried with the worldgen worker, which the desktop
task includes. In a world without land, the spawn search looks 32 chunks out on the game thread, which the server now
does at startup. Loading a save whose generation changed compares its chunks with the new generation on the game
thread.
does at startup. Saved chunks are read on the game thread, which waits for the host (see `read_chunk` in
`server/game/worker.ts`): much faster than generating them, but Minecraft reads them ahead instead.
+17 -18
View File
@@ -69,8 +69,8 @@ import { update_crafting_result } from "./crafting.ts";
import type { Menu } from "./menu.ts";
import { SavedPlayer, ServerPlayer } from "./player.ts";
import { encode_skin, MAX_SKIN_BYTES, skin_problem } from "./skins.ts";
import { FINGERPRINT_CHUNKS, ServerWorld, SPAWN_AREA_CHUNKS, Tile } from "./world.ts";
import type { WorldSave } from "./saves.ts";
import { ServerWorld, SPAWN_AREA_CHUNKS, Tile } from "./world.ts";
import type { WorldSave, WorldSource } from "./saves.ts";
import {
BLOCK_DROP_PICKUP_DELAY,
ITEM_ENTITY_TYPE,
@@ -135,8 +135,6 @@ export interface GameHost {
export interface SavedLevel {
version: 5;
seed: string;
// see ServerWorld.worldgen_fingerprint
worldgen: string;
// world time in ticks
time: number;
tiles: SavedTile[];
@@ -206,7 +204,7 @@ export class GameServer {
// world.fallbacks each second for the last minute, for /tps
#fallback_history: number[] = [];
constructor(host: GameHost, save: WorldSave | undefined, default_seed: string, mods: GameMods) {
constructor(host: GameHost, save: WorldSource | undefined, default_seed: string, mods: GameMods) {
this.#host = host;
this.#mods = mods;
this.mods = mods.runtime;
@@ -265,9 +263,7 @@ export class GameServer {
},
});
this.mods.storage = upgrade_mod_storage(saved?.mod_storage ?? {});
if (saved) {
this.world.load_chunks(save?.chunks ?? [], saved.worldgen);
}
if (save) this.world.use_saved_chunks(save.chunks);
this.world.time = saved?.time ?? 0;
this.#day = this.world.day;
for (const [id, items] of Object.entries(saved?.containers ?? {})) {
@@ -287,8 +283,8 @@ export class GameServer {
}
this.entities.load(saved?.version === 4 ? upgrade_v4_entities(saved.entities) : saved?.entities ?? []);
this.#saved_players = saved?.players ?? {};
// 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();
// a new world is saved straight away
this.world.dirty = !saved;
this.#register_commands();
// players without the chunk get the block with it when they do, like minecraft
@@ -430,7 +426,7 @@ export class GameServer {
}
}
// level.json and the chunks changed since the last save
// level.json and the chunks generated or changed since the last save
save(): Required<WorldSave> {
for (const player of this.#players.values()) {
this.#saved_players[player.name] = player.save_player();
@@ -438,7 +434,6 @@ export class GameServer {
const level: SavedLevel = {
version: 5,
seed: this.world.seed,
worldgen: this.world.worldgen_fingerprint(),
time: this.world.time,
tiles: [...this.world.tiles.values()].map((tile) => ({
id: tile.id,
@@ -1965,16 +1960,20 @@ export class GameServer {
}
// generates what's needed before players come with the pool, instead of on this thread when they do: the spawn
// search's chunks and the worldgen fingerprint's
// search's chunks
async warm_up() {
const pool = this.worldgen_pool;
if (!pool) return;
const reach = SPAWN_AREA_CHUNKS;
const around_spawn: [number, number][] = [];
for (let x = -reach; x <= reach; x++) for (let z = -reach; z <= reach; z++) around_spawn.push([x, z]);
await pool.prefetch([...around_spawn, ...FINGERPRINT_CHUNKS as [number, number][]]);
// what the chunks in it are built from, their neighbors' spills too. saved chunks need nothing
const reach = SPAWN_AREA_CHUNKS - 1;
const needed = new Map<string, [number, number]>();
for (let x = -reach; x <= reach; x++) {
for (let z = -reach; z <= reach; z++) {
for (const [rx, rz] of this.world.raws_needed(x, z)) needed.set(`${rx},${rz}`, [rx, rz]);
}
}
await pool.prefetch([...needed.values()]);
this.world.spawn_point();
this.world.worldgen_fingerprint();
}
// asks the pool for the raw chunks the nearest chunks each player is waiting for are built from, nearest first.
+12 -2
View File
@@ -3,10 +3,18 @@ import type { WorldSave } from "./saves.ts";
// messages between server/main.ts (the host) and the game server worker
// read_chunk's buffer: an i32 the game waits on while it's READ_WAITING, then an i32 the chunk's length, then the
// chunk. a length of -1 is no chunk. READ_TOO_SMALL says the buffer is too small and the length is how big the chunk is
export const READ_WAITING = 0;
export const READ_DONE = 1;
export const READ_TOO_SMALL = 2;
export const READ_HEADER = 8;
export type HostToGame =
| {
type: "init";
save: WorldSave;
// level.json, and where the saved chunks are. the game reads them with read_chunk when it needs them
save: { level?: string; chunks: [number, number][] };
default_seed: string;
// in load order, with the scripts' code since the worker can't read files
mods: {
@@ -36,7 +44,9 @@ export type GameToHost =
// text is a json message, bytes a binary one
| { type: "send"; conn: number; data: string | Uint8Array<ArrayBuffer> }
| { type: "close"; conn: number }
// level.json and the chunks that changed
// level.json and the chunks generated or changed since the last save
| { type: "save"; save: Required<WorldSave>; final: boolean }
// the game waits on buffer for a saved chunk, see READ_WAITING
| { type: "read_chunk"; x: number; z: number; buffer: SharedArrayBuffer }
// 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 };
+2 -2
View File
@@ -5,7 +5,7 @@ import type { ModData, ModListing } from "$/common/mod_loader.ts";
import { load_worldgen } from "$/common/worldgen_loader.ts";
import { worldgen_bundle } from "$/common/worldgen_bundle.ts";
import { GameHost, GameServer } from "./game_server.ts";
import type { WorldSave } from "./saves.ts";
import type { WorldSource } from "./saves.ts";
import { ModRuntime } from "./mod_runtime.ts";
import { register_entity_type } from "./entity/entity_types.ts";
import { mod_entity_factory } from "./entity/mod_entity.ts";
@@ -29,7 +29,7 @@ export interface ServerModSource {
export async function start_game(
host: GameHost,
save: WorldSave | undefined,
save: WorldSource | undefined,
default_seed: string,
mods: ServerModSource[],
): Promise<GameServer> {
+12 -2
View File
@@ -3,9 +3,12 @@ export class LruMap<K, V> {
#map = new Map<K, V>();
#newest: K | undefined;
readonly max_size: number;
// called with what's forgotten for being the least recently used
#on_evict?: (key: K, value: V) => void;
constructor(max_size: number) {
constructor(max_size: number, on_evict?: (key: K, value: V) => void) {
this.max_size = max_size;
this.#on_evict = on_evict;
}
get(key: K): V | undefined {
@@ -26,7 +29,9 @@ export class LruMap<K, V> {
this.#map.delete(key);
this.#map.set(key, value);
if (this.#map.size > this.max_size) {
this.#map.delete(this.#map.keys().next().value!);
const [oldest, value] = this.#map.entries().next().value!;
this.#map.delete(oldest);
this.#on_evict?.(oldest, value);
}
}
@@ -35,6 +40,11 @@ export class LruMap<K, V> {
return this.#map.has(key);
}
// get without counting as a use
peek(key: K): V | undefined {
return this.#map.get(key);
}
delete(key: K) {
this.#map.delete(key);
}
+67 -26
View File
@@ -5,13 +5,17 @@
// 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
// u8 biome palette size, then each entry: u8 id length, the id as utf-8
// the biome palette index of every column, u8 each, in the order of a layer's blocks
//
// 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
// meaning other blocks. every chunk the game generates is saved whole, like minecraft's, so a change to world
// generation only shows in chunks never generated before.
// format 1 had no biomes, and a bit per block after the blocks for whether world generation made it, from when only
// chunks players changed were saved. both are read
import { CHUNK_AREA, CHUNK_HEIGHT } from "$/common/constants.ts";
export const CHUNK_FORMAT = 1;
export const CHUNK_FORMAT = 2;
export const CHUNK_VOLUME = CHUNK_AREA * CHUNK_HEIGHT;
export interface SavedChunk {
@@ -20,32 +24,45 @@ export interface SavedChunk {
data: Uint8Array<ArrayBuffer>;
}
// a world as the host reads it and the game saves it. the game only saves the chunks that changed since it last did
// a world as the game saves it: level.json's text and the chunks that changed since it last saved
export interface WorldSave {
// level.json, without it the world is new
level?: string;
chunks: SavedChunk[];
}
// a world for the game to load. its chunks are read when they're needed, there can be far too many to keep
export interface WorldSource {
level?: string;
chunks: SavedChunks;
}
export interface SavedChunks {
// where every saved chunk is
list: [number, number][];
// a saved chunk's bytes, see encode_chunk. undefined when it can't be read, which generates it again
read(chunk_x: number, chunk_z: number): Uint8Array | undefined;
}
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;
// each column's, see ServerWorld.biome_at. format 1 chunks don't have them
biomes?: string[];
}
export function is_changed(chunk: ChunkBlocks, index: number) {
return (chunk.changed[index >> 3] & (1 << (index & 7))) !== 0;
}
export function encode_chunk(chunk: ChunkBlocks): Uint8Array<ArrayBuffer> {
export function encode_chunk(chunk: Required<ChunkBlocks>): Uint8Array<ArrayBuffer> {
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 biome_palette = [...new Set(chunk.biomes)];
if (chunk.biomes.length !== CHUNK_AREA || biome_palette.length > 255) throw new Error("Bad biomes");
const biome_ids = biome_palette.map((id) => new TextEncoder().encode(id));
if (biome_ids.some((id) => id.length > 255)) throw new Error("A biome id is too long to save");
const size = 1 + 4 + ids.reduce((sum, id) => sum + 1 + id.length + 2, 0) + CHUNK_VOLUME * (wide ? 2 : 1) +
1 + biome_ids.reduce((sum, id) => sum + 1 + id.length, 0) + CHUNK_AREA;
const bytes = new Uint8Array(size);
const view = new DataView(bytes.buffer);
let offset = 0;
@@ -59,15 +76,22 @@ export function encode_chunk(chunk: ChunkBlocks): Uint8Array<ArrayBuffer> {
view.setUint16(offset, state);
offset += 2;
});
for (let i = 0; i < CHUNK_VOLUME; i++) {
if (wide) {
if (wide) {
for (let i = 0; i < CHUNK_VOLUME; i++) {
view.setUint16(offset, chunk.blocks[i]);
offset += 2;
} else {
bytes[offset++] = chunk.blocks[i];
}
} else {
bytes.set(chunk.blocks, offset);
offset += CHUNK_VOLUME;
}
bytes.set(chunk.changed, offset);
view.setUint8(offset++, biome_palette.length);
for (const id of biome_ids) {
view.setUint8(offset++, id.length);
bytes.set(id, offset);
offset += id.length;
}
for (const biome of chunk.biomes) bytes[offset++] = biome_palette.indexOf(biome);
return bytes;
}
@@ -76,7 +100,7 @@ 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}`);
if (format !== CHUNK_FORMAT && format !== 1) 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");
@@ -89,19 +113,36 @@ export function decode_chunk(bytes: Uint8Array): ChunkBlocks {
offset += 2;
}
const wide = palette_size > 256;
if (bytes.length !== offset + CHUNK_VOLUME * (wide ? 2 : 1) + CHUNK_VOLUME / 8) {
if (format === 1 && bytes.length !== offset + CHUNK_VOLUME * (wide ? 2 : 1) + CHUNK_VOLUME / 8) {
throw new Error("Wrong size");
}
if (bytes.length < offset + CHUNK_VOLUME * (wide ? 2 : 1)) throw new Error("Wrong size");
const blocks = new Uint16Array(CHUNK_VOLUME);
for (let i = 0; i < CHUNK_VOLUME; i++) {
if (wide) {
if (wide) {
for (let i = 0; i < CHUNK_VOLUME; i++) {
blocks[i] = view.getUint16(offset);
offset += 2;
} else {
blocks[i] = bytes[offset++];
}
} else {
blocks.set(bytes.subarray(offset, offset + CHUNK_VOLUME));
offset += CHUNK_VOLUME;
}
for (let i = 0; i < CHUNK_VOLUME; i++) {
if (blocks[i] >= palette_size) throw new Error("Bad palette index");
}
const changed = bytes.slice(offset, offset + CHUNK_VOLUME / 8);
return { palette, blocks, changed };
if (format === 1) return { palette, blocks };
const biome_palette: string[] = [];
const biome_palette_size = view.getUint8(offset++);
for (let i = 0; i < biome_palette_size; i++) {
const length = view.getUint8(offset++);
biome_palette.push(new TextDecoder().decode(bytes.subarray(offset, offset + length)));
offset += length;
}
if (bytes.length !== offset + CHUNK_AREA) throw new Error("Wrong size");
const biomes = [...bytes.subarray(offset)].map((index) => {
if (index >= biome_palette_size) throw new Error("Bad biome palette index");
return biome_palette[index];
});
return { palette, blocks, biomes };
}
+26 -2
View File
@@ -3,19 +3,23 @@
// runs the game in a worker without any permissions, the host does files and networking
import type { GameServer } from "./game_server.ts";
import { GameLoop } from "./game_loop.ts";
import { GameToHost, HostToGame } from "./host_protocol.ts";
import { GameToHost, HostToGame, READ_DONE, READ_HEADER, READ_TOO_SMALL, READ_WAITING } from "./host_protocol.ts";
import { data_url, start_game } from "./load_mods.ts";
import { type WorkerPort, WorldgenPool } from "./worldgen_pool.ts";
const SAVE_INTERVAL_MS = 30_000;
// how long the worldgen workers get to load the mods before the game starts without them
const WORLDGEN_START_TIMEOUT_MS = 60_000;
// a host that takes longer to read a chunk is stuck, and the game can't go on without it
const CHUNK_READ_TIMEOUT_MS = 30_000;
let game: GameServer | undefined;
let starting: Promise<void> | undefined;
// downloads waiting for the host, by id
const downloads = new Map<number, { resolve: (bytes: Uint8Array) => void; reject: (error: Error) => void }>();
let next_download = 1;
// where the host puts saved chunks, grown when one doesn't fit
let chunk_buffer = new SharedArrayBuffer(READ_HEADER + 256 * 1024);
function post(message: GameToHost) {
// the chunks are moved to the host, not copied
@@ -27,6 +31,26 @@ function post(message: GameToHost) {
self.postMessage(message, transfer);
}
// a saved chunk from the host. the game waits for it, like minecraft's server waits for a chunk it needs right away,
// which takes much less than generating it
function read_chunk(x: number, z: number): Uint8Array | undefined {
for (;;) {
const header = new Int32Array(chunk_buffer, 0, 2);
Atomics.store(header, 0, READ_WAITING);
post({ type: "read_chunk", x, z, buffer: chunk_buffer });
if (Atomics.wait(header, 0, READ_WAITING, CHUNK_READ_TIMEOUT_MS) === "timed-out") {
throw new Error(`The host didn't read chunk ${x}, ${z}`);
}
const length = header[1];
if (Atomics.load(header, 0) === READ_TOO_SMALL) {
chunk_buffer = new SharedArrayBuffer(READ_HEADER + length);
continue;
}
if (Atomics.load(header, 0) !== READ_DONE) throw new Error(`Bad answer reading chunk ${x}, ${z}`);
return length < 0 ? undefined : new Uint8Array(chunk_buffer, READ_HEADER, length).slice();
}
}
self.onmessage = async (event: MessageEvent<HostToGame>) => {
const message = event.data;
@@ -86,7 +110,7 @@ async function init(message: Extract<HostToGame, { type: "init" }>) {
post({ type: "download", id, url, max_bytes });
}),
},
message.save,
{ level: message.save.level, chunks: { list: message.save.chunks, read: read_chunk } },
message.default_seed,
message.mods.map((mod) => ({
listing: mod.listing,
+145 -140
View File
@@ -6,7 +6,7 @@ import {
EverythingRegistry,
} from "$/common/everything_registry.ts";
import { generate_raw_chunk, RawChunk, WorldgenSetup } from "$/common/generation.ts";
import { AIR_ID, BlockChange } from "$/common/protocol.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";
@@ -14,7 +14,7 @@ import { collision_shape_at, EMPTY_SHAPE, type Shape } from "$/common/block_shap
import { farming_day } from "$/common/time.ts";
import { encode_level_chunk } from "$/common/chunk_streaming.ts";
import type { ItemData } from "$/common/inventory.ts";
import { CHUNK_VOLUME, ChunkBlocks, decode_chunk, encode_chunk, is_changed, SavedChunk } from "./saves.ts";
import { CHUNK_VOLUME, ChunkBlocks, decode_chunk, encode_chunk, SavedChunk, SavedChunks } from "./saves.ts";
// generation only, rebuilt when needed. 256 KB each. 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
@@ -32,8 +32,6 @@ const LIGHT_BOX = LIGHT_REACH * 2 + 1;
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;
// generated for worldgen_fingerprint, spread out so most changes to world generation touch at least one
export 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, but for item
export interface Tile {
@@ -47,11 +45,19 @@ export interface Tile {
item?: ItemData;
}
// a chunk as it is now, loaded from the save or generated
interface LoadedChunk {
blocks: Uint32Array;
biomes: string[];
// saved blocks of mods that are gone, by index in the chunk. air in blocks, and saved again until replaced
unknown?: Map<number, [string, number]>;
}
export function position_key(x: number, y: number, z: number) {
return `${x},${y},${z}`;
}
// the authoritative world: generated terrain plus everything players changed
// 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<string, number> = {};
@@ -62,9 +68,10 @@ export class ServerWorld {
#opacity: Uint8Array;
#emission: Uint8Array;
// what generation made, and the final blocks with neighbors' leaves and player changes applied
// 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<number, RawChunk>(RAW_CACHE_SIZE);
#chunks = new LruMap<number, Uint32Array>(CHUNK_CACHE_SIZE);
#chunks = new LruMap<number, LoadedChunk>(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<number, string[]>(SPILL_CACHE_SIZE);
#spills = new LruMap<number, Int32Array>(SPILL_CACHE_SIZE);
@@ -76,10 +83,13 @@ export class ServerWorld {
// 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<number, Int16Array>(COLUMN_CACHE_SIZE);
// changes from generated terrain, per chunk. saved as whole chunks
#changes = new Map<number, Map<string, BlockChange>>();
// chunks changed since they were last saved, by chunk_key
// 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<number>();
// chunks generated or changed since they were last saved, by chunk_key
#unsaved = new Map<number, [number, number]>();
// unsaved chunks #chunks forgot, ready to save, by chunk_key
#evicted = new Map<number, SavedChunk>();
tiles = new Map<string, Tile>();
// the tiles showing an item, by chunk_key, to send with their chunk
#item_tiles = new Map<number, Set<Tile>>();
@@ -195,8 +205,17 @@ export class ServerWorld {
biome_at(x: number, z: number): string {
const chunk_x = Math.floor(x / CHUNK_SIZE);
const chunk_z = Math.floor(z / CHUNK_SIZE);
const biomes = this.#biomes.get(chunk_key(chunk_x, chunk_z)) ?? this.#get_raw(chunk_x, chunk_z).biomes;
return biomes[column_index(x, z)];
return this.#chunk_biomes(chunk_x, chunk_z)[column_index(x, 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.biomes;
if (this.#is_saved(key)) return this.#get_loaded(chunk_x, chunk_z).biomes;
return this.#biomes.get(key) ?? this.#get_raw(chunk_x, chunk_z).biomes;
}
// builds the chunk now if it isn't, generating what it needs on this thread
@@ -217,7 +236,7 @@ export class ServerWorld {
// 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
find_blocks(chunk_x: number, chunk_z: number, wanted: Uint8Array): [number, number, number][] {
const blocks = this.#chunks.get(chunk_key(chunk_x, chunk_z));
const blocks = this.#chunks.get(chunk_key(chunk_x, chunk_z))?.blocks;
if (!blocks) return [];
const found: [number, number, number][] = [];
for (let i = 0; i < blocks.length; i++) {
@@ -356,14 +375,15 @@ export class ServerWorld {
const chunk_x = Math.floor(x / CHUNK_SIZE);
const chunk_z = Math.floor(z / CHUNK_SIZE);
const blocks = this.#get_chunk(chunk_x, chunk_z);
blocks[index_in_chunk(x, y, z, chunk_x, chunk_z)] = value;
const chunk = this.#get_loaded(chunk_x, chunk_z);
const index = index_in_chunk(x, y, z, chunk_x, chunk_z);
chunk.blocks[index] = value;
chunk.unknown?.delete(index);
this.#columns.delete(chunk_key(chunk_x, chunk_z));
this.#mark_unsaved(chunk_x, chunk_z);
const state_bits = value >>> 16;
this.#record_change(x, y, z, id, state_bits);
this.dirty = true;
this.on_block_change?.(x, y, z, id, state_bits);
}
@@ -372,8 +392,7 @@ export class ServerWorld {
return encode_level_chunk({
x: chunk_x,
z: chunk_z,
blocks: this.#get_chunk(chunk_x, chunk_z),
biomes: this.#biomes.get(chunk_key(chunk_x, chunk_z)) ?? this.#get_raw(chunk_x, chunk_z).biomes,
...this.#get_loaded(chunk_x, chunk_z),
});
}
@@ -387,86 +406,25 @@ export class ServerWorld {
return table;
}
#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<number>) => {
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;
// 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));
}
// 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;
}
this.#columns.delete(chunk_key(chunk_x, chunk_z));
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
// every chunk generated or 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)),
}));
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_x: number, chunk_z: number): ChunkBlocks {
#chunk_blocks(chunk: LoadedChunk): Required<ChunkBlocks> {
const palette: [string, number][] = [];
const palette_index = new Map<string, number>();
const index_of = (id: string, state: number) => {
@@ -481,27 +439,28 @@ export class ServerWorld {
const blocks = new Uint16Array(CHUNK_VOLUME);
const by_value = new Map<number, number>();
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<BlockRegistry>("blocks", nid)?.id ?? AIR_ID;
index = index_of(id, value >>> 16);
by_value.set(value, index);
// runs of the same block are common, air above the ground and stone below
let last_value = -1;
let last_index = 0;
for (let i = 0; i < CHUNK_VOLUME; i++) {
const value = chunk.blocks[i];
if (value !== last_value) {
let index = by_value.get(value);
if (index === undefined) {
const nid = value & ID_MASK;
const id = nid === AIR
? AIR_ID
: EverythingRegistry.get_by_id<BlockRegistry>("blocks", nid)?.id ?? AIR_ID;
index = index_of(id, value >>> 16);
by_value.set(value, index);
}
last_value = value;
last_index = 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);
blocks[i] = last_index;
}
return { palette, blocks, changed };
for (const [i, [id, state]] of chunk.unknown ?? []) blocks[i] = index_of(id, state);
return { palette, blocks, biomes: chunk.biomes };
}
get_tile(x: number, y: number, z: number) {
@@ -547,15 +506,14 @@ export class ServerWorld {
return this.#item_tiles.get(chunk_key(chunk_x, chunk_z)) ?? [];
}
#record_change(x: number, y: number, z: number, id: string, state: number) {
const key = chunk_key(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE));
let chunk_changes = this.#changes.get(key);
if (!chunk_changes) {
chunk_changes = new Map();
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)]);
#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) {
@@ -585,16 +543,17 @@ export class ServerWorld {
if (!this.#raw.has(key)) this.#keep_raw(key, raw);
}
// whether the chunk is built, or can be without generating anything: its own raw blocks and its neighbors' spills
// are here
// 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: its own, if it isn't built and its blocks aren't here,
// and its neighbors' whose spills aren't
// 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][] {
if (this.#chunks.has(chunk_key(chunk_x, chunk_z))) return [];
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++) {
@@ -612,25 +571,71 @@ export class ServerWorld {
}
#get_chunk(chunk_x: number, chunk_z: number) {
const key = chunk_key(chunk_x, chunk_z);
let blocks = this.#chunks.get(key);
if (!blocks) {
blocks = this.#build_chunk(chunk_x, chunk_z);
this.#chunks.set(key, blocks);
}
return blocks;
return this.#get_loaded(chunk_x, chunk_z).blocks;
}
// 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);
#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}`,
);
}
}
return blocks;
const blocks = this.#generate_chunk(chunk_x, chunk_z);
this.#mark_unsaved(chunk_x, chunk_z);
return { blocks, biomes: this.#biomes.get(key) ?? this.#get_raw(chunk_x, chunk_z).biomes };
}
#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);
});
const blocks = new Uint32Array(CHUNK_VOLUME);
let unknown: Map<number, [string, number]> | undefined;
for (let i = 0; i < CHUNK_VOLUME; i++) {
const value = values[saved.blocks[i]];
if (value === undefined) {
(unknown ??= new Map()).set(i, saved.palette[saved.blocks[i]]);
} else {
blocks[i] = value;
}
}
let biomes = saved.biomes;
if (!biomes) {
// saved before chunks had them. saved again with them
biomes = this.#biomes.get(chunk_key(chunk_x, chunk_z)) ?? this.#get_raw(chunk_x, chunk_z).biomes;
this.#mark_unsaved(chunk_x, chunk_z);
}
return { blocks, 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)) });
}
// own blocks, then neighbors' leaves only into air
+50 -15
View File
@@ -2,11 +2,11 @@
// server/main.ts runs it as a dedicated server, and the desktop app runs it for singleplayer
import { serveDir, serveFile } from "@std/http/file-server";
import { join } from "@std/path";
import { GameToHost, HostToGame } from "./game/host_protocol.ts";
import { GameToHost, HostToGame, READ_DONE, READ_HEADER, READ_TOO_SMALL } from "./game/host_protocol.ts";
import { load_bmods } from "./load_bmods.ts";
import { read_regions, write_chunks } from "./regions.ts";
import { list_chunks, read_chunk, write_chunks } from "./regions.ts";
import { default_worldgen_workers, start_worldgen_workers } from "./worldgen_workers.ts";
import type { SavedChunk, WorldSave } from "./game/saves.ts";
import type { SavedChunk } from "./game/saves.ts";
const MAX_MESSAGE_SIZE = 4096;
// in build/, see build.ts
@@ -62,8 +62,9 @@ export async function start_host(options: HostOptions): Promise<Host> {
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<string, SavedChunk>();
// chunks from saves that aren't written yet, by "x,z": the game reads them from here. ones that couldn't be written
// are tried again with the next save
const unwritten = new Map<string, SavedChunk>();
game.onmessage = (event: MessageEvent<GameToHost>) => {
const message = event.data;
@@ -86,14 +87,16 @@ export async function start_host(options: HostOptions): Promise<Host> {
break;
case "save": {
const { save, final } = message;
for (const chunk of save.chunks) unwritten.set(`${chunk.x},${chunk.z}`, chunk);
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();
// unless a later save has them again
for (const [key, chunk] of chunks) {
if (unwritten.get(key) === chunk) unwritten.delete(key);
}
} catch (e) {
unwritten = chunks;
console.error(`Couldn't save the world: ${(e as Error).message}`);
if (final) on_final_save?.(e as Error);
return;
@@ -105,6 +108,19 @@ export async function start_host(options: HostOptions): Promise<Host> {
});
break;
}
case "read_chunk": {
const { x, z, buffer } = message;
const unwritten_chunk = unwritten.get(`${x},${z}`);
(unwritten_chunk
? Promise.resolve(unwritten_chunk.data)
: read_chunk(region_dir(options.world_dir), x, z))
.catch((e) => {
console.error(`Couldn't read chunk ${x}, ${z}: ${(e as Error).message}`);
return undefined;
})
.then((data) => answer_chunk_read(buffer, data));
break;
}
case "download":
download(message.url, message.max_bytes).then(
(bytes) => post({ type: "downloaded", id: message.id, bytes }),
@@ -120,6 +136,7 @@ export async function start_host(options: HostOptions): Promise<Host> {
};
const save = await read_world(options.world_dir);
if (save.chunks.length) console.log(`${save.chunks.length} chunks saved`);
game.postMessage(
{
type: "init",
@@ -134,7 +151,7 @@ export async function start_host(options: HostOptions): Promise<Host> {
})),
worldgen_ports: worldgen.ports,
} satisfies HostToGame,
[...save.chunks.map((chunk) => chunk.data.buffer), ...worldgen.ports],
worldgen.ports,
);
function handle_socket(socket: WebSocket) {
@@ -271,20 +288,38 @@ async function download(url: string, max_bytes: number): Promise<Uint8Array> {
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<WorldSave> {
function region_dir(world_dir: string) {
return join(world_dir, REGION_DIR);
}
// level.json and where the saved chunks are. a folder that isn't there is a new world
async function read_world(dir: string): Promise<{ level?: string; chunks: [number, number][] }> {
let level: string | undefined;
try {
level = Deno.readTextFileSync(join(dir, LEVEL_FILE));
} catch (e) {
if (!(e instanceof Deno.errors.NotFound)) throw e;
}
return { level, chunks: level ? await read_regions(join(dir, REGION_DIR)) : [] };
return { level, chunks: level ? await list_chunks(region_dir(dir)) : [] };
}
// the chunks first, level.json says which world generation they were saved with
async function write_world(dir: string, save: Required<WorldSave>) {
await write_chunks(join(dir, REGION_DIR), save.chunks);
// gives the game waiting in read_chunk the chunk, see READ_WAITING
function answer_chunk_read(buffer: SharedArrayBuffer, data: Uint8Array | undefined) {
const header = new Int32Array(buffer, 0, 2);
if (data && READ_HEADER + data.length > buffer.byteLength) {
header[1] = data.length;
Atomics.store(header, 0, READ_TOO_SMALL);
} else {
if (data) new Uint8Array(buffer, READ_HEADER).set(data);
header[1] = data ? data.length : -1;
Atomics.store(header, 0, READ_DONE);
}
Atomics.notify(header, 0);
}
// the chunks first, then level.json
async function write_world(dir: string, save: { level: string; chunks: SavedChunk[] }) {
await write_chunks(region_dir(dir), save.chunks);
Deno.mkdirSync(dir, { recursive: true });
// write then rename so a crash mid write doesnt eat the world
const level = join(dir, LEVEL_FILE);
+50 -25
View File
@@ -8,7 +8,8 @@
// 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
// saving leaves the chunks as they were instead of half written. the game reads chunks one at a time, when it needs
// them
import { join } from "@std/path";
import type { SavedChunk } from "./game/saves.ts";
@@ -26,8 +27,8 @@ 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<SavedChunk[]> {
// where every chunk in the folder's region files is, from their headers
export async function list_chunks(dir: string): Promise<[number, number][]> {
let entries: Deno.DirEntry[];
try {
entries = [...Deno.readDirSync(dir)];
@@ -35,39 +36,62 @@ export async function read_regions(dir: string): Promise<SavedChunk[]> {
if (e instanceof Deno.errors.NotFound) return [];
throw e;
}
const chunks: SavedChunk[] = [];
const chunks: [number, number][] = [];
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) {
using file = await Deno.open(join(dir, entry.name));
const header = new Uint8Array(CHUNKS_PER_REGION * 4);
if (await read_at(file, 0, header) < header.length) {
console.error(`${entry.name} is too short to be a region file`);
continue;
}
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const view = new DataView(header.buffer);
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}`);
}
if (view.getUint32(i * 4) === 0) continue;
chunks.push([
region_x * REGION_CHUNKS + (i % REGION_CHUNKS),
region_z * REGION_CHUNKS + Math.floor(i / REGION_CHUNKS),
]);
}
}
return chunks;
}
// a chunk from its region file, uncompressed. undefined when it isn't there. throws when it can't be read
export async function read_chunk(dir: string, x: number, z: number): Promise<Uint8Array<ArrayBuffer> | undefined> {
const name = region_file(Math.floor(x / REGION_CHUNKS), Math.floor(z / REGION_CHUNKS));
using file = await open_if_there(join(dir, name));
if (!file) return undefined;
const location_bytes = new Uint8Array(4);
await read_at(file, chunk_index(x, z) * 4, location_bytes);
const location = new DataView(location_bytes.buffer).getUint32(0);
if (location === 0) return undefined;
const sectors = new Uint8Array((location & 0xFF) * SECTOR);
const read = await read_at(file, (location >>> 8) * SECTOR, sectors);
const view = new DataView(sectors.buffer);
if (read < 5) throw new Error(`chunk ${x}, ${z} goes past the end of ${name}`);
const length = view.getUint32(0);
const compression = view.getUint8(4);
if (compression !== ZLIB) throw new Error(`chunk ${x}, ${z} in ${name} has unknown compression ${compression}`);
if (length < 1 || 4 + length > read) throw new Error(`chunk ${x}, ${z} goes past the end of ${name}`);
return await inflate(sectors.subarray(5, 4 + length));
}
async function open_if_there(path: string) {
try {
return await Deno.open(path);
} catch (e) {
if (e instanceof Deno.errors.NotFound) return undefined;
throw e;
}
}
function chunk_index(x: number, z: number) {
return (x & (REGION_CHUNKS - 1)) + (z & (REGION_CHUNKS - 1)) * REGION_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<string, SavedChunk[]>();
@@ -115,7 +139,7 @@ async function write_region(path: string, chunks: SavedChunk[]) {
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;
const index = chunk_index(chunk.x, chunk.z);
view.setUint32(index * 4, (first << 8) | sectors);
view.setUint32(SECTOR + index * 4, now);
}
@@ -138,7 +162,7 @@ function free_sectors(used: boolean[], count: number) {
return start;
}
// reads as much of bytes as the file has there, a new file reads as zeros
// reads as much of bytes as the file has there, a new file reads as zeros. returns how much that was
async function read_at(file: Deno.FsFile, offset: number, bytes: Uint8Array) {
await file.seek(offset, Deno.SeekMode.Start);
let read = 0;
@@ -147,6 +171,7 @@ async function read_at(file: Deno.FsFile, offset: number, bytes: Uint8Array) {
if (n === null) break;
read += n;
}
return read;
}
async function write_at(file: Deno.FsFile, offset: number, bytes: Uint8Array) {
+88
View File
@@ -11,6 +11,9 @@ import { load_bmods } from "$/server/load_bmods.ts";
import { start_host } from "$/server/host.ts";
import { copy_dir } from "./helpers.ts";
import { PROTOCOL_VERSION } from "$/common/protocol.ts";
import { decode_level_chunk, type LevelChunk } from "$/common/chunk_streaming.ts";
import { decode_chunk, encode_chunk } from "$/server/game/saves.ts";
import { list_chunks, read_chunk, write_chunks } from "$/server/regions.ts";
const ENGINE_TEXTURES = ["engine:missing", ...Array.from({ length: 9 }, (_, i) => `engine:break_${i}`)];
@@ -324,6 +327,91 @@ Deno.test({
},
});
// joins a host as alice with view distance 4, until she has every chunk in view
async function join_host(port: number): Promise<LevelChunk[]> {
const socket = new WebSocket(`ws://localhost:${port}/ws`);
socket.binaryType = "arraybuffer";
const chunks: LevelChunk[] = [];
await new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error(`only ${chunks.length} chunks came`)), 60_000);
socket.onmessage = (event) => {
if (typeof event.data !== "string") {
chunks.push(decode_level_chunk(new Uint8Array(event.data)));
return;
}
const message = JSON.parse(event.data);
if (message.type === "welcome") socket.send(JSON.stringify({ type: "ready", view_distance: 4 }));
if (message.type === "chunk_batch_finished") {
socket.send(JSON.stringify({ type: "chunk_batch_received", chunks_per_tick: 64 }));
if (chunks.length >= 49) {
clearTimeout(timer);
resolve();
}
}
};
socket.onopen = () => socket.send(JSON.stringify({ type: "hello", name: "alice", protocol: PROTOCOL_VERSION }));
});
const closed = new Promise((resolve) => socket.onclose = resolve);
socket.close();
await closed;
return chunks;
}
Deno.test({
name: "a real host saves every chunk it generates, and players get them from the save after it starts again",
sanitizeOps: false,
sanitizeResources: false,
fn: async () => {
const { sources, folder } = await packed_mods();
const build = Deno.makeTempDirSync({ prefix: "bworld_build_" });
Deno.mkdirSync(`${build}/assets/textures`, { recursive: true });
Deno.writeTextFileSync(
`${build}/assets/textures/index.json`,
JSON.stringify(ENGINE_TEXTURES.slice(1).map((id) => id.split(":")[1])),
);
const run = async () => {
const host = await start_host({
build_dir: build,
server_mods_dir: folder,
world_dir: `${build}/world`,
seed: "saving-seed",
worldgen_workers: 2,
on_fatal: (message) => {
throw new Error(message);
},
});
const server = Deno.serve({ port: 0, onListen: () => {} }, host.handle);
try {
return await join_host(server.addr.port);
} finally {
await server.shutdown();
await host.shutdown();
}
};
try {
const first = await run();
const region = `${build}/world/region`;
const saved = await list_chunks(region);
for (const chunk of first) assert(saved.some(([x, z]) => x === chunk.x && z === chunk.z));
// a block at the top of every saved chunk, which generation never puts there
await write_chunks(
region,
await Promise.all(saved.map(async ([x, z]) => {
const chunk = decode_chunk((await read_chunk(region, x, z))!);
chunk.blocks[255 * 256] = chunk.palette.push(["bworld:stone", 0]) - 1;
return { x, z, data: encode_chunk(chunk as Required<typeof chunk>) };
})),
);
const second = await run();
assert(second.length >= 49);
for (const chunk of second) assert(chunk.blocks[255 * 256] !== 0, `${chunk.x},${chunk.z} is from the save`);
} finally {
for (const dir of [sources, folder, build]) Deno.removeSync(dir, { recursive: true });
}
},
});
// write_bmod without anything optional still makes a file read_bmod takes
Deno.test("a mod with only data packs and reads", () => {
const bmod = {
-1
View File
@@ -22,7 +22,6 @@ export async function game_with_pool(workers: number, seed?: string, mods_dir =
// ticks, answering chunk batches like a client, until the player has every chunk in view. the chunks they got, by
// "x,z", and how long the longest tick took
// deno-lint-ignore no-explicit-any
export async function load_view(
t: Awaited<ReturnType<typeof test_game>>,
conn: number,
+33 -2
View File
@@ -7,7 +7,7 @@ import { start_game } from "$/server/game/load_mods.ts";
import { PROTOCOL_VERSION } from "$/common/protocol.ts";
import { decode_level_chunk } from "$/common/chunk_streaming.ts";
import { CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "$/common/constants.ts";
import type { WorldSave } from "$/server/game/saves.ts";
import type { SavedChunk, SavedChunks, 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[] {
@@ -53,6 +53,23 @@ export function mod_sources(mods_dir: string): ServerModSource[] {
});
}
// saved chunks kept in memory, the last saved where a chunk is saved more than once
class MemoryChunks implements SavedChunks {
#chunks = new Map<string, SavedChunk>();
get list(): [number, number][] {
return [...this.#chunks.values()].map(({ x, z }) => [x, z]);
}
read(x: number, z: number) {
return this.#chunks.get(`${x},${z}`)?.data;
}
add(chunks: SavedChunk[]) {
for (const chunk of chunks) this.#chunks.set(`${chunk.x},${chunk.z}`, chunk);
}
}
// a game with an in memory host that remembers what it sent to each connection. the seed has low, dry land around
// 0, 0, where players spawn and where tests build things
export async function test_game(mods_dir: string, save?: WorldSave, seed = "test-seed-90") {
@@ -77,7 +94,21 @@ export async function test_game(mods_dir: string, save?: WorldSave, seed = "test
return bytes ? Promise.resolve(bytes) : Promise.reject(new Error("Couldn't download it"));
},
};
const game: GameServer = await start_game(host, save, seed, mod_sources(mods_dir));
const chunks = new MemoryChunks();
if (save) chunks.add(save.chunks);
const game: GameServer = await start_game(
host,
{ level: save?.level, chunks },
seed,
mod_sources(mods_dir),
);
// what it saves is read back from memory, like a host's region files
const save_game = game.save.bind(game);
game.save = () => {
const saved = save_game();
chunks.add(saved.chunks);
return saved;
};
game.chunk_send_budget_ms = Infinity;
// tests that want natural spawning turn it back on
game.do_mob_spawning = false;
+116 -55
View File
@@ -1,27 +1,48 @@
import { assert, assertEquals, assertNotEquals } from "@std/assert";
import { assert, assertEquals } 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 { CHUNK_AREA } from "$/common/constants.ts";
import { CHUNK_VOLUME, decode_chunk, encode_chunk, SavedChunk } from "$/server/game/saves.ts";
import { list_chunks, read_chunk, region_file, write_chunks } from "$/server/regions.ts";
import { sent_block, 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 };
const biomes = Array.from({ length: CHUNK_AREA }, (_, i) => `test:biome_${(i * seed) % 4}`);
return { palette, blocks, biomes };
}
Deno.test("a chunk's blocks come back as they were saved, with more than 256 kinds too", () => {
const index = (x: number, y: number, z: number) => y * CHUNK_AREA + z * 16 + x;
// what a chunk was saved as before chunks had biomes: a bit per block after the blocks instead, for whether world
// generation made it
function format_1(data: Uint8Array<ArrayBuffer>) {
const chunk = decode_chunk(data);
const biomes = 1 +
[...new Set(chunk.biomes)].reduce((sum, id) => sum + 1 + new TextEncoder().encode(id).length, 0) +
CHUNK_AREA;
const old = new Uint8Array(data.length - biomes + CHUNK_VOLUME / 8);
old.set(data.subarray(0, data.length - biomes));
old[0] = 1;
return old;
}
Deno.test("a chunk's blocks and biomes 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);
assertEquals(decoded.biomes, chunk.biomes);
}
// 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);
// format 1 chunks still load, without biomes
const old = decode_chunk(format_1(encode_chunk(chunk_data(3, 300))));
assertEquals(old.blocks, chunk_data(3, 300).blocks);
assertEquals(old.biomes, undefined);
});
Deno.test("region files keep chunks, including negative ones, and saving one again doesn't touch the others", async () => {
@@ -31,15 +52,24 @@ Deno.test("region files keep chunks, including negative ones, and saving one aga
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]]));
const positions = [[0, 0], [31, 31], [-1, -1], [-33, 40]];
const by_position = async () =>
Object.fromEntries(
await Promise.all(
positions.map(async ([x, z]) => [`${x},${z}`, decode_chunk((await read_chunk(dir, x, z))!).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 });
assertEquals((await list_chunks(dir)).sort(), positions.toSorted());
assertEquals(await by_position(), { "0,0": 2, "31,31": 1, "-1,-1": 0, "-33,40": 2 });
// one that isn't saved, in a region that is and one that isn't
assertEquals(await read_chunk(dir, 1, 0), undefined);
assertEquals(await read_chunk(dir, 100, 100), undefined);
// 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)}`;
@@ -47,27 +77,35 @@ Deno.test("region files keep chunks, including negative ones, and saving one aga
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 by_position(), { "0,0": 1, "31,31": 1, "-1,-1": 0, "-33,40": 2 });
assertEquals(await read_regions(`${dir}/nothing`), []);
assertEquals(await list_chunks(`${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 () => {
Deno.test("every chunk generated is saved whole, and saved again only when it changes", async () => {
const { game } = await test_game("mods");
game.world.build(5, 5);
game.set_block(3, 120, 5, "bworld:stone");
game.set_block(-20, 120, 40, "bworld:oak_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]]);
const positions = saved.chunks.map((c) => `${c.x},${c.z}`);
for (const chunk of ["0,0", "-2,2", "5,5"]) assert(positions.includes(chunk), `${chunk} is saved`);
// 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);
// every block, and each column's biome
const chunk = decode_chunk(saved.chunks.find((c) => c.x === 0 && c.z === 0)!.data);
assertEquals(chunk.palette[chunk.blocks[index(3, 120, 5)]], ["bworld:stone", 0]);
assert(chunk.palette[chunk.blocks[index(3, 10, 5)]][0] !== AIR_ID);
assertEquals(chunk.biomes![index(3, 0, 5)], game.world.biome_at(3, 5));
const untouched = decode_chunk(saved.chunks.find((c) => c.x === 5 && c.z === 5)!.data);
assertEquals(
Uint32Array.from(untouched.blocks, (block) => {
const [id, state] = untouched.palette[block];
return id === AIR_ID ? 0 : game.world.block_ids[id] | (state << 16);
}),
game.world.generated_blocks(5, 5),
);
assertEquals(game.save().chunks, []);
game.set_block(4, 120, 5, "bworld:stone");
@@ -82,54 +120,77 @@ Deno.test("changed blocks are saved as whole chunks, and only chunks that change
loaded.send(1, { type: "move", x: 3.5, y: 130, z: 5.5, yaw: 0, pitch: 0 });
loaded.game.tick();
assertEquals(sent_block(loaded.take(1), join, 3, 120, 5), ["bworld:stone", 0]);
// nothing to save again after loading
assertEquals(loaded.game.save().chunks, []);
// what was loaded isn't saved again, only what's new
const again = loaded.game.save().chunks.map((c) => `${c.x},${c.z}`);
for (const chunk of positions) assert(!again.includes(chunk), `${chunk} is saved again`);
});
// 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
// a world saved with a block in chunk 0, 0 that generation doesn't make there, like one generation made before it
// 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) };
const at_0_0 = saved.chunks.find((c) => c.x === 0 && c.z === 0)!;
const chunk = decode_chunk(at_0_0.data);
assertEquals(chunk.palette[chunk.blocks[index(3, 121, 5)]][0], AIR_ID);
chunk.blocks[index(3, 121, 5)] = chunk.blocks[index(3, 120, 5)];
at_0_0.data = encode_chunk(chunk as Required<typeof chunk>);
return { saved, at_0_0 };
}
Deno.test("when world generation is the same, blocks it made come from it", async () => {
Deno.test("saved chunks stay as they were saved, whatever generation makes there now", 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 } = 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");
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));
assertEquals(game.world.generated_blocks(0, 0)[index(3, 121, 5)], 0);
assertEquals(game.save().chunks.filter((c) => c.x === 0 && c.z === 0), []);
});
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);
Deno.test("chunks saved before they had biomes get them from generation, and are saved again with them", async () => {
const { saved, at_0_0 } = await saved_with_old_terrain();
const biomes = decode_chunk(at_0_0.data).biomes!;
at_0_0.data = format_1(at_0_0.data);
const { game } = await test_game("mods", saved);
assertEquals(game.world.get_block_id(3, 121, 5), "bworld:stone");
assertEquals(game.world.biome_at(3, 5), biomes[index(3, 0, 5)]);
const again = game.save().chunks.find((c) => c.x === 0 && c.z === 0)!;
assertEquals(decode_chunk(again.data).biomes, biomes);
});
Deno.test("blocks of a mod that's gone are kept in the save until something replaces them", async () => {
const { saved, at_0_0 } = await saved_with_old_terrain();
const chunk = decode_chunk(at_0_0.data);
chunk.palette[chunk.blocks[index(3, 120, 5)]] = ["gone:thing", 2];
at_0_0.data = encode_chunk(chunk as Required<typeof 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");
// air stands in for it
assertEquals(game.world.get_block_id(3, 120, 5), AIR_ID);
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]);
const again = decode_chunk(game.save().chunks.find((c) => c.x === 0 && c.z === 0)!.data);
assertEquals(again.palette[again.blocks[index(3, 120, 5)]], ["gone:thing", 2]);
assertEquals(again.palette[again.blocks[index(3, 121, 5)]], ["gone:thing", 2]);
game.set_block(3, 120, 5, "bworld:oak_planks");
const replaced = decode_chunk(game.save().chunks.find((c) => c.x === 0 && c.z === 0)!.data);
assertEquals(replaced.palette[replaced.blocks[index(3, 120, 5)]], ["bworld:oak_planks", 0]);
assertEquals(replaced.palette[replaced.blocks[index(3, 121, 5)]], ["gone:thing", 2]);
});
Deno.test("chunks forgotten before they're saved are still saved, and load from the save after", async () => {
const { game } = await test_game("mods");
game.set_block(100 * 16 + 3, 120, 5, "bworld:oak_planks");
game.set_block(100 * 16 + 3, 120, 16 + 5, "bworld:oak_planks");
// more than the world keeps built
for (let x = 101; x < 101 + 17; x++) for (let z = 0; z < 16; z++) game.world.build(x, z);
assert(!game.world.has_chunk(100, 0) && !game.world.has_chunk(100, 1));
assertEquals(game.world.get_block_id(100 * 16 + 3, 120, 16 + 5), "bworld:oak_planks");
const positions = game.save().chunks.map((c) => `${c.x},${c.z}`);
assert(positions.includes("100,0") && positions.includes("100,1"));
for (let x = 101; x < 101 + 17; x++) {
for (let z = 0; z < 16; z++) assert(positions.includes(`${x},${z}`), `${x},${z} is saved`);
}
assertEquals(game.world.get_block_id(100 * 16 + 3, 120, 5), "bworld:oak_planks");
});