Region file format
This commit is contained in:
+28
-37
@@ -14,7 +14,6 @@ import { BlockRegistry, EverythingRegistry, ItemRegistry } from "$/common/everyt
|
||||
import { can_take_output, click_slot, Container, ItemData, ItemStack, take_output } from "$/common/inventory.ts";
|
||||
import {
|
||||
AIR_ID,
|
||||
BlockChange,
|
||||
ClientMessage,
|
||||
ContainerKey,
|
||||
CRAFTING_RESULT_SLOT,
|
||||
@@ -45,6 +44,7 @@ import { consume_recipe_items, update_crafting_result } from "./crafting.ts";
|
||||
import { OpenScreen, SavedPlayer, ServerPlayer } from "./player.ts";
|
||||
import { encode_skin, MAX_SKIN_BYTES, skin_problem } from "./skins.ts";
|
||||
import { ServerWorld, Tile } from "./world.ts";
|
||||
import type { WorldSave } from "./saves.ts";
|
||||
import {
|
||||
BLOCK_DROP_PICKUP_DELAY,
|
||||
DESPAWN_TICKS,
|
||||
@@ -91,20 +91,22 @@ export interface GameHost {
|
||||
download(url: string, max_bytes: number): Promise<Uint8Array>;
|
||||
}
|
||||
|
||||
export interface SavedWorld {
|
||||
version: 3;
|
||||
// level.json, everything saved but the blocks, which are in region files (see saves.ts)
|
||||
export interface SavedLevel {
|
||||
version: 4;
|
||||
seed: string;
|
||||
// world time in ticks, 0 in saves from before the day and night cycle
|
||||
time?: number;
|
||||
changes: BlockChange[];
|
||||
// see ServerWorld.worldgen_fingerprint
|
||||
worldgen: string;
|
||||
// world time in ticks
|
||||
time: number;
|
||||
tiles: SavedTile[];
|
||||
// every ctx.containers container, by id
|
||||
containers?: Record<string, (ItemData | null)[]>;
|
||||
containers: Record<string, (ItemData | null)[]>;
|
||||
players: Record<string, SavedPlayer>;
|
||||
// items on the ground
|
||||
entities?: SavedItemEntity[];
|
||||
entities: SavedItemEntity[];
|
||||
// ctx.storage of every mod, by mod id
|
||||
mod_storage?: Record<string, Record<string, unknown>>;
|
||||
mod_storage: Record<string, Record<string, unknown>>;
|
||||
}
|
||||
|
||||
interface SavedTile {
|
||||
@@ -114,9 +116,6 @@ interface SavedTile {
|
||||
z: number;
|
||||
// what BlockRef.data holds
|
||||
mod_data?: unknown;
|
||||
// version 2, when chests and furnaces were engine code: their fields and their items
|
||||
data?: Record<string, unknown>;
|
||||
containers?: Record<string, (ItemData | null)[]>;
|
||||
}
|
||||
|
||||
// the loaded mods, see load_mods.ts
|
||||
@@ -148,17 +147,21 @@ export class GameServer {
|
||||
// what runs tick(), for /tps. tests call tick() themselves
|
||||
loop?: GameLoop;
|
||||
|
||||
constructor(host: GameHost, save: string | undefined, default_seed: string, mods: GameMods) {
|
||||
constructor(host: GameHost, save: WorldSave | undefined, default_seed: string, mods: GameMods) {
|
||||
this.#host = host;
|
||||
this.#mods = mods;
|
||||
this.mods = mods.runtime;
|
||||
this.recipes = mods.recipes;
|
||||
|
||||
// version 1 saves only had the seed and block changes
|
||||
const saved: Partial<SavedWorld> | undefined = save ? JSON.parse(save) : undefined;
|
||||
const saved: SavedLevel | undefined = save?.level ? JSON.parse(save.level) : undefined;
|
||||
if (saved && saved.version !== 4) {
|
||||
throw new Error(`The world was saved in format ${saved.version}, this server only loads format 4`);
|
||||
}
|
||||
this.world = new ServerWorld(saved?.seed ?? default_seed, mods.worldgen);
|
||||
this.mods.storage = saved?.mod_storage ?? {};
|
||||
this.world.load_changes(saved?.changes ?? []);
|
||||
if (saved) {
|
||||
this.world.load_chunks(save?.chunks ?? [], saved.worldgen);
|
||||
}
|
||||
this.world.time = saved?.time ?? 0;
|
||||
this.#day = this.world.day;
|
||||
for (const [id, items] of Object.entries(saved?.containers ?? {})) {
|
||||
@@ -167,14 +170,15 @@ export class GameServer {
|
||||
this.containers.set(id, container);
|
||||
}
|
||||
for (const tile of saved?.tiles ?? []) {
|
||||
this.world.add_tile({ id: tile.id, x: tile.x, y: tile.y, z: tile.z, mod_data: this.#upgrade_tile(tile) });
|
||||
this.world.add_tile({ id: tile.id, x: tile.x, y: tile.y, z: tile.z, mod_data: tile.mod_data });
|
||||
}
|
||||
for (const entity of saved?.entities ?? []) {
|
||||
const item = ItemEntity.load(this.#new_entity_id(), entity);
|
||||
this.#entities.set(item.id, item);
|
||||
}
|
||||
this.#saved_players = saved?.players ?? {};
|
||||
this.world.dirty = saved?.version !== 3;
|
||||
// a new world is saved straight away, and a loaded one when load_chunks had to save chunks again
|
||||
this.world.dirty = !saved || this.world.has_unsaved_chunks();
|
||||
this.#register_commands();
|
||||
|
||||
this.world.on_block_change = (x, y, z, id, state) =>
|
||||
@@ -273,15 +277,16 @@ export class GameServer {
|
||||
}
|
||||
}
|
||||
|
||||
save(): string {
|
||||
// level.json and the chunks changed since the last save
|
||||
save(): Required<WorldSave> {
|
||||
for (const player of this.#players.values()) {
|
||||
this.#saved_players[player.name] = player.save();
|
||||
}
|
||||
const saved: SavedWorld = {
|
||||
version: 3,
|
||||
const level: SavedLevel = {
|
||||
version: 4,
|
||||
seed: this.world.seed,
|
||||
worldgen: this.world.worldgen_fingerprint(),
|
||||
time: this.world.time,
|
||||
changes: this.world.all_changes(),
|
||||
tiles: [...this.world.tiles.values()].map((tile) => ({
|
||||
id: tile.id,
|
||||
x: tile.x,
|
||||
@@ -297,7 +302,7 @@ export class GameServer {
|
||||
mod_storage: this.mods.storage,
|
||||
};
|
||||
this.world.dirty = false;
|
||||
return JSON.stringify(saved);
|
||||
return { level: JSON.stringify(level), chunks: this.world.save_chunks() };
|
||||
}
|
||||
|
||||
// used by block behaviors and mods
|
||||
@@ -540,20 +545,6 @@ export class GameServer {
|
||||
|
||||
// version 2 saves had chests and furnaces in the engine, with their fields in data and their items in
|
||||
// containers.main. the components keep those fields and put the items in a ctx.containers container
|
||||
#upgrade_tile(tile: SavedTile): unknown {
|
||||
if (tile.mod_data !== undefined || (!tile.data && !tile.containers)) {
|
||||
return tile.mod_data;
|
||||
}
|
||||
const data: Record<string, unknown> = { ...tile.data };
|
||||
const items = tile.containers?.main;
|
||||
if (items) {
|
||||
const { id, container } = this.create_container(items.length);
|
||||
container.load(items);
|
||||
data.container = id;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
// messages
|
||||
|
||||
// hello -> welcome, then ready -> join. see "Delivery to clients" in MODS.md
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import type { ModData, ModListing } from "$/common/mod_loader.ts";
|
||||
import type { WorldSave } from "./saves.ts";
|
||||
|
||||
// messages between server/main.ts (the host) and the game server worker
|
||||
|
||||
export type HostToGame =
|
||||
| {
|
||||
type: "init";
|
||||
save: string | undefined;
|
||||
save: WorldSave;
|
||||
default_seed: string;
|
||||
// in load order, with the scripts' code since the worker can't read files
|
||||
mods: { listing: ModListing; data: ModData; server_code?: string; worldgen_code?: string }[];
|
||||
@@ -23,6 +24,7 @@ export type GameToHost =
|
||||
| { type: "failed"; error: string }
|
||||
| { type: "send"; conn: number; data: string }
|
||||
| { type: "close"; conn: number }
|
||||
| { type: "save"; data: string; final: boolean }
|
||||
// level.json and the chunks that changed
|
||||
| { type: "save"; save: Required<WorldSave>; final: boolean }
|
||||
// the worker can't use the network, so the host fetches urls for it, like skins
|
||||
| { type: "download"; id: number; url: string; max_bytes: number };
|
||||
|
||||
@@ -4,6 +4,7 @@ import { register_mod_data } from "$/common/mod_loader.ts";
|
||||
import type { ModData, ModListing } from "$/common/mod_loader.ts";
|
||||
import { load_worldgen } from "$/common/worldgen_loader.ts";
|
||||
import { GameHost, GameServer } from "./game_server.ts";
|
||||
import type { WorldSave } from "./saves.ts";
|
||||
import { ModRuntime } from "./mod_runtime.ts";
|
||||
|
||||
export interface ServerModSource {
|
||||
@@ -16,7 +17,7 @@ export interface ServerModSource {
|
||||
|
||||
export async function start_game(
|
||||
host: GameHost,
|
||||
save: string | undefined,
|
||||
save: WorldSave | undefined,
|
||||
default_seed: string,
|
||||
mods: ServerModSource[],
|
||||
): Promise<GameServer> {
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
// what a world is saved as, apart from the files: level.json's text and each chunk's blocks. server/regions.ts puts
|
||||
// the chunks into region files, this is what's inside one chunk's entry before it's compressed:
|
||||
//
|
||||
// u8 format, CHUNK_FORMAT
|
||||
// u32 palette size, then each entry: u8 id length, the id as utf-8, u16 state bits
|
||||
// the palette index of every block, in ServerWorld's order (y, then z, then x): u8 each for up to 256 entries,
|
||||
// u16 each for more
|
||||
// a bit per block, set where it isn't what world generation makes there, like a block a player placed
|
||||
//
|
||||
// numbers are big-endian. blocks are saved by their string ids, so mods can come and go without a save's numbers
|
||||
// meaning other blocks
|
||||
import { CHUNK_AREA, CHUNK_HEIGHT } from "$/common/constants.ts";
|
||||
|
||||
export const CHUNK_FORMAT = 1;
|
||||
export const CHUNK_VOLUME = CHUNK_AREA * CHUNK_HEIGHT;
|
||||
|
||||
export interface SavedChunk {
|
||||
x: number;
|
||||
z: number;
|
||||
data: Uint8Array<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
|
||||
export interface WorldSave {
|
||||
// level.json, without it the world is new
|
||||
level?: string;
|
||||
chunks: SavedChunk[];
|
||||
}
|
||||
|
||||
export interface ChunkBlocks {
|
||||
// an id and its state bits
|
||||
palette: [string, number][];
|
||||
// the palette index of each block
|
||||
blocks: Uint16Array;
|
||||
// CHUNK_VOLUME bits, see is_changed
|
||||
changed: Uint8Array;
|
||||
}
|
||||
|
||||
export function is_changed(chunk: ChunkBlocks, index: number) {
|
||||
return (chunk.changed[index >> 3] & (1 << (index & 7))) !== 0;
|
||||
}
|
||||
|
||||
export function encode_chunk(chunk: ChunkBlocks): Uint8Array<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 bytes = new Uint8Array(size);
|
||||
const view = new DataView(bytes.buffer);
|
||||
let offset = 0;
|
||||
view.setUint8(offset++, CHUNK_FORMAT);
|
||||
view.setUint32(offset, chunk.palette.length);
|
||||
offset += 4;
|
||||
chunk.palette.forEach(([, state], i) => {
|
||||
view.setUint8(offset++, ids[i].length);
|
||||
bytes.set(ids[i], offset);
|
||||
offset += ids[i].length;
|
||||
view.setUint16(offset, state);
|
||||
offset += 2;
|
||||
});
|
||||
for (let i = 0; i < CHUNK_VOLUME; i++) {
|
||||
if (wide) {
|
||||
view.setUint16(offset, chunk.blocks[i]);
|
||||
offset += 2;
|
||||
} else {
|
||||
bytes[offset++] = chunk.blocks[i];
|
||||
}
|
||||
}
|
||||
bytes.set(chunk.changed, offset);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
// throws when the bytes aren't a chunk this can read
|
||||
export function decode_chunk(bytes: Uint8Array): ChunkBlocks {
|
||||
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
let offset = 0;
|
||||
const format = view.getUint8(offset++);
|
||||
if (format !== CHUNK_FORMAT) throw new Error(`Unknown chunk format ${format}`);
|
||||
const palette_size = view.getUint32(offset);
|
||||
offset += 4;
|
||||
if (palette_size > CHUNK_VOLUME) throw new Error("Bad palette");
|
||||
const palette: [string, number][] = [];
|
||||
for (let i = 0; i < palette_size; i++) {
|
||||
const length = view.getUint8(offset++);
|
||||
const id = new TextDecoder().decode(bytes.subarray(offset, offset + length));
|
||||
offset += length;
|
||||
palette.push([id, view.getUint16(offset)]);
|
||||
offset += 2;
|
||||
}
|
||||
const wide = palette_size > 256;
|
||||
if (bytes.length !== offset + CHUNK_VOLUME * (wide ? 2 : 1) + CHUNK_VOLUME / 8) {
|
||||
throw new Error("Wrong size");
|
||||
}
|
||||
const blocks = new Uint16Array(CHUNK_VOLUME);
|
||||
for (let i = 0; i < CHUNK_VOLUME; i++) {
|
||||
if (wide) {
|
||||
blocks[i] = view.getUint16(offset);
|
||||
offset += 2;
|
||||
} else {
|
||||
blocks[i] = bytes[offset++];
|
||||
}
|
||||
if (blocks[i] >= palette_size) throw new Error("Bad palette index");
|
||||
}
|
||||
const changed = bytes.slice(offset, offset + CHUNK_VOLUME / 8);
|
||||
return { palette, blocks, changed };
|
||||
}
|
||||
@@ -15,7 +15,9 @@ const downloads = new Map<number, { resolve: (bytes: Uint8Array) => void; reject
|
||||
let next_download = 1;
|
||||
|
||||
function post(message: GameToHost) {
|
||||
self.postMessage(message);
|
||||
// the chunks are moved to the host, not copied
|
||||
const transfer = message.type === "save" ? message.save.chunks.map((chunk) => chunk.data.buffer) : [];
|
||||
self.postMessage(message, transfer);
|
||||
}
|
||||
|
||||
self.onmessage = async (event: MessageEvent<HostToGame>) => {
|
||||
@@ -53,7 +55,7 @@ self.onmessage = async (event: MessageEvent<HostToGame>) => {
|
||||
game.on_disconnect(message.conn);
|
||||
break;
|
||||
case "shutdown":
|
||||
post({ type: "save", data: game.save(), final: true });
|
||||
post({ type: "save", save: game.save(), final: true });
|
||||
break;
|
||||
}
|
||||
};
|
||||
@@ -92,7 +94,7 @@ async function init(message: Extract<HostToGame, { type: "init" }>) {
|
||||
|
||||
setInterval(() => {
|
||||
if (game!.world.dirty) {
|
||||
post({ type: "save", data: game!.save(), final: false });
|
||||
post({ type: "save", save: game!.save(), final: false });
|
||||
}
|
||||
}, SAVE_INTERVAL_MS);
|
||||
|
||||
|
||||
+133
-13
@@ -5,12 +5,15 @@ import { AIR_ID, BlockChange } from "$/common/protocol.ts";
|
||||
import { block_value, chunk_key, default_block_value } from "$/common/utils.ts";
|
||||
import { LruMap } from "./lru.ts";
|
||||
import { CYCLE_TICKS } from "$/common/time.ts";
|
||||
import { CHUNK_VOLUME, ChunkBlocks, decode_chunk, encode_chunk, is_changed, SavedChunk } from "./saves.ts";
|
||||
|
||||
// generation only, rebuilt when needed. 256 KB each
|
||||
const RAW_CACHE_SIZE = 128;
|
||||
const CHUNK_CACHE_SIZE = 256;
|
||||
// how far from the middle of the world to look for dry land to spawn on, in chunks
|
||||
const SPAWN_SEARCH_CHUNKS = 32;
|
||||
// generated for worldgen_fingerprint, spread out so most changes to world generation touch at least one
|
||||
const FINGERPRINT_CHUNKS = [[0, 0], [7, -3], [-45, 18], [130, -80], [-310, 260], [1000, -1000]];
|
||||
|
||||
// a block with data the server keeps, like where a chest's items are. never sent to clients
|
||||
export interface Tile {
|
||||
@@ -38,8 +41,10 @@ export class ServerWorld {
|
||||
#raw = new LruMap<number, RawChunk>(RAW_CACHE_SIZE);
|
||||
#chunks = new LruMap<number, Uint32Array>(CHUNK_CACHE_SIZE);
|
||||
|
||||
// changes from generated terrain, per chunk. these and the tiles are what gets saved
|
||||
// changes from generated terrain, per chunk, which is also what clients get sent. saved as whole chunks
|
||||
#changes = new Map<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>();
|
||||
|
||||
// ticks since 06:00 of day 1, see common/time.ts
|
||||
@@ -159,10 +164,120 @@ export class ServerWorld {
|
||||
return all;
|
||||
}
|
||||
|
||||
load_changes(changes: BlockChange[]) {
|
||||
for (const [x, y, z, id, state] of changes) {
|
||||
this.#record_change(x, y, z, id, state ?? 0);
|
||||
#fingerprint: string | undefined;
|
||||
|
||||
// a hash of some generated chunks, saved with the world: when it's different world generation changed, like a mod
|
||||
// update, and saved chunks can't be trusted to say which of their blocks generation made
|
||||
worldgen_fingerprint(): string {
|
||||
if (this.#fingerprint === undefined) {
|
||||
// fnv-1a
|
||||
let hash = 0x811c9dc5;
|
||||
const add = (values: ArrayLike<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) {
|
||||
@@ -187,6 +302,7 @@ export class ServerWorld {
|
||||
this.#changes.set(key, chunk_changes);
|
||||
}
|
||||
chunk_changes.set(position_key(x, y, z), state ? [x, y, z, id, state] : [x, y, z, id]);
|
||||
this.#unsaved.set(key, [Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE)]);
|
||||
}
|
||||
|
||||
#get_raw(chunk_x: number, chunk_z: number) {
|
||||
@@ -209,8 +325,20 @@ export class ServerWorld {
|
||||
return blocks;
|
||||
}
|
||||
|
||||
// same rules as the client: own blocks, then neighbors' leaves only into air, then player changes
|
||||
// same rules as the client: what generation makes, then player changes
|
||||
#build_chunk(chunk_x: number, chunk_z: number) {
|
||||
const blocks = this.#generate_chunk(chunk_x, chunk_z);
|
||||
for (const [x, y, z, id, state] of this.#changes.get(chunk_key(chunk_x, chunk_z))?.values() ?? []) {
|
||||
const nid = id === AIR_ID ? AIR : this.block_ids[id];
|
||||
if (nid !== undefined) {
|
||||
blocks[index_in_chunk(x, y, z, chunk_x, chunk_z)] = block_value(nid, state ?? 0);
|
||||
}
|
||||
}
|
||||
return blocks;
|
||||
}
|
||||
|
||||
// own blocks, then neighbors' leaves only into air
|
||||
#generate_chunk(chunk_x: number, chunk_z: number) {
|
||||
const blocks = this.#get_raw(chunk_x, chunk_z).blocks.slice();
|
||||
|
||||
for (let dx = -1; dx <= 1; dx++) {
|
||||
@@ -231,14 +359,6 @@ export class ServerWorld {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const [x, y, z, id, state] of this.#changes.get(chunk_key(chunk_x, chunk_z))?.values() ?? []) {
|
||||
const nid = id === AIR_ID ? AIR : this.block_ids[id];
|
||||
if (nid !== undefined) {
|
||||
blocks[index_in_chunk(x, y, z, chunk_x, chunk_z)] = block_value(nid, state ?? 0);
|
||||
}
|
||||
}
|
||||
|
||||
return blocks;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user