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
+29
View File
@@ -5,8 +5,11 @@ import type { GameServer } from "./game_server.ts";
import { GameLoop } from "./game_loop.ts";
import { GameToHost, HostToGame } from "./host_protocol.ts";
import { data_url, start_game } from "./load_mods.ts";
import { type WorkerPort, WorldgenPool } from "./worldgen_pool.ts";
const SAVE_INTERVAL_MS = 30_000;
// how long the worldgen workers get to load the mods before the game starts without them
const WORLDGEN_START_TIMEOUT_MS = 60_000;
let game: GameServer | undefined;
let starting: Promise<void> | undefined;
@@ -31,6 +34,12 @@ self.onmessage = async (event: MessageEvent<HostToGame>) => {
starting = init(message);
return;
}
if (message.type === "worldgen_port") {
// the worker it replaces crashed. the pool resends what it was working on
await starting;
game?.worldgen_pool?.replace(message.index, message.port as unknown as WorkerPort);
return;
}
if (message.type === "downloaded") {
const pending = downloads.get(message.id);
downloads.delete(message.id);
@@ -93,6 +102,26 @@ async function init(message: Extract<HostToGame, { type: "init" }>) {
return;
}
// chunks are generated in the worldgen workers, except what can't wait for them
if (message.worldgen_ports.length > 0) {
const pool = new WorldgenPool(message.worldgen_ports as unknown as WorkerPort[], game.worldgen_bundle!);
game.use_worldgen_pool(pool);
try {
let timer: ReturnType<typeof setTimeout> | undefined;
await Promise.race([
pool.ready(),
new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error("they took too long")), WORLDGEN_START_TIMEOUT_MS);
}),
]).finally(() => clearTimeout(timer));
await game.warm_up();
} catch (e) {
console.error(`The worldgen workers didn't start, generating on the game thread: ${(e as Error).message}`);
game.use_worldgen_pool(undefined);
pool.close();
}
}
const loop = new GameLoop(() => game!.tick());
game.loop = loop;
loop.start();