《OGRE 3D 渲染引擎原理与架构》4.1 脚本编译器

脚本编译器把文本变成引擎资源:compile 走词法→语法→AST→imports/objects/variables 处理→翻译五段流水线,错误码枚举收集 (code,file,line);ScriptCompilerListener 的 postConversion 可否决编译,registerCustomWordId 分配自定义词 ID。lab 复现流水线与监听器时序。

4.1 脚本编译器

OGRE 的大量内容(材质、粒子、合成器)不是硬编码进 C++,而是写在 .material、.particle、.compositor 脚本里,运行时由脚本编译器统一处理。ScriptCompiler 是这条流水线的总装车间:从原始文本开始,一步步把它变成真正的引擎资源。这一节先看流水线骨架,再深入错误收集、监听器拦截、自定义词注册三个扩展点。

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

第 3 章讲资源/存档/编解码器,是「数据从哪来」;本节开始讲「脚本怎么写、怎么进引擎」。4.1 讲 ScriptCompiler 的编译流水线与扩展点,4.2 以材质脚本为例讲 ScriptTranslator 怎么把 AST 翻译成资源对象,4.3 下沉到词法/语法两级,看文本怎么变成 token、token 怎么变成树。

编译流水线:五段处理

ScriptCompiler 的类注释点明它的职责——把 CST(Concrete Syntax Tree)处理成 AST(Abstract Syntax Tree),再用翻译器把 AST 变成最终资源:

