如何在循环中打印顶点结构

How to Print Vertex Structure in a Loop

我想要打印我的顶点缓冲区的内容。我想在打印到控制台时循环遍历所有顶点和纹理坐标。具体来说,我想同时查看顶点位置和纹素(纹理坐标)。这将如何在循环中完成?

//vertex structure
struct Vertex
{
    XMFLOAT3 Pos;
    XMFLOAT2 Tex;
};

D3D11_MAPPED_SUBRESOURCE ms;
pContext->Map(buff, NULL, D3D11_MAP_READ, NULL, &ms); 
Vertex* vertices = new Vertex[ms.DepthPitch];     
memcpy(vertices, ms.pData, ms.DepthPitch); 
pContext->Unmap(buff, 0);

//I know how to write a basic for loop,
//But I don't know how to query only pos or tex? 
for (int i = 0; i < 2678; i++) {
  cout << vertices[i] << "\n";
}

上面的代码有多种失败方式,因此包含错误处理很重要。

此外 D3D11_MAPPED_SUBRESOURCE 不会通过任何值报告顶点缓冲区的 大小 ,因此您需要从 D3D11_BUFFER_DESC 中获取它通过 GetDesc.

DepthPitch is only a valid value if you are mapping a volume (3D) texture.

您还假设顶点缓冲区本身是您可以直接 Map 的东西,因为您使用 D3D11_USAGE_STAGINGD3D11_USAGE_DYNAMIC 创建它并使用了 D3D11_CPU_ACCESS_FLAG

//vertex structure
struct Vertex
{
    XMFLOAT3 Pos;
    XMFLOAT2 Tex;
};

D3D11_MAPPED_SUBRESOURCE ms = {};
if (FAILED(pContext->Map(buff, 0, D3D11_MAP_READ, 0, &ms)))
{
   cout << "Failed Map" << endl;
}
else
{
    D3D11_BUFFER_DESC desc = {};
    buff->GetDesc(&desc);

    size_t nVerts = desc.ByteWidth / sizeof(Vertex);
    if (!nVerts)
    {
        cout << "Failed computing nVerts" << endl;
    }
    else
    {
        auto vertices = new Vertex[nVerts];     
        memcpy(vertices, ms.pData, nVerts * sizeof(Vertex)); 
        for (size_t i = 0; i < nVerts; i++)
        {
            cout << vertices[i].Pos.x << ", "
                 << vertices[i].Pos.y << ", "
                 << vertices[i].Pos.z << endl;
        }
        delete [] vertices;
    }

    pContext->Unmap(buff, 0);
}  

Note a better way to handle the temporary vertices memory is to use auto vertices = std::make_unique<Vertex[]>(nVerts); and add #include <memory> to the top. This avoids the need to remember to manually delete the memory in all cases.

You should also be using Microsoft::WRL::ComPtr instead of raw COM interface pointers to avoid memory leaks with DirectX COM objects.

另见 DirectX Tool Kit for DX11