DirectX HLSL - Pixel Shader中的常量缓冲区为空,但不是顶点着色器

时间:2015-02-16 20:40:54

标签: c++ directx hlsl zero pixel-shader

我正在DirectX 11项目中实现照明。我遇到的问题是,当我尝试从Pixel Shader函数访问cbuffer值时,它只返回float3(0,0,0),同时当我在Vertex Shader函数中访问相同的值时,它返回正确的值。这是着色器:

/*********************************************\
                 VERTEX SHADER
\*********************************************/

//Constant buffers
cbuffer Object : register(cb0) {
    float4x4 WorldMatrix;
};
cbuffer Camera : register(cb1) {
    float4x4 ViewMatrix;
    float4x4 ProjectionMatrix;
};
cbuffer LightBuffer : register(cb2) {
    float3 AmbientColor;
}


//IO Structs
struct VS_INPUT {
    float3 Position : POSITION;
    float2 UV : TEXCOORD;
    float3 Normal : NORMAL;
};
struct VS_OUTPUT {
    float4 Position : SV_POSITION;
    float2 UV : TEXCOORD;
    float3 Normal : NORMAL;
};

VS_OUTPUT VS(VS_INPUT input){
    VS_OUTPUT output;

    float4 Position;

    //Multiply position with AmbientColor (should be 1, 1, 1), position unchanged
    Position = mul(ViewMatrix, float4(input.Position * AmbientColor, 1));
    Position = mul(ProjectionMatrix, Position);
    Position = mul(WorldMatrix, Position);

    output.Position = Position;
    output.UV = input.UV;
    output.Normal = mul(WorldMatrix, input.Normal);
    return output;
}

/*********************************************\
                PIXEL SHADER
\*********************************************/

SamplerState TextureState;
Texture2D<float4> Texture;
float4 PS(VS_OUTPUT input) : SV_TARGET {
    float4 MaterialColor = Texture.Sample(TextureState, input.UV);

    //Multiply color with AmbientColor (should be 1, 1, 1), returns black
    float3 FinalColor = MaterialColor.xyz * AmbientColor;

    return float4(FinalColor, MaterialColor.a);
}

这里是我发送的值(c ++):

_LightsUniform.AmbientColor = XMFLOAT3(1, 1, 1); 
DeviceContext->UpdateSubresource(_LightBuffer, 0, NULL, &_LightsUniform, 0, 0);
DeviceContext->VSSetConstantBuffers(2, 1, &_LightBuffer);
DeviceContext->PSSetConstantBuffers(2, 1, &_LightBuffer);

结果如下: http://i.gyazo.com/357f1ed3ea33e6569ad2346b368cd975.png

结果没有倍增颜色:http://gyazo.com/b60b385daa94d3373e9552a523928e3f

我看不出有什么问题。还有其他人有同样的问题吗?

1 个答案:

答案 0 :(得分:4)

我发现了问题。事实证明我的cbuffer的寄存器是错误的,我使用了cb#,其中应该使用b#。 (我误解了这里所写的内容:https://msdn.microsoft.com/en-us/library/windows/desktop/hh447212(v=vs.85).aspx

错误的代码:

cbuffer LightBuffer : register(cb2) {

更改为:

cbuffer LightBuffer : register(b2) {