《游戏编辑器技术原理与架构》4.1 命令表与路由

菜单、工具栏、快捷键、脚本宏——编辑器里每一种操作入口,最终都必须落到同一个 execute。本节实现 CommandTable:命令注册、按 id 路由执行、enabled 上下文校验、快捷键全局唯一;6 条用例本机真跑,钉住「未知命令给明确原因、禁用命令被拒绝」两条失败路径。

4.1 命令表与路由

编辑器里同一个操作有无数入口:菜单点一下、工具栏按一下、快捷键按一下、脚本里调一句。如果每个入口都直接调「那个方法」,这些入口就会各自长成不同的代码路径,快捷键处理器的逻辑、菜单的灰化逻辑、脚本调用的逻辑各写一份。命令系统解决的就是这个:把操作收拢成一条命令,所有入口只做一件事——execute(commandId, context)。

本节的 CommandTable 是最小但完整的命令表:

  • register(cmd):注册一条命令(id、label、run、可选 enabled、可选 shortcut)。id 全局唯一。
  • execute(id, ctx):按 id 路由到实现,先校验可用性,再执行。
  • canExecute(id, ctx):查询「当前上下文里这条命令能不能用」——这是菜单灰化、工具栏禁用、快捷键响应是否打铃的共同基础。
  • 失败给原因不给崩溃:未知命令返回 unknown command: id,被禁用的命令返回 command disabled in this context: id。失败的两种形态都被写进返回值,而不是靠 throw 中断。

本章与站内既有内容的分工

helio 卷三第 8 章已经有一个最小命令栈(do/undo);本节做的是命令表(路由层),两者分工不同。

主题站内既有内容本节做什么
命令栈 do/undohelio 9.2 事务、合并与撤销栈命令栈记录已执行的命令以支持撤销;命令表路由待执行的命令。命令表与栈互补
命令系统深化第 10 章 撤销系统深化本节定义命令形态,第 10 章做事务、异步与跨会话撤销
菜单与快捷键4.2 菜单、工具栏与快捷键注册菜单层消费命令表:菜单项就是 commandId 加显示信息

一个会合点,三个入口

命令表的本质是把「做什么」和「怎么触发」分开。命令只管 run(ctx);触发方式(菜单、快捷键、工具栏、脚本宏)在别处,但它们都指向同一条命令 id。这样改「旋转 90°」的实现,只改一条命令;给它加快捷键、加菜单、加工具栏按钮,各自都是一行注册。

enabled(ctx) 是上下文敏感的钩子——「删除」在没选中任何东西时不该可用。命令表把它做成每个命令的可选谓词,canExecute 是查询、execute 是强制校验。两条路径都走同一个谓词,菜单灰化和实际执行永远不会意见不一致——这正是工业级编辑器最需要的一致性保证。

对标命令注册与执行条件

编辑器公开扩展入口
Unity 6MenuItem 将静态方法注册为菜单命令,可为同一路径注册验证方法。快捷键也可通过独立的 ShortcutAttribute 声明。 MenuItem · ShortcutAttribute
Unreal Engine 5FUICommandList::MapAction 将命令信息与执行、可执行判断等委托绑定到命令列表。 MapAction
Godot 4.5EditorPlugin.add_tool_menu_item 接收菜单名称和 Callable。运行时项目动作的 InputMap 不宜作为编辑器菜单注册接口来对照。 EditorPlugin
Cocos Creator 3.8扩展在 package.json 的 contributions 下分别声明菜单、快捷键和消息。 扩展贡献点

helio 将可用性谓词和默认快捷键放在命令定义里。示例的冲突检查比较同一个注册表内的快捷键字符串。

可运行产物:6 条用例钉住路由

下面 src/command-table.ts 层级 L1,完整可编译,命令 node --test test/04-1-command-table-routing.test.ts:

// file: src/command-table.ts
// tier: L1
// verify: node --test test/04-1-command-table-routing.test.ts
//
// 命令系统(第四章):命令表与路由。
// CommandTable 把编辑器的每个操作注册成一条命令(id + run + 可选 enabled
// + 可选快捷键),execute(id, ctx) 按 id 路由到实现并校验可用性。
// 菜单、工具栏、快捷键、脚本宏最终都落到同一个入口 execute——命令表是
// 编辑器操作的唯一会合点。

export interface CommandContext {
  /** 当前选中的对象 id。 */
  selection: string[];
  /** 其它上下文数据(场景、资产等)。 */
  [key: string]: unknown;
}

export type CommandResult =
  | { ok: true; detail?: string }
  | { ok: false; reason: string };

export interface Command {
  id: string;
  label: string;
  run(ctx: CommandContext): CommandResult;
  /** 上下文敏感:只在某些状态下可执行。缺省始终可用。 */
  enabled?: (ctx: CommandContext) => boolean;
  /** 可选快捷键(形如 Mod+K)。 */
  shortcut?: string;
}

export class CommandTable {
  readonly #commands = new Map<string, Command>();

