《游戏编辑器技术原理与架构》7.3 文档不变量校验

操作 API 负责改得对,不变量校验负责查得对。checkInvariants 把文档按 id 唯一、parent 存在、无环、children 与 parent 双向一致四条不变量过一遍,返回错误列表;加载、撤销、脚本写入之后各跑一次,结构坏在第一时间暴露。6 条用例本机真跑,对标 Unity/Unreal 编辑器启动时的场景一致性检查。

7.3 文档不变量校验

7.1 的操作 API 让文档「改得对」——每个操作都有前置检查。但工业级编辑器还需要另一层保障:查得对。脚本往文档里写东西(第 6 章的脚本桥、第 9 章的 Prefab 更新、加载器读文件),总有机会绕过操作 API 直接动节点表;撤销系统回放时也可能碰出意外结构。这种时候,靠「操作时检查」已经来不及了,需要一次全文档体检。

checkInvariants(nodes) 把文档按四条不变量过一遍,返回错误列表(空 = 通过):

  • id 唯一:两张表里同一个 id 不能出现两次——id 是身份。
  • parent 存在:parent 引用的节点必须在文档里,不能悬空指向虚无。
  • 无环:沿 parent 上溯不能回到自己——父子图必须是树,环会毁掉级联删除、脏传播、序列化一切东西。
  • children 与 parent 双向一致:node.children 里列出的节点,其 parent 必须指回 node。这是最重要的检查——很多编辑器用「children 数组 + parent 指针」双份存储,两份一旦漂移,遍历结果就诡异。

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

主题站内既有内容本节做什么
操作 API7.1 场景文档操作 API操作时逐条检查;本节做全文档体检
稳定 id7.2 稳定 id 与脏传播稳定 id 保证身份可追踪;校验保证身份唯一
场景格式第 8 章 序列化与场景格式加载器读盘后先跑校验,再进编辑循环

什么时候跑体检

体检的时机比内容更重要——在「信不过文档」的关口各跑一次:

  1. 加载之后:磁盘文件可能来自旧版本、别的工具、手改。读进来先体检,坏的直接弹错误,而不是进编辑循环后神秘崩溃。
  2. 撤销回放之后:撤销是逆序回放操作,边角情况下可能留下不一致结构。回放完体检,把撤销 bug 扼杀在当天。
  3. 脚本写入之后:脚本桥(6.3)让外部脚本能动文档。脚本是人写的,人写的就有 bug——写入后体检兜底。

对标结构校验的边界

Godot 的 Node API 管理父子关系,owner 还影响节点是否随场景打包。编辑器树中的父子结构和保存范围需要分别检查。Unity 的 Undo API 和 Unreal 的事务 API 负责记录可撤销修改,不能据此推断引擎会在每次撤销后运行统一的文档校验。 Godot Node · Unity Undo · Unreal UObject::Modify

helio 的 checkInvariants 针对本节的节点表检查 ID、父节点、环与父子引用。加载器可在替换当前文档前调用它,撤销或脚本修改后的检查则由调用方接入。

可运行产物:6 条用例

下面 src/doc-invariants.ts 层级 L1,完整可编译,命令 node --test test/07-3-document-invariants-validation.test.ts:

// file: src/doc-invariants.ts
// tier: L1
// verify: node --test test/07-3-document-invariants-validation.test.ts
//
// 文档模型与脏标记深化(第七章):文档不变量校验。
// 场景文档在任何时刻都必须满足一组不变量:id 唯一、parent 存在、无环、
// children 与 parent 双向一致。checkInvariants 把文档按这些不变量过一遍,
// 返回错误列表(空 = 通过)。这是编辑器的「文档体检」:加载、撤销、
// 脚本写入之后各跑一次,结构坏在第一时间暴露。

export interface NodeLink {
  id: string;
  parent: string | null;
  children: string[];
}

/** 检查一组文档不变量,返回错误列表(空 = 全部通过)。 */
export function checkInvariants(nodes: NodeLink[]): string[] {
  const errors: string[] = [];
  const byId = new Map<string, NodeLink>();
  for (const n of nodes) {
    if (byId.has(n.id)) errors.push(`duplicate id: ${n.id}`);
    byId.set(n.id, n);
  }

  // parent 存在 + 环检测(沿 parent 上溯)
  for (const n of nodes) {
    if (n.parent !== null && !byId.has(n.parent)) {
      errors.push(`dangling parent: ${n.id} -> ${n.parent}`);
    }
    if (n.parent !== null && isAncestor(n.id, n.parent, byId)) {
      errors.push(`cycle: ${n.id} -> ${n.parent}`);
    }
  }

  // children 双向一致:children 里的节点必须存在,且其 parent 指回自己
  for (const n of nodes) {
    for (const c of n.children) {
      const child = byId.get(c);
      if (!child) { errors.push(`dangling child: ${n.id} -> ${c}`); continue; }
      if (child.parent !== n.id) {
        errors.push(`inconsistent parent: ${c}.parent=${child.parent} but ${n.id} lists it as child`);
      }
    }
  }
  return errors;
}

