// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later // a chunk's blocks in sections of 16x16x16, from the bottom of its dimension up, like minecraft's LevelChunkSection. a // section that's all one block keeps just that value: most of a tall column is air above the ground and stone under it import { AIR, CHUNK_AREA, ID_MASK } from "./constants.ts"; import type { Reader, Writer } from "./bytes.ts"; import { HIGHEST_Y, LOWEST_Y, SECTION_HEIGHT, type WorldShape } from "./world_shape.ts"; export const SECTION_VOLUME = CHUNK_AREA * SECTION_HEIGHT; // a block's place in its section, y then z then x like a chunk's layers. world coordinates work as they are, since // sections start at multiples of 16 export function section_index(x: number, y: number, z: number) { return ((y & 15) << 8) | ((z & 15) << 4) | (x & 15); } // what a section is made of, a block value or every block's, what's sent to and from workers export type SectionData = number | Uint32Array; export class Section { // the block, while blocks is null value: number; // every block's value, once they differ blocks: Uint32Array | null; constructor(data: SectionData) { this.value = typeof data === "number" ? data : 0; this.blocks = typeof data === "number" ? null : data; } // a copy of values, one value when they're all the same static of(values: Uint32Array): Section { const first = values[0]; for (let i = 1; i < values.length; i++) { if (values[i] !== first) return new Section(values.slice()); } return new Section(first); } get data(): SectionData { return this.blocks ?? this.value; } get(index: number): number { return this.blocks === null ? this.value : this.blocks[index]; } set(index: number, value: number) { if (this.blocks === null) { if (value === this.value) return; this.blocks = new Uint32Array(SECTION_VOLUME).fill(this.value); } this.blocks[index] = value; } } // biomes are one per block across, and one every BIOME_CELL_HEIGHT blocks up: a cell export const BIOME_CELL_HEIGHT = 4; export const SECTION_BIOMES = CHUNK_AREA * SECTION_HEIGHT / BIOME_CELL_HEIGHT; // a column's biome palette can't be longer, since a cell's index in it is a byte export const MAX_COLUMN_BIOMES = 256; // a biome cell's place in its section's biomes: its layer of cells, then z, then x export function biome_index(x: number, y: number, z: number) { return (((y & 15) >> 2) << 8) | ((z & 15) << 4) | (x & 15); } // a section's biomes: one index into its column's biome palette for all of it, or SECTION_BIOMES of them. an array is // never changed once it's made, see ChunkColumn.set_biome, so sections with the same biomes can share one: most of a // column's when biomes don't change with height export type SectionBiomes = number | Uint8Array; // a chunk's biomes export interface ColumnBiomes { // every biome in it, at most MAX_COLUMN_BIOMES palette: string[]; // by section from the bottom up, like its blocks sections: SectionBiomes[]; } // biomes from each cell's biome id, a layer of cells at a time from the bottom of the world up, then z, then x. or // CHUNK_AREA of them, each column's biome all the way up. count is how many sections there are export function column_biomes(cells: string[], count: number): ColumnBiomes { const palette: string[] = []; const indexes = new Map(); const sections: SectionBiomes[] = []; const section = new Uint8Array(SECTION_BIOMES); // runs of the same biome are common, it's only looked up when it changes let last: string | undefined; let last_index = 0; for (let s = 0; s < count; s++) { let same = true; for (let i = 0; i < SECTION_BIOMES; i++) { const biome = cells[cells.length === CHUNK_AREA ? i & 255 : s * SECTION_BIOMES + i]; if (biome !== last) { last = biome; let index = indexes.get(biome); if (index === undefined) { if (palette.length === MAX_COLUMN_BIOMES) throw new Error(`More than ${MAX_COLUMN_BIOMES} biomes`); index = palette.push(biome) - 1; indexes.set(biome, index); } last_index = index; } section[i] = last_index; if (last_index !== section[0]) same = false; } sections.push(same ? section[0] : section.slice()); } share_same(sections); return { palette, sections }; } // sections whose biomes are the same as the one below's share its array function share_same(sections: SectionBiomes[]) { for (let s = 1; s < sections.length; s++) { const below = sections[s - 1]; const here = sections[s]; if (typeof below === "number" || typeof here === "number" || below === here) continue; let i = 0; while (i < SECTION_BIOMES && below[i] === here[i]) i++; if (i === SECTION_BIOMES) sections[s] = below; } } // the biome at world coordinates in a chunk's biomes, see ChunkColumn.biome_at export function biome_in(biomes: ColumnBiomes, shape: WorldShape, x: number, y: number, z: number): string { y = Math.min(Math.max(y, shape.min_y), shape.max_y - 1); const section = biomes.sections[(y - shape.min_y) >> 4]; return biomes.palette[typeof section === "number" ? section : section[biome_index(x, y, z)]]; } // a chunk's blocks and biomes, its dimension's whole height export class ChunkColumn { readonly x: number; readonly z: number; readonly shape: WorldShape; // from min_y up readonly sections: Section[]; readonly biomes: ColumnBiomes; constructor(x: number, z: number, shape: WorldShape, sections: Section[], biomes: ColumnBiomes) { if (sections.length * SECTION_HEIGHT !== shape.height || biomes.sections.length !== sections.length) { throw new Error(`Chunk ${x}, ${z} has ${sections.length} sections, its dimension ${shape.height / 16}`); } this.x = x; this.z = z; this.shape = shape; this.sections = sections; this.biomes = biomes; } // from every block's value in one array, y from min_y then z then x, which is copied, and the biomes of its cells, // see column_biomes static from_flat(x: number, z: number, shape: WorldShape, blocks: Uint32Array, biomes: string[]): ChunkColumn { const sections: Section[] = []; for (let start = 0; start < blocks.length; start += SECTION_VOLUME) { sections.push(Section.of(blocks.subarray(start, start + SECTION_VOLUME))); } return new ChunkColumn(x, z, shape, sections, column_biomes(biomes, sections.length)); } // the biome at world coordinates. above and below the dimension it's the one at its top or bottom biome_at(x: number, y: number, z: number): string { return biome_in(this.biomes, this.shape, x, y, z); } // sets the biome of the cell y is in. does nothing outside the dimension's height set_biome(x: number, y: number, z: number, biome: string) { if (!this.shape.contains(y)) return; const { palette, sections } = this.biomes; let index = palette.indexOf(biome); if (index === -1) { if (palette.length === MAX_COLUMN_BIOMES) { throw new Error(`More than ${MAX_COLUMN_BIOMES} biomes in a chunk`); } index = palette.push(biome) - 1; } const s = (y - this.shape.min_y) >> 4; const section = sections[s]; if (section === index) return; // a copy, since other sections and other chunks' copies can share the array const changed = typeof section === "number" ? new Uint8Array(SECTION_BIOMES).fill(section) : section.slice(); changed[biome_index(x, y, z)] = index; sections[s] = changed; } // the block value at world coordinates, air outside the dimension's height get(x: number, y: number, z: number): number { if (!this.shape.contains(y)) return AIR; return this.sections[(y - this.shape.min_y) >> 4].get(section_index(x, y, z)); } // does nothing outside the dimension's height set(x: number, y: number, z: number, value: number) { if (!this.shape.contains(y)) return; this.sections[(y - this.shape.min_y) >> 4].set(section_index(x, y, z), value); } clone(): ChunkColumn { const sections = this.sections.map((section) => new Section(section.blocks?.slice() ?? section.value)); // the sections' biome arrays are never changed, so they can be shared const biomes = { palette: [...this.biomes.palette], sections: [...this.biomes.sections] }; return new ChunkColumn(this.x, this.z, this.shape, sections, biomes); } // every block's value in one array, like from_flat's to_flat(): Uint32Array { return to_flat(this.sections); } } export function to_flat(sections: Section[]): Uint32Array { const blocks = new Uint32Array(sections.length * SECTION_VOLUME); sections.forEach((section, i) => { if (section.blocks) blocks.set(section.blocks, i * SECTION_VOLUME); else blocks.fill(section.value, i * SECTION_VOLUME, (i + 1) * SECTION_VOLUME); }); return blocks; } // bits per value of a paletted container's palette, the smallest that fits. more than 256 kinds are written whole const PALETTE_BITS = [1, 2, 4, 8]; const DIRECT_BITS = 32; // a column's sections and biomes, as level_chunk and saved chunks hold them (see common/chunk_streaming.ts and // server/game/saves.ts). the network sends block values, a save the index of each block in its own palette: // // u16 biome palette size, then each biome: u8 length and the id as utf-8 // u16 how many sections there are // each section, bottom first: // its 16x16x16 blocks, a paletted container of their values // its biome cells (see biome_index), a paletted container of their biome palette indexes // // a paletted container, like minecraft's: // u8 bits per value // 0: u32 every value // 1, 2, 4, 8: u16 palette size, u32 each value, then each one's palette index packed from the low bits up // 32: u32 each value export function write_column(writer: Writer, sections: Section[], biomes: ColumnBiomes) { if (biomes.sections.length !== sections.length || biomes.palette.length > MAX_COLUMN_BIOMES) { throw new Error("Bad biomes"); } writer.u16(biomes.palette.length); for (const biome of biomes.palette) writer.string(biome); writer.u16(sections.length); sections.forEach((section, i) => { write_paletted(writer, section.blocks ?? section.value); write_paletted(writer, biomes.sections[i]); }); } function write_paletted(writer: Writer, values: number | Uint32Array | Uint8Array) { if (typeof values === "number") { writer.u8(0); writer.u32(values); return; } // each value's palette index. runs of the same value are common, so it's looked up when the value changes const indexes = new Uint16Array(values.length); const palette: number[] = []; const index_of = new Map(); let last_value = values[0] + 1; let last_index = 0; for (let i = 0; i < values.length; i++) { const value = values[i]; if (value !== last_value) { last_value = value; let index = index_of.get(value); if (index === undefined) { index = palette.push(value) - 1; index_of.set(value, index); } last_index = index; } indexes[i] = last_index; } if (palette.length === 1) { writer.u8(0); writer.u32(palette[0]); return; } const bits = PALETTE_BITS.find((bits) => palette.length <= 1 << bits); if (bits === undefined) { writer.u8(DIRECT_BITS); for (const value of values) writer.u32(value); return; } writer.u8(bits); writer.u16(palette.length); for (const value of palette) writer.u32(value); const per_byte = 8 / bits; for (let i = 0; i < values.length; i += per_byte) { let byte = 0; for (let j = 0; j < per_byte; j++) byte |= indexes[i + j] << (j * bits); writer.u8(byte); } } // throws when it isn't what write_column writes. map turns each block value read into what the sections hold, and can // throw for a value that's wrong. flat_biomes reads what came before biomes had heights (format 3 saves): after the // biome palette, a u8 palette index per column (x then z) when there's more than one, and sections of blocks alone export function read_column( reader: Reader, map: (value: number) => number, flat_biomes = false, ): { sections: Section[]; biomes: ColumnBiomes } { const palette: string[] = []; const palette_size = reader.u16(); if (palette_size === 0 || palette_size > MAX_COLUMN_BIOMES) throw new Error("Bad biome palette"); for (let i = 0; i < palette_size; i++) palette.push(reader.string()); const biome = (index: number) => { if (index >= palette_size) throw new Error("Bad biome index"); return index; }; let columns: string[] | undefined; if (flat_biomes) { columns = Array.from({ length: CHUNK_AREA }, () => palette[palette_size > 1 ? biome(reader.u8()) : 0]); } const count = reader.u16(); if (count * SECTION_HEIGHT > HIGHEST_Y - LOWEST_Y) throw new Error(`Too many sections, ${count}`); const sections: Section[] = []; const cells: SectionBiomes[] = []; for (let i = 0; i < count; i++) { sections.push(new Section(read_paletted(reader, new Uint32Array(SECTION_VOLUME), map))); if (!flat_biomes) cells.push(read_paletted(reader, new Uint8Array(SECTION_BIOMES), biome)); } share_same(cells); return { sections, biomes: columns ? column_biomes(columns, count) : { palette, sections: cells } }; } // into values, unless they're all one, which is returned instead function read_paletted( reader: Reader, values: T, map: (value: number) => number, ): number | T { const bits = reader.u8(); if (bits === 0) return map(reader.u32()); if (bits === DIRECT_BITS) { for (let i = 0; i < values.length; i++) values[i] = map(reader.u32()); return values; } if (!PALETTE_BITS.includes(bits)) throw new Error(`Bad bits per value ${bits}`); const palette: number[] = []; const size = reader.u16(); if (size > 1 << bits) throw new Error("Bad palette"); for (let i = 0; i < size; i++) palette.push(map(reader.u32())); const per_byte = 8 / bits; const mask = (1 << bits) - 1; for (let i = 0; i < values.length; i += per_byte) { const byte = reader.u8(); for (let j = 0; j < per_byte; j++) { const index = (byte >> (j * bits)) & mask; if (index >= size) throw new Error("Bad palette index"); values[i + j] = palette[index]; } } return values; } // per column of a chunk (z * 16 + x), the highest y that isn't air, min_y - 1 for an empty one, then the lowest y with // nothing above it that stops light, where sky light is 15 (see light_at in server/game/world.ts). opacity is by // numeric id. sections that are all air, or all clear, are passed over whole export function column_heights(column: ChunkColumn, opacity: Uint8Array): Int16Array { const heights = new Int16Array(CHUNK_AREA * 2); const { sections, shape } = column; for (let c = 0; c < CHUNK_AREA; c++) { // from the top, by y above min_y let y = shape.height - 1; while (y >= 0) { const section = sections[y >> 4]; if (section.blocks === null && (section.value & ID_MASK) === AIR) { y = (y & ~15) - 1; continue; } if ((section.get(((y & 15) << 8) | c) & ID_MASK) !== AIR) break; y--; } heights[c] = shape.min_y + y; while (y >= 0) { const section = sections[y >> 4]; if (section.blocks === null && opacity[section.value & ID_MASK] === 0) { y = (y & ~15) - 1; continue; } if (opacity[section.get(((y & 15) << 8) | c) & ID_MASK] !== 0) break; y--; } heights[CHUNK_AREA + c] = shape.min_y + y + 1; } return heights; }