417 lines
15 KiB
TypeScript
417 lines
15 KiB
TypeScript
import { AIR, CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE, ID_MASK } from "$/common/constants.ts";
|
|
import { BlockRegistry, 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 { block_value, chunk_key, default_block_value } from "$/common/utils.ts";
|
|
import { LruMap } from "./lru.ts";
|
|
import { CYCLE_TICKS } 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";
|
|
|
|
// generation only, rebuilt when needed. 256 KB each
|
|
const RAW_CACHE_SIZE = 128;
|
|
const CHUNK_CACHE_SIZE = 256;
|
|
// how far from the middle of the world to look for dry land to spawn on, in chunks
|
|
const SPAWN_SEARCH_CHUNKS = 32;
|
|
// generated for worldgen_fingerprint, spread out so most changes to world generation touch at least one
|
|
const FINGERPRINT_CHUNKS = [[0, 0], [7, -3], [-45, 18], [130, -80], [-310, 260], [1000, -1000]];
|
|
|
|
// a block with data the server keeps, like where a chest's items are. never sent to clients, but for item
|
|
export interface Tile {
|
|
id: string;
|
|
x: number;
|
|
y: number;
|
|
z: number;
|
|
// what BlockRef.data holds
|
|
mod_data?: unknown;
|
|
// the item it shows, sent to clients, see BlockRegistry.item_display. only set through set_tile_item
|
|
item?: ItemData;
|
|
}
|
|
|
|
export function position_key(x: number, y: number, z: number) {
|
|
return `${x},${y},${z}`;
|
|
}
|
|
|
|
// the authoritative world: generated terrain plus everything players changed
|
|
export class ServerWorld {
|
|
readonly seed: string;
|
|
readonly block_ids: Record<string, number> = {};
|
|
readonly worldgen: WorldgenSetup | undefined;
|
|
// what a freshly placed or generated block stores, by numeric id: the id with its default states
|
|
readonly default_values: number[] = [];
|
|
|
|
// what generation made, and the final blocks with neighbors' leaves and player changes applied
|
|
#raw = new LruMap<number, RawChunk>(RAW_CACHE_SIZE);
|
|
#chunks = new LruMap<number, Uint32Array>(CHUNK_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
|
|
#unsaved = new Map<number, [number, number]>();
|
|
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>>();
|
|
|
|
// ticks since 06:00 of day 1, see common/time.ts
|
|
time = 0;
|
|
|
|
// days since the world started, going up at 06:00. the farming day, unlike the clock's day that starts at midnight
|
|
get day() {
|
|
return Math.floor(this.time / CYCLE_TICKS);
|
|
}
|
|
|
|
// set when anything that gets saved changes
|
|
dirty = false;
|
|
|
|
on_block_change?: (x: number, y: number, z: number, id: string, state: number) => void;
|
|
on_tile_item_change?: (x: number, y: number, z: number, item: ItemData | undefined) => void;
|
|
|
|
constructor(seed: string, worldgen?: WorldgenSetup) {
|
|
this.seed = seed;
|
|
this.worldgen = worldgen;
|
|
EverythingRegistry.get_registry<BlockRegistry>("blocks").forEach((block, nid) => {
|
|
this.block_ids[block.id] = nid;
|
|
this.default_values[nid] = default_block_value(nid, block);
|
|
});
|
|
}
|
|
|
|
#spawn: { x: number; y: number; z: number } | undefined;
|
|
|
|
// where new players start: the dry land closest to the middle of the world, like minecraft's world spawn
|
|
spawn_point() {
|
|
if (!this.#spawn) {
|
|
this.#spawn = this.#find_spawn();
|
|
}
|
|
return this.#spawn;
|
|
}
|
|
|
|
#find_spawn() {
|
|
const water = this.block_ids["bworld:water"];
|
|
// chunks in rings around the middle, one column each
|
|
for (let radius = 0; radius <= SPAWN_SEARCH_CHUNKS; radius++) {
|
|
for (let cz = -radius; cz <= radius; cz++) {
|
|
for (let cx = -radius; cx <= radius; cx++) {
|
|
if (Math.max(Math.abs(cx), Math.abs(cz)) !== radius) continue;
|
|
const x = cx * CHUNK_SIZE + CHUNK_SIZE / 2;
|
|
const z = cz * CHUNK_SIZE + CHUNK_SIZE / 2;
|
|
let y = CHUNK_HEIGHT - 1;
|
|
while (y > 0 && this.get_block_nid(x, y, z) === AIR) y--;
|
|
if (y > 0 && this.get_block_nid(x, y, z) !== water) {
|
|
return { x: x + 0.5, y: y + 1, z: z + 0.5 };
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return { x: 0.5, y: CHUNK_HEIGHT - 1, z: 0.5 };
|
|
}
|
|
|
|
get_block_id(x: number, y: number, z: number): string {
|
|
const nid = this.get_block_nid(x, y, z);
|
|
return nid === AIR ? AIR_ID : EverythingRegistry.get_by_id<BlockRegistry>("blocks", nid)?.id ?? AIR_ID;
|
|
}
|
|
|
|
get_block_nid(x: number, y: number, z: number): number {
|
|
if (y < 0 || y >= CHUNK_HEIGHT) {
|
|
return AIR;
|
|
}
|
|
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);
|
|
return blocks[index_in_chunk(x, y, z, chunk_x, chunk_z)] & ID_MASK;
|
|
}
|
|
|
|
// the id with its state bits
|
|
get_block_value(x: number, y: number, z: number): number {
|
|
if (y < 0 || y >= CHUNK_HEIGHT) {
|
|
return AIR;
|
|
}
|
|
const chunk_x = Math.floor(x / CHUNK_SIZE);
|
|
const chunk_z = Math.floor(z / CHUNK_SIZE);
|
|
return this.#get_chunk(chunk_x, chunk_z)[index_in_chunk(x, y, z, chunk_x, chunk_z)];
|
|
}
|
|
|
|
// whether entities bump into the block there, water and other blocks with "collision": false don't
|
|
has_collision(x: number, y: number, z: number) {
|
|
return this.get_block_info(x, y, z)?.has_collision ?? false;
|
|
}
|
|
|
|
get_block_info(x: number, y: number, z: number): BlockRegistry | undefined {
|
|
const nid = this.get_block_nid(x, y, z);
|
|
return nid === AIR ? undefined : EverythingRegistry.get_by_id<BlockRegistry>("blocks", nid);
|
|
}
|
|
|
|
// only changes the block, the game server runs behaviors and tiles. state bits default to the block's defaults
|
|
set_block(x: number, y: number, z: number, id: string, state?: number) {
|
|
if (y < 0 || y >= CHUNK_HEIGHT) {
|
|
return;
|
|
}
|
|
const nid = id === AIR_ID ? AIR : this.block_ids[id];
|
|
if (nid === undefined) {
|
|
throw new Error(`Unknown block ${id}`);
|
|
}
|
|
const value = state === undefined ? this.default_values[nid] ?? nid : block_value(nid, state);
|
|
|
|
const chunk_x = Math.floor(x / CHUNK_SIZE);
|
|
const chunk_z = Math.floor(z / CHUNK_SIZE);
|
|
const blocks = this.#get_chunk(chunk_x, chunk_z);
|
|
blocks[index_in_chunk(x, y, z, chunk_x, chunk_z)] = value;
|
|
|
|
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);
|
|
}
|
|
|
|
// what clients are sent, the whole chunk as it is now. block values use this world's numeric ids, see block_table
|
|
level_chunk(chunk_x: number, chunk_z: number): Uint8Array<ArrayBuffer> {
|
|
return encode_level_chunk({
|
|
x: chunk_x,
|
|
z: chunk_z,
|
|
blocks: this.#get_chunk(chunk_x, chunk_z),
|
|
biomes: this.#get_raw(chunk_x, chunk_z).biomes,
|
|
});
|
|
}
|
|
|
|
// the block id of each numeric id, for clients to read level_chunk with
|
|
block_table(): string[] {
|
|
const table: string[] = [];
|
|
for (const [id, nid] of Object.entries(this.block_ids)) {
|
|
table[nid] = id;
|
|
}
|
|
table[AIR] = AIR_ID;
|
|
return table;
|
|
}
|
|
|
|
#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;
|
|
}
|
|
|
|
// chunks from a save. with a different fingerprint every block is compared with what generation makes now, so the
|
|
// saved terrain stays as it was and only chunks never saved get the new generation, like minecraft
|
|
load_chunks(chunks: SavedChunk[], fingerprint: string | undefined) {
|
|
const regenerate = chunks.length > 0 && fingerprint !== this.worldgen_fingerprint();
|
|
if (regenerate) {
|
|
console.log(`World generation changed, comparing ${chunks.length} saved chunks with it`);
|
|
}
|
|
for (const { x: chunk_x, z: chunk_z, data } of chunks) {
|
|
let chunk: ChunkBlocks;
|
|
try {
|
|
chunk = decode_chunk(data);
|
|
} catch (e) {
|
|
console.error(`Couldn't load chunk ${chunk_x}, ${chunk_z}: ${(e as Error).message}`);
|
|
continue;
|
|
}
|
|
const generated = regenerate ? this.#generate_chunk(chunk_x, chunk_z) : undefined;
|
|
// unknown ids, from mods that are gone, stay as changes so they come back with the mod
|
|
const values = chunk.palette.map(([id, state]) => {
|
|
const nid = id === AIR_ID ? AIR : this.block_ids[id];
|
|
return nid === undefined ? -1 : block_value(nid, state);
|
|
});
|
|
for (let i = 0; i < CHUNK_VOLUME; i++) {
|
|
const block = chunk.blocks[i];
|
|
if (generated ? generated[i] === values[block] : !is_changed(chunk, i)) {
|
|
continue;
|
|
}
|
|
const [id, state] = chunk.palette[block];
|
|
const x = chunk_x * CHUNK_SIZE + (i % CHUNK_SIZE);
|
|
const z = chunk_z * CHUNK_SIZE + Math.floor(i / CHUNK_SIZE) % CHUNK_SIZE;
|
|
this.#record_change(x, Math.floor(i / CHUNK_AREA), z, id, state);
|
|
}
|
|
if (regenerate) {
|
|
this.#unsaved.set(chunk_key(chunk_x, chunk_z), [chunk_x, chunk_z]);
|
|
this.dirty = true;
|
|
} else {
|
|
this.#unsaved.delete(chunk_key(chunk_x, chunk_z));
|
|
}
|
|
}
|
|
}
|
|
|
|
has_unsaved_chunks() {
|
|
return this.#unsaved.size > 0;
|
|
}
|
|
|
|
// every chunk changed since the last call, as saved chunks
|
|
save_chunks(): SavedChunk[] {
|
|
const saved = [...this.#unsaved.values()].map(([x, z]) => ({
|
|
x,
|
|
z,
|
|
data: encode_chunk(this.#chunk_blocks(x, z)),
|
|
}));
|
|
this.#unsaved.clear();
|
|
return saved;
|
|
}
|
|
|
|
#chunk_blocks(chunk_x: number, chunk_z: number): ChunkBlocks {
|
|
const palette: [string, number][] = [];
|
|
const palette_index = new Map<string, number>();
|
|
const index_of = (id: string, state: number) => {
|
|
const key = `${id} ${state}`;
|
|
let index = palette_index.get(key);
|
|
if (index === undefined) {
|
|
index = palette.push([id, state]) - 1;
|
|
palette_index.set(key, index);
|
|
}
|
|
return index;
|
|
};
|
|
|
|
const blocks = new Uint16Array(CHUNK_VOLUME);
|
|
const by_value = new Map<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);
|
|
}
|
|
blocks[i] = index;
|
|
});
|
|
|
|
// the changes, which also keeps blocks of mods that are gone
|
|
const changed = new Uint8Array(CHUNK_VOLUME / 8);
|
|
for (const [x, y, z, id, state] of this.#changes.get(chunk_key(chunk_x, chunk_z))?.values() ?? []) {
|
|
const i = index_in_chunk(x, y, z, chunk_x, chunk_z);
|
|
blocks[i] = index_of(id, state ?? 0);
|
|
changed[i >> 3] |= 1 << (i & 7);
|
|
}
|
|
return { palette, blocks, changed };
|
|
}
|
|
|
|
get_tile(x: number, y: number, z: number) {
|
|
return this.tiles.get(position_key(x, y, z));
|
|
}
|
|
|
|
add_tile(tile: Tile) {
|
|
const item = tile.item;
|
|
delete tile.item;
|
|
this.tiles.set(position_key(tile.x, tile.y, tile.z), tile);
|
|
if (item) this.set_tile_item(tile, item);
|
|
this.dirty = true;
|
|
}
|
|
|
|
remove_tile(x: number, y: number, z: number) {
|
|
const tile = this.get_tile(x, y, z);
|
|
if (tile?.item) this.set_tile_item(tile, undefined);
|
|
this.tiles.delete(position_key(x, y, z));
|
|
this.dirty = true;
|
|
}
|
|
|
|
set_tile_item(tile: Tile, item: ItemData | undefined) {
|
|
const key = chunk_key(Math.floor(tile.x / CHUNK_SIZE), Math.floor(tile.z / CHUNK_SIZE));
|
|
let tiles = this.#item_tiles.get(key);
|
|
if (item) {
|
|
tile.item = item;
|
|
if (!tiles) {
|
|
tiles = new Set();
|
|
this.#item_tiles.set(key, tiles);
|
|
}
|
|
tiles.add(tile);
|
|
} else {
|
|
delete tile.item;
|
|
tiles?.delete(tile);
|
|
if (tiles?.size === 0) this.#item_tiles.delete(key);
|
|
}
|
|
this.dirty = true;
|
|
this.on_tile_item_change?.(tile.x, tile.y, tile.z, item);
|
|
}
|
|
|
|
// the tiles in a chunk that show an item
|
|
item_tiles(chunk_x: number, chunk_z: number): Iterable<Tile> {
|
|
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)]);
|
|
}
|
|
|
|
#get_raw(chunk_x: number, chunk_z: number) {
|
|
const key = chunk_key(chunk_x, chunk_z);
|
|
let raw = this.#raw.get(key);
|
|
if (!raw) {
|
|
raw = generate_raw_chunk(chunk_x, chunk_z, this.seed, this.block_ids, this.worldgen, this.default_values);
|
|
this.#raw.set(key, raw);
|
|
}
|
|
return raw;
|
|
}
|
|
|
|
#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;
|
|
}
|
|
|
|
// same rules as the client: what generation makes, then player changes
|
|
#build_chunk(chunk_x: number, chunk_z: number) {
|
|
const blocks = this.#generate_chunk(chunk_x, chunk_z);
|
|
for (const [x, y, z, id, state] of this.#changes.get(chunk_key(chunk_x, chunk_z))?.values() ?? []) {
|
|
const nid = id === AIR_ID ? AIR : this.block_ids[id];
|
|
if (nid !== undefined) {
|
|
blocks[index_in_chunk(x, y, z, chunk_x, chunk_z)] = block_value(nid, state ?? 0);
|
|
}
|
|
}
|
|
return blocks;
|
|
}
|
|
|
|
// own blocks, then neighbors' leaves only into air
|
|
#generate_chunk(chunk_x: number, chunk_z: number) {
|
|
const blocks = this.#get_raw(chunk_x, chunk_z).blocks.slice();
|
|
|
|
for (let dx = -1; dx <= 1; dx++) {
|
|
for (let dz = -1; dz <= 1; dz++) {
|
|
if (dx === 0 && dz === 0) {
|
|
continue;
|
|
}
|
|
const spills = this.#get_raw(chunk_x + dx, chunk_z + dz).spills;
|
|
for (let i = 0; i < spills.length; i += 4) {
|
|
const [x, y, z, nid] = [spills[i], spills[i + 1], spills[i + 2], spills[i + 3]];
|
|
if (Math.floor(x / CHUNK_SIZE) !== chunk_x || Math.floor(z / CHUNK_SIZE) !== chunk_z) {
|
|
continue;
|
|
}
|
|
const index = index_in_chunk(x, y, z, chunk_x, chunk_z);
|
|
if (blocks[index] === AIR) {
|
|
blocks[index] = nid;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return blocks;
|
|
}
|
|
}
|
|
|
|
function index_in_chunk(x: number, y: number, z: number, chunk_x: number, chunk_z: number) {
|
|
return y * CHUNK_AREA + (z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE);
|
|
}
|