Wooooorld files

This commit is contained in:
2026-11-06 23:41:32 -03:00
parent 1fa47c027d
commit 8e14e9842a
9 changed files with 501 additions and 383 deletions
+70 -100
View File
@@ -2,24 +2,30 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// 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:
// the chunks into region files, this is what's inside one chunk's entry before it's compressed, little-endian:
//
// u8 format, CHUNK_FORMAT
// i16 the bottom of the lowest section, the dimension's min_y when it was saved
// 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 from the dimension's min_y, then z, then x): u8 each
// for up to 256 entries, u16 each for more. how many there are is the dimension's, see WorldShape.volume:
// a chunk saved with another height doesn't read, and is generated again
// 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
// the biomes and the sections, bottom first, each block the index of its entry in the palette. see write_column in
// common/section.ts, which level_chunk uses too
//
// 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. 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
// blocks are saved by their string ids, so mods can come and go without a save's numbers 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. a chunk loaded into a dimension with another height keeps the sections both have (see
// ServerWorld's #from_saved).
// formats 1 and 2 are still read. they're big-endian and from when the world was 0 to 256 high: after the palette, the
// index of every block from y 0 up, then z, then x, u8 each or u16 for more than 256 entries. format 2 then has a u8
// biome palette size, each biome as u8 length and utf-8, and a u8 biome index a column. format 1 has no biomes, but a
// bit per block for whether world generation made it, from when only chunks players changed were saved
import { CHUNK_AREA } from "@/common/constants.ts";
import { Reader, Writer } from "@/common/bytes.ts";
import { read_column, Section, SECTION_VOLUME, write_column } from "@/common/section.ts";
import { SECTION_HEIGHT } from "@/common/world_shape.ts";
export const CHUNK_FORMAT = 2;
export const CHUNK_FORMAT = 3;
// how many blocks a chunk of formats 1 and 2 has
const FLAT_VOLUME = CHUNK_AREA * 256;
export interface SavedChunk {
x: number;
@@ -50,103 +56,67 @@ export interface SavedChunks {
export interface ChunkBlocks {
// an id and its state bits
palette: [string, number][];
// the palette index of each block
blocks: Uint16Array;
// the bottom of the lowest section
min_y: number;
// the palette index of each block, a section at a time from min_y up
sections: Section[];
// each column's, see ServerWorld.biome_at. format 1 chunks don't have them
biomes?: string[];
}
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 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 volume = chunk.blocks.length;
const size = 1 + 4 + ids.reduce((sum, id) => sum + 1 + id.length + 2, 0) + 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;
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;
});
if (wide) {
for (let i = 0; i < volume; i++) {
view.setUint16(offset, chunk.blocks[i]);
offset += 2;
}
} else {
bytes.set(chunk.blocks, offset);
offset += volume;
const writer = new Writer();
writer.u8(CHUNK_FORMAT);
writer.i16(chunk.min_y);
writer.u32(chunk.palette.length);
for (const [id, state] of chunk.palette) {
writer.string(id);
writer.u16(state);
}
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;
write_column(writer, chunk.sections, chunk.biomes);
return writer.bytes().slice();
}
// throws when the bytes aren't a chunk this can read. volume is how many blocks the dimension's chunks hold
export function decode_chunk(bytes: Uint8Array, volume: number): ChunkBlocks {
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
let offset = 0;
const format = view.getUint8(offset++);
if (format !== CHUNK_FORMAT && format !== 1) throw new Error(`Unknown chunk format ${format}`);
const palette_size = view.getUint32(offset);
offset += 4;
if (palette_size > volume) throw new Error("Bad palette");
// throws when the bytes aren't a chunk this can read
export function decode_chunk(bytes: Uint8Array): ChunkBlocks {
const format = bytes[0];
if (format !== CHUNK_FORMAT && format !== 2 && format !== 1) throw new Error(`Unknown chunk format ${format}`);
const reader = new Reader(bytes.subarray(1), format === CHUNK_FORMAT);
const min_y = format === CHUNK_FORMAT ? reader.i16() : 0;
if (min_y % SECTION_HEIGHT !== 0) throw new Error(`Bad min_y ${min_y}`);
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 (format === 1 && bytes.length !== offset + volume * (wide ? 2 : 1) + volume / 8) {
throw new Error("Wrong size");
}
if (bytes.length < offset + volume * (wide ? 2 : 1)) throw new Error("Wrong size");
const blocks = new Uint16Array(volume);
if (wide) {
for (let i = 0; i < volume; i++) {
blocks[i] = view.getUint16(offset);
offset += 2;
}
} else {
blocks.set(bytes.subarray(offset, offset + volume));
offset += volume;
}
for (let i = 0; i < volume; i++) {
if (blocks[i] >= palette_size) throw new Error("Bad palette index");
}
if (format === 1) return { palette, blocks };
const palette_size = reader.u32();
for (let i = 0; i < palette_size; i++) palette.push([reader.string(), reader.u16()]);
const index = (value: number) => {
if (value >= palette_size) throw new Error("Bad palette index");
return value;
};
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 (format === CHUNK_FORMAT) {
const { sections, biomes } = read_column(reader, index);
if (!reader.done) throw new Error("Wrong size");
return { palette, min_y, sections, biomes };
}
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 };
const blocks = new Uint32Array(FLAT_VOLUME);
const wide = palette_size > 256;
for (let i = 0; i < FLAT_VOLUME; i++) blocks[i] = index(wide ? reader.u16() : reader.u8());
const sections = Array.from(
{ length: FLAT_VOLUME / SECTION_VOLUME },
(_, i) => Section.of(blocks.subarray(i * SECTION_VOLUME, (i + 1) * SECTION_VOLUME)),
);
let biomes: string[] | undefined;
if (format === 1) {
reader.take(FLAT_VOLUME / 8);
} else {
const biome_palette: string[] = [];
const biome_palette_size = reader.u8();
for (let i = 0; i < biome_palette_size; i++) biome_palette.push(reader.string());
biomes = [...reader.take(CHUNK_AREA)].map((i) => {
if (i >= biome_palette_size) throw new Error("Bad biome palette index");
return biome_palette[i];
});
}
if (!reader.done) throw new Error("Wrong size");
return { palette, min_y, sections, biomes };
}
+35 -22
View File
@@ -2,8 +2,8 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import { AIR, CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts";
import type { WorldShape } from "@/common/world_shape.ts";
import { ChunkColumn, column_heights, SECTION_VOLUME } from "@/common/section.ts";
import { SECTION_HEIGHT, type WorldShape } from "@/common/world_shape.ts";
import { ChunkColumn, column_heights, Section, SECTION_VOLUME } from "@/common/section.ts";
import {
block_light_emission,
block_light_opacity,
@@ -501,13 +501,9 @@ export class ServerWorld {
};
const { sections, biomes } = chunk.column;
const blocks = new Uint16Array(this.shape.volume);
sections.forEach((section, s) => {
const start = s * SECTION_VOLUME;
if (section.blocks === null) {
blocks.fill(value_index(section.value), start, start + SECTION_VOLUME);
return;
}
const saved = sections.map((section) => {
if (section.blocks === null) return new Section(value_index(section.value));
const indexes = new Uint32Array(SECTION_VOLUME);
// runs of the same block are common, like air above the ground and stone below
let last_value = -1;
let last_index = 0;
@@ -517,11 +513,14 @@ export class ServerWorld {
last_value = value;
last_index = value_index(value);
}
blocks[start + i] = last_index;
indexes[i] = last_index;
}
return new Section(indexes);
});
for (const [i, [id, state]] of chunk.unknown ?? []) blocks[i] = index_of(id, state);
return { palette, blocks, biomes };
for (const [i, [id, state]] of chunk.unknown ?? []) {
saved[Math.floor(i / SECTION_VOLUME)].set(i % SECTION_VOLUME, index_of(id, state));
}
return { palette, min_y: this.shape.min_y, sections: saved, biomes };
}
get_tile(x: number, y: number, z: number) {
@@ -671,7 +670,7 @@ export class ServerWorld {
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, this.shape.volume));
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}`,
@@ -689,16 +688,30 @@ export class ServerWorld {
const nid = id === AIR_ID ? AIR : this.block_ids[id];
return nid === undefined ? undefined : block_value(nid, state);
});
const blocks = new Uint32Array(this.shape.volume);
let unknown: Map<number, [string, number]> | undefined;
for (let i = 0; i < blocks.length; i++) {
const value = values[saved.blocks[i]];
if (value === undefined) {
(unknown ??= new Map()).set(i, saved.palette[saved.blocks[i]]);
} else {
blocks[i] = value;
// sections the save doesn't have are air, and ones the dimension doesn't have are left out
const offset = (this.shape.min_y - saved.min_y) / SECTION_HEIGHT;
const sections = Array.from({ length: this.shape.height / SECTION_HEIGHT }, (_, s) => {
const section = saved.sections[offset + s];
if (!section) return new Section(AIR);
const start = s * SECTION_VOLUME;
const blocks = section.blocks;
if (blocks === null) {
const value = values[section.value];
if (value === undefined) {
for (let i = 0; i < SECTION_VOLUME; i++) {
(unknown ??= new Map()).set(start + i, saved.palette[section.value]);
}
}
return new Section(value ?? AIR);
}
}
for (let i = 0; i < SECTION_VOLUME; i++) {
const value = values[blocks[i]];
if (value === undefined) (unknown ??= new Map()).set(start + i, saved.palette[blocks[i]]);
blocks[i] = value ?? AIR;
}
return section;
});
let biomes = saved.biomes;
if (!biomes) {
// saved before chunks had them. saved again with them
@@ -706,7 +719,7 @@ export class ServerWorld {
biomes = [...this.#biomes.get(key) ?? this.#get_raw(chunk_x, chunk_z).column.biomes];
this.#mark_unsaved(chunk_x, chunk_z);
}
return { column: ChunkColumn.from_flat(chunk_x, chunk_z, this.shape, blocks, biomes), unknown };
return { column: new ChunkColumn(chunk_x, chunk_z, this.shape, sections, biomes), unknown };
}
// an unsaved chunk is encoded to be saved, instead of being generated again or kept whole