5.2 实例批
5.1 节讲了 InstanceManager 怎么把实例分进批次,本节看批次内部——一份 InstanceBatch 到底怎么把顶点数据组织成 GPU 能高效处理的形态。答案因技术路线而异:HW 后端克隆一份顶点缓冲并追加每实例数据,Shader 后端共享顶点缓冲、每实例数据走常数。两条路线在 build/buildFrom/setupVertices 这些方法上分道扬镳。
本章与站内既有内容的分工
第 5.1 节聚焦管理器的池与批次划分,本节下沉到批次内部的数据组织,是「管理」到「数据」的一步。卷二讲的 RenderOperation/VertexData/VertexDeclaration 在这里被实例化场景重新组合:同一份几何数据要喂给 N 个实例,N 份变换数据要找到自己的 GPU 位置。
基类构建流程:build 与 RenderOperation
InstanceBatch 的 build 方法把基础装配和子类钩子串起来:
// OgreMain/src/OgreInstanceBatch.cpp:build(v14.6.3 源码摘录,已删减)
RenderOperation InstanceBatch::build( const SubMesh* baseSubMesh )
{
if( checkSubMeshCompatibility( baseSubMesh ) )
{
//Only triangle list at the moment
mRenderOperation.operationType = RenderOperation::OT_TRIANGLE_LIST;
mRenderOperation.srcRenderable = this;
mRenderOperation.useIndexes = true;
setupVertices( baseSubMesh );
setupIndices( baseSubMesh );
createAllInstancedEntities();
}
return mRenderOperation;
}
build 是批次的装配总入口,五步:校验子网格兼容性、设置渲染操作为三角形列表、调用 setupVertices 搭顶点数据、setupIndices 搭索引数据、createAllInstancedEntities 预分配实体池(5.1 节讲过的那个池)。其中 setupVertices/setupIndices 是虚方法——HW 和 Shader 后端各自实现,这正是两条路线分叉的起点。
buildFrom 是另一个入口,它吃一个已经存在的 RenderOperation 而不是原始 SubMesh。InstanceBatchHW 的 buildFrom 展示了复用与定制的平衡:
// OgreMain/src/OgreInstanceBatchHW.cpp:buildFrom(v14.6.3 源码摘录,已删减)
void InstanceBatchHW::buildFrom( const SubMesh *baseSubMesh, const RenderOperation &renderOperation )
{
InstanceBatch::buildFrom( baseSubMesh, renderOperation );
//We need to clone the VertexData (but just reference all buffers, except the last one)
//because last buffer contains data specific to this batch, we need a different binding
mRenderOperation.vertexData = mRenderOperation.vertexData->clone( false );
mRemoveOwnVertexData = true;
VertexData *thisVertexData = mRenderOperation.vertexData;
const unsigned short lastSource = thisVertexData->vertexDeclaration->getMaxSource();
auto vertexBuffer = HardwareBufferManager::getSingleton().createVertexBuffer(
thisVertexData->vertexDeclaration->getVertexSize(lastSource), mInstancesPerBatch, HBU_CPU_TO_GPU);
thisVertexData->vertexBufferBinding->setBinding( lastSource, vertexBuffer );
vertexBuffer->setIsInstanceData( true );
vertexBuffer->setInstanceDataStepRate( 1 );
}
buildFrom 的注释直接点明策略:克隆 VertexData 但「只引用所有缓冲,除了最后一个」——因为最后一个缓冲装的是本批特有的每实例数据,需要独立的绑定。克隆后检查最大的 source 号,为它新建一个 mInstancesPerBatch 大小的顶点缓冲,绑定为新 source,并标记 setIsInstanceData(true) + setInstanceDataStepRate(1)——这两个标记告诉渲染后端:这个缓冲是实例数据,每实例步进 1。
HW 后端:克隆顶点 + 每实例 TEXCOORD
InstanceBatchHW 的类文档先定义了这条路线的基本策略:
// OgreMain/include/OgreInstanceBatchHW.h:InstanceBatchHW 类文档(v14.6.3 源码摘录,已删减)
/** This is technique requires true instancing hardware support.
Basically it creates a cloned vertex buffer from the original, with an extra buffer containing
3 additional @c TEXCOORDS (12 bytes) repeated as much as the instance count.
That will be used for each instance data.
The main advantage of this technique is that it's <em>VERY</em> fast; but it doesn't support
skeletal animation at all. Very reduced memory consumption and bandwidth. Great for particles,
debris, bricks, trees, sprites.
This batch is one of the few (if not the only) techniques that allows culling on an individual
basis. This means we can save vertex shader performance for instances that aren't in scene or
just not focused by the camera.
*/
class _OgreExport InstanceBatchHW : public InstanceBatch
HW 路线的本质:克隆顶点缓冲,再加一个额外缓冲,装 3 个 TEXCOORD 作为每实例数据。注释列出的三组特性决定了它的适用场景:极快(VERY fast)、不支持骨骼动画、可逐实例剔除。因此它最适合粒子、碎片、砖块、树、精灵这类「小物体大量重复」的场合。类文档说的「3 additional TEXCOORDs (12 bytes)」与实现细节略有出入——实际每个 TEXCOORD 元素是 VET_FLOAT4(16 字节),3 个共 48 字节,正好装一个 4x3 矩阵(12 个 float)。这在 setupVertices 里落实:
// OgreMain/src/OgreInstanceBatchHW.cpp:setupVertices(v14.6.3 源码摘录,已删减)
void InstanceBatchHW::setupVertices( const SubMesh* baseSubMesh )
{
//No skeletal animation support in this technique, sorry
mRenderOperation.vertexData = baseSubMesh->vertexData->_cloneRemovingBlendData();
mRemoveOwnVertexData = true; //Raise flag to remove our own vertex data in the end (not always needed)
VertexData *thisVertexData = mRenderOperation.vertexData;
//Modify the declaration so it contains an extra source, where we can put the per instance data
size_t offset = 0;
unsigned short nextTexCoord = thisVertexData->vertexDeclaration->getNextFreeTextureCoordinate();
const unsigned short newSource = thisVertexData->vertexDeclaration->getMaxSource() + 1;
for (unsigned char i = 0; i < 3 + mCreator->getNumCustomParams(); ++i)
{
thisVertexData->vertexDeclaration->addElement( newSource, offset, VET_FLOAT4,
VES_TEXTURE_COORDINATES, nextTexCoord++ );
offset = thisVertexData->vertexDeclaration->getVertexSize( newSource );
}
//Create the vertex buffer containing per instance data
auto vertexBuffer = HardwareBufferManager::getSingleton().createVertexBuffer(
thisVertexData->vertexDeclaration->getVertexSize(newSource), mInstancesPerBatch, HBU_CPU_TO_GPU);
thisVertexData->vertexBufferBinding->setBinding( newSource, vertexBuffer );
vertexBuffer->setIsInstanceData( true );
vertexBuffer->setInstanceDataStepRate( 1 );
}
setupVertices 四步走:
- 克隆顶点数据:
_cloneRemovingBlendData()深拷贝基础网格的顶点,同时剔除骨骼混合数据(HW 不支持骨骼动画,注释自嘲「sorry」)。克隆后mRemoveOwnVertexData = true,标记批次析构时要释放自己的顶点数据。 - 扩展声明:找下一个空闲 TEXCOORD 槽位和最大 source 号,从
newSource = getMaxSource() + 1开始追加3 + 自定义参数数个VET_FLOAT4元素,语义是纹理坐标,index 递增。注意 offset 的更新方式——addElement后offset = getVertexSize(newSource),元素逐个紧贴。 - 建每实例缓冲:大小是
vertexSize * mInstancesPerBatch,即每个实例固定一段 3 个 FLOAT4。 - 标记实例数据:
setIsInstanceData(true)+setInstanceDataStepRate(1)。
setupIndices 就简单得多——直接克隆基础网格的索引数据:
// OgreMain/src/OgreInstanceBatchHW.cpp:setupIndices(v14.6.3 源码摘录,已删减)
void InstanceBatchHW::setupIndices( const SubMesh* baseSubMesh )
{
//We could use just a reference, but the InstanceManager will in the end attampt to delete
//the pointer, and we can't give it something that doesn't belong to us.
mRenderOperation.indexData = baseSubMesh->indexData->clone( true );
mRemoveOwnIndexData = true; //Raise flag to remove our own index data in the end (not always needed)
}
注释解释了为什么不直接引用:InstanceManager 最终会尝试删除索引数据指针,不能给它一个不属于本批的对象,所以要克隆并设 mRemoveOwnIndexData = true。
Shader 后端:共享缓冲 + 着色器常数
InstanceBatchShader 走了另一条路——顶点缓冲共享:
// OgreMain/include/OgreInstanceBatchShader.h:InstanceBatchShader 类文档(v14.6.3 源码摘录,已删减)
/** Basically it creates a large vertex buffer with many repeating entities, and sends per instance
data through shader constants. Because SM 2.0 & 3.0 have up to 256 shader constant registers,
this means there can be approx up to 84 instances per batch, assuming they're not skinned
But using shader constants for other stuff (i.e. lighting) also affects negatively this number
A mesh with skeletally animated 2 bones reduces the number 84 to 42 instances per batch.
The main advantage of this technique is that it's supported on a high variety of hardware
(SM 2.0 cards are required) and the same shader can be used for both skeletally animated
normal entities and instanced entities without a single change required.
The developer doesn't need to worry about
reaching the 84 instances limit, the InstanceManager automatically takes care of splitting
and creating new batches. But beware internally, this means less performance improvement.
Another improvement is that vertex buffers are shared between batches, which significantly
reduces GPU VRAM usage.
*/
class _OgreExport InstanceBatchShader : public InstanceBatch
Shader 路线的核心差异:每实例数据通过着色器常数发送,而不是塞进顶点缓冲。类文档给出一个很有价值的数字——SM 2.0/3.0 有 256 个常数寄存器,每实例约需 3 个(4x3 矩阵),所以每批大约 84 个实例;但常数寄存器还要给光照等用途分,实际更少;骨骼动画每实例再占 2 个骨索引相关常数,84 就折半到 42。注释强调两件事:开发者不用操心 84 上限——InstanceManager 会自动拆批;以及顶点缓冲在批次间共享,显著降低显存占用(不克隆、不重复)。
setupVertices 在 Shader 后端就不克隆了——mRenderOperation.vertexData = baseSubMesh->vertexData 直接引用基础网格的顶点数据(对应 lab 里 sh.build(&base) 后 vertexData == &baseVD 的断言)。两条路线形成鲜明对照:
| 维度 | HW 实例化 | Shader 实例化 |
|---|---|---|
| 顶点缓冲 | 克隆 + 剔除骨骼数据 | 直接共享 |
| 每实例数据 | 顶点缓冲追加 3×FLOAT4 TEXCOORD | 着色器常数寄存器 |
| 每批上限 | 高(硬件支持时) | 约 84(SM2/3 常数寄存器限制) |
| 骨骼动画 | 不支持 | 支持(同一 shader 通用) |
| 逐实例剔除 | 支持 | 不支持 |
| 显存占用 | 每批独立 | 批次间共享 |
合批改变的是提交与更新粒度
实例批次让多个对象共享几何,通过实例缓冲或程序常量传入差异。静态合批建立区域几何,更新代价来自重新构建。能减少 draw 的前提是兼容的材质与布局。
按相同资源、相机、对象数和变换更新频率比较三条路径。记录 draw、缓冲更新量、CPU 时间和后端 GPU 时间,再讨论适用边界。
批次共享与每实例更新
flowchart LR
M["共享 Mesh 与兼容 Pass"] --> B["实例批次"]
O["每个对象的变换或自定义参数"] --> I["实例流或程序常量"]
I --> B
B --> D["批次 draw"]
O -.->|"更新频率决定写入代价"| I
S["静态对象"] --> C["合并到区域几何"]
C --> Q["区域 draw"]
源码定位
OgreMain/src/OgreInstanceBatch.cpp:build(220-235)、buildFrom(237-241)、createAllInstancedEntities(174-185)OgreMain/src/OgreInstanceBatchHW.cpp:buildFrom(67-82)、setupVertices(84-109)、setupIndices(111-117)、checkSubMeshCompatibility(119-141)OgreMain/include/OgreInstanceBatchHW.h:类文档(42-54)OgreMain/include/OgreInstanceBatchShader.h:类文档(42-57)
上游引用固定到 OGRE v14.6.3 源码 。
可运行产物:C++ 最小验证
下面用纯 C++ 复现两种实例批后端:HW 的克隆顶点 + 追加每实例 TEXCOORD,Shader 的共享顶点缓冲。它与 src/ogre-ext-05-2-instance-batch.cpp 逐字节一致:
// file: src/ogre-ext-05-2-instance-batch.cpp
// tier: L1
// verify: clang++ -std=c++20 -I. src/ogre-ext-05-2-instance-batch.cpp -o bin/ogre-ext-05-2-instance-batch && ./bin/ogre-ext-05-2-instance-batch
//
// 复现实例批次的两种后端(对应 OgreInstanceBatchHW.h 42-53 的类文档、
// OgreMain/src/OgreInstanceBatchHW.cpp 67-109 的 buildFrom/setupVertices,
// 以及 OgreInstanceBatchShader.h 42-57 的共享缓冲设计):
// HW 后端克隆顶点数据并在新 source 上追加 3 个 FLOAT4 TEXCOORD 装每实例
// 4x3 矩阵(12 float),缓冲标实例数据、步长 1;Shader 后端共享顶点缓冲,
// 每实例数据走着色器常数。两者复用 InstanceBatch 的实体池。
// 独立最小验证,非 OGRE 源码。
#include "verify.h"
#include <algorithm>
#include <cstdint>
#include <map>
#include <vector>
namespace ogre_repro {
// 顶点元素:VET_FLOAT4 = 16 字节(对应 OgreInstanceBatchHW.cpp 96-101 的 addElement)
struct VertexElement {
uint16_t source;
size_t offset;
uint8_t type; // 4 = FLOAT4
uint8_t semantic; // 0=POSITION 1=TEXCOORD
uint8_t index;
size_t size() const { return type * 4; }
};
class VertexDeclaration {
public:
void addElement(uint16_t source, size_t offset, uint8_t type, uint8_t semantic, uint8_t index) {
VertexElement e{source, offset, type, semantic, index};
mElements.push_back(e);
}
size_t getVertexSize(uint16_t source) const {
size_t max = 0;
for (const auto& e : mElements)
if (e.source == source) max = std::max(max, e.offset + e.size());
return max;
}
uint8_t getMaxSource() const {
uint16_t max = 0;
for (const auto& e : mElements) max = std::max(max, e.source);
return static_cast<uint8_t>(max);
}
uint8_t getNextFreeTextureCoordinate() const {
uint8_t max = 0;
for (const auto& e : mElements)
if (e.semantic == 1) max = std::max(max, static_cast<uint8_t>(e.index + 1));
return max;
}
std::vector<VertexElement> mElements;
};
class VertexBuffer {
public:
VertexBuffer(size_t vertexSize, size_t numVertices)
: mData(vertexSize * numVertices, 0.0f),
mVertexSize(vertexSize), mNumVertices(numVertices) {}
std::vector<float> mData;
size_t mVertexSize;
size_t mNumVertices;
bool mIsInstanceData = false;
uint32_t mInstanceDataStepRate = 0;
};
// 顶点数据:声明 + source→缓冲 绑定
struct VertexData {
VertexDeclaration decl;
std::map<uint16_t, VertexBuffer*> binding;
bool mRemoveOwnVertexData = false;
};
// 极简 RenderOperation(对应 InstanceBatch::build 221-231 的装配)
struct RenderOperation {
uint8_t operationType = 3; // OT_TRIANGLE_LIST
VertexData* vertexData = nullptr;
VertexBuffer* indexData = nullptr;
size_t indexCount = 0;
size_t numberOfInstances = 0;
};
// 极简 SubMesh:一个顶点流 + 索引流
struct SubMesh {
VertexData* vertexData = nullptr;
VertexBuffer* indexData = nullptr;
size_t indexCount = 0;
};
// HW 后端(对应 OgreInstanceBatchHW.cpp 84-109):克隆顶点 + 每实例 TEXCOORD
class InstanceBatchHW {
public:
void build(const SubMesh* base) {
mRenderOperation.vertexData = cloneRemovingBlendData(base->vertexData);
mRenderOperation.indexData = new VertexBuffer(base->indexData->mVertexSize, base->indexData->mNumVertices);
mRenderOperation.indexData->mData = base->indexData->mData; // 克隆索引
mRenderOperation.indexCount = base->indexCount;
VertexData* vd = mRenderOperation.vertexData;
size_t offset = 0;
uint8_t nextTex = vd->decl.getNextFreeTextureCoordinate();
const uint16_t newSource = static_cast<uint16_t>(vd->decl.getMaxSource() + 1);
for (uint8_t i = 0; i < 3; ++i) { // 3 个 TEXCOORD 装 4x3 矩阵
vd->decl.addElement(newSource, offset, 4, 1, nextTex++);
offset = vd->decl.getVertexSize(newSource);
}
auto* perInstance = new VertexBuffer(vd->decl.getVertexSize(newSource), 4); // 每批 4 实例
perInstance->mIsInstanceData = true;
perInstance->mInstanceDataStepRate = 1;
vd->binding.emplace(newSource, perInstance);
vd->mRemoveOwnVertexData = true;
}
RenderOperation mRenderOperation;
size_t mInstancesPerBatch = 4;
private:
// 对应 _cloneRemovingBlendData:深度复制(只保留 source 0 的顶点流)
VertexData* cloneRemovingBlendData(const VertexData* base) {
auto* vd = new VertexData();
vd->decl = base->decl;
for (const auto& kv : base->binding) {
auto* buf = new VertexBuffer(kv.second->mVertexSize, kv.second->mNumVertices);
buf->mData = kv.second->mData;
vd->binding.emplace(kv.first, buf);
}
return vd;
}
};
// Shader 后端(对应 OgreInstanceBatchShader.h 42-57):共享顶点缓冲
class InstanceBatchShader {
public:
void build(const SubMesh* base) {
mRenderOperation.vertexData = base->vertexData; // 不克隆,直接引用
mRenderOperation.indexData = base->indexData;
mRenderOperation.indexCount = base->indexCount;
}
RenderOperation mRenderOperation;
std::vector<float> mInstanceParams; // 每实例数据走着色器常数
};
} // namespace ogre_repro
int main() {
using namespace ogre_repro;
// 基础网格:source 0 位置 + 法线,每顶点 32 字节,6 个顶点,12 个索引
VertexDeclaration baseDecl;
baseDecl.addElement(0, 0, 4, 0, 0); // POSITION FLOAT4
baseDecl.addElement(0, 16, 4, 0, 0); // 法线 FLOAT4
CHECK_EQ(baseDecl.getVertexSize(0), size_t(32));
CHECK_EQ(baseDecl.getMaxSource(), uint8_t(0));
CHECK_EQ(baseDecl.getNextFreeTextureCoordinate(), uint8_t(0));
VertexBuffer baseVB(32, 6);
baseVB.mData = {0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1,
1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1,
1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1};
VertexData baseVD;
baseVD.decl = baseDecl;
baseVD.binding.emplace(0, &baseVB);
VertexBuffer baseIB(2, 12); // 16 位索引
SubMesh base;
base.vertexData = &baseVD;
base.indexData = &baseIB;
base.indexCount = 12;
// HW 后端:克隆 + 每实例 3 个 FLOAT4 TEXCOORD
InstanceBatchHW hw;
hw.build(&base);
VertexData* hvd = hw.mRenderOperation.vertexData;
CHECK(hvd != &baseVD); // 顶点数据被克隆(非共享)
CHECK(hvd->mRemoveOwnVertexData);
CHECK_EQ(hw.mRenderOperation.indexData->mNumVertices, size_t(12));
CHECK_EQ(hvd->decl.getVertexSize(0), size_t(32)); // base 段保留
// 新 source 1:3 个 TEXCOORD,offset 0/16/32 → 顶点大小 48
CHECK_EQ(hvd->decl.getMaxSource(), uint8_t(1));
CHECK_EQ(hvd->decl.getNextFreeTextureCoordinate(), uint8_t(3));
CHECK_EQ(hvd->decl.getVertexSize(1), size_t(48));
VertexBuffer* instBuf = hvd->binding.at(1);
CHECK(instBuf->mIsInstanceData);
CHECK_EQ(instBuf->mInstanceDataStepRate, uint32_t(1));
CHECK_EQ(instBuf->mNumVertices, size_t(4)); // 每批 4 实例
// Shader 后端:共享顶点缓冲,不克隆
InstanceBatchShader sh;
sh.build(&base);
CHECK(sh.mRenderOperation.vertexData == &baseVD);
CHECK(sh.mRenderOperation.indexData == &baseIB);
CHECK_EQ(sh.mRenderOperation.indexCount, size_t(12));
// 两后端的渲染装配一致:三角形列表
CHECK_EQ(hw.mRenderOperation.operationType, uint8_t(3));
CHECK_EQ(sh.mRenderOperation.operationType, uint8_t(3));
// HW 每实例数据区:4 个实例各 12 float(4x3 矩阵)
CHECK_EQ(instBuf->mData.size(), size_t(48 * 4));
CHECK_EQ(instBuf->mVertexSize, size_t(48));
return lab::report("5.2 实例批");
}
本机实测(Apple clang 16,clang++ -std=c++20 -Wall):编译通过(零警告),断言 20/20 通过。
小结
InstanceBatch::build五步装配:校验兼容性 → 三角形列表 →setupVertices→setupIndices→ 预分配实体池。- HW 后端克隆顶点数据(剔除骨骼数据),追加
3+自定义参数数个VET_FLOAT4TEXCOORD。 - 每实例缓冲标记
isInstanceData+stepRate 1,索引数据克隆而非引用。 - Shader 后端共享顶点缓冲,每实例数据走着色器常数;SM2/3 常数寄存器限制每批约 84 实例。
- HW 适合大量重复小物体(粒子/树/碎片),Shader 兼容面广且支持骨骼动画。
阅读导航:上一节:5.1 实例管理器 · 下一节:5.3 静态几何 。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。