0
votes

I'm a total beginner to HLSL and have got some sample code that renders a flat triangle. If I try to replace the PShader function from one that returns an explicit color to one that references a global variable (mycol) below, then it no longer renders the triangle in color but in black.

float4 mycol = float4(1.0f, 1.0f, 0.0f, 1.0f);

float4 VShader(float4 position : POSITION) : SV_POSITION
{
        return position;
}

float4 PShader(float4 position : SV_POSITION) : SV_Target
{
    return mycol; // float4(1.0f, 0.0f, 1.0f, 1.0f);
}

I've tried reading the HLSL specs but feel I'm probably missing something obvious?

any help appreciated, GMan

2

2 Answers

0
votes

I believe you can only pass global values using constant buffers in directx. You need to initiate the constant buffer in the c++ code:

    D3D11_BUFFER_DESC constDesc;
ZeroMemory( &constDesc, sizeof( constDesc ) );
constDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
constDesc.ByteWidth = sizeof(XMFLOAT4);
constDesc.Usage = D3D11_USAGE_DEFAULT;

d3dResult = d3dDevice_->CreateBuffer( &constDesc, 0, &shaderCB_ );

if( FAILED( d3dResult ) )
{
    return false;
}

Then in your rendering code:

XMFLOAT4 mycol = XMFLOAT4(1,1,0,1);
d3dContext_->UpdateSubresource(shaderCB_, 0, 0, &mycol, 0, 0);

and in your shader:

cbuffer colorbuf : register(b0)
{
    float4 mycol;
};
0
votes

It's possible that your global variable have changed the value if you are using separated shaders... try passaing forward the variable:

float4 mycol = float4(1.0f, 1.0f, 0.0f, 1.0f);

struct VS_OUT
{
    float4 pos : SV_Position;
    float4 color : COLOR0;
}

VS_OUT VShader(float4 position : POSITION)
{
    VS_OUT ret;
    ret.pos = position;
    ret.color = mycol; // forward variable
    return ret; 
}

float4 PShader(VS_OUT input) : SV_Target
{
    return input.color;
}