HLSL着色器显示奇怪的颜色

时间:2014-05-12 11:10:34

标签: c++ colors shader direct3d hlsl

我正在尝试创建一个着色器,其中我输入了顶点的位置,一些变换矩阵和一个用于顶点颜色的float4。操作位置工作正常,但我没有得到正确的颜色。

enter image description here

好的,这里是着色器的Inputlayout:

D3D11_INPUT_ELEMENT_DESC solidColorLayout[] =
{
    { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
    { "COLOR", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }
};

着色器本身看起来像这样:

cbuffer cbChangesEveryFrame : register(b0)
{
    matrix worldMatrix;
};

cbuffer cbNeverChanges : register(b1)
{
    matrix viewMatrix;
};

cbuffer cbChangeOnResize : register(b2)
{
    matrix projMatrix;
};

struct VS_Input
{
    float4 pos  : POSITION;
    float4 color : COLOR;
};

struct PS_Input
{
    float4 pos: SV_POSITION;
    float4 color: COLOR;
};

PS_Input VS_Main(VS_Input vert)
{
    PS_Input vsout = (PS_Input)0;
    vsout.color = vert.color;

    float4 worldPos = mul(vert.pos, worldMatrix);
    vsout.pos = mul(worldPos, viewMatrix);
    vsout.pos = mul(vsout.pos, projMatrix);

    return vsout;
}


float4 PS_Main(PS_Input psinput) : SV_TARGET
{
    return psinput.color;
}

不要对矩阵那些变换是正确的,我确实得到了正确的顶点,等等,但我得不到我定义的颜色。

所以例如我创建这样的顶点:

struct VertexPos
{
    XMFLOAT3 pos;
    XMFLOAT4 color;
};
...

VertexPos vertices[] =
{
    { XMFLOAT3(-1.0f, 0.0f, -1.0f), XMFLOAT4(0.1f,0.1f, 0.1f, 0.1f)},
    { XMFLOAT3(1.0f, 0.0f, -1.0f), XMFLOAT4(0.1f, 0.1f, 0.1f, 0.1f) },
    { XMFLOAT3(1.0f, 0.0f, 1.0f), XMFLOAT4(0.1f, 0.1f, 0.1f, 0.1f) },
    { XMFLOAT3(-1.0f, 0.0f, 1.0f), XMFLOAT4(0.1f, 0.1f, 0.1f, 0.1f) },
};

使用一些indexbuffer和drawcall本身很简单:

unsigned int stride = sizeof(VertexPos);
unsigned int offset = 0;

//set inputlayout and topology for drawing the sprites
context->IASetVertexBuffers(0, 1, &m_vertexBuffer, &stride, &offset);
context->IASetIndexBuffer(m_indexBuffer, DXGI_FORMAT_R16_UINT, 0);

//calculate cube stuff
XMMATRIX worldMat = getWorldMatrix();
worldMat = XMMatrixTranspose(worldMat);
context->UpdateSubresource(worldBuffer, 0, 0, &worldMat, 0, 0);//update world matrix
//draw
context->DrawIndexed(6, 0, 0);

所以我想知道它有什么问题吗? (参见网站上的线条和小脸,它们应该有颜色)

1 个答案:

答案 0 :(得分:1)

得到了它: 我的D3D11_INPUT_ELEMENT_DESC错了。我忘记了AlignedByteOffset。所以正确的Ofset应该是:

D3D11_INPUT_ELEMENT_DESC solidColorLayout[] =
{
    { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
    { "COLOR", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }
};

痘痘12毁了它。但它现在工作正常。 甚至可以改为:

D3D11_INPUT_ELEMENT_DESC solidColorLayout[] =
{
    { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
    { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }
};

备选方案,您可以使用D3D11_APPEND_ALIGNED_ELEMENT,它会自动计算正确的值。 (不确定它是否"保存")