I have a question regarding vertex buffers. How does one read the vertices from the vertex buffer in D3D11? I want to get a particular vertex's position for calculations, if this approach is wrong, how would one do it? The following code does not (obviously) work.
VERTEX* vert;
D3D11_MAPPED_SUBRESOURCE ms;
devcon->Map(pVBufferSphere, NULL, D3D11_MAP_READ, NULL, &ms);
vert = (VERTEX*) ms.pData;
devcon->Unmap(pVBufferSphere, NULL);
Thanks.
Where your code is wrong:
Map()
),operator=()
),Unmap()
).After unmap, you can't really say where your pointer now points. It can point to memory location where already allocated another stuff or at memory of your girlfriend's laptop (just kidding =) ). You must copy data (all or it's part), not pointer in between
Map()
Unmap()
: use memcopy,for
loop, anything. Put it in array,std::vector
, BST, everything.Typical mistakes that newcomers can made here:
HRESULT
return value fromID3D11DeviceContext::Map
method. If map fails it can return whatever pointer it likes. Dereferencing such pointer leads to undefined behavior. So, better check any DirectX function return value.D3D11_CPU_ACCESS_READ
CPU access flag which means that you must also setD3D11_USAGE_STAGING
usage fag.How do we usualy read from buffer:
ID3D11DeviceContext::CopyResource()
orID3D11DeviceContext::CopySubresourceRegion()
), and then copying data to system memory (memcopy()
).Drop's answer was helpful. I figured that the reason why I wasn't able to read the buffer was because I didn't have the CPU_ACCESS_FLAG set to D3D11_CPU_ACCESS_READ before. Here
And then to read data I did
I agree it's a performance decline, I wanted to do this, just to be able to debug the values!
Thanks anyway! =)
The following code only get the address of the mapped resource, you didn't read anything before Unmap.
If you want to read data from the mapped resource, first allocate enough memory, then use memcpy to copy the data, I don't know your VERTEX structure, so I suppose vert is void*, you can convert it yourself