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
+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) {