《OGRE 3D 渲染引擎原理与架构》10.3 纹理硬件加载

纹理硬件加载由 _loadImages、createInternalResources 与 getBuffer 三环组成:_loadImages 从图像取尺寸/格式并 clamp mip,createInternalResources 用门闩保护并调后端纯虚实现建 GPU 表面,getBuffer 按 face*(mip+1)+mip 索引表面表。TextureManager::createOrRetrieve 先查后建。lab 复现整条链路。

10.3 纹理硬件加载

前两节讲了「采样状态」,这节讲「纹理数据怎么进显存」。Texture 是 Resource 的子类,加载路径的骨架由 OgreTexture.cpp 的三个函数构成:_loadImages 解析输入、createInternalResources 建 GPU 表面、getBuffer 按 (face, mip) 取表面。上层的 TextureManager::createOrRetrieve 负责「已有就复用、没有才新建」。

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

helio 四卷的纹理创建是「CPU 图片 → VkImage + 上传」一条线性路径;OGRE 的 Texture 把「资源生命周期」与「GPU 表面创建」分离:_loadImages 只做解析与决策,真正建表面是各后端实现的纯虚 createInternalResourcesImpl。这是资源管理与后端差异解耦的典型。

Texture:尺寸、格式与 mip 的状态

Texture 的尺寸/格式成员是加载链路的输入:

// OgreMain/include/OgreTexture.h:Texture 保护成员(v14.6.3 源码摘录,已删减)
    protected:
        uint32 mHeight;
        uint32 mWidth;
        uint32 mDepth;

        uint32 mNumRequestedMipmaps;
        uint32 mNumMipmaps;

        float mGamma;
        uint mFSAA;

        PixelFormat mFormat;
        int mUsage; /// Bit field, so this can't be TextureUsage

        PixelFormat mSrcFormat;
        uint32 mSrcWidth, mSrcHeight, mSrcDepth;

        bool mTreatLuminanceAsAlpha;
        bool mInternalResourcesCreated;
        bool mMipmapsHardwareGenerated;
        bool mHwGamma;

        String mFSAAHint;

        /// Vector of pointers to subsurfaces
        typedef std::vector<HardwarePixelBufferSharedPtr> SurfaceList;
        SurfaceList mSurfaceList;

注意 mSrcWidth 与 mWidth 并存:mSrc* 是原始输入尺寸,m* 是实际 GPU 尺寸(硬件可能要求不同)。mSurfaceList 就是「每 face 每 mip 一块显存表面」的扁表,getBuffer 负责索引。

_loadImages:输入解析与决策

_loadImages 是 loadImpl 调用的内部方法。它把输入图像的信息灌进纹理状态,并做两处关键决策——格式与 mip 数:

