《OGRE 3D 渲染引擎原理与架构》7.3 示例工程结构

OGRE 示例工程三层结构:Sample 继承 InputListener/TrayListener/FrameListener,_setup 建场景、_shutdown 逆序清理;SampleSet 是带 Comparer 的 set 按标题排序;SamplePlugin 持有样例集合;SampleContext 一次跑一个样例,runSample 先关旧再开新。lab 复现排序与切换。

7.3 示例工程结构

OGRE 的 Samples/ 树每个目录是一个插件(SamplePlugin),每个插件持有一组 Sample,由 SampleContext 一次运行一个。这一节把这三个类的职责与协作拆开:样例本身、样例容器、运行上下文。

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

7.1/7.2 介绍了 Bites 的应用上下文与输入模型;SampleContext 正是 ApplicationContext 的子类。本节在其上加的是「样例」这一层:Sample 把输入回调、托盘回调、帧监听三个接口合并到一个类,SamplePlugin 用 std::set 按标题排序组织样例,SampleContext::runSample 负责切换。

样例:Sample 的合并接口与状态机

Sample 同时继承 InputListener、TrayListener 与 Ogre::FrameListener——一个样例既接收输入、也接收每帧事件。构造函数把 mInfo 的键预填默认值,这样后续 getInfo().at("Title") 不会因为键缺失而抛出:

