// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later /// // generates chunks for the game, off its thread. the host starts it without permissions, like the game, and hands it // a port the game talks to it through (see server/worldgen_workers.ts and worldgen_pool.ts). the game sends the // worldgen bundle once, then chunks to generate, and gets their blocks back moved, not copied import { load_bundle, type LoadedBundle } from "@/common/worldgen_bundle.ts"; import { expose_engine } from "@/common/hooks.ts"; import { common_engine } from "@/common/engine_modules.ts"; import type { PoolToWorker, WorkerToPool } from "./worldgen_pool.ts"; self.onmessage = (event: MessageEvent<{ port: MessagePort }>) => { const port = event.data.port; const send = (message: WorkerToPool, transfer: Transferable[] = []) => port.postMessage(message, transfer); let loaded: Promise | undefined; port.onmessage = async (event: MessageEvent) => { const message = event.data; if (message.type === "init") { // worldgen phases with engine access hook engine.common here, in this worker's own copy of the engine expose_engine({ common: common_engine() }); loaded = load_bundle(message.bundle); try { await loaded; send({ type: "ready" }); } catch (e) { send({ type: "failed", error: e instanceof Error ? e.message : String(e) }); } return; } const { x, z } = message; try { const raw = (await loaded!).generate(x, z); const sections = raw.column.sections.map((section) => section.data); // sections can share their biomes' array const buffers = new Set( [...sections, ...raw.column.biomes.sections].flatMap((data) => typeof data === "number" ? [] : [data.buffer] ), ); send({ type: "chunk", x, z, sections, spills: raw.spills, biomes: raw.column.biomes }, [ ...buffers, raw.spills.buffer, ]); } catch (e) { send({ type: "error", x, z, error: e instanceof Error ? e.message : String(e) }); } }; };