I'm working on a Directx C++/CX (Universal Windows) project.
I'm not all that familiar with Directx11 by the way.
My code is mostly based on the sample projects on MSDN related to rendering directx in UWP using swapchainpanels.
Now I wanted to add a float variable to the shader. I believe this has to be done using the constantbuffer. Currently this is as follows (and works):
//c++:
struct ModelViewProjectionConstantBuffer
{
DirectX::XMFLOAT4X4 model;
DirectX::XMFLOAT4X4 view;
DirectX::XMFLOAT4X4 projection;
//float distance;
};
//hlsl:
cbuffer ModelViewProjectionConstantBuffer : register(b0)
{
matrix model;
matrix view;
matrix projection;
//float distance;
};
Now when I add a float, it stops working. It throws an exception when I update the constant buffer (which happens before each rendered frame):
_d3dContext->UpdateSubresource(
_constantBuffer.Get(),
0,
NULL,
&_constantBufferData,
0,
0
);
The exception is a SEHException (so as far as I can find, this doesn't tell me anything).
I'm basing all this on the following page: https://msdn.microsoft.com/en-us/library/ff476896(v=vs.85).aspx
Can anyone tell me what I'm doing wrong?
Constant buffers have size aligned on 16 bytes, when you had a single float at the end, you in fact inflate the constant buffer size by 16, but on the code side, your struct only inflate by 4. What is happening is that UpdateSubResource try to read these 12 extra bytes and produce a memory access violation.
You should be able to fix things by adding the padding like that
struct ModelViewProjectionConstantBuffer
{
DirectX::XMFLOAT4X4 model;
DirectX::XMFLOAT4X4 view;
DirectX::XMFLOAT4X4 projection;
float distance;
float pad[3]
};
You can read about the padding rules here for more details : https://msdn.microsoft.com/en-us/library/windows/desktop/bb509632(v=vs.85).aspx