// how the server streams the world to clients, like minecraft java since 1.20.2: whole chunks in batches around each // player, and which chunks are in a player's view. see "Chunk Streaming" in docs/modding_plan.md import { deflateSync, inflateSync } from "fflate"; import { CHUNK_AREA, CHUNK_HEIGHT } from "./constants.ts"; // the view distances clients can ask for, in chunks, like minecraft's export const MIN_VIEW_DISTANCE = 2; export const MAX_VIEW_DISTANCE = 32; export const SECTION_HEIGHT = 16; const SECTION_VOLUME = CHUNK_AREA * SECTION_HEIGHT; const SECTIONS = CHUNK_HEIGHT / SECTION_HEIGHT; const CHUNK_VOLUME = CHUNK_AREA * CHUNK_HEIGHT; // the first byte of a binary message, the only kind there is so far export const LEVEL_CHUNK = 1; // bits per block of a section's indirect palette, the smallest that fits. more than 256 kinds are stored directly const PALETTE_BITS = [1, 2, 4, 8]; const DIRECT_BITS = 32; // minecraft's ChunkTrackingView.isWithinDistance: a round view, with the ring of chunks around it (outer) that the // client needs to mesh and light the edge of what it shows export function is_within_view( center_x: number, center_z: number, view_distance: number, x: number, z: number, outer = true, ) { const dx = Math.max(0, Math.abs(x - center_x) - 1); const dz = Math.max(0, Math.abs(z - center_z) - 1); const far = Math.max(0, Math.max(dx, dz) - (outer ? 1 : 0)); const near = Math.min(dx, dz); return near * near + far * far < view_distance * view_distance; } export interface LevelChunk { x: number; z: number; // block values (numeric id | state bits << 16) in the sender's numbering, y then z then x blocks: Uint32Array; // each column's biome, x then z biomes: string[]; } // a level_chunk message, like minecraft's ClientboundLevelChunkWithLightPacket without the light (clients light // chunks themselves). sent as a binary websocket message, little-endian: // // u8 LEVEL_CHUNK // i32 chunk x, i32 chunk z // the rest deflated: // u16 biome palette size, then each biome: u8 length and the id as utf-8 // u8 each column's biome palette index, x then z. left out when there's one biome // 16 sections of 16x16x16 blocks, bottom first, each a paletted container like minecraft's: // u8 bits per block // 0: u32 the value of every block // 1, 2, 4, 8: u16 palette size, u32 each value, then each block's palette index packed from the low bits up // 32: u32 each block's value export function encode_level_chunk(chunk: LevelChunk): Uint8Array { const writer = new Writer(); const biome_palette = [...new Set(chunk.biomes)]; writer.u16(biome_palette.length); for (const biome of biome_palette) writer.string(biome); if (biome_palette.length > 1) { for (const biome of chunk.biomes) writer.u8(biome_palette.indexOf(biome)); } for (let section = 0; section < SECTIONS; section++) { write_section(writer, chunk.blocks.subarray(section * SECTION_VOLUME, (section + 1) * SECTION_VOLUME)); } const body = deflateSync(writer.bytes()); const bytes = new Uint8Array(9 + body.length); const view = new DataView(bytes.buffer); bytes[0] = LEVEL_CHUNK; view.setInt32(1, chunk.x, true); view.setInt32(5, chunk.z, true); bytes.set(body, 9); return bytes; } function write_section(writer: Writer, blocks: Uint32Array) { const palette: number[] = []; const index_of = new Map(); for (const value of blocks) { if (!index_of.has(value)) { index_of.set(value, palette.length); palette.push(value); } } 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 blocks) 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 < SECTION_VOLUME; i += per_byte) { let byte = 0; for (let j = 0; j < per_byte; j++) byte |= index_of.get(blocks[i + j])! << (j * bits); writer.u8(byte); } } // throws when the bytes aren't a level_chunk. map turns each block value into the receiver's numbering export function decode_level_chunk(bytes: Uint8Array, map: (value: number) => number = (value) => value): LevelChunk { if (bytes[0] !== LEVEL_CHUNK || bytes.length < 9) throw new Error("Not a level_chunk"); const header = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); const x = header.getInt32(1, true); const z = header.getInt32(5, true); const reader = new Reader(inflateSync(bytes.subarray(9))); const biome_palette: string[] = []; const biome_count = reader.u16(); if (biome_count === 0) throw new Error("No biomes"); for (let i = 0; i < biome_count; i++) biome_palette.push(reader.string()); const biomes: string[] = new Array(CHUNK_AREA); for (let column = 0; column < CHUNK_AREA; column++) { const index = biome_count > 1 ? reader.u8() : 0; if (index >= biome_count) throw new Error("Bad biome index"); biomes[column] = biome_palette[index]; } const blocks = new Uint32Array(CHUNK_VOLUME); for (let section = 0; section < SECTIONS; section++) { read_section(reader, blocks.subarray(section * SECTION_VOLUME, (section + 1) * SECTION_VOLUME), map); } if (!reader.done) throw new Error("Wrong size"); return { x, z, blocks, biomes }; } function read_section(reader: Reader, blocks: Uint32Array, map: (value: number) => number) { const bits = reader.u8(); if (bits === 0) { blocks.fill(map(reader.u32())); return; } if (bits === DIRECT_BITS) { for (let i = 0; i < SECTION_VOLUME; i++) blocks[i] = map(reader.u32()); return; } if (!PALETTE_BITS.includes(bits)) throw new Error(`Bad bits per block ${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 < SECTION_VOLUME; 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"); blocks[i + j] = palette[index]; } } } class Writer { #bytes = new Uint8Array(16 * 1024); #view = new DataView(this.#bytes.buffer); #length = 0; #reserve(size: number) { if (this.#length + size <= this.#bytes.length) return; const bytes = new Uint8Array(Math.max(this.#bytes.length * 2, this.#length + size)); bytes.set(this.#bytes); this.#bytes = bytes; this.#view = new DataView(bytes.buffer); } u8(value: number) { this.#reserve(1); this.#bytes[this.#length++] = value; } u16(value: number) { this.#reserve(2); this.#view.setUint16(this.#length, value, true); this.#length += 2; } u32(value: number) { this.#reserve(4); this.#view.setUint32(this.#length, value, true); this.#length += 4; } string(text: string) { const bytes = new TextEncoder().encode(text); if (bytes.length > 255) throw new Error(`${text} is too long to send`); this.u8(bytes.length); this.#reserve(bytes.length); this.#bytes.set(bytes, this.#length); this.#length += bytes.length; } bytes() { return this.#bytes.subarray(0, this.#length); } } class Reader { #bytes: Uint8Array; #view: DataView; #offset = 0; constructor(bytes: Uint8Array) { this.#bytes = bytes; this.#view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); } get done() { return this.#offset === this.#bytes.length; } #take(size: number) { if (this.#offset + size > this.#bytes.length) throw new Error("Too short"); const offset = this.#offset; this.#offset += size; return offset; } u8() { return this.#bytes[this.#take(1)]; } u16() { return this.#view.getUint16(this.#take(2), true); } u32() { return this.#view.getUint32(this.#take(4), true); } string() { const length = this.u8(); const offset = this.#take(length); return new TextDecoder().decode(this.#bytes.subarray(offset, offset + length)); } }