// OgreMain/src/OgreTexture.cpp:Texture::_loadImages(v14.6.3 源码摘录,已删减)
    void Texture::_loadImages( const ConstImagePtrList& images )
    {
        OgreAssert(!images.empty(), "Cannot load empty vector of images");

        // Set desired texture size and properties from images[0]
        mSrcWidth = mWidth = images[0]->getWidth();
        mSrcHeight = mHeight = images[0]->getHeight();
        mSrcDepth = mDepth = images[0]->getDepth();
        mSrcFormat = images[0]->getFormat();
        ...
        if (mDesiredFormat != PF_UNKNOWN)
        {
            // If have desired format, use it
            mFormat = mDesiredFormat;
        }
        else
        {
            // Get the format according with desired bit depth
            mFormat = PixelUtil::getFormatForBitDepths(mSrcFormat, mDesiredIntegerBitDepth, mDesiredFloatBitDepth);
        }

        // The custom mipmaps in the image clamp the request
        uint32 imageMips = images[0]->getNumMipmaps();

        if(imageMips > 0)
        {
            mNumMipmaps = mNumRequestedMipmaps = std::min(mNumRequestedMipmaps, imageMips);
            // Disable flag for auto mip generation
            mUsage &= ~TU_AUTOMIPMAP;
        }

        // Create the texture
        createInternalResources();

两条规则值得记:期望格式优先(mDesiredFormat != PF_UNKNOWN 就用它,否则按位深换算);自定义 mip 数封顶请求数(图像自带 mip 时 mNumMipmaps = min(请求, 图像自带),并关掉自动生成)。

createInternalResources:门闩 + 纯虚实现

建 GPU 表面由 createInternalResources 统一入口,内部先 clamp 再调后端实现:

// OgreMain/src/OgreTexture.cpp:Texture::createInternalResources(v14.6.3 源码摘录,已删减)
    uint32 Texture::getMaxMipmaps() const {
        // see ARB_texture_non_power_of_two
        return Bitwise::mostSignificantBitSet(std::max(mWidth, std::max(mHeight, mDepth)));
    }
    void Texture::createInternalResources(void)
    {
        if (!mInternalResourcesCreated)
        {
            // Check requested number of mipmaps
            mNumMipmaps = std::min(mNumMipmaps, getMaxMipmaps());

            createInternalResourcesImpl();
            mInternalResourcesCreated = true;
            ...
        }
    }

mInternalResourcesCreated 门闩保证只建一次;getMaxMipmaps 用最高位的位数算出「还能对半分几次」。createInternalResourcesImpl 是纯虚(OgreTexture.h 503 行 virtual void createInternalResourcesImpl(void) = 0;),Metal/GL/D3D11 各自实现真正的 MTLTexture/GLTexture/ID3D11Texture2D 创建。

表面表由 createSurfaceList 填充,getBuffer 是它的读取端:

// OgreMain/src/OgreTexture.cpp:Texture::getBuffer(v14.6.3 源码摘录)
    const HardwarePixelBufferSharedPtr& Texture::getBuffer(size_t face, size_t mipmap)
    {
        OgreAssert(face < getNumFaces(), "out of range");
        OgreAssert(mipmap <= mNumMipmaps, "out of range");

        size_t idx = face * (mNumMipmaps + 1) + mipmap;
        assert(idx < mSurfaceList.size());
        return mSurfaceList[idx];
    }

索引公式 face * (mNumMipmaps + 1) + mipmap 把二维 (face, mip) 压成一维下标——因为每个 face 有 mNumMipmaps+1 级(含基础级)表面。

createOrRetrieve:先查后建

TextureManager 在 v14.6.3 里的 API 是 createOrRetrieve(不是老版本的名字):

// OgreMain/src/OgreTextureManager.cpp:TextureManager::createOrRetrieve(v14.6.3 源码摘录,已删减)
    TextureManager::ResourceCreateOrRetrieveResult TextureManager::createOrRetrieve(
            const String &name, const String& group, bool isManual, ManualResourceLoader* loader,
            const NameValuePairList* createParams, TextureType texType, int numMipmaps, Real gamma,
            bool isAlpha, PixelFormat desiredFormat, bool hwGamma)
    {
        ResourceCreateOrRetrieveResult res =
            Ogre::ResourceManager::createOrRetrieve(name, group, isManual, loader, createParams);
        // Was it created?
        if(res.second)
        {
            TexturePtr tex = static_pointer_cast<Texture>(res.first);
            tex->setTextureType(texType);
            tex->setNumMipmaps((numMipmaps == MIP_DEFAULT)? mDefaultNumMipmaps :
                static_cast<uint32>(numMipmaps));
            tex->setGamma(gamma);
            ...
            tex->setFormat(desiredFormat);
            tex->setHardwareGammaEnabled(hwGamma);
        }
        return res;
    }

res.second 是「是否新创建」标记。新建时才把 texType/numMipmaps/gamma/desiredFormat/hwGamma 这些参数写进纹理;命中缓存时原样返回旧对象。load 在此基础上加一句 tex->load():

// OgreMain/src/OgreTextureManager.cpp:TextureManager::load(v14.6.3 源码摘录,已删减)
    TexturePtr TextureManager::load(const String& name, const String& group, TextureType texType,
                                    int numMipmaps, Real gamma, bool isAlpha, PixelFormat desiredFormat,
                                    bool hwGamma)
    {
        auto res = createOrRetrieve(name, group, false, 0, 0, texType, numMipmaps, gamma, isAlpha,
                                    desiredFormat, hwGamma);
        TexturePtr tex = static_pointer_cast<Texture>(res.first);
        tex->load();
        return tex;
    }

Texture::loadImpl 还有个分支值得注意:若 mUsage & TU_RENDERTARGET(这是渲染目标纹理),直接 createInternalResources 返回,不读任何图像——RT 纹理没有源文件。

从 CPU 像素到可采样纹理

加载路径要确定尺寸、格式、mip 数量和目标面。后端内部资源创建后,逐面或逐 mip 取得像素缓冲并上传。纹理对象的生命周期与使用它的纹理单元、采样器状态相连。

用带行间距的图像和显式格式观察复制行为。对不支持的格式,记录后端转换、回退或失败,避免直接从文件扩展名推断 GPU 内存格式。

源码定位

  • OgreMain/include/OgreTexture.h :class _OgreExport Texture : public Resource(138)、setWidth/setHeight(264-268)、getNumFaces(394)、getBuffer 声明(414)、保护成员(463-491)、createInternalResourcesImpl(void) = 0(503)
  • OgreMain/src/OgreTexture.cpp :_loadImages(164-202)、getMaxMipmaps(312-315)、createInternalResources(316-336)、createSurfaceList(355-378)、getBuffer(409-417)、loadImpl(538-561)
  • OgreMain/include/OgreTextureManager.h :class _OgreExport TextureManager : public ResourceManager, public Singleton<TextureManager>(60)、createOrRetrieve 声明(111-116)、load 声明(154-156)
  • OgreMain/src/OgreTextureManager.cpp :createOrRetrieve(93-115)、load(128-137)

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

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

下面用纯 C++ 复现纹理硬件加载链路。它与 src/10-3-texture-hardware-load.cpp 逐字节一致:

// file: src/10-3-texture-hardware-load.cpp
// tier: L1
// verify: clang++ -std=c++20 -I. src/10-3-texture-hardware-load.cpp -o bin/10-3-texture-hardware-load && ./bin/10-3-texture-hardware-load
//
// 复现纹理硬件加载链路(对应 OgreMain/src/OgreTexture.cpp 164-202、316-336、
// 409-417 与 OgreMain/src/OgreTextureManager.cpp 93-115):
//   _loadImages 从 image[0] 取尺寸/格式,按期望格式与自定义 mip 数解析后调
//   createInternalResources;createInternalResources 用 mInternalResourcesCreated
//   门闩保护并把 mNumMipmaps clamp 到 getMaxMipmaps;getBuffer 按
//   face*(mNumMipmaps+1)+mipmap 索引 mSurfaceList;TextureManager::createOrRetrieve
//   命中返回旧对象、未命中新建并设置类型/格式等默认。
// 独立最小验证,非 OGRE 源码。
#include "verify.h"

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

namespace ogre_repro {

enum PixelFormat : uint32_t { PF_UNKNOWN, PF_R8G8B8, PF_A8R8G8B8, PF_DXT1 };
enum TextureType : uint8_t { TEX_TYPE_2D, TEX_TYPE_CUBE_MAP };

// 简化磁盘加载出的 Image
struct Image {
  uint32_t width = 0;
  uint32_t height = 0;
  uint32_t depth = 1;
  PixelFormat format = PF_UNKNOWN;
  uint32_t numMipmaps = 0;  // 0 = 无自定义 mip
};

// 简化 GPU 像素缓冲(后端创建的一块显存表面)
struct HardwarePixelBuffer {
  uint32_t width = 0;
  uint32_t height = 0;
  PixelFormat format = PF_UNKNOWN;
};

// 对应 Bitwise::mostSignificantBitSet
static uint32_t msb(uint32_t v) {
  uint32_t r = 0;
  while (v > 1) {
    v >>= 1;
    ++r;
  }
  return r;
}

// 对应 Texture(OgreTexture.h 138-544)的关键子集
class Texture {
 public:
  Texture() = default;
  ~Texture() { for (auto* b : mSurfaceList) delete b; }

  void setWidth(uint32_t w) { mWidth = mSrcWidth = w; }
  void setHeight(uint32_t h) { mHeight = mSrcHeight = h; }
  void setNumMipmaps(uint32_t n) { mNumRequestedMipmaps = mNumMipmaps = n; }
  void setDesiredFormat(PixelFormat f) { mDesiredFormat = f; }
  void setTextureType(TextureType t) { mTextureType = t; }
  void setUsage(uint32_t u) { mUsage = u; }

  uint32_t getNumMipmaps() const { return mNumMipmaps; }
  uint32_t getWidth() const { return mWidth; }
  uint32_t getHeight() const { return mHeight; }
  PixelFormat getFormat() const { return mFormat; }
  bool hasInternalResources() const { return mInternalResourcesCreated; }
  uint32_t getNumFaces() const { return mTextureType == TEX_TYPE_CUBE_MAP ? 6 : 1; }
  size_t surfaceCount() const { return mSurfaceList.size(); }
  uint32_t createImplCalls() const { return mCreateImplCalls; }

  // 对应 getMaxMipmaps(OgreTexture.cpp 312-315)
  uint32_t getMaxMipmaps() const {
    const uint32_t m = std::max(mWidth, std::max(mHeight, mDepth));
    return msb(m);
  }

  // 对应 _loadImages(OgreTexture.cpp 164-202)的尺寸/格式/mip 解析
  void _loadImages(const Image& img) {
    mSrcWidth = mWidth = img.width;
    mSrcHeight = mHeight = img.height;
    mSrcDepth = mDepth = img.depth;
    mSrcFormat = img.format;
    mFormat = (mDesiredFormat != PF_UNKNOWN) ? mDesiredFormat : img.format;
    if (img.numMipmaps > 0) {
      mNumMipmaps = std::min(mNumMipmaps, img.numMipmaps);
    }
    createInternalResources();
  }

  // 对应 createInternalResources(OgreTexture.cpp 316-336):门闩 + clamp + 虚实现
  void createInternalResources() {
    if (!mInternalResourcesCreated) {
      mNumMipmaps = std::min(mNumMipmaps, getMaxMipmaps());
      createInternalResourcesImpl();
      mInternalResourcesCreated = true;
    }
  }

  // 对应 getBuffer(OgreTexture.cpp 409-417)
  const HardwarePixelBuffer* getBuffer(size_t face, size_t mipmap) const {
    const size_t idx = face * (mNumMipmaps + 1) + mipmap;
    return mSurfaceList[idx];
  }

  // 对应 loadImpl:渲染目标纹理只建内部资源,不走 _loadImages
  void load(const Image* img) {
    if (mUsage & TU_RENDERTARGET) {
      createInternalResources();
      return;
    }
    if (img) _loadImages(*img);
  }

  enum { TU_AUTOMIPMAP = 1u << 0, TU_RENDERTARGET = 1u << 1 };

 protected:
  // 对应各后端 createInternalResourcesImpl:按 face*mip 建 GPU 表面
  virtual void createInternalResourcesImpl() {
    mSurfaceList.clear();
    const uint32_t faces = getNumFaces();
    for (uint32_t face = 0; face < faces; ++face) {
      uint32_t w = mWidth;
      uint32_t h = mHeight;
      for (uint32_t mip = 0; mip <= mNumMipmaps; ++mip) {
        HardwarePixelBuffer* buf = new HardwarePixelBuffer();
        buf->width = w;
        buf->height = h;
        buf->format = mFormat;
        mSurfaceList.push_back(buf);
        if (w > 1) w >>= 1;
        if (h > 1) h >>= 1;
      }
    }
    ++mCreateImplCalls;
  }

  uint32_t mWidth = 0, mHeight = 0, mDepth = 1;
  uint32_t mSrcWidth = 0, mSrcHeight = 0, mSrcDepth = 1;
  uint32_t mNumRequestedMipmaps = 0, mNumMipmaps = 0;
  PixelFormat mFormat = PF_UNKNOWN, mSrcFormat = PF_UNKNOWN, mDesiredFormat = PF_UNKNOWN;
  TextureType mTextureType = TEX_TYPE_2D;
  uint32_t mUsage = 0;
  bool mInternalResourcesCreated = false;
  uint32_t mCreateImplCalls = 0;
  std::vector<HardwarePixelBuffer*> mSurfaceList;
};

using TexturePtr = Texture*;

// 对应 TextureManager(OgreTextureManager.cpp 86-146)的关键子集
class TextureManager {
 public:
  struct CreateOrRetrieveResult {
    TexturePtr tex;
    bool created;
  };

  // 对应 createOrRetrieve:先查后建;新建时设默认
  CreateOrRetrieveResult createOrRetrieve(const std::string& name, int numMipmaps,
                                         PixelFormat desiredFormat) {
    auto it = mTextures.find(name);
    if (it != mTextures.end()) return {it->second, false};

    TexturePtr tex = new Texture();
    mTextures[name] = tex;
    tex->setNumMipmaps((numMipmaps == MIP_DEFAULT) ? mDefaultNumMipmaps
                                                   : static_cast<uint32_t>(numMipmaps));
    tex->setDesiredFormat(desiredFormat);
    return {tex, true};
  }

  // 对应 load:createOrRetrieve + tex->load()
  TexturePtr load(const std::string& name, const Image& img) {
    CreateOrRetrieveResult res = createOrRetrieve(name, MIP_DEFAULT, PF_UNKNOWN);
    res.tex->load(&img);
    return res.tex;
  }

  size_t size() const { return mTextures.size(); }

  enum { MIP_DEFAULT = -1 };
  uint32_t mDefaultNumMipmaps = 5;

 private:
  std::map<std::string, TexturePtr> mTextures;
};

}  // namespace ogre_repro

int main() {
  using namespace ogre_repro;

  TextureManager tm;

  // 新纹理:createOrRetrieve 返回 created=true 并按默认 mip 数设置
  TextureManager::CreateOrRetrieveResult res = tm.createOrRetrieve("wall", TextureManager::MIP_DEFAULT, PF_UNKNOWN);
  CHECK(res.created);
  CHECK(res.tex->getNumMipmaps() == 5);  // 管理器默认 mip 数

  // 同名再取:命中缓存 created=false
  TextureManager::CreateOrRetrieveResult res2 = tm.createOrRetrieve("wall", TextureManager::MIP_DEFAULT, PF_UNKNOWN);
  CHECK(!res2.created);
  CHECK(res2.tex == res.tex);

  // 加载 64x64、带 3 级自定义 mip 的图:mip 被 clamp 到 min(5,3)=3
  Image img;
  img.width = 64;
  img.height = 64;
  img.format = PF_R8G8B8;
  img.numMipmaps = 3;
  TexturePtr wall = tm.load("wall", img);
  CHECK(wall == res.tex);              // load 复用同一对象
  CHECK(wall->getWidth() == 64);
  CHECK(wall->getHeight() == 64);
  CHECK(wall->getFormat() == PF_R8G8B8);
  CHECK(wall->getNumMipmaps() == 3);   // 自定义 mip clamp 请求 mip
  CHECK(wall->hasInternalResources());

  // getMaxMipmaps:64x64 最多再分 6 次
  CHECK(wall->getMaxMipmaps() == 6);

  // getBuffer 索引:face*(mip+1)+mipmap
  CHECK(wall->surfaceCount() == (3 + 1));  // 单面 4 级表面
  CHECK(wall->getBuffer(0, 0)->width == 64);
  CHECK(wall->getBuffer(0, 1)->width == 32);
  CHECK(wall->getBuffer(0, 2)->width == 16);
  CHECK(wall->getBuffer(0, 3)->width == 8);

  // createInternalResources 门闩:重复调用不重建
  uint32_t callsBefore = wall->createImplCalls();
  wall->createInternalResources();
  CHECK(wall->createImplCalls() == callsBefore);

  // 无自定义 mip 时:mip 只受 getMaxMipmaps 约束(256x256 -> 8 次)
  Image big;
  big.width = 256;
  big.height = 256;
  big.format = PF_A8R8G8B8;
  TexturePtr road = tm.load("road", big);
  CHECK(road->getNumMipmaps() == 5);  // min(默认 5, 8) = 5
  CHECK(road->getMaxMipmaps() == 8);

  // 渲染目标纹理:load 只建内部资源,不读图像
  TexturePtr rt = tm.createOrRetrieve("rt", TextureManager::MIP_DEFAULT, PF_UNKNOWN).tex;
  rt->setUsage(Texture::TU_RENDERTARGET);
  rt->setWidth(512);
  rt->setHeight(512);
  rt->load(nullptr);
  CHECK(rt->hasInternalResources());
  CHECK(rt->getFormat() == PF_UNKNOWN);  // 未解析图像格式

  return lab::report("10-3 纹理硬件加载");
}

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

小结

  • _loadImages 从 images[0] 取尺寸/格式:期望格式优先,否则按位深换算;自定义 mip 数封顶请求数。
  • createInternalResources 用 mInternalResourcesCreated 门闩保证只建一次,并把 mNumMipmaps clamp 到 getMaxMipmaps。
  • createInternalResourcesImpl 是纯虚,真正的 GPU 表面创建由 Metal/GL/D3D11 后端各自实现。
  • getBuffer(face, mip) 用 face * (mNumMipmaps + 1) + mipmap 索引 mSurfaceList 扁表。
  • TextureManager::createOrRetrieve 先查资源表:命中返回旧对象(created=false),未命中才新建并写入类型/格式等参数;load 在此基础上调用 tex->load()。

阅读导航:上一节:10.2 Sampler 采样器 · 下一节:11.1 帧缓冲抽象 。

继续阅读

探索更多技术文章

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

全部文章 返回首页

「books」更多文章

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