Workers for chunk generation !

This commit is contained in:
2026-10-11 01:15:14 -03:00
parent 3d2b235f64
commit cd3b39c3d7
24 changed files with 1119 additions and 91 deletions
+13 -2
View File
@@ -5,6 +5,7 @@ import { join } from "@std/path";
import { GameToHost, HostToGame } from "./game/host_protocol.ts";
import { load_bmods } from "./load_bmods.ts";
import { read_regions, write_chunks } from "./regions.ts";
import { default_worldgen_workers, start_worldgen_workers } from "./worldgen_workers.ts";
import type { SavedChunk, WorldSave } from "./game/saves.ts";
const MAX_MESSAGE_SIZE = 4096;
@@ -25,6 +26,9 @@ export interface HostOptions {
// the world's folder: level.json, and the blocks in region/
world_dir: string;
seed?: string;
// how many workers generate chunks, besides the game. 0 generates on the game's thread. a few by default, see
// default_worldgen_workers
worldgen_workers?: number;
// the game can't go on, like the worker crashing
on_fatal(message: string): void;
}
@@ -46,7 +50,12 @@ export async function start_host(options: HostOptions): Promise<Host> {
type: "module",
deno: { permissions: "none" },
} as WorkerOptions);
const post = (message: HostToGame) => game.postMessage(message);
const post = (message: HostToGame, transfer: Transferable[] = []) => game.postMessage(message, transfer);
// without permissions like the game, which can't start them itself
const worldgen = start_worldgen_workers(options.worldgen_workers ?? default_worldgen_workers(), {
permissions: "none",
on_restart: (index, port) => post({ type: "worldgen_port", index, port }, [port]),
});
const sockets = new Map<number, WebSocket>();
let next_conn = 1;
@@ -123,8 +132,9 @@ export async function start_host(options: HostOptions): Promise<Host> {
worldgen_code: bmod.scripts.worldgen,
shared_code: bmod.scripts.shared,
})),
worldgen_ports: worldgen.ports,
} satisfies HostToGame,
save.chunks.map((chunk) => chunk.data.buffer),
[...save.chunks.map((chunk) => chunk.data.buffer), ...worldgen.ports],
);
function handle_socket(socket: WebSocket) {
@@ -191,6 +201,7 @@ export async function start_host(options: HostOptions): Promise<Host> {
on_final_save = (error) => {
clearTimeout(timeout);
game.terminate();
worldgen.terminate();
if (error) {
reject(error);
} else {