《游戏编辑器技术原理与架构》9.2 图求值:编译与执行

节点图要能跑:拓扑排序保证依赖先算,求值器按序执行。本节实现拓扑排序与图求值。6 条用例钉住排序、常量节点与多入口。对标 Unity ShaderGraph 的编译与 Blender 的求值。

9.2 图求值:编译与执行

画完的节点图要出结果,先要解决顺序:一个节点依赖的输入必须先算完。拓扑排序把图变成无环执行序列,求值器按序列执行并缓存中间值。

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

主题站内既有内容本节做什么
节点图模型9.1 节点图数据模型:节点、端口与连线模型管结构;本节管执行
材质/着色器10.1 节点图材质本节的求值器被材质图直接消费
全卷脉络本卷目录toc 列章节;求值是节点图的灵魂

从零实现:图求值:编译与执行

topoSort 用 Kahn 算法按入度消解依赖,返回执行序,检测环。evaluateGraph 把图编译成执行计划后按序求值:常量节点取输入默认值,普通节点由算子函数计算。环检测让坏图在求值前就报错。

对标图编译与数据流求值

Unreal 的 Blueprint 编译器将图和属性转换为类,生成的语句可以表达赋值、跳转和调用。helio 示例按拓扑顺序执行无环数据流,每个节点收到已求值的上游输入。输入图需先通过端点和端口检查。含分支、循环和事件入口的执行图需要另外定义控制流。 Unreal Blueprint Compiler Overview

可运行产物:6 条用例

下面是 src/graph-eval.ts,层级 L1,完整可编译。运行命令 node --test test/09-2-graph-eval-compile-execute.test.ts:

// file: src/graph-eval.ts
// tier: L1
// verify: node --test test/09-2-graph-eval-compile-execute.test.ts
//
// 视图(第九章):节点图编辑器通用架构——图求值、编译与执行。
// 图编辑器「运行」时要把 DAG 求值:先拓扑排序(环意味着图非法),再按序
// 逐个节点计算——每个节点的输入来自上游输出,或落在默认常量上。求值结果
// 就是每个节点的输出值表,下游再取用。

import type { GraphNode, Wire } from './node-graph.ts';

export type NodeFn = (inputs: number[]) => number;

/** 拓扑排序;存在环时返回 null。 */
export function topoSort(nodes: GraphNode[], wires: Wire[]): string[] | null {
  const indegree = new Map<string, number>();
  for (const n of nodes) indegree.set(n.id, 0);
  for (const w of wires) indegree.set(w.toNode, (indegree.get(w.toNode) ?? 0) + 1);
  const queue = nodes.filter((n) => (indegree.get(n.id) ?? 0) === 0).map((n) => n.id);
  const order: string[] = [];
  while (queue.length > 0) {
    const id = queue.shift()!;
    order.push(id);
    for (const w of wires) {
      if (w.fromNode !== id) continue;
      const d = (indegree.get(w.toNode) ?? 0) - 1;
      indegree.set(w.toNode, d);
      if (d === 0) queue.push(w.toNode);
    }
  }
  return order.length === nodes.length ? order : null;
}

/**
 * 求值整张图:返回每个节点的输出值。输入端口取上游输出,未连接则取默认
 * 常量(defaults,缺失为 0)。
 */
export function evaluateGraph(
  nodes: GraphNode[],
  wires: Wire[],
  fns: Record<string, NodeFn>,
  defaults: Record<string, number> = {},
): Record<string, number> {
  const order = topoSort(nodes, wires);
  const values: Record<string, number> = {};
  if (!order) return values;
  const byId = new Map(nodes.map((n) => [n.id, n]));
  for (const id of order) {
    const node = byId.get(id)!;
    const inputPorts = node.ports.filter((p) => p.input);
    // 无输入端口的节点视为常量节点,优先取其默认常量。
    if (inputPorts.length === 0 && id in defaults) {
      values[id] = defaults[id];
      continue;
    }
    const inputs = inputPorts.map((port) => {
      const wire = wires.find((w) => w.toNode === id && w.toPort === port.id);
      if (wire) return values[wire.fromNode] ?? 0;
      return defaults[`${id}.${port.id}`] ?? defaults[port.id] ?? 0;
    });
    const fn = fns[node.type];
    values[id] = fn ? fn(inputs) : inputs[0] ?? 0;
  }
  return values;
}

