Search code examples
directxshaderpixelalphablending

what is the 'alpha' value of pixel shader?


hi there day i am in process to make 2d game using directx11 api. and it come to point that i need to use transparent effect.

so i have a green background and one footprint on middle. enter image description here and simply without setting anything but alpha value of returning color in pixel shader, i made a bit of success, but the problem is that it doesn't work for white color.

this is Pixel Shader code

cbuffer CB_TRANSPARENCY : register(b0)
{
    float tp;
};

Texture2D footprint : register(t0);
SamplerState samplerState : register(s0);

struct PS_INPUT
{
    float4 pos : SV_POSITION;
    float2 tex : TEXCOORD;
};

float4 main(PS_INPUT input) : SV_Target
{
    float3 texColor = footprint.Sample(samplerState, input.tex).xyz;
    return float4(texColor, tp);
}

it there something that i miss? or should i use some blendingstate thing? any help would be appreciated

[edit] here's something to edit. actually alpha value doesn't do anything without blending setting. just one variable to be used for any custom calculation. In my project, i was using spritebathch,spritefont class for rendering font on screen, So i guess in spritebatch class, there might be blendingState under the hood that blend black color, so that i have got this effect without setting my blendingState.


Solution

  • Yes, you need to create a blend state with appropriate alpha processing mode and then make sure that created blend state is attached to output merging stage of the rendering pipeline prior to drawing:

    D3D11_BLEND_DESC blendStateDesc{};
    blendStateDesc.AlphaToCoverageEnable = FALSE;
    blendStateDesc.IndependentBlendEnable = FALSE;        
    blendStateDesc.RenderTarget[0].BlendEnable = TRUE;
    blendStateDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
    blendStateDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
    blendStateDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
    blendStateDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_SRC_ALPHA;
    blendStateDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_DEST_ALPHA;
    blendStateDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
    blendStateDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
    
    if(not SUCCEEDED(p_device->CreateBlendState(&blendStateDesc, &blendState)))
    {
        std::abort();
    }
    
    p_device_context->OMSetBlendState(blendState, nullptr, 0xFFFFFFFF);
    //draw calls...