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

时间:2016-10-23 01:21:11

标签: visual-c++ rendering directx-11 direct3d

我想更新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)

当上面的更新代码被注释掉时,这就是它的样子:

enter image description here

这看起来像是未注释的:

enter image description here

更新缓冲区的屏幕截图应与上面的相同,因为顶点不会改变位置。

1 个答案:

答案 0 :(得分:1)

事实证明,memcpy的大小很小。问题中的代码仅复制第一个XMFLOAT3向量的x。当我渲染缓冲区时,第一行将从中心转到第一个向量的x。

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