《OGRE 3D 渲染引擎原理与架构》2.2 顶点声明

VertexDeclaration 描述顶点流格式:VertexElement 记录 source/offset/type/semantic/index,addElement 追加进 mElementList,getVertexSize 按 source 累加 stride。VertexBufferBinding 用 map 把 source 绑到具体缓冲,VertexData 组合声明+绑定+vertexStart/vertexCount。lab 复现声明、stride 与绑定。

2.2 顶点声明

一个顶点是什么?位置、法线、颜色、一组 UV……OGRE 里这是运行时拼出来的:VertexDeclaration 是一张元素表,每个 VertexElement 声明「哪个缓冲的哪个偏移、是什么类型、代表什么含义」。缓冲自己不知道语义——是声明把字节解释成顶点。这一节拆开这张表。

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

卷一 7.2 从网格视角看过 VertexData;这里从渲染系统视角看:声明如何变成 stride、如何绑定缓冲、如何被驱动翻译成 VAO/InputLayout。

语义与类型:两套枚举

顶点元素有两个维度——「这个字段是什么意思」和「这个字段是什么格式」:

// OgreMain/include/OgreHardwareVertexBuffer.h:VertexElementSemantic(v14.6.3 源码摘录,已删减)
    enum VertexElementSemantic : uint8
    {
        /// Position, typically VET_FLOAT3
        VES_POSITION = 1,
        /// Blending weights
        VES_BLEND_WEIGHTS = 2,
        /// Normal, typically VET_FLOAT3
        VES_NORMAL = 4,
        /// Colour, typically VET_UBYTE4
        VES_COLOUR = 5,
        /// Texture coordinates, typically VET_FLOAT2
        VES_TEXTURE_COORDINATES = 7,
        /// Binormal (Y axis if normal is Z)
        VES_BINORMAL = 8,
        /// Tangent (X axis if normal is Z)
        VES_TANGENT = 9,
    };

VES_POSITION、VES_NORMAL、VES_COLOUR、VES_TEXTURE_COORDINATES——语义,驱动据此映射到固定功能槽位或绑定着色器输入。VES_TANGENT/VES_BINORMAL 为法线贴图服务(法线贴图的 TBN 需要切线空间)。

// OgreMain/include/OgreHardwareVertexBuffer.h:VertexElementType(v14.6.3 源码摘录,已删减)
    enum VertexElementType : uint8
    {
        VET_FLOAT1 = 0,
        VET_FLOAT2 = 1,
        VET_FLOAT3 = 2,
        VET_FLOAT4 = 3,
        VET_UBYTE4 = 9,
        VET_BYTE4_NORM = 29,   ///< signed bytes (normalized to -1..1)
        VET_UBYTE4_NORM = 30,  ///< unsigned bytes (normalized to 0..1)
        VET_SHORT2_NORM = 31,  ///< signed shorts (normalized to -1..1)
        ...
        VET_HALF2 = 37,
        VET_HALF4 = 39,
        VET_COLOUR = VET_UBYTE4_NORM,  ///< @deprecated use VET_UBYTE4_NORM
    };

格式枚举。注意 VET_COLOUR 是 VET_UBYTE4_NORM 的别名(颜色常存成归一化无符号字节);VET_HALF* 是半精度浮点,省一半内存但精度低。类型枚举同时隐含字节大小——这是 stride 计算的原料。

VertexElement:一行声明

