Improve commands

This commit is contained in:
2026-09-27 00:38:55 -03:00
parent 535bd36d91
commit 8c7ca92891
13 changed files with 1095 additions and 109 deletions
+151 -78
View File
@@ -1,5 +1,4 @@
import {
AIR,
CHUNK_HEIGHT,
CHUNK_SIZE,
FACE_OFFSETS,
@@ -27,9 +26,19 @@ import {
import type { ModListing, RecipeBook } from "$/common/mod_loader.ts";
import type { WorldgenSetup } from "$/common/generation.ts";
import { CYCLE_TICKS, format_clock, time_of_day, TIMES_OF_DAY } from "$/common/time.ts";
import { can_place, can_stand_on, placement_target } from "$/common/utils.ts";
import { can_place, can_stand_on, display_name, placement_target } from "$/common/utils.ts";
import { EXHAUSTION, MAX_HEALTH } from "./vitals.ts";
import { ModRuntime, run_guarded } from "./mod_runtime.ts";
import { item_argument, ModRuntime, run_guarded, type ServerCommandSource } from "./mod_runtime.ts";
import {
argument,
choice,
type CommandContext,
CommandError,
type CommandNode,
integer,
literal,
word,
} from "$/common/commands.ts";
import type { GameLoop } from "./game_loop.ts";
import { consume_recipe_items, update_crafting_result } from "./crafting.ts";
import { OpenScreen, SavedPlayer, ServerPlayer } from "./player.ts";
@@ -53,6 +62,8 @@ const MERGE_DISTANCE = 0.5;
// tiles further than this many chunks from every player don't tick
const SIMULATION_DISTANCE = 6;
const MAX_GIVE = 64 * 36;
// the most suggestions sent for one request
const MAX_SUGGESTIONS = 100;
// falls up to this many blocks don't hurt, like minecraft
const SAFE_FALL = 3;
// faster than walking (4 blocks a second) and slower than sprinting (7)
@@ -160,6 +171,7 @@ export class GameServer {
}
this.#saved_players = saved?.players ?? {};
this.world.dirty = saved?.version !== 3;
this.#register_commands();
this.world.on_block_change = (x, y, z, id, state) =>
this.#broadcast(state ? { type: "set_block", x, y, z, id, state } : { type: "set_block", x, y, z, id });
@@ -661,6 +673,9 @@ export class GameServer {
case "chat":
this.#chat(player, message.text);
break;
case "suggest":
this.#suggest(player, message.id, message.text);
break;
}
}
@@ -890,85 +905,143 @@ export class GameServer {
this.mods.after.chat_send.emit({ player: before.player, message });
}
#command(player: ServerPlayer, text: string) {
const [command, ...args] = text.slice(1).split(/\s+/);
if (command === "give") {
// TODO: only let operators do this
let [item_id, count] = args;
if (!item_id) {
this.#send(player, { type: "chat", text: "Usage: /give <item> [count]" });
return;
}
// a name without a namespace works when only one mod has an item called that
if (!item_id.includes(":")) {
const matches = EverythingRegistry.entries("items").map(([id]) => id).filter((id) =>
id.endsWith(`:${item_id}`)
);
if (matches.length > 1) {
this.#send(player, { type: "chat", text: `Which one? ${matches.join(", ")}` });
return;
}
item_id = matches[0] ?? item_id;
}
const amount = count === undefined ? 1 : Number(count);
if (!EverythingRegistry.get("items", item_id)) {
this.#send(player, { type: "chat", text: `Unknown item ${item_id}` });
return;
}
if (!Number.isInteger(amount) || amount < 1 || amount > MAX_GIVE) {
this.#send(player, { type: "chat", text: `Count must be between 1 and ${MAX_GIVE}` });
return;
}
this.give(player, item_id, amount);
return;
}
if (command === "time") {
this.#time_command(player, args);
return;
}
if (command === "tps") {
if (!this.loop) {
this.#send(player, { type: "chat", text: "The game loop isn't running" });
return;
}
const { tps, mspt, skipped } = this.loop.stats;
this.#send(player, {
type: "chat",
text: `${tps} ticks per second (aiming for ${TICKS_PER_SECOND}), ${mspt.toFixed(1)} ms per tick, ` +
`${skipped} skipped since starting`,
});
return;
}
const mod_command = this.mods.commands.get(command);
if (mod_command) {
run_guarded(mod_command.mod, `/${command}`, () => mod_command.command.run(args, this.mods.player(player)));
return;
}
this.#send(player, { type: "chat", text: `Unknown command /${command}` });
// what typed commands run as
#command_source(player: ServerPlayer): ServerCommandSource {
const api = this.mods.player(player);
return { player: api, server_player: player, send_message: (text) => this.send_chat(player, text) };
}
// /time shows the time, /time set <ticks or day, noon, sunset, night, midnight> changes it, /time add <ticks>
#time_command(player: ServerPlayer, [action, value]: string[]) {
const usage = "Usage: /time [set <ticks|day|noon|sunset|night|midnight> | add <ticks>]";
if (action === undefined) {
this.#send(player, { type: "chat", text: `${format_clock(this.world.time)} (tick ${this.world.time})` });
#command(player: ServerPlayer, text: string) {
const input = text.slice(1);
try {
this.mods.commands.execute(input, this.#command_source(player));
} catch (e) {
if (e instanceof CommandError) {
this.send_chat(player, e.message);
return;
}
// a bug in whoever made the command, not something the player did
const name = input.split(" ")[0];
console.error(`[${this.mods.command_owners.get(name) ?? "?"}] /${name} threw:`, e);
this.send_chat(player, `Something went wrong running /${name}`);
}
}
// what could come next while they type a command, see common/commands.ts
#suggest(player: ServerPlayer, id: unknown, text: unknown) {
if (!is_int(id) || typeof text !== "string" || !text.startsWith("/") || text.length > MAX_CHAT_LENGTH) {
return;
}
const ticks = Number(value);
if (action === "set" && value !== undefined && value in TIMES_OF_DAY) {
// the next time it's that time of day, so days keep counting up
const now = this.world.time;
const target = now - time_of_day(now) + TIMES_OF_DAY[value];
this.set_time(target >= now ? target : target + CYCLE_TICKS);
} else if (action === "set" && Number.isInteger(ticks) && ticks >= 0) {
this.set_time(ticks);
} else if (action === "add" && Number.isInteger(ticks) && this.world.time + ticks >= 0) {
this.set_time(this.world.time + ticks);
} else {
this.#send(player, { type: "chat", text: usage });
return;
}
this.#broadcast({ type: "chat", text: `${player.name} set the time to ${format_clock(this.world.time)}` });
const { start, suggestions } = this.mods.commands.suggest(text.slice(1), this.#command_source(player));
this.#send(player, {
type: "suggestions",
id,
start: start + 1,
suggestions: suggestions.slice(0, MAX_SUGGESTIONS),
});
}
// the engine's own commands, registered like mods' so they're in /help and suggested the same way
#register_commands() {
const register = (node: CommandNode<ServerCommandSource>) => this.mods.register_command("engine", node);
// TODO: only let operators do this
const give = (context: CommandContext<ServerCommandSource>, count: number) => {
const id = context.get<string>("item");
this.give(context.source.server_player, id, count);
context.source.send_message(`Gave ${count} ${display_name(id)}`);
};
register(
literal<ServerCommandSource>("give").describe("Gives you an item").then(
argument<string, ServerCommandSource>("item", item_argument())
.executes((context) => give(context, 1))
.then(
argument<number, ServerCommandSource>("count", integer(1, MAX_GIVE))
.executes((context) => give(context, context.get<number>("count"))),
),
),
);
const set_time = (context: CommandContext<ServerCommandSource>, time: number) => {
this.set_time(time);
this.#broadcast({
type: "chat",
text: `${context.source.server_player.name} set the time to ${format_clock(this.world.time)}`,
});
};
register(
literal<ServerCommandSource>("time")
.describe("Shows or changes the time of day")
.executes((context) =>
context.source.send_message(`${format_clock(this.world.time)} (tick ${this.world.time})`)
)
.then(
literal<ServerCommandSource>("set")
.then(
argument<string, ServerCommandSource>("time_of_day", choice(Object.keys(TIMES_OF_DAY)))
.executes((context) => {
// the next time it's that time of day, so days keep counting up
const now = this.world.time;
const target = now - time_of_day(now) +
TIMES_OF_DAY[context.get<string>("time_of_day")];
set_time(context, target >= now ? target : target + CYCLE_TICKS);
}),
)
.then(
argument<number, ServerCommandSource>("ticks", integer(0))
.executes((context) => set_time(context, context.get<number>("ticks"))),
),
)
.then(
literal<ServerCommandSource>("add").then(
argument<number, ServerCommandSource>("ticks", integer())
.executes((context) =>
set_time(context, Math.max(0, this.world.time + context.get<number>("ticks")))
),
),
),
);
register(
literal<ServerCommandSource>("tps").describe("Shows how the game loop keeps up").executes((context) => {
if (!this.loop) {
context.source.send_message("The game loop isn't running");
return;
}
const { tps, mspt, skipped } = this.loop.stats;
context.source.send_message(
`${tps} ticks per second (aiming for ${TICKS_PER_SECOND}), ${mspt.toFixed(1)} ms per tick, ` +
`${skipped} skipped since starting`,
);
}),
);
// every command's usage, or one's. aliases like /mod:name aren't listed twice
const commands = this.mods.commands;
const help = (context: CommandContext<ServerCommandSource>, only?: string) => {
const nodes = commands.root.children.filter((node) =>
!node.name.includes(":") && (!only || node.name === only)
);
if (nodes.length === 0) throw new CommandError(`There's no command /${only}`);
for (const node of nodes) {
const usage = `/${commands.usage(node, context.source)}`;
context.source.send_message(node.description ? `${usage} - ${node.description}` : usage);
}
};
register(
literal<ServerCommandSource>("help")
.describe("Lists commands")
.executes((context) => help(context))
.then(
argument<string, ServerCommandSource>("command", word())
.suggests((partial) =>
commands.root.children
.filter((node) => !node.name.includes(":") && node.name.startsWith(partial))
.map((node) => ({ text: node.name }))
)
.executes((context) => help(context, context.get<string>("command"))),
),
);
}
#close_screen(player: ServerPlayer) {