Visual C++ DirectX11 - 更新动态资源未按预期工作

Visual C++ DirectX11 - Updating Dynamic Resource not working as expected

我想更新 DirectX11 ID3D11Buffer 的顶点,但它不起作用。我遵循了 Microsoft 的指南 How to use dynamic resources

这是我的缓冲区代码:

// Create vertex buffer
int verticesAmount = 5;
pVertices = new XMFLOAT3[verticesAmount];
pVertices[0] = XMFLOAT3( -0.1f, -0.1f, 0 );
pVertices[1] = XMFLOAT3( -0.1f, 0.1f, 0 );
pVertices[2] = XMFLOAT3( 0.1f, 0.1f, 0 );
pVertices[3] = XMFLOAT3( 0.1f, -0.1f, 0 );
pVertices[4] = XMFLOAT3( -0.1f, -0.1f, 0 );

D3D11_BUFFER_DESC bd;
ZeroMemory( &bd, sizeof(bd) );
bd.Usage = D3D11_USAGE_DYNAMIC;
bd.ByteWidth = sizeof( XMFLOAT3 ) * verticesAmount;//sizeof(vertices);
bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
bd.MiscFlags = 0;
bd.StructureByteStride = 0;

D3D11_SUBRESOURCE_DATA InitData;
ZeroMemory( &InitData, sizeof(InitData) );
InitData.pSysMem = pVertices;
InitData.SysMemPitch = 0;
InitData.SysMemSlicePitch = 0;

result = pDevice->CreateBuffer( &bd, &InitData, &pLineStripBuffer )

这是我更新时的代码:

//pVertices[2].x += 0.1f;  commented because I want to test whether it updates at all
D3D11_MAPPED_SUBRESOURCE mappedResource;
ZeroMemory(&mappedResource, sizeof(D3D11_MAPPED_SUBRESOURCE));
//  Disable GPU access to the vertex buffer data.
pContext->Map(pLineStripBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
//  Update the vertex buffer here.
memcpy(mappedResource.pData, pVertices, 5);
//  Reenable GPU access to the vertex buffer data.
pContext->Unmap(pLineStripBuffer, 0)

上面的更新代码被注释掉后的样子:

这是未注释的样子:

更新缓冲区的截图应该和上面的一样,因为顶点没有改变位置。

原来是memcpy的大小太小了。问题中的代码仅复制第一个 XMFLOAT3 向量的 x。当我渲染缓冲区时,第一行将从第一个向量的中心到 x。

memcpy(mappedResource.pData, pVertices, 5 * sizeof(XMFLOAT3));