《OGRE 3D 渲染引擎原理与架构》10.1 纹理单元状态

TextureUnitState 描述材质 Pass 中一个纹理单元的完整状态:持有纹理名、内容类型、坐标集与 SamplerPtr;采样相关 setter 都经 _getLocalSampler 延迟创建本地采样器再委托,getter 直接读 mSampler。lab 用纯 C++ 复现状态成员与委托链。

10.1 纹理单元状态

从这节开始进入纹理子系统。一个 Material 的 Pass 里可以挂多个纹理单元,每个单元就是 TextureUnitState——它把「用哪张图、怎么采样、坐标怎么变换、颜色怎么混合」装进一个对象。这节先解剖它的状态成员和委托设计:为什么采样相关的 setter 都绕道 _getLocalSampler(),getter 却直接读 mSampler。

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

helio 四卷的材质系统用 Texture/SamplerDesc 两个结构装采样状态;这里看 OGRE 的 TextureUnitState:它是纹理单元的状态容器,承载的不只是采样参数,还有纹理名、动画帧、坐标集、颜色混合与纹理效果(环境映射/滚动等),与卷一 ogre-core 的 Pass 结构直接相关。

类定义:一个状态容器

OgreTextureUnitState.h 里的 TextureUnitState 注释很直白:它代表材质的一个 Pass 中单个纹理单元的状态。类开头的枚举先划定「状态」的维度:

