Files
bworld/server/game/world.ts
T

570 lines
21 KiB
TypeScript

import { AIR, CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE, ID_MASK } from "$/common/constants.ts";
import {
block_light_emission,
block_light_opacity,
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;
// surface and sky heights, 1 KB each
const COLUMN_CACHE_SIZE = 1024;
// light reaches at most this far, see light_at
const LIGHT_REACH = 15;
const LIGHT_BOX = LIGHT_REACH * 2 + 1;
// how far from the middle of the world to look for dry land to spawn on, in chunks
const SPAWN_SEARCH_CHUNKS = 32;
// 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[] = [];
// for light_at, by numeric id
#opacity: Uint8Array;
#emission: Uint8Array;
// 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);
// what generation decided each column's biome is, kept for longer than the rest of it
#biomes = new LruMap<number, string[]>(COLUMN_CACHE_SIZE);
// 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
#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;
const blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks");
this.#opacity = new Uint8Array(ID_MASK + 1);
this.#emission = new Uint8Array(ID_MASK + 1);
blocks.forEach((block, nid) => {
this.block_ids[block.id] = nid;
this.default_values[nid] = default_block_value(nid, block);
this.#opacity[nid] = block_light_opacity(block);
this.#emission[nid] = block_light_emission(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);
}
// like "bworld:plains", what generation decided
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)];
}
// whether the chunk is built and kept, like a loaded chunk in minecraft. nothing builds one by asking
has_chunk(chunk_x: number, chunk_z: number) {
return this.#chunks.has(chunk_key(chunk_x, chunk_z));
}
// counts as using the chunk so it's kept longer, if it's there. returns whether it is, see has_chunk
keep_chunk(chunk_x: number, chunk_z: number) {
return this.#chunks.get(chunk_key(chunk_x, chunk_z)) !== undefined;
}
// whether every chunk within radius blocks of x, z is, see has_chunk
has_chunks_around(x: number, z: number, radius: number) {
for (let cx = Math.floor((x - radius) / CHUNK_SIZE); cx <= Math.floor((x + radius) / CHUNK_SIZE); cx++) {
for (let cz = Math.floor((z - radius) / CHUNK_SIZE); cz <= Math.floor((z + radius) / CHUNK_SIZE); cz++) {
if (!this.has_chunk(cx, cz)) return false;
}
}
return true;
}
// how much light going through the block there loses, 0-15
light_opacity(x: number, y: number, z: number) {
return this.#opacity[this.get_block_nid(x, y, z)];
}
// the highest block that isn't air, -1 for an empty column. minecraft's WORLD_SURFACE heightmap
surface_height(x: number, z: number): number {
return this.#columns_of(x, z)[column_index(x, z)];
}
// the lowest y with nothing above it that stops light, where sky light is 15
sky_height(x: number, z: number): number {
return this.#columns_of(x, z)[CHUNK_AREA + column_index(x, z)];
}
// the sky and block light there, 0-15, the same as clients work out (see client/workers/lighting.ts) but for one
// position: searching out from it, cheapest first, for the brightest place light could come from. light loses
// max(1, opacity) for every block it goes into, and never gets further than 15 blocks
light_at(x: number, y: number, z: number): { sky: number; block: number } {
if (y >= CHUNK_HEIGHT) return { sky: 15, block: 0 };
if (y < 0) return { sky: 0, block: 0 };
// the box around it, 3x3 chunks at most, fetched once each. blocks are in it by their offset from the start
const first_x = Math.floor((x - LIGHT_REACH) / CHUNK_SIZE);
const first_z = Math.floor((z - LIGHT_REACH) / CHUNK_SIZE);
const chunks: (Uint32Array | undefined)[] = [];
const skies: (Int16Array | undefined)[] = [];
const box_index = (dx: number, dy: number, dz: number) =>
((dy + LIGHT_REACH) * LIGHT_BOX + dz + LIGHT_REACH) * LIGHT_BOX + dx + LIGHT_REACH;
// what light loses on its way from a block to the start. 255 is not reached yet
const cost = new Uint8Array(LIGHT_BOX ** 3).fill(255);
const queues: number[][] = Array.from({ length: LIGHT_REACH }, () => []);
let next = 0;
const reach = (dx: number, dy: number, dz: number) => {
if (y + dy < 0 || y + dy >= CHUNK_HEIGHT) return;
const at = box_index(dx, dy, dz);
if (cost[at] <= next) return;
cost[at] = next;
queues[next].push(dx, dy, dz);
};
reach(0, 0, 0);
let sky = 0;
let block = 0;
for (let lost = 0; lost < LIGHT_REACH; lost++) {
// nothing further away can be brighter than what's been found
if (LIGHT_REACH - lost <= sky && LIGHT_REACH - lost <= block) break;
const queue = queues[lost];
for (let i = 0; i < queue.length; i += 3) {
const dx = queue[i], dy = queue[i + 1], dz = queue[i + 2];
if (cost[box_index(dx, dy, dz)] !== lost) continue;
const bx = x + dx, by = y + dy, bz = z + dz;
const chunk_x = Math.floor(bx / CHUNK_SIZE);
const chunk_z = Math.floor(bz / CHUNK_SIZE);
const which = (chunk_z - first_z) * 3 + chunk_x - first_x;
const blocks = chunks[which] ??= this.#get_chunk(chunk_x, chunk_z);
const column = (bz - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + bx - chunk_x * CHUNK_SIZE;
const nid = blocks[by * CHUNK_AREA + column] & ID_MASK;
const columns = skies[which] ??= this.#columns_of(bx, bz);
if (by >= columns[CHUNK_AREA + column]) sky = Math.max(sky, LIGHT_REACH - lost);
block = Math.max(block, this.#emission[nid] - lost);
// light comes to this block from its neighbors, losing what going into it costs
next = lost + Math.max(1, this.#opacity[nid]);
if (next >= LIGHT_REACH) continue;
reach(dx, dy - 1, dz);
reach(dx, dy + 1, dz);
reach(dx - 1, dy, dz);
reach(dx + 1, dy, dz);
reach(dx, dy, dz - 1);
reach(dx, dy, dz + 1);
}
}
return { sky, block };
}
#columns_of(x: number, z: number) {
const chunk_x = Math.floor(x / CHUNK_SIZE);
const chunk_z = Math.floor(z / CHUNK_SIZE);
const key = chunk_key(chunk_x, chunk_z);
let columns = this.#columns.get(key);
if (!columns) {
const blocks = this.#get_chunk(chunk_x, chunk_z);
columns = new Int16Array(CHUNK_AREA * 2);
for (let column = 0; column < CHUNK_AREA; column++) {
let y = CHUNK_HEIGHT - 1;
while (y >= 0 && (blocks[y * CHUNK_AREA + column] & ID_MASK) === AIR) y--;
columns[column] = y;
while (y >= 0 && this.#opacity[blocks[y * CHUNK_AREA + column] & ID_MASK] === 0) y--;
columns[CHUNK_AREA + column] = y + 1;
}
this.#columns.set(key, columns);
}
return columns;
}
// only changes the block, the game server runs behaviors and tiles. state bits default to the block's defaults
set_block(x: number, y: number, z: number, id: string, state?: number) {
if (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;
this.#columns.delete(chunk_key(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);
}
// 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;
}
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
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);
this.#biomes.set(key, raw.biomes);
}
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);
}
// a column's place in its chunk, the same as its blocks' in a layer
function column_index(x: number, z: number) {
return (z - Math.floor(z / CHUNK_SIZE) * CHUNK_SIZE) * CHUNK_SIZE + x - Math.floor(x / CHUNK_SIZE) * CHUNK_SIZE;
}