// OgreMain/include/OgreScriptCompiler.h:ScriptCompiler(v14.6.3 源码摘录,已删减)
    class _OgreExport ScriptCompiler : public ScriptCompilerAlloc
    {
    public: // Externally accessible types
        //typedef std::map<String,uint32> IdMap;
        typedef std::unordered_map<String,uint32> IdMap;

        // These are the built-in error codes
        enum{
            CE_STRINGEXPECTED,
            CE_NUMBEREXPECTED,
            CE_FEWERPARAMETERSEXPECTED,
            CE_VARIABLEEXPECTED,
            CE_UNDEFINEDVARIABLE,
            CE_OBJECTNAMEEXPECTED,
            CE_OBJECTALLOCATIONERROR,
            CE_INVALIDPARAMETERS,
            CE_DUPLICATEOVERRIDE,
            CE_UNEXPECTEDTOKEN,
            CE_OBJECTBASENOTFOUND,
            CE_REFERENCETOANONEXISTINGOBJECT,
            CE_DEPRECATEDSYMBOL
        };
        static String formatErrorCode(uint32 code);

        /// Takes in a string of script code and compiles it into resources
        /**
         * @param str The script code
         * @param source The source of the script code (e.g. a script file)
         * @param group The resource group to place the compiled resources into
         */
        bool compile(const String &str, const String &source, const String &group);
        /// Compiles resources from the given concrete node list
        bool compile(const ConcreteNodeListPtr &nodes, const String &group);
        /// Adds the given error to the compiler's list of errors
        void addError(uint32 code, const String &file, int line, const String &msg = "");

错误码枚举是编译器错误体系的基石——CE_STRINGEXPECTED、CE_NUMBEREXPECTED、CE_OBJECTNAMEEXPECTED、CE_UNEXPECTEDTOKEN 这些枚举值贯穿整个编译与翻译阶段,4.2 节的翻译器会看到它们的具体用法。compile 有两个重载:一个吃原始字符串(从文本开始),一个吃已经解析好的 ConcreteNodeListPtr(跳过词法/语法)。这两个入口最终都汇到同一个核心流水线:

// OgreMain/src/OgreScriptCompiler.cpp:compile(CST)(v14.6.3 源码摘录,已删减)
    bool ScriptCompiler::compile(const ConcreteNodeListPtr &nodes, const String &group)
    {
        if(nodes && !nodes->empty())
        {
            mSourceFile = nodes->front()->file;
        }

        // Set up the compilation context
        mGroup = group;

        // Clear the past errors
        mErrors.clear();

        // Clear the environment
        mEnv.clear();

        if(mListener)
            mListener->preConversion(this, nodes);

        // Convert our nodes to an AST
        AbstractNodeListPtr ast = convertToAST(*nodes);
        // Processes the imports for this script
        processImports(*ast);
        // Process object inheritance
        processObjects(*ast, *ast);
        // Process variable expansion
        std::set<String> expadingVars;
        processVariables(*ast, expadingVars);

        // Allows early bail-out through the listener
        if(mListener && !mListener->postConversion(this, ast))
            return mErrors.empty();

        // Translate the nodes
        for(auto & i : *ast)
        {
#if DEBUG_AST
            logAST(0, i);
#endif

流水线可以画成五段:

阶段函数干什么
1preConversion 回调监听器在 AST 转换前介入
2convertToASTCST → AST(抽象节点树)
3processImports处理 #import 引用
4processObjects + processVariables对象继承覆盖与 $变量 展开
5postConversion 回调 + 翻译监听器可否决;循环翻译每个节点

两个细节值得注意。第一,每次编译开始前清空错误列表(mErrors.clear())和清空环境(mEnv.clear())——编译器实例是持久的,错误不能跨脚本累积。第二,postConversion 是提前退出的钩子:返回 false 就跳过翻译阶段直接返回 mErrors.empty()。

错误收集:Error 结构

mErrors 是编译错误的总账,每条错误一个结构:

// OgreMain/include/OgreScriptCompiler.h:Error(v14.6.3 源码摘录,已删减)
    private:
        friend String getPropertyName(const ScriptCompiler *compiler, uint32 id);
        String mSourceFile;
        // Resource group
        String mGroup;
        // The word -> id conversion table
        IdMap mIds;

		// The largest registered id
		uint32 mLargestRegisteredWordId;

        // This is an environment map
        typedef std::map<String,String> Environment;
        Environment mEnv;

        // This stores the imports of the scripts, so they are separated and can be treated specially
        AbstractNodeList mImportTable;

        // Error list
        // The container for errors
        struct Error
        {
            String file, message;
            int line;
            uint32 code;
        };
        typedef std::list<Error> ErrorList;
        ErrorList mErrors;

Error 携带四元组:文件名、行号、错误码、消息。翻译阶段每发现一个错误就 addError(code, file, line, msg) 塞进链表。错误码给机器,消息给人——formatErrorCode 能把错误码格式化成可读文本,日志里常见到「compiler error near line 12: CE_OBJECTNAMEEXPECTED」。

监听器:转换前介入,转换后可否决

脚本编译器的扩展点集中在一个接口上——ScriptCompilerListener:

// OgreMain/include/OgreScriptCompiler.h:ScriptCompilerListener(v14.6.3 源码摘录,已删减)
    class _OgreExport ScriptCompilerListener
    {
    public:
        ScriptCompilerListener();
        virtual ~ScriptCompilerListener() {}

        /// Returns the concrete node list from the given file
        virtual ConcreteNodeListPtr importFile(ScriptCompiler *compiler, const String &name);
        /// Allows for responding to and overriding behavior before a CST is translated into an AST
        virtual void preConversion(ScriptCompiler *compiler, ConcreteNodeListPtr nodes);
        /// Allows vetoing of continued compilation after the entire AST conversion process finishes
        /**
         @remarks   Once the script is turned completely into an AST, including import
                    and override handling, this function allows a listener to exit
                    the compilation process.
         @return True continues compilation, false aborts
         */
        virtual bool postConversion(ScriptCompiler *compiler, const AbstractNodeListPtr&);
        /// Called when an error occurred
        virtual void handleError(ScriptCompiler *compiler, uint32 code, const String &file, int line, const String &msg);
        /// Called when an event occurs during translation, return true if handled
        virtual bool handleEvent(ScriptCompiler *compiler, ScriptCompilerEvent *evt, void *retval);
    };

监听器有五个钩子,其中与流水线直接相关的是 preConversion 和 postConversion。preConversion 在 CST 转 AST 之前调用,可用来修改节点列表;postConversion 在完整 AST 转换(含 import 和 override)之后调用,返回 false 即可否决后续编译——这正是上面 compile 第 356-357 行提前退出的机制。handleEvent 是翻译阶段的事件通道,4.2 节的 CreateMaterialScriptCompilerEvent 就走这条路。

自定义词 ID:翻译器的语言扩展

registerCustomWordId 允许自定义翻译器往编译器里注入自己的关键词:

// OgreMain/include/OgreScriptCompiler.h:registerCustomWordId(v14.6.3 源码摘录,已删减)
		/// Adds a custom word id which can be used for custom script translators
		/** 
		@param
		word The word to be registered.

		@return
		The word id for the registered word.
		
		@note
		If the word is already registered, the already registered id is returned.
		*/
		uint32 registerCustomWordId(const String &word);

脚本解析时,每个词都会被映射成数值 ID(mIds 无序表)。内建关键词(technique、pass、ambient…)在 initWordMap() 里占用了从 0 起的 ID 段;registerCustomWordId 从 mLargestRegisteredWordId 往上递增分配,保证自定义词 ID 永远大于内建词。自定义翻译器拿到这些 ID 后就能在自己的 switch 里识别扩展关键词。重复注册同一个词返回已分配的 ID——注释里的 @note 就是这层保证。

脚本编译器的输入输出

flowchart LR
  A["脚本文本"] --> B["Lexer token"]
  B --> C["Parser 具体语法节点"]
  C --> D["抽象语法节点"]
  D --> E["导入、继承和变量处理"]
  E --> F["Translator 分发"]
  F --> G["Material 等资源"]
  E -.-> H["编译错误记录"]
  F -.-> H

脚本翻译发生在资源加载之前

编译器依次处理词法、语法结构、导入和继承等操作,翻译器消费抽象节点并登记资源。解析成功后仍需通过资源加载和后端支持检查,才能得到可用的 Technique。

用原生场景的材质文件验证“已登记、未加载”。对照拼错属性时编译报告的文件和位置,再按卷一 6.3 追踪归档和组。

源码定位

  • OgreMain/include/OgreScriptCompiler.h :ScriptCompiler 类(213-356)、错误码枚举(219-234)、compile(246-248)、addError(250-252)、registerCustomWordId(264-275)、ScriptCompilerListener(379-410)、ScriptCompilerManager(418-478)
  • OgreMain/src/OgreScriptCompiler.cpp :compile(str)(266-270)、compile(CST)(326-357)、mErrors.clear()(337)、preConversion(343)、convertToAST(346)、processImports(348)、processObjects(350)、processVariables(353)、postConversion 提前退出(356-357)

上游引用固定到 OGRE v14.6.3 源码 。

可运行产物:C++ 最小验证

下面用纯 C++ 复现脚本编译器骨架:错误码枚举、compile 流水线、监听器的 preConversion/postConversion 时序与可否决、registerCustomWordId 的自增 ID。它与 src/ogre-ext-04-1-script-compiler.cpp 逐字节一致:

// file: src/ogre-ext-04-1-script-compiler.cpp
// tier: L1
// verify: clang++ -std=c++20 -I. src/ogre-ext-04-1-script-compiler.cpp -o bin/ogre-ext-04-1-script-compiler && ./bin/ogre-ext-04-1-script-compiler
//
// 复现脚本编译器骨架(对应 OgreMain/include/OgreScriptCompiler.h 213-356 的
//   ScriptCompiler、219-234 的错误码枚举,OgreScriptCompiler.cpp 266-270 的
//   compile(str) 与 326-357 的 compile(CST) 主体):监听器 preConversion 在前、
//   postConversion 可否决;registerCustomWordId 为自定义词分配大于内建基线的 ID;
//   错误以 (code,file,line) 收集,每次编译开始前清空。
// 独立最小验证,非 OGRE 源码。
#include "verify.h"

#include <cstdint>
#include <map>
#include <string>
#include <vector>

namespace ogre_repro {

using String = std::string;

// 对应 ScriptCompiler.h 219-234 的内建错误码(取一部分)
enum {
  CE_STRINGEXPECTED,
  CE_NUMBEREXPECTED,
  CE_OBJECTNAMEEXPECTED,
  CE_OBJECTALLOCATIONERROR,
  CE_UNEXPECTEDTOKEN,
  CE_REFERENCETOANONEXISTINGOBJECT,
  CE_DEPRECATEDSYMBOL
};

// 错误条目:对应 ScriptCompiler.h 320-325 的 Error 结构
struct Error {
  String file;
  int line;
  uint32_t code;
};

// 对应 ScriptCompiler.h 363-373:编译事件(简化)
struct ScriptCompilerEvent {
  String mType;
  explicit ScriptCompilerEvent(const String& type) : mType(type) {}
  virtual ~ScriptCompilerEvent() {}
};

// 对应 ScriptCompiler.h 379-410:监听器
class ScriptCompilerListener {
 public:
  virtual ~ScriptCompilerListener() {}
  virtual void preConversion() {}
  virtual bool postConversion(bool hadErrors) { return !hadErrors; }
  virtual bool handleEvent(ScriptCompilerEvent* evt) {
    (void)evt;
    return false;
  }
};

// 对应 OgreScriptCompiler.cpp 326-357:最小编译流水线
class ScriptCompiler {
 public:
  ScriptCompiler() { mLargestRegisteredWordId = 1000; }

  // 对应 OgreScriptCompiler.cpp 266-270:str → 词法/解析(此处简化为合法性判定)
  bool compile(const String& str, const String& source) {
    mSourceFile = source;
    mErrors.clear();
    mTranslated = false;
    if (mListener) mListener->preConversion();

    // 极简 CST:对象名为空或直接以左花括号开头 → CE_OBJECTNAMEEXPECTED
    if (str.empty() || str[0] == '{') {
      addError(CE_OBJECTNAMEEXPECTED, source, 1);
    }

    // 允许监听器在 AST 转换后提早退出(对应 OgreScriptCompiler.cpp 356-357)
    if (mListener && !mListener->postConversion(!mErrors.empty()))
      return mErrors.empty();

    if (mErrors.empty()) mTranslated = true;  // 模拟翻译阶段
    return mErrors.empty();
  }

  // 对应 OgreScriptCompiler.h 264-275:注册自定义词,返回递增的 ID
  uint32_t registerCustomWordId(const String& word) {
    auto it = mIds.find(word);
    if (it != mIds.end()) return it->second;
    uint32_t id = ++mLargestRegisteredWordId;
    mIds.emplace(word, id);
    return id;
  }

  void addError(uint32_t code, const String& file, int line) {
    Error e;
    e.code = code;
    e.file = file;
    e.line = line;
    mErrors.push_back(e);
  }

  void setListener(ScriptCompilerListener* l) { mListener = l; }

  String mSourceFile;
  std::vector<Error> mErrors;
  std::map<String, uint32_t> mIds;
  uint32_t mLargestRegisteredWordId;
  bool mTranslated = false;
  ScriptCompilerListener* mListener = nullptr;
};

// 记录调用序的监听器
class RecordingListener : public ScriptCompilerListener {
 public:
  std::vector<String> calls;
  void preConversion() override { calls.push_back("preConversion"); }
  bool postConversion(bool hadErrors) override {
    calls.push_back("postConversion");
    return !hadErrors;
  }
};

// 可否决编译的监听器(postConversion 返回 false)
class VetoListener : public ScriptCompilerListener {
 public:
  bool postConversion(bool hadErrors) override {
    (void)hadErrors;
    return false;
  }
};

}  // namespace ogre_repro

int main() {
  using namespace ogre_repro;

  ScriptCompiler compiler;

  // 无监听器:空脚本 → CE_OBJECTNAMEEXPECTED,编译失败
  bool ok = compiler.compile("", "test.material");
  CHECK(!ok);
  CHECK_EQ(compiler.mErrors.size(), size_t(1));
  CHECK_EQ(compiler.mErrors[0].code, uint32_t(CE_OBJECTNAMEEXPECTED));
  CHECK(compiler.mErrors[0].file == "test.material");

  // 缺对象名的左花括号同样报错
  bool ok2 = compiler.compile("{ diffuse 1 1 1 }", "test.material");
  CHECK(!ok2);
  CHECK_EQ(compiler.mErrors.size(), size_t(1));

  // 合法脚本(简化判定:非空且不以 { 开头)
  bool ok3 = compiler.compile("MyMaterial { technique { pass { } } }", "test.material");
  CHECK(ok3);
  CHECK_EQ(compiler.mErrors.size(), size_t(0));

  // 监听器:preConversion 先于 postConversion 被调用
  RecordingListener rec;
  compiler.setListener(&rec);
  compiler.compile("MyMaterial {}", "test.material");
  CHECK_EQ(rec.calls.size(), size_t(2));
  CHECK(rec.calls[0] == "preConversion");
  CHECK(rec.calls[1] == "postConversion");

  // postConversion 返回 false → 提早退出,翻译阶段被跳过(cpp 356-357)
  VetoListener veto;
  compiler.setListener(&veto);
  bool ok4 = compiler.compile("MyMaterial {}", "test.material");
  CHECK(ok4);
  CHECK(!compiler.mTranslated);

  // 每次 compile 开始前清空错误列表(cpp 337)
  compiler.setListener(nullptr);
  compiler.compile("", "test.material");
  compiler.compile("Ok { }", "test.material");
  CHECK_EQ(compiler.mErrors.size(), size_t(0));

  // 自定义词 ID:从 1001 开始递增,重复注册返回同一 ID
  uint32_t id1 = compiler.registerCustomWordId("my_keyword");
  uint32_t id2 = compiler.registerCustomWordId("my_keyword");
  uint32_t id3 = compiler.registerCustomWordId("another_keyword");
  CHECK_EQ(id1, uint32_t(1001));
  CHECK_EQ(id2, id1);
  CHECK_EQ(id3, uint32_t(1002));
  CHECK_EQ(compiler.mIds.size(), size_t(2));

  return lab::report("4.1 脚本编译器");
}

本机实测(Apple clang 16,clang++ -std=c++20 -Wall):编译通过(零警告),断言 18/18 通过。

小结

  • 编译流水线五段:preConversion → convertToAST → processImports/processObjects/processVariables → postConversion+翻译。
  • 错误以 (file, line, code, msg) 四元组收集,每次编译前清空。
  • ScriptCompilerListener::postConversion 返回 false 可跳过翻译阶段提前退出。
  • registerCustomWordId 从 mLargestRegisteredWordId 起分配,自定义词 ID 大于内建词。
  • 内建关键词在 initWordMap() 占 ID 段,翻译器靠数值 ID 做 switch 分发。

阅读导航:上一节:3.3 编解码器 · 下一节:4.2 材质脚本解析 。

继续阅读

探索更多技术文章

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

全部文章 返回首页

「books」更多文章

  1. 《大规模分布式计算深入解析》15.3 落地:从 Neo4j 到自研图引擎
  2. 《大规模分布式计算深入解析·图计算与图数据库内核》 · 目录与学习路径(45 篇)
  3. 《大规模分布式计算深入解析》15.2 十一卷主线:从切分到图