// OgreMain/include/OgreTextureUnitState.h:TextureUnitState 类定义(v14.6.3 源码摘录,已删减)
    class _OgreExport TextureUnitState : public TextureUnitStateAlloc
    {
        friend class RenderSystem;
    public:
        /** Definition of the broad types of texture effect you can apply to a texture unit.
        */
        enum TextureEffectType
        {
            /// Generate all texture coords based on angle between camera and vertex.
            ET_ENVIRONMENT_MAP,
            /// Generate texture coords based on a frustum.
            ET_PROJECTIVE_TEXTURE,
            /// Constant u/v scrolling effect.
            ET_UVSCROLL,
            /// Constant u scrolling effect.
            ET_USCROLL,
            /// Constant u/v scrolling effect.
            ET_VSCROLL,
            /// Constant rotation.
            ET_ROTATE,
            /// More complex transform.
            ET_TRANSFORM
        };
        ...
        enum ContentType : uint8
        {
            /// The default option, this derives texture content from a texture name, loaded by
            /// ordinary means from a file or having been manually created with a given name.
            CONTENT_NAMED = 0,
            /// A shadow texture, automatically bound by engine
            CONTENT_SHADOW = 1,
            /// This option allows you to reference a texture from a compositor, and is only valid
            /// when the pass is rendered within a compositor sequence.
            CONTENT_COMPOSITOR = 2
        };

ContentType 是理解纹理单元的关键:大多数单元是 CONTENT_NAMED(按名字加载),但也有引擎自动绑定的影子纹理(CONTENT_SHADOW)和合成器引用的 CONTENT_COMPOSITOR。私有状态成员的排布本身有讲究:

// OgreMain/include/OgreTextureUnitState.h:TextureUnitState 私有状态(v14.6.3 源码摘录,已删减)
    private:
        // State
        /// The current animation frame.
        unsigned int mCurrentFrame;

        /// Duration of animation in seconds.
        Real mAnimDuration;

        int mUnorderedAccessMipLevel;

        LayerBlendModeEx mColourBlendMode;
        SceneBlendFactor mColourBlendFallbackSrc;
        SceneBlendFactor mColourBlendFallbackDest;

        LayerBlendModeEx mAlphaBlendMode;
        Real mGamma;
        float mUMod, mVMod;
        float mUScale, mVScale;
        Radian mRotate;
        mutable Matrix4 mTexModMatrix;

        /// Content type of texture (normal loaded texture, auto-texture).
        ContentType mContentType;

        mutable bool mTextureLoadFailed;
        mutable bool mRecalcTexMatrix;

        uint8 mTextureCoordSetIndex;
        ...
        // Complex members (those that can't be copied using memcpy) are at the end to 
        // allow for fast copying of the basic members.
        mutable std::vector<TexturePtr> mFramePtrs; // must at least contain a single nullptr
        SamplerPtr mSampler;
        String mName;               ///< Optional name for the TUS.
        EffectMap mEffects;
        ...
        Pass* mParent;
        ControllerFloat* mAnimController;

注意注释里的设计意图:基本标量成员在前(可以直接 memcpy 快拷),复杂成员(向量、共享指针、字符串)放末尾。mFramePtrs 是动画帧的纹理指针数组,mEffects 是纹理效果表(std::multimap<TextureEffectType, TextureEffect>),mSampler 是采样器共享指针——采样参数本身不直接存进 TextureUnitState,而是存进 Sampler。

委托设计:setter 绕道,getter 直读

TextureUnitState 对采样参数的暴露方式不是「自己存一份」,而是全部委托给 mSampler。看方法签名就能发现规律:

// OgreMain/include/OgreTextureUnitState.h:TextureUnitState 采样接口(v14.6.3 源码摘录,已删减)
        /// get the associated sampler
        const SamplerPtr& getSampler() const { return mSampler; }
        void setSampler(const SamplerPtr& sampler)
        {
            OgreAssert(sampler, "sampler must not be NULL");
            mSampler = sampler;
        }
        ...
        void setTextureAddressingMode( Ogre::TextureAddressingMode tam) { _getLocalSampler()->setAddressingMode(tam); }
        ...
        void setTextureBorderColour(const ColourValue& colour) { _getLocalSampler()->setBorderColour(colour); }
        ...
        void setTextureFiltering(TextureFilterOptions filterType)
        {
            _getLocalSampler()->setFiltering(filterType);
        }
        ...
        void setTextureCompareEnabled(bool enabled) { _getLocalSampler()->setCompareEnabled(enabled); }
        ...
        void setTextureAnisotropy(unsigned int maxAniso) { _getLocalSampler()->setAnisotropy(maxAniso); }
        ...
        unsigned int getTextureAnisotropy() const { return mSampler->getAnisotropy(); }

两条线:

  • setter 一律 _getLocalSampler()->方法(...)——_getLocalSampler 返回本单元专属采样器(没有就造一个),改的是单元自己的采样器;
  • getter 一律 mSampler->方法()——直接读,不修改。

为什么这样?OGRE 允许「共享采样器」:多个 TextureUnitState 可以 setSampler 指向同一个 SamplerPtr,减少重复状态。但共享意味着「改一个影响所有」不可控,所以 setter 走 _getLocalSampler 保证写操作一定落在本单元专属采样器上,读操作才可能命中共享对象。

_getLocalSampler 的签名也有讲究——它返回 const SamplerPtr& 引用而非指针值,避免拷贝计数:

// OgreMain/include/OgreTextureUnitState.h:_getLocalSampler 声明(v14.6.3 源码摘录)
        /// return a sampler local to this TUS instead of the shared global one
        const SamplerPtr& _getLocalSampler();

纹理名、动画帧与坐标集

除了采样参数,TextureUnitState 还管「用哪张图」。setTextureName 存名字,setAnimatedTextureName 则进入多帧动画模式:

// OgreMain/include/OgreTextureUnitState.h:动画纹理接口(v14.6.3 源码摘录,已删减)
        void setAnimatedTextureName( const String& name, size_t numFrames, Real duration = 0 );
        ...
        void setCurrentFrame( unsigned int frameNumber );
        ...
        unsigned int getNumFrames(void) const;

配合 mCurrentFrame 与 mFramePtrs:动画纹理就是一组同尺寸图片(如 flame_0.jpg、flame_1.jpg……),setCurrentFrame 切换当前帧。坐标集用 mTextureCoordSetIndex 记录——一个网格可以有多套 UV,这套材质用第几套由它决定:

// OgreMain/include/OgreTextureUnitState.h:坐标集接口(v14.6.3 源码摘录,已删减)
        uint8 getTextureCoordSet(void) const;
        void setTextureCoordSet(uint8 set);

源码定位

  • OgreMain/include/OgreTextureUnitState.h :class _OgreExport TextureUnitState : public TextureUnitStateAlloc(243)、enum TextureEffectType(249-266)、enum ContentType(477-487)、私有状态成员(1069-1121)、getSampler/setSampler(642-647)、_getLocalSampler(1066)

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

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

下面用纯 C++ 复现 TextureUnitState 的状态成员与对 Sampler 的委托。它与 src/10-1-texture-unit.cpp 逐字节一致:

// file: src/10-1-texture-unit.cpp
// tier: L1
// verify: clang++ -std=c++20 -I. src/10-1-texture-unit.cpp -o bin/10-1-texture-unit && ./bin/10-1-texture-unit
//
// 复现 TextureUnitState 的状态成员与对 Sampler 的委托(对应
// OgreMain/include/OgreTextureUnitState.h 243-1143):
//   TextureUnitState 持有 mSampler(SamplerPtr)、mContentType、mTextureCoordSetIndex 等状态;
//   采样参数 setter(寻址/过滤/各向异性)经 _getLocalSampler() 延迟创建并委托给 Sampler;
//   getter 直接读 mSampler;setAnimatedTextureName/setCurrentFrame 维护动画帧状态。
// 独立最小验证,非 OGRE 源码。
#include "verify.h"

#include <cstdint>
#include <memory>
#include <string>

namespace ogre_repro {

// 对应 Sampler 类(OgreTextureUnitState.h 54-226)的关键子集
class Sampler {
 public:
  enum TextureAddressingMode { TAM_WRAP, TAM_MIRROR, TAM_CLAMP, TAM_BORDER };
  enum FilterType { FT_MIN, FT_MAG, FT_MIP };
  enum FilterOptions { FO_NONE, FO_POINT, FO_LINEAR, FO_ANISOTROPIC };

  // 对应 Sampler::UVWAddressingMode
  struct UVWAddressingMode {
    TextureAddressingMode u, v, w;
  };

  const UVWAddressingMode& getAddressingMode() const { return mAddressMode; }
  void setAddressingMode(TextureAddressingMode tam) { setAddressingMode({tam, tam, tam}); }
  void setAddressingMode(const UVWAddressingMode& uvw) {
    mAddressMode = uvw;
    mDirty = true;
  }
  void setFiltering(FilterType ftype, FilterOptions opts) {
    if (ftype == FT_MIN) mMinFilter = opts;
    else if (ftype == FT_MAG) mMagFilter = opts;
    else mMinFilter = opts, mMipFilter = opts;  // 简化:FT_MIP 同时写两个
    mDirty = true;
  }
  FilterOptions getFiltering(FilterType ftype) const {
    if (ftype == FT_MIN) return mMinFilter;
    if (ftype == FT_MAG) return mMagFilter;
    return mMipFilter;
  }
  void setAnisotropy(unsigned int maxAniso) {
    mMaxAniso = maxAniso;
    mDirty = true;
  }
  unsigned int getAnisotropy() const { return mMaxAniso; }

  bool isDirty() const { return mDirty; }

 private:
  UVWAddressingMode mAddressMode{TAM_WRAP, TAM_WRAP, TAM_WRAP};
  FilterOptions mMinFilter{FO_LINEAR};
  FilterOptions mMagFilter{FO_LINEAR};
  FilterOptions mMipFilter{FO_POINT};
  unsigned int mMaxAniso{1};
  bool mDirty{false};
};

using SamplerPtr = std::shared_ptr<Sampler>;

// 简化的 Pass 父对象,仅用于让 TextureUnitState 有 parent
class Pass {
 public:
  std::string mName;
};

// 对应 TextureUnitState(OgreTextureUnitState.h 243-1143)的关键子集
class TextureUnitState {
 public:
  enum ContentType : uint8_t {
    CONTENT_NAMED = 0,
    CONTENT_SHADOW = 1,
    CONTENT_COMPOSITOR = 2,
  };

  explicit TextureUnitState(Pass* parent) : mParent(parent) {}

  void setTextureName(const std::string& name) { mTextureName = name; }
  const std::string& getTextureName() const { return mTextureName; }

  void setContentType(ContentType ct) { mContentType = ct; }
  ContentType getContentType() const { return mContentType; }

  void setTextureCoordSet(uint8_t set) { mTextureCoordSetIndex = set; }
  uint8_t getTextureCoordSet() const { return mTextureCoordSetIndex; }

  // 对应 getSampler/setSampler
  const SamplerPtr& getSampler() const { return mSampler; }
  void setSampler(const SamplerPtr& sampler) { mSampler = sampler; }

  // 对应 setTextureAddressingMode:经 _getLocalSampler 委托
  void setTextureAddressingMode(Sampler::TextureAddressingMode tam) {
    _getLocalSampler()->setAddressingMode(tam);
  }
  void setTextureFiltering(Sampler::FilterType ftype, Sampler::FilterOptions opts) {
    _getLocalSampler()->setFiltering(ftype, opts);
  }
  void setTextureAnisotropy(unsigned int maxAniso) {
    _getLocalSampler()->setAnisotropy(maxAniso);
  }
  unsigned int getTextureAnisotropy() const { return mSampler->getAnisotropy(); }

  // 动画帧状态
  void setAnimatedTextureName(const std::string& base, size_t numFrames, float duration = 0) {
    mBaseTextureName = base;
    mNumFrames = numFrames;
    mAnimDuration = duration;
    mCurrentFrame = 0;
  }
  size_t getNumFrames() const { return mNumFrames; }
  void setCurrentFrame(unsigned int frame) { mCurrentFrame = frame; }
  unsigned int getCurrentFrame() const { return mCurrentFrame; }

  // 对应 _getLocalSampler:本单元专属采样器
  const SamplerPtr& _getLocalSampler() {
    if (!mSampler) mSampler = std::make_shared<Sampler>();
    return mSampler;
  }

  Pass* getParent() const { return mParent; }

 private:
  std::string mTextureName;
  std::string mBaseTextureName;
  ContentType mContentType{CONTENT_NAMED};
  uint8_t mTextureCoordSetIndex{0};
  unsigned int mCurrentFrame{0};
  size_t mNumFrames{1};
  float mAnimDuration{0};
  SamplerPtr mSampler;
  Pass* mParent;
};

}  // namespace ogre_repro

int main() {
  using namespace ogre_repro;

  Pass pass;
  TextureUnitState tus(&pass);

  // 默认状态:命名纹理、纹理坐标集 0、父 Pass 已挂接
  CHECK(tus.getContentType() == TextureUnitState::CONTENT_NAMED);
  CHECK(tus.getTextureCoordSet() == 0);
  CHECK(tus.getParent() == &pass);

  // 纹理名与坐标集设置
  tus.setTextureName("brickwall.jpg");
  CHECK(tus.getTextureName() == "brickwall.jpg");
  tus.setTextureCoordSet(1);
  CHECK(tus.getTextureCoordSet() == 1);

  // 内容类型:影子纹理
  tus.setContentType(TextureUnitState::CONTENT_SHADOW);
  CHECK(tus.getContentType() == TextureUnitState::CONTENT_SHADOW);

  // 采样参数经 _getLocalSampler 延迟创建并委托
  CHECK(tus.getSampler() == nullptr);  // 未触碰采样参数时没有本地采样器
  tus.setTextureAddressingMode(Sampler::TAM_CLAMP);
  CHECK(tus.getSampler() != nullptr);
  CHECK(tus.getSampler()->getAddressingMode().u == Sampler::TAM_CLAMP);
  CHECK(tus.getSampler()->getAddressingMode().v == Sampler::TAM_CLAMP);
  CHECK(tus.getSampler()->getAddressingMode().w == Sampler::TAM_CLAMP);
  CHECK(tus.getSampler()->isDirty());

  // 过滤与各向异性同样委托
  tus.setTextureFiltering(Sampler::FT_MAG, Sampler::FO_LINEAR);
  CHECK(tus.getSampler()->getFiltering(Sampler::FT_MAG) == Sampler::FO_LINEAR);
  tus.setTextureAnisotropy(8);
  CHECK(tus.getTextureAnisotropy() == 8);

  // 共享采样器:显式 setSampler 覆盖
  SamplerPtr shared = std::make_shared<Sampler>();
  tus.setSampler(shared);
  tus.setTextureAddressingMode(Sampler::TAM_MIRROR);
  CHECK(tus.getSampler() == shared);
  CHECK(shared->getAddressingMode().u == Sampler::TAM_MIRROR);

  // 动画帧:帧数与当前帧
  tus.setAnimatedTextureName("flame.jpg", 4, 2.0f);
  CHECK(tus.getNumFrames() == 4);
  CHECK(tus.getCurrentFrame() == 0);
  tus.setCurrentFrame(2);
  CHECK(tus.getCurrentFrame() == 2);

  return lab::report("10-1 纹理单元状态");
}

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

小结

  • TextureUnitState 是材质 Pass 中单个纹理单元的状态容器:纹理名、内容类型、坐标集、动画帧、颜色混合与采样器都在这里。
  • 基本标量成员在前、复杂成员(向量/共享指针/字符串)在尾,便于 memcpy 快拷。
  • 采样参数不直接存:SamplerPtr mSampler 持有采样器,setter 经 _getLocalSampler() 延迟创建并委托,getter 直接读 mSampler。
  • ContentType 区分命名纹理、影子纹理与合成器引用三种内容来源。
  • 动画纹理用 mFramePtrs + mCurrentFrame 维护,setAnimatedTextureName/setCurrentFrame 操作之。

阅读导航:上一节:9.3 三后端对比 · 下一节:10.2 Sampler 采样器 。

继续阅读

探索更多技术文章

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

全部文章 返回首页

「books」更多文章

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