// Samples/Common/include/Sample.h:Sample(v14.6.3 源码摘录,已删减)
    class Sample : public InputListener, public TrayListener, public Ogre::FrameListener
    {
    public:
        /*=============================================================================
        | Utility comparison structure for sorting samples using SampleSet.
        =============================================================================*/
        struct Comparer
        {
            bool operator()(const Sample* a, const Sample* b) const
            {
                return a->getInfo().at("Title") < b->getInfo().at("Title");
            }
        };

        Sample()
        {
...
            mRoot = Ogre::Root::getSingletonPtr();
            mWindow = 0;
            mSceneMgr = 0;
            mDone = true;
            mContentSetup = false;

            mCamera = 0;
            mCameraNode = 0;
            mViewport = 0;

            mContext = 0;

            // so we don't have to worry about checking if these keys exist later
            mInfo["Title"] = "Untitled";
            mInfo["Description"] = "";
            mInfo["Category"] = "Unsorted";
            mInfo["Thumbnail"] = "thumb_error.png";
            mInfo["Help"] = "";
        }
...
        /*-----------------------------------------------------------------------------
        | Retrieves custom sample info.
        -----------------------------------------------------------------------------*/
        const Ogre::NameValuePairList& getInfo() const { return mInfo; }
        Ogre::NameValuePairList& getInfo() { return mInfo; }
...
        virtual void testCapabilities(const Ogre::RenderSystemCapabilities* caps) {}
...
        virtual Ogre::StringVector getRequiredPlugins() { return Ogre::StringVector(); }

状态由 mDone 与 mContentSetup 两个布尔驱动:_setup 建场景管理器、视口与内容,把 mContentSetup 置真、mDone 置假;_shutdown 逆序清理——先 cleanupContent(若内容已建),再清场景、卸资源、销毁场景管理器,最后把 mDone 复位:

// Samples/Common/include/Sample.h:Sample::_setup / _shutdown(v14.6.3 源码摘录,已删减)
        virtual void _setup(ApplicationContextBase* context)
        {
            mContext = context;
            mWindow = context->getRenderWindow();

            createSceneManager();
            setupView();
            setupContent();
            mContentSetup = true;

            mDone = false;
        }

        virtual void _shutdown()
        {
            Ogre::ControllerManager::getSingleton().clearControllers();

            if (mContentSetup)
                cleanupContent();
            if (mSceneMgr)
                mSceneMgr->clearScene();
            mContentSetup = false;

            unloadResources();
            if (mSceneMgr) 
            {
...
                mRoot->destroySceneManager(mSceneMgr);              
            }
            mSceneMgr = 0;

            mDone = true;
        }

覆写点从 createSceneManager(默认建通用 SceneManager)到 setupView、setupContent、cleanupContent、unloadResources,子类按需覆写。Comparer 是 getInfo().at("Title") 的字典序比较——它被 SampleSet 的模板参数使用。

容器:SampleSet 与 SamplePlugin

SampleSet 就是 std::set<Sample*, Sample::Comparer>,所以插入自动按标题排序且天然去重。SamplePlugin 继承 Ogre::Plugin,addSample 插入集合、getSamples 返回整个集合:

// Samples/Common/include/Sample.h:SampleSet(v14.6.3 源码摘录,已删减)
    typedef std::set<Sample*, Sample::Comparer> SampleSet;
// Samples/Common/include/SamplePlugin.h:SamplePlugin(v14.6.3 源码摘录,已删减)
    class _OgreSampleExport SamplePlugin : public Ogre::Plugin
    {
    public:

        SamplePlugin(const Ogre::String& name)
        : mName(name)
        {
        }

        const Ogre::String& getName() const override
        {
            return mName;
        }
        
        void install() override {}
        void uninstall() override {}
        void initialise() override {}
        void shutdown() override {}

        /*-----------------------------------------------------------------------------
        | Adds a sample to the queue.
        -----------------------------------------------------------------------------*/
        void addSample(Sample* s)
        {
            mSamples.insert(s);
        }

        /*-----------------------------------------------------------------------------
        | Retrieves the queue of samples.
        -----------------------------------------------------------------------------*/
        const SampleSet& getSamples()
        {
            return mSamples;
        }

    protected:

        Ogre::String mName;
        SampleSet mSamples;
    };

DefaultSamplesPlugin 等各示例插件就通过 addSample(new XxxSample) 逐个注册。安装/卸载钩子留空,因为样例没有需要特殊处理的安装期资源。

运行:SampleContext::runSample 与 go

SampleContext 继承 ApplicationContext(拿到窗口/资源/渲染循环)与 InputListener(转发全局输入)。runSample 是先关后开的两步:当前样例 _shutdown,新样例先查必需插件与能力再 _setup;样例切走时 removeAllViewports 清掉旧视口:

// Samples/Common/include/SampleContext.h:SampleContext::runSample(v14.6.3 源码摘录,已删减)
        virtual void runSample(Sample* s)
        {
            Ogre::Profiler* prof = Ogre::Profiler::getSingletonPtr();
            if (prof)
                prof->setEnabled(false);

            if (mCurrentSample)
            {
                mCurrentSample->_shutdown();    // quit current sample
                mSamplePaused = false;          // don't pause the next sample
            }

            mWindow->removeAllViewports();                  // wipe viewports
            mWindow->resetStatistics();

            if (s)
            {
                // retrieve sample's required plugins and currently installed plugins
                for (const auto& p : s->getRequiredPlugins())
                {
                    bool found = false;
                    // try to find the required plugin in the current installed plugins
                    for (const auto *i : mRoot->getInstalledPlugins())
                    {
                        if (i->getName() == p)
                        {
                            found = true;
                            break;
                        }
                    }
                    if (!found)  // throw an exception if a plugin is not found
                    {
                        OGRE_EXCEPT(Ogre::Exception::ERR_NOT_IMPLEMENTED, "Sample requires plugin: " + p);
                    }
                }

                // test system capabilities against sample requirements
                s->testCapabilities(mRoot->getRenderSystem()->getCapabilities());
                s->_setup(this);   // start new sample
            }

            if (prof)
                prof->setEnabled(true);

            mCurrentSample = s;
        }

go 是上下文整个生命周期的封装:外层 while (!mLastRun) 支持重配置后重跑;每次迭代先假设这是最后一轮,initApp() 起来后恢复上次样例(非首轮)或启动初始样例(首轮),进渲染循环,closeApp(),最后翻转 mFirstRun:

// Samples/Common/include/SampleContext.h:SampleContext::go(v14.6.3 源码摘录,已删减)
        virtual void go(Sample* initialSample = 0)
        {
...
            while (!mLastRun)
            {
                mLastRun = true;  // assume this is our last run

                initApp();

#if OGRE_PLATFORM != OGRE_PLATFORM_ANDROID
                // restore the last sample if there was one or, if not, start initial sample
                if (!mFirstRun) recoverLastSample();
                else if (initialSample) runSample(initialSample);
#endif

                loadStartUpSample();

                if (mRoot->getRenderSystem() != NULL)
                {
                    mRoot->startRendering();    // start the render loop
                }

                closeApp();

                mFirstRun = false;
            }
...
        }

loadStartUpSample() 是子类钩子(如 SdkSample 展示用的示例浏览器),recoverLastSample() 在渲染系统重配置后恢复上次样例。整棵示例树的分工因此是:SamplePlugin 收集、SampleSet 排序、SampleContext 运行、Sample 表现。

源码定位

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

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

下面复现样例工程结构:Sample 的状态机(_setup/_shutdown 阶段顺序与布尔翻转)、SampleSet 按标题排序与去重、SamplePlugin 的 addSample/getSamples、SampleContext::runSample 先关后开与 go 的单次循环。它与 src/ogre-ext-07-3-sample-structure.cpp 逐字节一致:

// file: src/ogre-ext-07-3-sample-structure.cpp
// tier: L1
// verify: clang++ -std=c++20 -I. src/ogre-ext-07-3-sample-structure.cpp -o bin/ogre-ext-07-3-sample-structure && ./bin/ogre-ext-07-3-sample-structure
//
// 复现 Sample / SampleSet / SamplePlugin / SampleContext 的示例工程结构
// (对应 Sample.h 56-202、292、SamplePlugin.h 54-93、SampleContext.h 43-147):
//   Sample 默认 Title="Untitled";_setup 依次 createSceneManager/setupView/setupContent,
//   mContentSetup=true、mDone=false;_shutdown 逆序 cleanupContent 并把 mDone 复位;
//   SampleSet 是 std::set<Sample*, Comparer>,按 Title 排序;
//   SamplePlugin 用 set 持有样例(addSample 去重、getSamples 取出);
//   SampleContext::runSample 先 _shutdown 旧样例再 _setup 新样例,go 封装整个生命周期。
// 独立最小验证,非 OGRE 源码。
#include "verify.h"

#include <cstdint>
#include <set>
#include <string>
#include <vector>

namespace ogre_repro {

// 对应 Sample(Sample.h 56-202)
class Sample {
 public:
  Sample() { mInfoTitle = "Untitled"; mDone = true; mContentSetup = false; }
  virtual ~Sample() = default;
  const std::string& getTitle() const { return mInfoTitle; }
  void setTitle(const std::string& t) { mInfoTitle = t; }
  bool isDone() const { return mDone; }
  bool isContentSetup() const { return mContentSetup; }
  const std::vector<int>& getPhaseOrder() const { return mPhaseOrder; }

  // _setup(Sample.h 164-175)
  void _setup() {
    createSceneManager();
    setupView();
    setupContent();
    mContentSetup = true;
    mDone = false;
  }
  // _shutdown(Sample.h 180-202)
  void _shutdown() {
    if (mContentSetup) cleanupContent();
    mContentSetup = false;
    mDone = true;
  }

 protected:
  virtual void createSceneManager() { mPhaseOrder.push_back(1); }
  virtual void setupView() { mPhaseOrder.push_back(2); }
  virtual void setupContent() { mPhaseOrder.push_back(3); }
  virtual void cleanupContent() { mPhaseOrder.push_back(4); }

  std::string mInfoTitle;  // 对应 mInfo["Title"]
  bool mDone;              // flag to mark the end of the sample
  bool mContentSetup;      // whether or not scene was created
  std::vector<int> mPhaseOrder;
};

// Comparer(Sample.h 62-68):按 Title 升序
struct Comparer {
  bool operator()(const Sample* a, const Sample* b) const {
    return a->getTitle() < b->getTitle();
  }
};

// SampleSet(Sample.h 292)
typedef std::set<Sample*, Comparer> SampleSet;

// 对应 SamplePlugin(SamplePlugin.h 54-93)
class SamplePlugin {
 public:
  explicit SamplePlugin(const std::string& name) : mName(name) {}
  const std::string& getName() const { return mName; }
  void addSample(Sample* s) { mSamples.insert(s); }
  size_t sampleCount() const { return mSamples.size(); }
  const SampleSet& getSamples() const { return mSamples; }

 private:
  std::string mName;
  SampleSet mSamples;  // 对应 mSamples
};

// 对应 SampleContext(SampleContext.h 43-147)
class SampleContext {
 public:
  SampleContext() : mCurrentSample(nullptr) {}
  Sample* getCurrentSample() { return mCurrentSample; }
  size_t runCount() const { return mRunCount; }

  // runSample(SampleContext.h 65-110)
  void runSample(Sample* s) {
    if (mCurrentSample) mCurrentSample->_shutdown();  // quit current sample
    if (s) s->_setup();                               // start new sample
    mCurrentSample = s;
  }
  // go(SampleContext.h 115-147 简化)
  void go(Sample* initialSample) {
    while (!mLastRun) {
      mLastRun = true;  // assume this is our last run
      initApp();
      if (!mFirstRun) { /* recoverLastSample 省略 */ }
      else if (initialSample) runSample(initialSample);
      startRendering();
      closeApp();
      mFirstRun = false;
    }
  }

 private:
  void initApp() { mRunCount++; }
  void startRendering() { mRendered = true; }
  void closeApp() { mClosed = true; }

  Sample* mCurrentSample;
  bool mLastRun = false;
  bool mFirstRun = true;
  bool mRendered = false;
  bool mClosed = false;
  size_t mRunCount = 0;
};

}  // namespace ogre_repro

int main() {
  using namespace ogre_repro;

  // Sample 默认状态:Title="Untitled"、mDone、未 setup(Sample.h 70-94)
  Sample s;
  CHECK(s.getTitle() == "Untitled");
  CHECK(s.isDone());
  CHECK(!s.isContentSetup());

  s.setTitle("Cube");
  CHECK(s.getTitle() == "Cube");

  // _setup 按序建场景/视口/内容,翻转状态(Sample.h 164-175)
  s._setup();
  CHECK(!s.isDone());
  CHECK(s.isContentSetup());
  CHECK(s.getPhaseOrder().size() == 3);
  CHECK(s.getPhaseOrder()[0] == 1);
  CHECK(s.getPhaseOrder()[1] == 2);
  CHECK(s.getPhaseOrder()[2] == 3);

  // _shutdown 逆序清理并把 mDone 复位(Sample.h 180-202)
  s._shutdown();
  CHECK(s.isDone());
  CHECK(!s.isContentSetup());
  CHECK(s.getPhaseOrder()[3] == 4);  // cleanupContent 被调用

  // SampleSet 按 Title 排序:乱序插入、升序迭代(Sample.h 62-68、292)
  Sample a, b, c;
  a.setTitle("Tessellation");
  b.setTitle("Animation");
  c.setTitle("BumpMapping");
  SampleSet set;
  set.insert(&a);
  set.insert(&b);
  set.insert(&c);
  CHECK(set.size() == 3);
  std::string joined;
  for (const Sample* p : set) { if (!joined.empty()) joined += ","; joined += p->getTitle(); }
  CHECK(joined == "Animation,BumpMapping,Tessellation");

  // SamplePlugin:addSample 去重,getSamples 原样返回(SamplePlugin.h 76-87)
  SamplePlugin plugin("Samples");
  plugin.addSample(&a);
  plugin.addSample(&b);
  plugin.addSample(&c);
  plugin.addSample(&c);  // set 去重
  CHECK(plugin.getName() == "Samples");
  CHECK(plugin.sampleCount() == 3);
  CHECK(plugin.getSamples().size() == 3);

  // runSample:先关旧样例再开新样例(SampleContext.h 65-110)
  SampleContext ctx;
  Sample first, second;
  first.setTitle("First");
  second.setTitle("Second");
  ctx.runSample(&first);
  CHECK(ctx.getCurrentSample() == &first);
  CHECK(!first.isDone());       // 已启动
  ctx.runSample(&second);
  CHECK(ctx.getCurrentSample() == &second);
  CHECK(first.isDone());        // 旧样例已关闭
  CHECK(!second.isDone());      // 新样例已启动
  ctx.runSample(nullptr);       // 关闭当前样例
  CHECK(ctx.getCurrentSample() == nullptr);
  CHECK(second.isDone());

  // go:单次循环 initApp 恰好一次,mFirstRun 翻转(SampleContext.h 115-147)
  SampleContext loop;
  Sample start;
  start.setTitle("Start");
  loop.go(&start);
  CHECK(loop.runCount() == 1);
  CHECK(loop.getCurrentSample() == &start);
  CHECK(!start.isDone());

  // 每个 sample 状态独立
  Sample p, q;
  p.setTitle("P");
  q.setTitle("Q");
  p._setup();
  CHECK(!p.isDone());
  CHECK(q.isDone());
  CHECK(q.getTitle() == "Q");

  return lab::report("07-3 示例工程结构");
}

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

小结

  • Sample 合并 InputListener、TrayListener、FrameListener 三个接口;mInfo 预填默认键。
  • _setup = 建场景/视口/内容 + 翻转布尔;_shutdown = 逆序清理 + 复位 mDone。
  • SampleSet = std::set<Sample*, Comparer>,按 Title 排序并去重。
  • SamplePlugin 继承 Ogre::Plugin,用 addSample/getSamples 持有并暴露样例集合。
  • SampleContext::runSample 先关旧样例再开新样例(含必需插件与能力检查);go 封装整个生命周期。

阅读导航:上一节:7.2 Bites 输入与主循环 · 下一节:8.1 GLES2 后端 。

继续阅读

探索更多技术文章

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

全部文章 返回首页

「books」更多文章

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