Files

304 lines
10 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// the desktop app's title screen, a main menu like luanti's. singleplayer lists the worlds in the app's data folder,
// to play one, make one or pick its mods. the app does the files and runs the world's server, see desktop/main.ts
import type { ModEntry, WorldEntry } from "@/desktop/saves.ts";
import { InputManager } from "@/client/input_manager.ts";
import { canvas, draw_rect, draw_text, measure_text } from "@/client/renderer/mod.ts";
import { server_address } from "@/client/handshake.ts";
import { GuiScreen } from "./gui_screen.ts";
import { platform } from "../platform.ts";
import type { JoinServer } from "./title_screen.ts";
import { Button, EditBox, ListBox, TEXT_HEIGHT, TEXT_SCALE, TextInput } from "./widgets.ts";
const WIDTH = 440;
const ROW_HEIGHT = 48;
const GAP = 20;
const LIST_WIDTH = 640;
const HALF_WIDTH = (LIST_WIDTH - GAP) / 2;
const TOP = 100;
// the name players have in singleplayer worlds, which what they carry is saved under
const SINGLEPLAYER_NAME = "singleplayer";
type Show = (screen: GuiScreen) => void;
export class MainMenuScreen extends GuiScreen {
#buttons: Button[];
constructor(show: Show, join: JoinServer) {
super();
const back = () => show(new MainMenuScreen(show, join));
// there's nothing behind these yet
const multiplayer = new Button("Multiplayer", WIDTH, ROW_HEIGHT, () => {});
const mods = new Button("Mods", WIDTH, ROW_HEIGHT, () => {});
multiplayer.active = mods.active = false;
this.#buttons = [
new Button("Singleplayer", WIDTH, ROW_HEIGHT, () => show(new WorldListScreen(show, join))),
multiplayer,
mods,
new Button("Credits", WIDTH, ROW_HEIGHT, () => show(platform.credits_screen(back))),
];
}
on_tick(_delta: number): void {
let y = (canvas.height - this.#buttons.length * (ROW_HEIGHT + GAP)) / 2 + 40;
for (const button of this.#buttons) {
button.x = (canvas.width - WIDTH) / 2;
button.y = y;
y += ROW_HEIGHT + GAP;
button.handle_input();
}
}
on_render(): void {
draw_centered("Cubi", this.#buttons[0].y - 140, 8);
for (const button of this.#buttons) button.render();
}
on_close(): void {}
}
// the worlds in the app's saves folder
class WorldListScreen extends GuiScreen {
#show: Show;
#join: JoinServer;
#worlds: WorldEntry[] = [];
#mods: ModEntry[] = [];
#list = new ListBox(LIST_WIDTH, 0, (row, double) => {
this.#list.selected = row;
if (double) this.#play();
});
#play_button = new Button("Play", HALF_WIDTH, ROW_HEIGHT, () => this.#play());
#new_button = new Button("New world", HALF_WIDTH, ROW_HEIGHT, () => this.#edit());
#mods_button = new Button("Mods", HALF_WIDTH, ROW_HEIGHT, () => this.#edit(this.#selected));
#back_button = new Button("Back", HALF_WIDTH, ROW_HEIGHT, () => this.#back());
#status = new Status();
#busy = true;
// select is the world selected at first, like one that was just made
constructor(show: Show, join: JoinServer, select?: string) {
super();
this.#show = show;
this.#join = join;
this.#status.set("Loading worlds...");
desktop("singleplayer").then((response) => response.json()).then(
({ worlds, mods }: { worlds: WorldEntry[]; mods: ModEntry[] }) => {
this.#worlds = worlds;
this.#mods = mods;
this.#list.rows = worlds.map((world) => ({ text: world.name }));
this.#list.selected = Math.max(0, worlds.findIndex((world) => world.name === select));
this.#status.set(worlds.length === 0 ? "There are no worlds yet, make one with New world" : "");
this.#busy = false;
},
(e) => this.#status.fail(e),
);
}
get #selected(): WorldEntry | undefined {
return this.#worlds[this.#list.selected];
}
on_tick(_delta: number): void {
const buttons = [this.#play_button, this.#new_button, this.#mods_button, this.#back_button];
const x = (canvas.width - LIST_WIDTH) / 2;
this.#list.x = x;
this.#list.y = TOP;
this.#list.height = canvas.height - TOP - 2 * (ROW_HEIGHT + GAP) - 120;
for (const [i, button] of buttons.entries()) {
button.x = x + (i % 2) * (HALF_WIDTH + GAP);
button.y = TOP + this.#list.height + GAP + Math.floor(i / 2) * (ROW_HEIGHT + GAP);
}
this.#play_button.active = this.#mods_button.active = !this.#busy && this.#selected !== undefined;
this.#new_button.active = !this.#busy;
if (InputManager.is_key_pressed("Escape")) return this.#back();
if (InputManager.is_key_pressed("Enter")) this.#play();
if (!this.#busy) this.#list.handle_input();
for (const button of buttons) button.handle_input();
}
on_render(): void {
draw_centered("Singleplayer", TOP / 2, 4);
this.#list.render();
for (const button of [this.#play_button, this.#new_button, this.#mods_button, this.#back_button]) {
button.render();
}
this.#status.render(this.#back_button.y + ROW_HEIGHT + GAP);
}
on_close(): void {}
#back() {
if (!this.#busy || this.#status.error) this.#show(new MainMenuScreen(this.#show, this.#join));
}
// a new world, or the mods of one there is
#edit(world?: WorldEntry) {
this.#show(new WorldModsScreen(this.#show, this.#join, this.#mods, world));
}
async #play() {
const world = this.#selected;
if (!world || this.#busy) return;
this.#busy = true;
this.#status.set(`Starting ${world.name}...`);
try {
await desktop("play", { world: world.name });
await this.#join(server_address(platform.page.host), SINGLEPLAYER_NAME, (text) => this.#status.set(text));
} catch (e) {
this.#status.fail(e);
this.#busy = false;
}
}
}
// a new world's name and mods, or the mods of one there is. turning a mod on turns on the mods it needs, and turning
// one off turns off the mods that need it
class WorldModsScreen extends GuiScreen {
#show: Show;
#join: JoinServer;
#mods: ModEntry[];
#world: WorldEntry | undefined;
#enabled: Set<string>;
#name = new EditBox(LIST_WIDTH, ROW_HEIGHT, new TextInput("", 32), "World name");
#list = new ListBox(LIST_WIDTH, 0, (row) => this.#toggle(this.#mods[row].id));
#save_button: Button;
#cancel_button: Button;
#status = new Status();
#busy = false;
constructor(show: Show, join: JoinServer, mods: ModEntry[], world?: WorldEntry) {
super();
this.#show = show;
this.#join = join;
this.#mods = mods;
this.#world = world;
// a new world starts with every mod. a world's mods that aren't in the folder anymore are dropped when it's saved
this.#enabled = new Set(mods.map(({ id }) => id).filter((id) => !world || world.mods.includes(id)));
this.#name.focused = !world;
this.#save_button = new Button(world ? "Save" : "Create", HALF_WIDTH, ROW_HEIGHT, () => this.#save());
this.#cancel_button = new Button("Cancel", HALF_WIDTH, ROW_HEIGHT, () => this.#back(world?.name));
this.#update_rows();
if (mods.length === 0) this.#status.set("There are no mods in the mods folder");
}
on_tick(_delta: number): void {
const x = (canvas.width - LIST_WIDTH) / 2;
let y = TOP;
if (!this.#world) {
this.#name.x = x;
this.#name.y = y;
y += ROW_HEIGHT + GAP;
}
this.#list.x = x;
this.#list.y = y;
this.#list.height = canvas.height - y - ROW_HEIGHT - GAP - 120;
this.#save_button.x = x;
this.#cancel_button.x = x + HALF_WIDTH + GAP;
this.#save_button.y = this.#cancel_button.y = y + this.#list.height + GAP;
this.#save_button.active = this.#name.active = !this.#busy;
if (InputManager.is_key_pressed("Escape")) return this.#back(this.#world?.name);
if (InputManager.is_key_pressed("Enter")) this.#save();
this.#name.handle_input();
this.#list.handle_input();
this.#save_button.handle_input();
this.#cancel_button.handle_input();
}
on_render(): void {
draw_centered(this.#world ? `${this.#world.name}'s mods` : "New world", TOP / 2, 4);
if (!this.#world) this.#name.render();
this.#list.render();
this.#save_button.render();
this.#cancel_button.render();
this.#status.render(this.#save_button.y + ROW_HEIGHT + GAP);
}
on_close(): void {}
#toggle(id: string) {
const by_id = new Map(this.#mods.map((mod) => [mod.id, mod]));
const on = (id: string) => {
this.#enabled.add(id);
for (const dependency of by_id.get(id)?.dependencies ?? []) {
if (by_id.has(dependency) && !this.#enabled.has(dependency)) on(dependency);
}
};
const off = (id: string) => {
this.#enabled.delete(id);
for (const mod of this.#mods) {
if (mod.dependencies.includes(id) && this.#enabled.has(mod.id)) off(mod.id);
}
};
(this.#enabled.has(id) ? off : on)(id);
this.#update_rows();
}
#update_rows() {
this.#list.rows = this.#mods.map((mod) => ({
text: `${mod.name} ${mod.version}`,
checked: this.#enabled.has(mod.id),
}));
}
async #save() {
if (this.#busy) return;
this.#busy = true;
const world = this.#world?.name ?? this.#name.value.trim();
try {
await desktop(this.#world ? "world_mods" : "create_world", { world, mods: [...this.#enabled] });
this.#back(world);
} catch (e) {
this.#status.fail(e);
this.#busy = false;
}
}
#back(select?: string) {
this.#show(new WorldListScreen(this.#show, this.#join, select));
}
}
// what's happening, or what went wrong, under a screen's buttons. a line each for messages that have several, like
// a world's mods' problems
class Status {
text = "";
error = false;
set(text: string) {
this.text = text;
this.error = false;
}
fail(e: unknown) {
this.text = e instanceof Error ? e.message : String(e);
this.error = true;
}
render(y: number) {
for (const line of this.text.split("\n").filter((line) => line !== "")) {
const width = measure_text(line, TEXT_SCALE);
const x = (canvas.width - width) / 2;
draw_rect(x - 8, y - 4, width + 16, TEXT_HEIGHT * TEXT_SCALE + 8, [0, 0, 0, 0.5]);
draw_text(line, x, y, TEXT_SCALE, this.error ? [1, 0.45, 0.45, 1] : [1, 1, 1, 1]);
y += TEXT_HEIGHT * TEXT_SCALE + 8;
}
}
}
function draw_centered(text: string, y: number, scale: number) {
draw_text(text, (canvas.width - measure_text(text, scale)) / 2, y - (TEXT_HEIGHT * scale) / 2, scale);
}
// asks the desktop app, see desktop/main.ts. throws with what the app said went wrong
async function desktop(path: string, body: unknown = {}): Promise<Response> {
const response = await fetch(new URL(`/desktop/${path}`, platform.page), {
method: "POST",
body: JSON.stringify(body),
});
if (!response.ok) throw new Error(await response.text());
return response;
}