Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I've read this: http://msdn.microsoft.com/en-us/library/windows/desktop/ff476898%28v=vs.85%29.aspx#Shader_Constant_Buffer but there's not much information in it. When creating a constant buffer do I have to worry about what I put in it and in what order? Do I have to stick to a multiplicity of some power of 2 in bytes or something?

share|improve this question

1 Answer 1

up vote 2 down vote accepted

You need to make sure that any variable you use within the constant buffer does not cross a 16 byte alignment boundary, or you won't be able to access it from the shader.

For example, you could have a constant buffer that looks like this:

struct constant_buffer
{
     XMFLOAT4X4 wvp; // 64 bytes -> 16 byte aligned = OK
     XMFLOAT3 position; // 12 bytes (4 bytes left to reach 16 byte boundary)
     XMFLOAT4 color; // 16 bytes -> error,  this isn't aligned 
};

You won't be able to read the last component (color) from your shader, since it's split between two 16 byte boundaries.

This can be solved by rearranging the order of the buffer, like this:

struct constant_buffer
{
     XMFLOAT4X4 wvp; // 64 bytes -> 16 byte aligned = OK
     XMFLOAT4 color; // 16 bytes -> still 16 byte aligned
     XMFLOAT3 position; // 12 bytes -> OK, no 16 byte boundary has been crossed 
};

Or you can add some padding, like this:

struct constant_buffer
{
     XMFLOAT4X4 wvp; // 64 bytes -> 16 byte aligned = OK
     XMFLOAT3 position; // 12 bytes (4 bytes left to reach 16 byte boundary)
     float padding; // 4 bytes for padding to reach next 16 byte boundary
     XMFLOAT4 color; // 12 bytes -> OK, no 16 byte boundary has been crossed
};

The first way is preferred since it has less data to send, but sometimes you have no other choice than padding.

There's more information at Windows Dev Center.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.