  register(cmd: Command): boolean {
    if (this.#commands.has(cmd.id)) return false;
    // 快捷键全局唯一:同一快捷键不能绑两条命令
    if (cmd.shortcut) {
      for (const other of this.#commands.values()) {
        if (other.shortcut === cmd.shortcut) return false;
      }
    }
    this.#commands.set(cmd.id, cmd);
    return true;
  }

  has(id: string): boolean { return this.#commands.has(id); }
  command(id: string): Command | undefined { return this.#commands.get(id); }
  ids(): string[] { return [...this.#commands.keys()]; }

  /** 查询一条命令在当前上下文中是否可用。 */
  canExecute(id: string, ctx: CommandContext): boolean {
    const cmd = this.#commands.get(id);
    if (!cmd) return false;
    return cmd.enabled ? cmd.enabled(ctx) : true;
  }

  /** 按 id 路由执行:未知命令、被禁用的命令都给出明确失败原因。 */
  execute(id: string, ctx: CommandContext): CommandResult {
    const cmd = this.#commands.get(id);
    if (!cmd) return { ok: false, reason: `unknown command: ${id}` };
    if (cmd.enabled && !cmd.enabled(ctx)) {
      return { ok: false, reason: `command disabled in this context: ${id}` };
    }
    return cmd.run(ctx);
  }
}

两个细节值得注意。一是 execute 与 canExecute 共享同一个 enabled 谓词:UI 层显示状态和实际执行使用同一事实来源,不会出现「按钮亮着但点下去说不能」或「按钮灰着但脚本能调」的分裂。二是快捷键查重放在 register 而不是 execute:冲突越早暴露越好——注册一条 Mod+K 命令时发现它已经被占,立刻拒绝,比用户真按 Mod+K 时发现走了错误的命令强得多。

可运行产物:6 条用例

下面是 test/04-1-command-table-routing.test.ts 层级 L1,命令 node --test test/04-1-command-table-routing.test.ts:

// file: test/04-1-command-table-routing.test.ts
// tier: L1
// verify: node --test test/04-1-command-table-routing.test.ts
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { CommandTable, type CommandContext } from '../src/command-table.ts';

const ctx: CommandContext = { selection: ['node-1'], scene: 'level-1' };

test('注册命令并路由执行,命令收到完整上下文', () => {
  const t = new CommandTable();
  let saw: CommandContext | null = null;
  t.register({
    id: 'edit.duplicate',
    label: 'Duplicate',
    run: (c) => { saw = c; return { ok: true }; },
  });
  const r = t.execute('edit.duplicate', ctx);
  assert.equal(r.ok, true);
  assert.equal(saw!.selection[0], 'node-1');
  assert.equal(saw!.scene, 'level-1');
});

test('重复注册被拒绝', () => {
  const t = new CommandTable();
  t.register({ id: 'a', label: 'A', run: () => ({ ok: true }) });
  assert.equal(t.register({ id: 'a', label: 'A2', run: () => ({ ok: true }) }), false);
  assert.equal(t.command('a')!.label, 'A'); // 第一次注册的仍在
});

test('未知命令给出明确失败原因', () => {
  const t = new CommandTable();
  const r = t.execute('no.such.command', ctx);
  assert.equal(r.ok, false);
  assert.match(r.reason, /unknown command/);
});

test('enabled 上下文敏感:禁用时 execute 拒绝', () => {
  const t = new CommandTable();
  t.register({
    id: 'edit.delete',
    label: 'Delete',
    enabled: (c) => c.selection.length > 0,
    run: () => ({ ok: true }),
  });
  assert.equal(t.canExecute('edit.delete', ctx), true);
  assert.equal(t.canExecute('edit.delete', { ...ctx, selection: [] }), false);
  const r = t.execute('edit.delete', { ...ctx, selection: [] });
  assert.equal(r.ok, false);
  assert.match(r.reason, /disabled/);
});

test('快捷键全局唯一:冲突注册被拒绝', () => {
  const t = new CommandTable();
  assert.equal(t.register({ id: 'a', label: 'A', shortcut: 'Mod+K', run: () => ({ ok: true }) }), true);
  assert.equal(t.register({ id: 'b', label: 'B', shortcut: 'Mod+K', run: () => ({ ok: true }) }), false);
});

test('同一快捷键可复用(不冲突时正常注册)', () => {
  const t = new CommandTable();
  assert.equal(t.register({ id: 'a', label: 'A', shortcut: 'Mod+K', run: () => ({ ok: true }) }), true);
  assert.equal(t.register({ id: 'b', label: 'B', shortcut: 'Mod+Shift+K', run: () => ({ ok: true }) }), true);
});

本机实测(Node v26.5.0,node --test test/04-1-command-table-routing.test.ts):tests 6、pass 6、fail 0,耗时约 43 ms。

第一条验证「路由 + 上下文透传」——命令收到 selection 和任意上下文键;第三条和第四条钉住两条失败路径,它们是最容易在实现里变成 throw 的地方;第五、六条把「快捷键冲突在注册时拒绝」焊死——同键不同命令拒绝、不同键正常注册,一个对照闭环。

小结

  • 命令表是编辑器操作的唯一会合点:菜单、工具栏、快捷键、脚本宏都只做 execute(id, ctx)。
  • canExecute 与 execute 共享同一 enabled 谓词,UI 灰化与实际执行永不分裂。
  • 失败给原因不给崩溃:unknown command / command disabled 写进返回值。
  • 快捷键全局唯一,冲突在 register 时暴露。
  • 下一节把命令表接到 UI:菜单、工具栏与快捷键注册——嵌套菜单构建、keymap 收集、冲突拒绝。

阅读导航:上一节:3.3 对标:ImGui、Qt 与 Unity 编辑器 UI · 下一节:4.2 菜单、工具栏与快捷键注册 。

继续阅读

探索更多技术文章

浏览归档,发现更多关于系统设计、工具链和工程实践的内容。

全部文章 返回首页

「books」更多文章

  1. 《大规模分布式计算深入解析·向量数据库与 AI 检索内核》 · 目录与学习路径(45 篇)
  2. 《大规模分布式计算深入解析》15.3 自研向量引擎:可执行骨架与工程缺口
  3. 《大规模分布式计算深入解析》14.1 Milvus:组件架构、段管理与检索链路