9.2 D3D11 渲染系统
上一节看了 Apple 的 Metal 后端,这节转到微软的 Direct3D 11 后端。OGRE 的 D3D11 后端同时继承 RenderSystem 和 D3D11DeviceResourceManager——后一个基类让它能接收「设备丢失 / 设备恢复」事件(handleDeviceLost 里重建设备后通过它通知所有资源)。这节聚焦三件事:设备包装(D3D11Device)、能力上报(显式排除固定功能)、顶点 InputLayout 的按 shader 缓存。
本章与站内既有内容的分工
helio 四卷自实现的渲染器没有 D3D11 路径(以 Vulkan 为对标);卷一 ogre-core 讲过 RenderSystem 基类;这里对比 Metal 看 D3D11 的设备生命周期与资源缓存策略,属于「后端差异」而非图形学原理。
D3D11RenderSystem:双继承的渲染系统
OgreD3D11RenderSystem.h 的类声明同时继承两个基类:
// RenderSystems/Direct3D11/include/OgreD3D11RenderSystem.h:D3D11RenderSystem 类定义(v14.6.3 源码摘录,已删减)
class _OgreD3D11Export D3D11RenderSystem
: public RenderSystem
, protected D3D11DeviceResourceManager
{
private:
...
/// Direct3D rendering device
D3D11Device mDevice;
...
ID3D11DeviceN* createD3D11Device(D3D11Driver* d3dDriver, D3D_DRIVER_TYPE driverType,
D3D_FEATURE_LEVEL minFL, D3D_FEATURE_LEVEL maxFL, D3D_FEATURE_LEVEL* pFeatureLevel);
...
/// Internal method for populating the capabilities structure
RenderSystemCapabilities* createRenderSystemCapabilities() const;
...
ComPtr<ID3D11ShaderResourceView> mDSTResView;
...
public:
...
const String& getName(void) const;
...
D3D11Device &_getDevice() { return mDevice; }
注意私有成员清单里的三个层级:设备对象(mDevice)、能力方法(createRenderSystemCapabilities)、已绑定状态缓存(ComPtr<ID3D11ShaderResourceView> 等——D3D11 后端把「当前绑定的混合/光栅/深度模板状态」都缓存成 ComPtr,状态没变就不重设)。getName() 的实现与 Metal 同构:
// RenderSystems/Direct3D11/src/OgreD3D11RenderSystem.cpp:D3D11RenderSystem::getName(v14.6.3 源码摘录)
const String& D3D11RenderSystem::getName() const
{
static String strName( "Direct3D11 Rendering Subsystem");
return strName;
}
D3D11Device:设备与即时上下文的包装
D3D11 不像 Metal 那样用裸 id<MTLDevice>,而是包了一层 D3D11Device。OgreD3D11Device.h 里它持有 ComPtr 的多个 COM 对象:
// RenderSystems/Direct3D11/include/OgreD3D11Device.h:D3D11Device 类定义(v14.6.3 源码摘录,已删减)
class _OgreD3D11Export D3D11Device
{
private:
ComPtr<ID3D11DeviceN> mD3D11Device;
ComPtr<ID3D11DeviceContextN> mImmediateContext;
ComPtr<ID3D11ClassLinkage> mClassLinkage;
ComPtr<ID3D11InfoQueue> mInfoQueue;
LARGE_INTEGER mDriverVersion;
ComPtr<IDXGIFactoryN> mDXGIFactory;
...
public:
...
bool isNull() { return !mD3D11Device; }
ID3D11DeviceN* get() { return mD3D11Device.Get(); }
ID3D11DeviceContextN* GetImmediateContext() { return mImmediateContext.Get(); }
...
ID3D11DeviceN* operator->() const
{
assert(mD3D11Device);
if (D3D_NO_EXCEPTION != mExceptionsErrorLevel)
{
clearStoredErrorMessages();
}
return mD3D11Device.Get();
}
...
static D3D_FEATURE_LEVEL parseFeatureLevel(const Ogre::String& value, D3D_FEATURE_LEVEL fallback);
static D3D_DRIVER_TYPE parseDriverType(const Ogre::String& value, D3D_DRIVER_TYPE fallback = D3D_DRIVER_TYPE_HARDWARE);
};
operator-> 是这类的核心:把设备包装对象变成「伪设备指针」,上层代码写 mDevice->CheckFeatureSupport(...) 就像直接用 ID3D11Device*。重载它时还顺带在每次解引用前清理错误队列(clearStoredErrorMessages),于是错误状态是「用一次清一次」的。
设备是在 createDevice() 里创建的。_initialise 先从配置选项读出 Driver type、Rendering Device 等,再调用:
// RenderSystems/Direct3D11/src/OgreD3D11RenderSystem.cpp:D3D11RenderSystem::createDevice(v14.6.3 源码摘录,已删减)
void D3D11RenderSystem::createDevice()
{
mDevice.ReleaseAll();
D3D11Driver* d3dDriver = getDirect3DDrivers(true)->findByName(mDriverName);
mActiveD3DDriver = *d3dDriver; // store copy of selected driver, so that it is not lost when drivers would be re-enumerated
...
ID3D11DeviceN * device = createD3D11Device(d3dDriver, mDriverType, mMinRequestedFeatureLevel, mMaxRequestedFeatureLevel, &mFeatureLevel);
mDevice.TransferOwnership(device);
...
}
两个要点:createD3D11Device 只负责用 D3D11CreateDevice 造出 COM 设备并回填实际 mFeatureLevel;TransferOwnership 把所有权交给 mDevice 包装。特征级别被记录在 mFeatureLevel,后续能力上报全部按它分支。
能力上报:显式关闭固定功能
D3D11 是纯可编程管线,没有 GL 那样的固定功能阶段。createRenderSystemCapabilities 里这行注释就是宣言:
// RenderSystems/Direct3D11/src/OgreD3D11RenderSystem.cpp:D3D11RenderSystem::createRenderSystemCapabilities(v14.6.3 源码摘录,已删减)
RenderSystemCapabilities* D3D11RenderSystem::createRenderSystemCapabilities() const
{
RenderSystemCapabilities* rsc = new RenderSystemCapabilities();
rsc->setDriverVersion(mDriverVersion);
rsc->setDeviceName(mActiveD3DDriver.DriverDescription());
rsc->setRenderSystemName(getName());
// Does NOT support fixed-function!
//rsc->setCapability(RSC_FIXED_FUNCTION);
rsc->setCapability(RSC_HWSTENCIL);
...
// Set number of texture units, cap at OGRE_MAX_TEXTURE_LAYERS
rsc->setNumTextureUnits(OGRE_MAX_TEXTURE_LAYERS);
rsc->setNumVertexAttributes(D3D11_STANDARD_VERTEX_ELEMENT_COUNT);
rsc->setCapability(RSC_ANISOTROPY);
...
rsc->setCapability(RSC_TEXTURE_COMPRESSION);
rsc->setCapability(RSC_TEXTURE_COMPRESSION_DXT);
...
rsc->setCapability(RSC_UNIFORM_BUFFERS);
...
rsc->addShaderProfile("hlsl");
...
}
与 Metal 的对比值得记一笔:Metal 后端用默认着色器模拟固定功能(getFixedFunctionParams 内部加载 MetalDefaultVP/FP),D3D11 干脆声明不支持,上层走了另一条降级路径。能力表本身是幂等的位集合——setCapability 只或运算不覆盖。
InputLayout:按 shader 键的缓存
D3D11 的顶点输入布局(ID3D11InputLayout)由「顶点元素描述数组 + 顶点着色器字节码」共同决定,创建成本不低。D3D11VertexDeclaration 用 std::map 按 shader 程序指针缓存:
// RenderSystems/Direct3D11/include/OgreD3D11VertexDeclaration.h:D3D11VertexDeclaration 类定义(v14.6.3 源码摘录,已删减)
class _OgreD3D11Export D3D11VertexDeclaration
: public VertexDeclaration
, protected D3D11DeviceResource
{
protected:
D3D11Device & mlpD3DDevice;
typedef std::map<D3D11HLSLProgram*, ComPtr<ID3D11InputLayout>> ShaderToILayoutMap;
typedef ShaderToILayoutMap::iterator ShaderToILayoutMapIterator;
typedef std::map<D3D11HLSLProgram*, std::vector<D3D11_INPUT_ELEMENT_DESC>> ShaderToInputDesc;
...
ShaderToInputDesc mD3delems;
ShaderToILayoutMap mShaderToILayoutMap;
/** Gets the D3D11-specific vertex declaration. */
ID3D11InputLayout * getILayoutByShader(D3D11HLSLProgram* boundVertexProgram, VertexBufferBinding* binding);
...
void clearCache();
...
};
getILayoutByShader 的实现是典型的「命中返回,miss 创建后入表」:
// RenderSystems/Direct3D11/src/OgreD3D11VertexDeclaration.cpp:D3D11VertexDeclaration::getILayoutByShader(v14.6.3 源码摘录,已删减)
ID3D11InputLayout* D3D11VertexDeclaration::getILayoutByShader(D3D11HLSLProgram* boundVertexProgram, VertexBufferBinding* binding)
{
ShaderToILayoutMapIterator foundIter = mShaderToILayoutMap.find(boundVertexProgram);
ComPtr<ID3D11InputLayout> pVertexLayout;
if (foundIter == mShaderToILayoutMap.end())
{
// if not found - create
DWORD dwShaderFlags = 0;
const MicroCode & vSBuf = boundVertexProgram->getMicroCode();
D3D11_INPUT_ELEMENT_DESC * pVertexDecl=getD3DVertexDeclaration(boundVertexProgram, binding);
HRESULT hr = mlpD3DDevice->CreateInputLayout(
pVertexDecl,
boundVertexProgram->getInputParams().size(),
&vSBuf[0],
vSBuf.size(),
pVertexLayout.ReleaseAndGetAddressOf() );
if (FAILED(hr)|| mlpD3DDevice.isError())
{
...
}
mShaderToILayoutMap[boundVertexProgram] = pVertexLayout;
}
else
{
pVertexLayout = foundIter->second;
}
return pVertexLayout.Get(); // lifetime is determined by map
}
创建所需的 D3D11_INPUT_ELEMENT_DESC 数组本身也按 shader 缓存(mD3delems)。这样每帧 bindToShader 只是查表 + IASetInputLayout,CreateInputLayout 只发生一次。注意返回注释:对象生命周期由 map 决定,调用方拿裸指针但无权释放。
源码定位
RenderSystems/Direct3D11/include/OgreD3D11RenderSystem.h:class _OgreD3D11Export D3D11RenderSystem(58-61)、D3D11Device mDevice;(71)、const String& getName(void) const;(232)RenderSystems/Direct3D11/src/OgreD3D11RenderSystem.cpp:D3D11RenderSystem::getName(216-220)、createRenderSystemCapabilities(781-828)、createDevice(1272-1297)RenderSystems/Direct3D11/include/OgreD3D11Device.h:class _OgreD3D11Export D3D11Device(36-105)、operator->(70-78)RenderSystems/Direct3D11/include/OgreD3D11VertexDeclaration.h:ShaderToILayoutMap mShaderToILayoutMap(53)、getILayoutByShader(56)RenderSystems/Direct3D11/src/OgreD3D11VertexDeclaration.cpp:getILayoutByShader(129-173)、bindToShader(175-180)
上游引用固定到 OGRE v14.6.3 源码 。
可运行产物:C++ 最小验证
下面用纯 C++ 复现 D3D11 的设备包装、能力位与 InputLayout 缓存。它与 src/09-2-d3d11-render-system.cpp 逐字节一致:
// file: src/09-2-d3d11-render-system.cpp
// tier: L1
// verify: clang++ -std=c++20 -I. src/09-2-d3d11-render-system.cpp -o bin/09-2-d3d11-render-system && ./bin/09-2-d3d11-render-system
//
// 复现 D3D11RenderSystem、D3D11Device 与 InputLayout 缓存(对应
// RenderSystems/Direct3D11 的 OgreD3D11RenderSystem.cpp 216-220、781-828,
// OgreD3D11VertexDeclaration.cpp 129-180):
// getName() 返回 "Direct3D11 Rendering Subsystem";
// D3D11Device 包装 ID3D11Device 与即时上下文,operator-> 解引用;
// 能力对象显式不设 RSC_FIXED_FUNCTION,设置 HWSTENCIL/ANISOTROPY/32BIT/UNIFORM;
// D3D11VertexDeclaration 以 shader 为键惰性创建 InputLayout 并缓存复用。
// 独立最小验证,非 OGRE 源码。
#include "verify.h"
#include <cstdint>
#include <map>
#include <string>
namespace ogre_repro {
// 能力位:对应 RenderSystemCapabilities 的 RSC_* 枚举子集
enum RsCapability : uint32_t {
RSC_FIXED_FUNCTION = 1u << 0,
RSC_HWSTENCIL = 1u << 1,
RSC_ANISOTROPY = 1u << 2,
RSC_32BIT_INDEX = 1u << 3,
RSC_UNIFORM_BUFFERS = 1u << 4,
};
class RenderSystemCapabilities {
public:
void setRenderSystemName(const std::string& n) { mName = n; }
void setDeviceName(const std::string& n) { mDeviceName = n; }
const std::string& getDeviceName() const { return mDeviceName; }
void setCapability(RsCapability c) { mCaps |= c; }
bool hasCapability(RsCapability c) const { return (mCaps & c) != 0u; }
void setNumTextureUnits(uint16_t n) { mNumTU = n; }
uint16_t getNumTextureUnits() const { return mNumTU; }
private:
std::string mName;
std::string mDeviceName;
uint32_t mCaps = 0;
uint16_t mNumTU = 0;
};
// 简化 ID3D11Device:只有名字的哑设备句柄
struct DeviceHandle {
std::string name;
};
// 对应 D3D11Device 包装类(OgreD3D11Device.h 36-105)
class D3D11Device {
public:
void TransferOwnership(DeviceHandle* dev) { mDevice = dev; }
bool isNull() const { return mDevice == nullptr; }
DeviceHandle* get() { return mDevice; }
// 对应 operator->:返回裸设备指针
DeviceHandle* operator->() { return mDevice; }
private:
DeviceHandle* mDevice = nullptr;
};
// 简化顶点着色器程序句柄
struct Program {
std::string name;
size_t inputParamCount = 0;
};
// 简化 InputLayout(D3D11 的 ID3D11InputLayout)
struct InputLayout {
size_t id;
};
// 对应 D3D11VertexDeclaration(OgreD3D11VertexDeclaration.h 39-69)
class VertexDeclaration {
public:
explicit VertexDeclaration(D3D11Device& dev) : mDevice(dev) {}
// 对应 getILayoutByShader:按 shader 缓存,miss 才创建
InputLayout* getILayoutByShader(Program* prog, size_t bindingVertexCount) {
auto it = mShaderToILayout.find(prog);
if (it == mShaderToILayout.end()) {
if (mDevice.isNull()) return nullptr; // CreateInputLayout 无设备即失败
auto* layout = new InputLayout{mNextLayoutId++};
mShaderToILayout[prog] = layout;
mInputParamCount = prog->inputParamCount;
(void)bindingVertexCount;
}
return mShaderToILayout[prog];
}
// 对应 bindToShader:取布局并绑定到即时上下文
InputLayout* bindToShader(Program* prog, size_t bindingVertexCount) {
return getILayoutByShader(prog, bindingVertexCount);
}
size_t layoutCount() const { return mShaderToILayout.size(); }
size_t cachedInputParamCount() const { return mInputParamCount; }
private:
D3D11Device& mDevice;
std::map<Program*, InputLayout*> mShaderToILayout;
size_t mNextLayoutId = 1;
size_t mInputParamCount = 0;
};
class D3D11RenderSystem {
public:
const std::string& getName() const {
static const std::string n("Direct3D11 Rendering Subsystem");
return n;
}
D3D11Device mDevice;
// 对应 createRenderSystemCapabilities(OgreD3D11RenderSystem.cpp 781-828)
RenderSystemCapabilities createRenderSystemCapabilities() const {
RenderSystemCapabilities rsc;
rsc.setDeviceName("NVIDIA GeForce RTX 4080");
rsc.setRenderSystemName(getName());
// D3D11 不支持固定功能:显式不设 RSC_FIXED_FUNCTION
rsc.setCapability(RSC_HWSTENCIL);
rsc.setNumTextureUnits(16);
rsc.setCapability(RSC_ANISOTROPY);
rsc.setCapability(RSC_32BIT_INDEX);
rsc.setCapability(RSC_UNIFORM_BUFFERS);
return rsc;
}
};
} // namespace ogre_repro
int main() {
using namespace ogre_repro;
D3D11RenderSystem rs;
// getName:后端自报家门
CHECK(rs.getName() == "Direct3D11 Rendering Subsystem");
// 设备包装:初始为空
CHECK(rs.mDevice.isNull());
DeviceHandle dev;
dev.name = "D3D11 Hardware Adapter";
rs.mDevice.TransferOwnership(&dev);
CHECK(!rs.mDevice.isNull());
CHECK(rs.mDevice->name == "D3D11 Hardware Adapter"); // operator-> 解引用
// 能力对象:无固定功能、有现代能力
RenderSystemCapabilities caps = rs.createRenderSystemCapabilities();
CHECK(caps.getDeviceName() == "NVIDIA GeForce RTX 4080");
CHECK(!caps.hasCapability(RSC_FIXED_FUNCTION));
CHECK(caps.hasCapability(RSC_HWSTENCIL));
CHECK(caps.hasCapability(RSC_ANISOTROPY));
CHECK(caps.hasCapability(RSC_32BIT_INDEX));
CHECK(caps.hasCapability(RSC_UNIFORM_BUFFERS));
CHECK(caps.getNumTextureUnits() == 16);
// InputLayout 缓存:同一 shader 只创建一次
VertexDeclaration vd(rs.mDevice);
Program vsA;
vsA.name = "vs_deferred";
vsA.inputParamCount = 4;
Program vsB;
vsB.name = "vs_forward";
vsB.inputParamCount = 6;
InputLayout* la1 = vd.getILayoutByShader(&vsA, 3);
InputLayout* la2 = vd.getILayoutByShader(&vsA, 3);
CHECK(la1 == la2); // 缓存命中,同一个对象
CHECK(vd.layoutCount() == 1);
InputLayout* lb = vd.bindToShader(&vsB, 3);
CHECK(vd.layoutCount() == 2);
CHECK(la1 != lb);
CHECK(vd.cachedInputParamCount() == 6);
// 无设备时 CreateInputLayout 失败路径
D3D11Device nullDev;
VertexDeclaration broken(nullDev);
CHECK(broken.getILayoutByShader(&vsA, 3) == nullptr);
return lab::report("09-2 D3D11 渲染系统");
}
本机实测(Apple clang 16,clang++ -std=c++20 -Wall -I.):编译零警告,断言 17/17 通过。
小结
D3D11RenderSystem双继承RenderSystem与D3D11DeviceResourceManager;getName()返回"Direct3D11 Rendering Subsystem"。D3D11Device用ComPtr包装设备/即时上下文,operator->让上层像用裸指针。createDevice()先ReleaseAll,再创建并TransferOwnership,特征级别记入mFeatureLevel。- 能力上报显式不设
RSC_FIXED_FUNCTION——D3D11 没有固定功能阶段。 - 顶点 InputLayout 以 shader 指针为键缓存,
CreateInputLayout只发生一次,生命周期由 map 决定。
阅读导航:上一节:9.1 Metal 渲染系统 · 下一节:9.3 三后端对比 。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。