200 lines
7.8 KiB
TypeScript
200 lines
7.8 KiB
TypeScript
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
// region files, laid out like minecraft's since mcregion (a mod, part of the game from beta 1.3): the chunks of a
|
|
// 32 by 32 chunk square in one file, so saving writes only the chunks that changed. the file is 4 KiB sectors, the
|
|
// first two are the header:
|
|
//
|
|
// 1024 locations, one per chunk: u24 first sector, u8 how many sectors. 0 and 0 where there's no chunk
|
|
// 1024 timestamps: u32 seconds, when the chunk was last written
|
|
//
|
|
// a chunk's place in those is (x & 31) + (z & 31) * 32. its sectors start with u32 the length of what follows, u8
|
|
// the compression (2, zlib like minecraft's default), then the compressed chunk from server/game/saves.ts.
|
|
// big-endian. a chunk saved again goes into sectors nothing uses and the header is written last, so a crash while
|
|
// saving leaves the chunks as they were instead of half written. the game reads chunks one at a time, when it needs
|
|
// them
|
|
import { join } from "@std/path";
|
|
import type { SavedChunk } from "./game/saves.ts";
|
|
|
|
const SECTOR = 4096;
|
|
const REGION_CHUNKS = 32;
|
|
const CHUNKS_PER_REGION = REGION_CHUNKS * REGION_CHUNKS;
|
|
const HEADER_SECTORS = 2;
|
|
const HEADER_SIZE = HEADER_SECTORS * SECTOR;
|
|
const ZLIB = 2;
|
|
// what fits in a location's sector count, 1 MB
|
|
const MAX_CHUNK_SECTORS = 255;
|
|
const REGION_FILE = /^r\.(-?\d+)\.(-?\d+)\.bwr$/;
|
|
|
|
export function region_file(region_x: number, region_z: number) {
|
|
return `r.${region_x}.${region_z}.bwr`;
|
|
}
|
|
|
|
// where every chunk in the folder's region files is, from their headers
|
|
export async function list_chunks(dir: string): Promise<[number, number][]> {
|
|
let entries: Deno.DirEntry[];
|
|
try {
|
|
entries = [...Deno.readDirSync(dir)];
|
|
} catch (e) {
|
|
if (e instanceof Deno.errors.NotFound) return [];
|
|
throw e;
|
|
}
|
|
const chunks: [number, number][] = [];
|
|
for (const entry of entries) {
|
|
const match = entry.isFile && REGION_FILE.exec(entry.name);
|
|
if (!match) continue;
|
|
const [region_x, region_z] = [Number(match[1]), Number(match[2])];
|
|
using file = await Deno.open(join(dir, entry.name));
|
|
const header = new Uint8Array(CHUNKS_PER_REGION * 4);
|
|
if (await read_at(file, 0, header) < header.length) {
|
|
console.error(`${entry.name} is too short to be a region file`);
|
|
continue;
|
|
}
|
|
const view = new DataView(header.buffer);
|
|
for (let i = 0; i < CHUNKS_PER_REGION; i++) {
|
|
if (view.getUint32(i * 4) === 0) continue;
|
|
chunks.push([
|
|
region_x * REGION_CHUNKS + (i % REGION_CHUNKS),
|
|
region_z * REGION_CHUNKS + Math.floor(i / REGION_CHUNKS),
|
|
]);
|
|
}
|
|
}
|
|
return chunks;
|
|
}
|
|
|
|
// a chunk from its region file, uncompressed. undefined when it isn't there. throws when it can't be read
|
|
export async function read_chunk(dir: string, x: number, z: number): Promise<Uint8Array<ArrayBuffer> | undefined> {
|
|
const name = region_file(Math.floor(x / REGION_CHUNKS), Math.floor(z / REGION_CHUNKS));
|
|
using file = await open_if_there(join(dir, name));
|
|
if (!file) return undefined;
|
|
const location_bytes = new Uint8Array(4);
|
|
await read_at(file, chunk_index(x, z) * 4, location_bytes);
|
|
const location = new DataView(location_bytes.buffer).getUint32(0);
|
|
if (location === 0) return undefined;
|
|
const sectors = new Uint8Array((location & 0xFF) * SECTOR);
|
|
const read = await read_at(file, (location >>> 8) * SECTOR, sectors);
|
|
const view = new DataView(sectors.buffer);
|
|
if (read < 5) throw new Error(`chunk ${x}, ${z} goes past the end of ${name}`);
|
|
const length = view.getUint32(0);
|
|
const compression = view.getUint8(4);
|
|
if (compression !== ZLIB) throw new Error(`chunk ${x}, ${z} in ${name} has unknown compression ${compression}`);
|
|
if (length < 1 || 4 + length > read) throw new Error(`chunk ${x}, ${z} goes past the end of ${name}`);
|
|
return await inflate(sectors.subarray(5, 4 + length));
|
|
}
|
|
|
|
async function open_if_there(path: string) {
|
|
try {
|
|
return await Deno.open(path);
|
|
} catch (e) {
|
|
if (e instanceof Deno.errors.NotFound) return undefined;
|
|
throw e;
|
|
}
|
|
}
|
|
|
|
function chunk_index(x: number, z: number) {
|
|
return (x & (REGION_CHUNKS - 1)) + (z & (REGION_CHUNKS - 1)) * REGION_CHUNKS;
|
|
}
|
|
|
|
// saves the chunks into their region files, making them and the folder when needed
|
|
export async function write_chunks(dir: string, chunks: SavedChunk[]) {
|
|
const regions = new Map<string, SavedChunk[]>();
|
|
for (const chunk of chunks) {
|
|
const name = region_file(Math.floor(chunk.x / REGION_CHUNKS), Math.floor(chunk.z / REGION_CHUNKS));
|
|
regions.set(name, [...regions.get(name) ?? [], chunk]);
|
|
}
|
|
if (regions.size) Deno.mkdirSync(dir, { recursive: true });
|
|
for (const [name, region_chunks] of regions) {
|
|
await write_region(join(dir, name), region_chunks);
|
|
}
|
|
}
|
|
|
|
async function write_region(path: string, chunks: SavedChunk[]) {
|
|
const compressed = await Promise.all(chunks.map((chunk) => deflate(chunk.data)));
|
|
using file = await Deno.open(path, { read: true, write: true, create: true });
|
|
|
|
const header = new Uint8Array(HEADER_SIZE);
|
|
await read_at(file, 0, header);
|
|
const view = new DataView(header.buffer);
|
|
|
|
// the sectors the header points at now, which stay untouched until the new header is written
|
|
const used: boolean[] = [];
|
|
for (let i = 0; i < HEADER_SECTORS; i++) used[i] = true;
|
|
for (let i = 0; i < CHUNKS_PER_REGION; i++) {
|
|
const location = view.getUint32(i * 4);
|
|
const [first, count] = [location >>> 8, location & 0xFF];
|
|
for (let sector = first; sector < first + count; sector++) used[sector] = true;
|
|
}
|
|
|
|
const now = Math.floor(Date.now() / 1000);
|
|
for (const [i, chunk] of chunks.entries()) {
|
|
const data = compressed[i];
|
|
const sectors = Math.ceil((5 + data.length) / SECTOR);
|
|
if (sectors > MAX_CHUNK_SECTORS) {
|
|
throw new Error(`Chunk ${chunk.x}, ${chunk.z} is too big to save (${data.length} bytes)`);
|
|
}
|
|
const first = free_sectors(used, sectors);
|
|
for (let sector = first; sector < first + sectors; sector++) used[sector] = true;
|
|
|
|
const bytes = new Uint8Array(sectors * SECTOR);
|
|
const chunk_view = new DataView(bytes.buffer);
|
|
chunk_view.setUint32(0, data.length + 1);
|
|
chunk_view.setUint8(4, ZLIB);
|
|
bytes.set(data, 5);
|
|
await write_at(file, first * SECTOR, bytes);
|
|
|
|
const index = chunk_index(chunk.x, chunk.z);
|
|
view.setUint32(index * 4, (first << 8) | sectors);
|
|
view.setUint32(SECTOR + index * 4, now);
|
|
}
|
|
|
|
// the chunks are on disk before the header points at them
|
|
await file.syncData();
|
|
await write_at(file, 0, header);
|
|
}
|
|
|
|
// the first of the first run of that many sectors nothing uses, which can be past the end of the file
|
|
function free_sectors(used: boolean[], count: number) {
|
|
let start = HEADER_SECTORS;
|
|
for (let sector = HEADER_SECTORS; sector < used.length; sector++) {
|
|
if (used[sector]) {
|
|
start = sector + 1;
|
|
} else if (sector - start + 1 === count) {
|
|
return start;
|
|
}
|
|
}
|
|
return start;
|
|
}
|
|
|
|
// reads as much of bytes as the file has there, a new file reads as zeros. returns how much that was
|
|
async function read_at(file: Deno.FsFile, offset: number, bytes: Uint8Array) {
|
|
await file.seek(offset, Deno.SeekMode.Start);
|
|
let read = 0;
|
|
while (read < bytes.length) {
|
|
const n = await file.read(bytes.subarray(read));
|
|
if (n === null) break;
|
|
read += n;
|
|
}
|
|
return read;
|
|
}
|
|
|
|
async function write_at(file: Deno.FsFile, offset: number, bytes: Uint8Array) {
|
|
await file.seek(offset, Deno.SeekMode.Start);
|
|
let written = 0;
|
|
while (written < bytes.length) {
|
|
written += await file.write(bytes.subarray(written));
|
|
}
|
|
}
|
|
|
|
// "deflate" is zlib's format, what minecraft calls compression 2
|
|
function deflate(bytes: Uint8Array<ArrayBuffer>) {
|
|
return transform(bytes, new CompressionStream("deflate"));
|
|
}
|
|
|
|
function inflate(bytes: Uint8Array<ArrayBuffer>) {
|
|
return transform(bytes, new DecompressionStream("deflate"));
|
|
}
|
|
|
|
async function transform(bytes: Uint8Array<ArrayBuffer>, stream: CompressionStream | DecompressionStream) {
|
|
return new Uint8Array(await new Response(new Blob([bytes]).stream().pipeThrough(stream)).arrayBuffer());
|
|
}
|