Awesome menu and saves
This commit is contained in:
+22
-58
@@ -4,18 +4,23 @@
|
||||
/// <reference lib="deno.desktop" />
|
||||
|
||||
// the desktop app: the web client in a bundled chromium (deno desktop's cef backend), so people whose browser has no
|
||||
// webgpu (firefox) can still play. it joins servers like the browser does, and runs its own game server for
|
||||
// singleplayer, like minecraft java. build it with deno task desktop, see the desktop/ docs for how deno desktop works
|
||||
// webgpu (firefox) can still play. its title screen is a main menu like luanti's: singleplayer worlds are played on
|
||||
// a game server of its own, with the mods each world picked from its data folder, see saves.ts. build it with deno
|
||||
// task desktop, see the desktop/ docs for how deno desktop works
|
||||
import { fromFileUrl, join } from "@std/path";
|
||||
import { type Host, serve_static, start_host } from "../server/host.ts";
|
||||
import { serve_static } from "../server/host.ts";
|
||||
import { PROTOCOL_VERSION } from "../common/protocol.ts";
|
||||
import { current_client, update_client } from "./client_updates.ts";
|
||||
import { guard_shortcuts } from "./shortcuts.ts";
|
||||
import { center_mouse } from "./center_mouse.ts";
|
||||
import { data_dir, install_mods } from "./saves.ts";
|
||||
import { singleplayer_server } from "./singleplayer.ts";
|
||||
|
||||
// where the project was built from: build/ and server_mods/ (the .cubi files) are bundled into the app with --include
|
||||
const ROOT = fromFileUrl(new URL("../", import.meta.url));
|
||||
const BUILD_DIR = join(ROOT, "build");
|
||||
const DATA_DIR = data_dir();
|
||||
install_mods(join(ROOT, "server_mods"), DATA_DIR);
|
||||
|
||||
// the server the address field starts with. "" leaves it empty for the player to fill in
|
||||
const config: { server?: string; client_updates?: string } = JSON.parse(
|
||||
@@ -31,7 +36,7 @@ const UPDATE_WAIT_MS = 3000;
|
||||
const client_options = {
|
||||
source: updates_from,
|
||||
bundled_dir: BUILD_DIR,
|
||||
cache_dir: join(data_dir(), "client"),
|
||||
cache_dir: join(DATA_DIR, "client"),
|
||||
protocol: PROTOCOL_VERSION,
|
||||
};
|
||||
const client_dir: Promise<string> = updates_from === "off" || updates_from === ""
|
||||
@@ -45,40 +50,21 @@ client_dir.then((dir) => console.log(`Playing the client in ${dir}`));
|
||||
const win = new Deno.BrowserWindow({ title: "bworld", width: 1280, height: 720 });
|
||||
guard_shortcuts(win);
|
||||
|
||||
// the singleplayer game server, started the first time singleplayer connects so players who only join other servers
|
||||
// don't get a world made for them. it plays the .cubi files the app was built with
|
||||
let host: Promise<Host> | undefined;
|
||||
|
||||
function singleplayer_host(): Promise<Host> {
|
||||
host ??= (async () => {
|
||||
const worlds = join(data_dir(), "worlds");
|
||||
Deno.mkdirSync(worlds, { recursive: true });
|
||||
return await start_host({
|
||||
build_dir: BUILD_DIR,
|
||||
server_mods_dir: join(ROOT, "server_mods"),
|
||||
config_dir: join(data_dir(), "config"),
|
||||
world_dir: join(worlds, "world"),
|
||||
on_fatal(message) {
|
||||
console.error(message);
|
||||
alert(`The singleplayer world stopped: ${message}`);
|
||||
Deno.exit(1);
|
||||
},
|
||||
});
|
||||
})();
|
||||
return host;
|
||||
}
|
||||
const singleplayer = singleplayer_server({
|
||||
build_dir: BUILD_DIR,
|
||||
data_dir: DATA_DIR,
|
||||
on_fatal(message) {
|
||||
console.error(message);
|
||||
alert(`The singleplayer world stopped: ${message}`);
|
||||
Deno.exit(1);
|
||||
},
|
||||
});
|
||||
|
||||
// the world gets saved before the app closes. it always exits by itself: deno desktop's own shutdown freezes on the
|
||||
// last frame when chromium's ctrl+w closed the window, and Deno.serve keeps the process alive anyway
|
||||
win.addEventListener("close", async (event) => {
|
||||
event.preventDefault();
|
||||
if (host) {
|
||||
try {
|
||||
await (await host).shutdown();
|
||||
} catch (e) {
|
||||
console.error((e as Error).message);
|
||||
}
|
||||
}
|
||||
await singleplayer.stop();
|
||||
Deno.exit(0);
|
||||
});
|
||||
|
||||
@@ -91,7 +77,7 @@ Deno.serve(async (req) => {
|
||||
const url = new URL(req.url);
|
||||
if (url.pathname === "/") {
|
||||
// ?server= fills in the address field, without it the field would start with this app's own address.
|
||||
// ?singleplayer shows the singleplayer button, which joins this app's own server
|
||||
// ?singleplayer shows the main menu instead of the browser's title screen
|
||||
const start = new URL("/client/", url);
|
||||
start.searchParams.set("server", default_server);
|
||||
start.searchParams.set("singleplayer", "");
|
||||
@@ -102,29 +88,7 @@ Deno.serve(async (req) => {
|
||||
center_mouse();
|
||||
return new Response(null, { status: 204 });
|
||||
}
|
||||
// the singleplayer server's socket and its .cubi downloads
|
||||
if (url.pathname === "/ws" || url.pathname.startsWith("/mods/")) {
|
||||
try {
|
||||
return (await singleplayer_host()).handle(req);
|
||||
} catch (e) {
|
||||
// its mods have problems, the title screen shows why the connection failed
|
||||
console.error((e as Error).message);
|
||||
host = undefined;
|
||||
return new Response((e as Error).message, { status: 500 });
|
||||
}
|
||||
}
|
||||
const response = await singleplayer.handle(req, url);
|
||||
if (response) return response;
|
||||
return serve_static(await client_dir, req, url);
|
||||
});
|
||||
|
||||
// where the app keeps its worlds, the usual place for app data on each os
|
||||
function data_dir() {
|
||||
const home = Deno.env.get("HOME") ?? Deno.env.get("USERPROFILE") ?? ".";
|
||||
switch (Deno.build.os) {
|
||||
case "windows":
|
||||
return join(Deno.env.get("APPDATA") ?? join(home, "AppData", "Roaming"), "bworld");
|
||||
case "darwin":
|
||||
return join(home, "Library", "Application Support", "bworld");
|
||||
default:
|
||||
return join(Deno.env.get("XDG_DATA_HOME") ?? join(home, ".local", "share"), "bworld");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// the desktop app's data folder, like luanti's: every .cubi in mods/, and the singleplayer worlds in saves/. a world
|
||||
// is a folder the game server saves into, with a world.json of its own saying which mods it's played with
|
||||
import { join } from "@std/path";
|
||||
import { z } from "zod";
|
||||
import { read_manifest } from "../common/mod.ts";
|
||||
import { data_file, FORMAT_VERSION } from "../common/mod_data.ts";
|
||||
import { mod_files } from "../server/load_mods.ts";
|
||||
|
||||
// what the mod lists show
|
||||
export interface ModEntry {
|
||||
id: string;
|
||||
name: string;
|
||||
version: string;
|
||||
description?: string;
|
||||
// the ids of the mods it needs
|
||||
dependencies: string[];
|
||||
// in mods/
|
||||
file: string;
|
||||
}
|
||||
|
||||
export interface WorldEntry {
|
||||
// its folder's name
|
||||
name: string;
|
||||
// the ids of its mods
|
||||
mods: string[];
|
||||
}
|
||||
|
||||
const WORLD_FILE = "world.json";
|
||||
const world_file = data_file("mods", z.array(z.string()));
|
||||
// what works as a folder name on every os
|
||||
const WORLD_NAME = /^[A-Za-z0-9_\- ]{1,32}$/;
|
||||
|
||||
// the usual place for app data on each os
|
||||
export function data_dir() {
|
||||
const home = Deno.env.get("HOME") ?? Deno.env.get("USERPROFILE") ?? ".";
|
||||
switch (Deno.build.os) {
|
||||
case "windows":
|
||||
return join(Deno.env.get("APPDATA") ?? join(home, "AppData", "Roaming"), "cubi");
|
||||
case "darwin":
|
||||
return join(home, "Library", "Application Support", "cubi");
|
||||
default:
|
||||
return join(Deno.env.get("XDG_DATA_HOME") ?? join(home, ".local", "share"), "cubi");
|
||||
}
|
||||
}
|
||||
|
||||
export function mods_dir(data: string) {
|
||||
return join(data, "mods");
|
||||
}
|
||||
|
||||
function saves_dir(data: string) {
|
||||
return join(data, "saves");
|
||||
}
|
||||
|
||||
// puts the .cubi files the app was built with, like the base game, in mods/. they replace the ones with the same file
|
||||
// name, so they're updated along with the app
|
||||
export function install_mods(from: string, data: string) {
|
||||
Deno.mkdirSync(mods_dir(data), { recursive: true });
|
||||
for (const file of mod_files(from)) {
|
||||
const bytes = Deno.readFileSync(join(from, file));
|
||||
const to = join(mods_dir(data), file);
|
||||
if (!same_bytes(bytes, read_if_there(to))) Deno.writeFileSync(to, bytes);
|
||||
}
|
||||
}
|
||||
|
||||
// the mods in mods/ that can be read, by name. ones that can't are left out and logged
|
||||
export function list_mods(data: string): ModEntry[] {
|
||||
const mods = new Map<string, ModEntry>();
|
||||
for (const file of mod_files(mods_dir(data))) {
|
||||
try {
|
||||
const manifest = read_manifest(Deno.readFileSync(join(mods_dir(data), file)), file);
|
||||
const other = mods.get(manifest.id);
|
||||
if (other) {
|
||||
console.warn(`${file} is left out, ${other.file} is the mod "${manifest.id}" too`);
|
||||
continue;
|
||||
}
|
||||
mods.set(manifest.id, {
|
||||
id: manifest.id,
|
||||
name: manifest.name,
|
||||
version: manifest.version,
|
||||
description: manifest.description,
|
||||
dependencies: (manifest.dependencies ?? []).map(({ id }) => id),
|
||||
file,
|
||||
});
|
||||
} catch (e) {
|
||||
console.warn((e as Error).message);
|
||||
}
|
||||
}
|
||||
return [...mods.values()].sort((a, b) => a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
// the folders in saves/ with a world.json, by name
|
||||
export function list_worlds(data: string): WorldEntry[] {
|
||||
const worlds: WorldEntry[] = [];
|
||||
for (const entry of read_dir(saves_dir(data))) {
|
||||
if (!entry.isDirectory) continue;
|
||||
try {
|
||||
worlds.push({ name: entry.name, mods: read_world_mods(data, entry.name) });
|
||||
} catch (e) {
|
||||
if (!(e instanceof Deno.errors.NotFound)) console.warn(`${entry.name}: ${(e as Error).message}`);
|
||||
}
|
||||
}
|
||||
return worlds.sort((a, b) => a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
// a new world, which the game server makes once it's played. errors are told to the player
|
||||
export function create_world(data: string, name: unknown, mods: unknown) {
|
||||
if (typeof name !== "string" || !WORLD_NAME.test(name.trim())) {
|
||||
throw new Error("A world's name has to be 1 to 32 letters, numbers, spaces, - and _");
|
||||
}
|
||||
const trimmed = name.trim();
|
||||
// any folder, and case insensitive like windows' and macos' folders
|
||||
const taken = [...read_dir(saves_dir(data))].some((entry) => entry.name.toLowerCase() === trimmed.toLowerCase());
|
||||
if (taken) throw new Error(`There's already a world called ${trimmed}`);
|
||||
const json = world_json(data, mods);
|
||||
const dir = join(saves_dir(data), trimmed);
|
||||
Deno.mkdirSync(dir, { recursive: true });
|
||||
Deno.writeTextFileSync(join(dir, WORLD_FILE), json);
|
||||
}
|
||||
|
||||
export function set_world_mods(data: string, name: unknown, mods: unknown) {
|
||||
Deno.writeTextFileSync(join(world_dir(data, name), WORLD_FILE), world_json(data, mods));
|
||||
}
|
||||
|
||||
// a world.json, for mods the page sent
|
||||
function world_json(data: string, mods: unknown) {
|
||||
const known = new Set(list_mods(data).map(({ id }) => id));
|
||||
if (!Array.isArray(mods) || mods.some((id) => !known.has(id))) {
|
||||
throw new Error("Those aren't all mods in the mods folder");
|
||||
}
|
||||
const json: z.infer<typeof world_file> = { format_version: FORMAT_VERSION, mods: [...new Set(mods)] };
|
||||
return JSON.stringify(json, null, "\t") + "\n";
|
||||
}
|
||||
|
||||
// what the game server needs to play a world: its folder, and the files in mods/ of its mods
|
||||
export function world_to_play(data: string, name: unknown): { dir: string; mod_files: string[] } {
|
||||
const dir = world_dir(data, name);
|
||||
const mods = new Map(list_mods(data).map((mod) => [mod.id, mod]));
|
||||
const mod_files = read_world_mods(data, name as string).map((id) => {
|
||||
const mod = mods.get(id);
|
||||
if (!mod) throw new Error(`This world plays with the mod "${id}", which isn't in the mods folder`);
|
||||
return mod.file;
|
||||
});
|
||||
return { dir, mod_files };
|
||||
}
|
||||
|
||||
// the folder of a world there is, from a name the page sent
|
||||
function world_dir(data: string, name: unknown) {
|
||||
if (typeof name !== "string" || !list_worlds(data).some((world) => world.name === name)) {
|
||||
throw new Error(`There's no world called ${name}`);
|
||||
}
|
||||
return join(saves_dir(data), name);
|
||||
}
|
||||
|
||||
function read_world_mods(data: string, name: string): string[] {
|
||||
const json = JSON.parse(Deno.readTextFileSync(join(saves_dir(data), name, WORLD_FILE)));
|
||||
const parsed = world_file.safeParse(json);
|
||||
if (!parsed.success) throw new Error(`${WORLD_FILE} must be { "format_version": 1, "mods": [...] }`);
|
||||
return parsed.data.mods as string[];
|
||||
}
|
||||
|
||||
// nothing when it isn't there yet
|
||||
function read_dir(dir: string): Deno.DirEntry[] {
|
||||
try {
|
||||
return [...Deno.readDirSync(dir)];
|
||||
} catch (e) {
|
||||
if (e instanceof Deno.errors.NotFound) return [];
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
function read_if_there(file: string): Uint8Array | undefined {
|
||||
try {
|
||||
return Deno.readFileSync(file);
|
||||
} catch (e) {
|
||||
if (e instanceof Deno.errors.NotFound) return undefined;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
function same_bytes(a: Uint8Array, b: Uint8Array | undefined) {
|
||||
return b !== undefined && a.length === b.length && a.every((byte, i) => byte === b[i]);
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// the desktop app's singleplayer: what the main menu asks it (see client/gui/main_menu.ts), and the game server of
|
||||
// the world being played, with the mods the world picked from the data folder. see saves.ts
|
||||
import { join } from "@std/path";
|
||||
import { type Host, start_host } from "../server/host.ts";
|
||||
import { create_world, list_mods, list_worlds, mods_dir, set_world_mods, world_to_play } from "./saves.ts";
|
||||
|
||||
export interface SingleplayerOptions {
|
||||
// what deno task build made: the client and the engine's assets
|
||||
build_dir: string;
|
||||
// the app's data folder, see saves.ts
|
||||
data_dir: string;
|
||||
// the world being played can't go on
|
||||
on_fatal(message: string): void;
|
||||
// how many workers generate chunks, see HostOptions
|
||||
worldgen_workers?: number;
|
||||
}
|
||||
|
||||
export function singleplayer_server(options: SingleplayerOptions) {
|
||||
const data = options.data_dir;
|
||||
// playing another world, or the same one again after changing its mods, stops it first
|
||||
let host: Promise<Host> | undefined;
|
||||
|
||||
async function play(world: unknown) {
|
||||
await stop();
|
||||
const { dir, mod_files } = world_to_play(data, world);
|
||||
host = start_host({
|
||||
build_dir: options.build_dir,
|
||||
server_mods_dir: mods_dir(data),
|
||||
mod_files,
|
||||
config_dir: join(data, "config"),
|
||||
world_dir: dir,
|
||||
worldgen_workers: options.worldgen_workers,
|
||||
on_fatal: options.on_fatal,
|
||||
});
|
||||
try {
|
||||
await host;
|
||||
} catch (e) {
|
||||
host = undefined;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
// saves the world being played
|
||||
async function stop() {
|
||||
const playing = host;
|
||||
host = undefined;
|
||||
try {
|
||||
await (await playing)?.shutdown();
|
||||
} catch (e) {
|
||||
console.error((e as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
// errors are told to the player
|
||||
async function menu_request(req: Request, url: URL): Promise<Response> {
|
||||
if (url.pathname === "/desktop/singleplayer") {
|
||||
return Response.json({ worlds: list_worlds(data), mods: list_mods(data) });
|
||||
}
|
||||
let body: Record<string, unknown>;
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
return new Response("Expected json", { status: 400 });
|
||||
}
|
||||
try {
|
||||
switch (url.pathname) {
|
||||
case "/desktop/create_world":
|
||||
create_world(data, body.world, body.mods);
|
||||
break;
|
||||
case "/desktop/world_mods":
|
||||
set_world_mods(data, body.world, body.mods);
|
||||
break;
|
||||
case "/desktop/play":
|
||||
await play(body.world);
|
||||
break;
|
||||
default:
|
||||
return new Response("Not found", { status: 404 });
|
||||
}
|
||||
} catch (e) {
|
||||
console.error((e as Error).message);
|
||||
return new Response((e as Error).message, { status: 400 });
|
||||
}
|
||||
return new Response(null, { status: 204 });
|
||||
}
|
||||
|
||||
return {
|
||||
// undefined for requests that aren't singleplayer's
|
||||
async handle(req: Request, url: URL): Promise<Response | undefined> {
|
||||
if (url.pathname.startsWith("/desktop/") && req.method === "POST") {
|
||||
return await menu_request(req, url);
|
||||
}
|
||||
// the world's socket and its .cubi downloads
|
||||
if (url.pathname === "/ws" || url.pathname.startsWith("/mods/")) {
|
||||
const playing = await host?.catch(() => undefined);
|
||||
return playing ? playing.handle(req) : new Response("No world is being played", { status: 503 });
|
||||
}
|
||||
return undefined;
|
||||
},
|
||||
stop,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user