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) {
+104 -16
View File
@@ -2,11 +2,13 @@
// see "Server scripts" in MODS.md. parts not built yet throw when used, saying so
import { BlockRegistry, EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts";
import { Container as EngineContainer, ItemStack as EngineItemStack } from "$/common/inventory.ts";
import { get_state_value, set_state_value } from "$/common/utils.ts";
import { display_name, get_state_value, set_state_value } from "$/common/utils.ts";
import type {
BlockComponent,
BlockRef,
Command,
CommandRegistry,
CommandSource,
Container,
ContainerScreenOptions,
EventSignal,
@@ -19,6 +21,21 @@ import type {
ServerContext,
} from "$/common/mod_api/server.ts";
import { ModLoadError } from "$/common/mod_loader.ts";
import {
argument,
block as block_argument,
boolean,
choice,
CommandDispatcher,
CommandError,
CommandNode,
greedy_string,
integer,
item,
literal,
number,
word,
} from "$/common/commands.ts";
import { AIR_ID } from "$/common/protocol.ts";
import type { GameServer } from "./game_server.ts";
import type { OpenScreen, ServerPlayer } from "./player.ts";
@@ -83,7 +100,10 @@ interface Timer {
export class ModRuntime {
block_components = new Map<string, { mod: string; component: BlockComponent }>();
item_components = new Map<string, { mod: string; component: ItemComponent }>();
commands = new Map<string, { mod: string; name: string; command: Command }>();
// every command, the engine's and mods', see common/commands.ts
commands = new CommandDispatcher<ServerCommandSource>();
// who registered each command name: "engine" or a mod's id
command_owners = new Map<string, string>();
before: Before = {
block_break: new Signal(),
@@ -192,6 +212,32 @@ export class ModRuntime {
}
}
// adds a command, and for mods the same command as /mod:name so it can always be told apart
register_command(owner: string, node: CommandNode<ServerCommandSource>) {
if (!/^[a-z0-9_]+$/.test(node.name)) {
throw new Error(`command name "${node.name}" must be a-z, 0-9 and _`);
}
const existing = this.command_owners.get(node.name);
if (existing) {
throw new Error(
existing === "engine"
? `/${node.name} belongs to the engine`
: `/${node.name} is also registered by ${existing}`,
);
}
this.commands.register(node);
this.command_owners.set(node.name, owner);
if (owner !== "engine") {
const alias = new CommandNode<ServerCommandSource>(`${owner}:${node.name}`);
alias.children.push(...node.children);
alias.command = node.command;
alias.requirement = node.requirement;
alias.description = node.description;
this.commands.root.then(alias);
this.command_owners.set(alias.name, owner);
}
}
// components on a block, with their params from its json
components_of(block_id: string): { mod: string; id: string; component: BlockComponent; params: unknown }[] {
const block = EverythingRegistry.get<{ components?: Record<string, unknown> }>("blocks", block_id);
@@ -309,23 +355,39 @@ export class ModRuntime {
},
},
commands: {
register: (name, command) => {
register: (name_or_node: string | CommandNode<CommandSource>, command?: Command) => {
setup_only("commands");
if (!/^[a-z0-9_]+$/.test(name)) {
throw new ModLoadError(mod, `command name "${name}" must be a-z, 0-9 and _`);
const node = typeof name_or_node === "string"
? simple_command(name_or_node, command!)
: name_or_node as unknown as CommandNode<ServerCommandSource>;
try {
this.register_command(mod, node as CommandNode<ServerCommandSource>);
} catch (e) {
throw new ModLoadError(mod, (e as Error).message);
}
if (["give", "tps", "time"].includes(name)) {
throw new ModLoadError(mod, `/${name} belongs to the engine`);
}
const existing = this.commands.get(name);
if (existing) {
throw new ModLoadError(mod, `/${name} is also registered by ${existing.mod}`);
}
const entry = { mod, name, command };
this.commands.set(name, entry);
this.commands.set(`${mod}:${name}`, entry);
},
},
literal: (name) => literal<CommandSource>(name),
argument: (name, type) => argument(name, type),
types: {
integer,
number,
boolean,
word,
greedy_string,
choice,
item: () => item_argument(),
block: () => block_argument(display_name_of_block),
player: () => ({
parse: (text: string) => {
const found = game().players().find((p) => p.name === text);
if (!found) throw new CommandError(`${text} isn't online`);
return this.player(found);
},
suggest: (partial: string) =>
game().players().filter((p) => p.name.startsWith(partial)).map((p) => ({ text: p.name })),
}),
},
} as CommandRegistry,
events: {
before: map_signals(this.before, mod),
after: map_signals(this.after, mod),
@@ -587,6 +649,32 @@ function not_yet_object<T>(mod: string, name: string, where: string): T {
const MAX_CONTAINER_SIZE = 256;
// who ran a command, as the engine sees it: what mods see plus the engine's player
export interface ServerCommandSource extends CommandSource {
server_player: ServerPlayer;
}
// register(name, { run }): the words after the name go to run, split on spaces
function simple_command(name: string, command: Command): CommandNode<ServerCommandSource> {
const run = (args: string[], source: ServerCommandSource) => command.run(args, source.player);
return literal<ServerCommandSource>(name)
.describe(command.description)
.executes((context) => run([], context.source))
.then(
argument<string, ServerCommandSource>("args", greedy_string()).executes((context) =>
run(context.get<string>("args").split(/\s+/).filter((word) => word.length > 0), context.source)
),
);
}
export function item_argument() {
return item((id) => display_name(id));
}
function display_name_of_block(id: string) {
return display_name(id);
}
// the engine's item stacks as mods see them: { id, count, data }
export function item_api(stack: EngineItemStack): ItemStack {
return {