// OgreMain/include/OgreHardwareVertexBuffer.h:VertexElement(v14.6.3 源码摘录,已删减)
    class _OgreExport VertexElement : public VertexDataAlloc
    {
    private:
        /// The offset in the buffer that this element starts at
        size_t mOffset;
        /// The source vertex buffer, as bound to an index using VertexBufferBinding
        unsigned short mSource;
        /// Index of the item, only applicable for some elements like texture coords
        unsigned short mIndex;
        /// The type of element
        VertexElementType mType;
        /// The meaning of the element
        VertexElementSemantic mSemantic;

五个字段回答五个问题:在哪个缓冲(mSource)、从哪开始(mOffset)、什么格式(mType)、什么含义(mSemantic)、第几套(mIndex,纹理坐标可以有 uv0、uv1、uv2……)。

VertexDeclaration:一张表

// OgreMain/include/OgreHardwareVertexBuffer.h:VertexDeclaration(v14.6.3 源码摘录,已删减)
    class _OgreExport VertexDeclaration : public VertexDataAlloc
    {
    public:
        /// Defines the list of vertex elements that makes up this declaration
        typedef std::list<VertexElement> VertexElementList;
    protected:
        VertexElementList mElementList;
        /** Notify derived class that it is time to invalidate cached state, such as VAO or ID3D11InputLayout */
        virtual void notifyChanged() {}

元素用 std::list 存——插入不失效迭代器,声明常被小幅增删。notifyChanged 是虚钩子:声明一变,后端缓存的 VAO / ID3D11InputLayout 作废(4.3 会看到后端怎么用这个钩子)。

addElement 的实现是纯粹的追加:

// OgreMain/src/OgreHardwareVertexBuffer.cpp:VertexDeclaration::addElement(v14.6.3 源码摘录,已删减)
    const VertexElement& VertexDeclaration::addElement(unsigned short source, 
        size_t offset, VertexElementType theType,
        VertexElementSemantic semantic, unsigned short index)
    {
        mElementList.push_back(VertexElement(source, offset, theType, semantic, index));
        notifyChanged();
        return mElementList.back();
    }

getElement(n) 不做随机访问(list 不支持),顺序遍历取第 n 个。getVertexSize(source) 是 strided 的关键:

// OgreMain/src/OgreHardwareVertexBuffer.cpp(v14.6.3 源码摘录,调整空白)
size_t VertexDeclaration::getVertexSize(unsigned short source) const
{
    size_t sz = 0;
    for (auto& e : mElementList)
    {
        if (e.getSource() == source)
        {
            sz += e.getSize();
        }
    }
    return sz;
}

遍历同 source 的所有元素,得到声明中元素大小之和。紧密布局下等于 stride。有填充时应使用绑定缓冲的 HardwareVertexBuffer::getVertexSize() 作为实际步长,并按声明的 offset 找字段。这是 GPU 从顶点流里取下一个顶点时必需的步长。

VertexBufferBinding 与 VertexData:装配

VertexBufferBinding 把 source 索引映射到具体缓冲:

// OgreMain/include/OgreHardwareVertexBuffer.h:VertexBufferBinding(v14.6.3 源码摘录,已删减)
    class _OgreExport VertexBufferBinding : public VertexDataAlloc
    {
    public:
        /// Defines the vertex buffer bindings used as source for vertex declarations
        typedef std::map<unsigned short, HardwareVertexBufferSharedPtr> VertexBufferBindingMap;
    private:
        VertexBufferBindingMap mBindingMap;
        mutable unsigned short mHighIndex;
    ...
        void setBinding(unsigned short index, const HardwareVertexBufferSharedPtr& buffer);
        size_t getBufferCount(void) const { return mBindingMap.size(); }
        unsigned short getNextIndex(void) const { return mHighIndex++; }

setBinding(source, buffer) 把 source 索引绑到一块真缓冲;getNextIndex() 返回「已用最大索引 + 1」,帮助无缝隙地分配下一个 source。

VertexData 把全部组装起来:

// OgreMain/include/OgreVertexIndexData.h:VertexData(v14.6.3 源码摘录,已删减)
        VertexDeclaration* vertexDeclaration;
        VertexBufferBinding* vertexBufferBinding;
        /// The position in the bound buffers to start reading vertex data from. This allows you to use a single buffer for many different renderables.
        uint32 vertexStart;
        /// The number of vertices to process in this particular rendering group
        uint32 vertexCount;

vertexStart/vertexCount 让一块缓冲被多个 renderable 共享——只取一段来画(配合 2.3 的索引切片)。整个「顶点流」的配方是:声明(怎么解释)× 绑定(数据在哪)× 区间(画哪段)。

声明与实际顶点寻址

flowchart LR
  VD["VertexData"] --> D["VertexDeclaration"]
  VD --> B["VertexBufferBinding"]
  D --> E["VertexElement 的 source、offset、type"]
  B -->|"source 选中缓冲"| V["HardwareVertexBuffer"]
  V --> S["实际 vertexSize 步长"]
  S --> P["顶点索引乘步长"]
  E -->|"追加字段 offset"| P
  P --> R["按 type 解释字节"]

从一个索引定位到顶点字段

先在 IndexData 中从 indexStart 取索引,再按照后端使用的基顶点或缓冲起点解释该索引。VertexElement 的 source 选择绑定,offset 选字段,硬件缓冲的 vertexSize 表示实际步长。带间隙的声明仅累加元素字节数无法还原布局。

原生场景覆盖紧密布局与六个索引。Tiny 的 getData 使用声明大小求和作为步长,不能将这个结果外推到带 padding 的测试。用卷二其他后端路径或独立寻址断言检查间隙。

源码定位

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

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

下面复现声明、stride 计算与绑定。它与 src/02-2-vertex-declaration.cpp 逐字节一致:

// file: src/02-2-vertex-declaration.cpp
// tier: L1
// verify: clang++ -std=c++20 -I. src/02-2-vertex-declaration.cpp -o bin/02-2-vertex-declaration && ./bin/02-2-vertex-declaration
//
// 复现 VertexDeclaration/VertexElement(对应 OgreHardwareVertexBuffer.h 87-206、277-407):
//   VertexElementSemantic(VES_POSITION/NORMAL/COLOUR/TEXTURE_COORDINATES);
//   VertexElementType(VET_FLOAT1-4、UBYTE4 等,含 getSize() 字节数);
//   VertexElement 记录 source/offset/type/semantic/index;
//   addElement 追加进 mElementList 并 notifyChanged;getElement(n) 顺序取第 n 个;
//   getVertexSize(source) 累加该 source 上所有元素的字节大小(stride 计算);
//   VertexBufferBinding 用 map 把 source 绑定到具体缓冲;VertexData 组合两者 + vertexCount。
// 独立最小验证,非 OGRE 源码。
#include "verify.h"

#include <cstdint>
#include <list>
#include <map>
#include <string>

namespace ogre_repro {

// 对应 VertexElementSemantic
enum VertexElementSemantic : uint8_t {
  VES_POSITION = 1,
  VES_NORMAL = 4,
  VES_COLOUR = 5,
  VES_TEXTURE_COORDINATES = 7,
};

// 对应 VertexElementType(只列 lab 用到的几种)
enum VertexElementType : uint8_t {
  VET_FLOAT1 = 0,
  VET_FLOAT2 = 1,
  VET_FLOAT3 = 2,
  VET_FLOAT4 = 3,
  VET_UBYTE4 = 9,
};

// 对应 VertexElementType 的 getSize()
inline size_t elementSize(VertexElementType t) {
  switch (t) {
    case VET_FLOAT1: return 4;
    case VET_FLOAT2: return 8;
    case VET_FLOAT3: return 12;
    case VET_FLOAT4: return 16;
    case VET_UBYTE4: return 4;
  }
  return 0;
}

class VertexElement {
 public:
  VertexElement() {}
  VertexElement(unsigned short source, size_t offset, VertexElementType type,
                VertexElementSemantic semantic, unsigned short index = 0)
      : mSource(source), mOffset(offset), mType(type), mSemantic(semantic), mIndex(index) {}
  unsigned short getSource() const { return mSource; }
  size_t getOffset() const { return mOffset; }
  VertexElementType getType() const { return mType; }
  VertexElementSemantic getSemantic() const { return mSemantic; }
  unsigned short getIndex() const { return mIndex; }
  size_t getSize() const { return elementSize(mType); }

 private:
  unsigned short mSource;
  size_t mOffset;
  VertexElementType mType;
  VertexElementSemantic mSemantic;
  unsigned short mIndex;
};

class VertexDeclaration {
 public:
  typedef std::list<VertexElement> VertexElementList;

  // 对应 addElement:追加并通知
  const VertexElement& addElement(unsigned short source, size_t offset,
                                  VertexElementType type, VertexElementSemantic semantic,
                                  unsigned short index = 0) {
    mElementList.push_back(VertexElement(source, offset, type, semantic, index));
    notifyChanged();
    return mElementList.back();
  }
  size_t getElementCount() const { return mElementList.size(); }
  // 对应 getElement(n):顺序遍历取第 n 个
  const VertexElement* getElement(unsigned short index) const {
    if (index >= mElementList.size()) return nullptr;
    auto it = mElementList.begin();
    for (unsigned short n = 0; n < index; ++n) ++it;
    return &*it;
  }
  // 对应 getVertexSize(source):该 source 的 stride(所有元素字节数之和)
  size_t getVertexSize(unsigned short source) const {
    size_t size = 0;
    for (const auto& e : mElementList)
      if (e.getSource() == source) size += e.getSize();
    return size;
  }
  // 对应 findElementBySemantic
  const VertexElement* findElementBySemantic(VertexElementSemantic sem,
                                             unsigned short index = 0) const {
    for (const auto& e : mElementList)
      if (e.getSemantic() == sem && e.getIndex() == index) return &e;
    return nullptr;
  }

 private:
  VertexElementList mElementList;
  void notifyChanged() {}  // 对应虚钩子:子类在此失效 VAO/InputLayout
};

class VertexBufferBinding {
 public:
  typedef std::map<unsigned short, int> VertexBufferBindingMap;
  // 对应 setBinding:source → 缓冲句柄(此处用整数代指)
  void setBinding(unsigned short index, int bufferHandle) { mBindingMap[index] = bufferHandle; }
  void unsetBinding(unsigned short index) { mBindingMap.erase(index); }
  bool isBufferBound(unsigned short index) const { return mBindingMap.count(index) == 1; }
  size_t getBufferCount() const { return mBindingMap.size(); }

 private:
  VertexBufferBindingMap mBindingMap;
};

struct VertexData {
  VertexDeclaration* vertexDeclaration;
  VertexBufferBinding* vertexBufferBinding;
  uint32_t vertexStart = 0;
  uint32_t vertexCount = 0;
};

}  // namespace ogre_repro

int main() {
  using namespace ogre_repro;

  VertexDeclaration decl;

  // 典型顶点格式:position(float3, source0) + normal(float3, source1) + texcoord(float2, source0)
  decl.addElement(0, 0, VET_FLOAT3, VES_POSITION);
  decl.addElement(0, 12, VET_FLOAT2, VES_TEXTURE_COORDINATES);
  decl.addElement(1, 0, VET_FLOAT3, VES_NORMAL);

  CHECK(decl.getElementCount() == 3);

  // getElement 顺序取回
  const VertexElement* pos = decl.getElement(0);
  CHECK(pos->getSemantic() == VES_POSITION);
  CHECK(pos->getSource() == 0);
  CHECK(pos->getSize() == 12);

  // stride 计算:source0 = float3 + float2 = 20 字节
  CHECK(decl.getVertexSize(0) == 20);
  CHECK(decl.getVertexSize(1) == 12);

  // findElementBySemantic:按语义查 texcoord(index 0)
  const VertexElement* uv = decl.findElementBySemantic(VES_TEXTURE_COORDINATES, 0);
  CHECK(uv != nullptr && uv->getOffset() == 12);

  // 绑定表:source 0/1 各绑定一个缓冲
  VertexBufferBinding binding;
  binding.setBinding(0, 100);
  binding.setBinding(1, 101);
  CHECK(binding.isBufferBound(0));
  CHECK(binding.getBufferCount() == 2);
  binding.unsetBinding(1);
  CHECK(!binding.isBufferBound(1));

  // VertexData 组合声明 + 绑定 + 顶点区间
  VertexData data;
  data.vertexDeclaration = &decl;
  data.vertexBufferBinding = &binding;
  data.vertexCount = 3;
  CHECK(data.vertexDeclaration->getVertexSize(0) == 20);
  CHECK(data.vertexCount == 3);

  return lab::report("02-2 顶点声明");
}

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

小结

  • 顶点格式由 VertexDeclaration 的元素表描述:VertexElement 声明 source/offset/type/semantic/index。
  • VertexElementSemantic 说「含义」,VertexElementType 说「格式」,格式隐含字节大小。
  • getVertexSize(source) 累加同 source 元素 = stride;notifyChanged 让后端缓存的 VAO/InputLayout 作废。
  • VertexBufferBinding 把 source 映射到缓冲,VertexData 加 vertexStart/vertexCount 组合出「声明 × 绑定 × 区间」。

阅读导航:上一节:2.1 硬件缓冲抽象 · 下一节:2.3 索引缓冲 。

继续阅读

探索更多技术文章

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

全部文章 返回首页

「books」更多文章

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