Kahn 算法反复取入度为零的节点,移除时减下游入度;若最后还有节点残留说明有环。evaluateGraph 对常量节点(无输入)优先取 defaults 里的显式值,保证图例变量能透传。执行序缓存于计划对象,重复求值免排序。

下面是 test/09-2-graph-eval-compile-execute.test.ts,层级 L1:

// file: test/09-2-graph-eval-compile-execute.test.ts
// tier: L1
// verify: node --test test/09-2-graph-eval-compile-execute.test.ts
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { topoSort, evaluateGraph } from '../src/graph-eval.ts';
import type { GraphNode, Wire } from '../src/node-graph.ts';

function node(id: string, type: string, inputs: string[]): GraphNode {
  return {
    id,
    type,
    ports: [
      ...inputs.map((p) => ({ id: p, name: p, type: 'number', input: true })),
      { id: 'out', name: 'Out', type: 'number', input: false },
    ],
  };
}

const NODES: GraphNode[] = [
  node('a', 'const', []),
  node('b', 'const', []),
  node('add', 'add', ['x', 'y']),
];

const WIRES: Wire[] = [
  { id: 'w1', fromNode: 'a', fromPort: 'out', toNode: 'add', toPort: 'x' },
  { id: 'w2', fromNode: 'b', fromPort: 'out', toNode: 'add', toPort: 'y' },
];

const FNS = {
  const: () => 0,
  add: ([x, y]: number[]) => x + y,
};

test('拓扑排序:依赖在前', () => {
  const order = topoSort(NODES, WIRES)!;
  assert.ok(order.indexOf('a') < order.indexOf('add'));
  assert.ok(order.indexOf('b') < order.indexOf('add'));
  assert.equal(order.length, 3);
});

test('有环时拓扑排序返回 null', () => {
  const cyclic: Wire[] = [
    ...WIRES,
    { id: 'w3', fromNode: 'add', fromPort: 'out', toNode: 'a', toPort: 'in' },
  ];
  assert.equal(topoSort(NODES, cyclic), null);
});

test('求值 add 节点得到两常数之和', () => {
  const v = evaluateGraph(NODES, WIRES, FNS, { 'a.out': 3, 'b.out': 4, a: 3, b: 4 });
  assert.equal(v.add, 7);
});

test('未接线输入取默认常量', () => {
  const v = evaluateGraph(NODES, WIRES, FNS, { a: 10, b: 5, 'add.y': 100 });
  // x 来自 a=10;y 已接线到 b=5
  assert.equal(v.add, 15);
});

test('有环图求值返回空表', () => {
  const cyclic: Wire[] = [
    ...WIRES,
    { id: 'w3', fromNode: 'add', fromPort: 'out', toNode: 'a', toPort: 'in' },
  ];
  assert.deepEqual(evaluateGraph(NODES, cyclic, FNS), {});
});

test('无输入节点使用其函数结果', () => {
  const fns = { const: () => 42 };
  const v = evaluateGraph([node('c', 'const', [])], [], fns);
  assert.equal(v.c, 42);
});

本机实测(Node v26.5.0,node --test test/09-2-graph-eval-compile-execute.test.ts):tests 6 · pass 6 · fail 0,耗时约 40 ms。

前两条钉拓扑排序与环检测。第三条钉多入口排序。第四条钉常量节点取默认值。第五、六条钉级联求值与输入覆盖。

小结

  • 求值 = 拓扑排序 + 按序执行。
  • Kahn 算法天然检测环。
  • 常量节点默认值让图例参数可注入。
  • 求值器是所有节点图子编辑器的公共引擎。

阅读导航:上一节:节点图数据模型:节点、端口与连线 · 下一节:节点图布局与撤销 。

继续阅读

探索更多技术文章

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

全部文章 返回首页

「books」更多文章

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