/** target 沿 parent 上溯是否能到达 ancestor(即 target 是 ancestor 的后代)。 */
function isAncestor(ancestor: string, target: string, byId: Map<string, NodeLink>): boolean {
  let cur: string | null = target;
  while (cur !== null) {
    if (cur === ancestor) return true;
    const n = byId.get(cur);
    cur = n ? n.parent : null;
  }
  return false;
}

isAncestor 与 7.1 的 #isDescendant 是同一条上溯逻辑的正反两面——那里用它防环(操作时),这里用它查环(体检时)。双向一致性检查是唯一需要双份存储都读的:children 里列了 c,就要求 c.parent === n.id,否则报 inconsistent parent。

可运行产物:6 条用例

下面是 test/07-3-document-invariants-validation.test.ts 层级 L1,命令 node --test test/07-3-document-invariants-validation.test.ts:

// file: test/07-3-document-invariants-validation.test.ts
// tier: L1
// verify: node --test test/07-3-document-invariants-validation.test.ts
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { checkInvariants } from '../src/doc-invariants.ts';
import type { NodeLink } from '../src/doc-invariants.ts';

function okDoc(): NodeLink[] {
  return [
    { id: 'scene', parent: null, children: ['group', 'leaf'] },
    { id: 'group', parent: 'scene', children: ['leaf2'] },
    { id: 'leaf', parent: 'scene', children: [] },
    { id: 'leaf2', parent: 'group', children: [] },
  ];
}

test('合法文档无错误', () => {
  assert.deepEqual(checkInvariants(okDoc()), []);
});

test('重复 id 被报出', () => {
  const doc = okDoc();
  doc.push({ id: 'leaf', parent: null, children: [] });
  const errs = checkInvariants(doc);
  assert.ok(errs.some((e) => e.includes('duplicate id: leaf')));
});

test('悬空 parent 被报出', () => {
  const doc = okDoc();
  doc[0] = { ...doc[0], children: ['ghost'] };
  doc.push({ id: 'ghost', parent: 'nobody', children: [] });
  const errs = checkInvariants(doc);
  assert.ok(errs.some((e) => e.includes('dangling parent: ghost -> nobody')));
});

test('环被报出', () => {
  const doc: NodeLink[] = [
    { id: 'a', parent: 'b', children: [] },
    { id: 'b', parent: 'a', children: [] },
  ];
  const errs = checkInvariants(doc);
  assert.ok(errs.some((e) => e.includes('cycle: a -> b')));
  assert.ok(errs.some((e) => e.includes('cycle: b -> a')));
});

test('children 与 parent 双向不一致被报出', () => {
  const doc = okDoc();
  doc[1] = { ...doc[1], parent: 'leaf' }; // group 的 parent 被改成 leaf,但 leaf.children 没写 group
  const errs = checkInvariants(doc);
  assert.ok(errs.some((e) => e.includes('inconsistent parent: group.parent=leaf')));
});

test('悬空 child 引用被报出', () => {
  const doc = okDoc();
  doc[0] = { ...doc[0], children: ['group', 'leaf', 'missing'] };
  const errs = checkInvariants(doc);
  assert.ok(errs.some((e) => e.includes('dangling child: scene -> missing')));
});

本机实测(Node v26.5.0,node --test test/07-3-document-invariants-validation.test.ts):tests 6、pass 6、fail 0,耗时约 38 ms。

四条坏结构全部被抓到:重复 id(第一条反面)、悬空 parent(第二条)、环(第三条,且 a->b、b->a 两个方向都报)、双向不一致(第四条,group.parent 被改成 leaf 却没同步 leaf.children)和悬空 child(第五条)。第四条是最刁钻的一种——单看 parent 指针文档是合法的,只有对着 children 双向核对才发现漂移。

小结

  • 四条不变量:id 唯一、parent 存在、无环、children 与 parent 双向一致——结构坏在第一时间暴露。
  • 体检时机:加载之后、撤销回放之后、脚本写入之后,在「信不过文档」的关口各跑一次。
  • 错误以列表返回,一次体检列全所有坏点,修复者看全局。
  • Godot 靠引擎维护结构天然难坏;helio 允许脚本直写文档,所以体检是必要闸门。
  • 第 7 章结束。下一章把文档模型接进磁盘:序列化与场景格式——可 diff 的格式设计、版本迁移链、对象图引用。

阅读导航:上一节:7.2 稳定 id 与脏传播 · 下一节:8.1 可 diff 的场景格式设计 。

继续阅读

探索更多技术文章

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

全部文章 返回首页

「books」更多文章

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