DX11 HLSL and Input Layout connection
Process of C++ vertex structure entering Shader input
The articles written on this blog were created with the goal of teaching. Also, the information in the article may be incorrect, so please be careful.
In DirectX 11, creating only a vertex buffer does not cause a triangle to appear. A Vertex Shader that processes the vertex position and a Pixel Shader that determines the pixel color are needed.
Basic HLSL
struct VSInput
{
float3 Position : POSITION;
float4 Color : COLOR;
};
struct VSOutput
{
float4 Position : SV_POSITION;
float4 Color : COLOR;
};
VSOutput VSMain(VSInput Input)
{
VSOutput Output;
Output.Position = float4(Input.Position, 1.0f);
Output.Color = Input.Color;
return Output;
}
float4 PSMain(VSOutput Input) : SV_TARGET
{
return Input.Color;
}
POSITIONclassCOLORis a semantic that tells what C++ vertex data means. SV_POSITIONis the screen position required by the rasterizer,SV_TARGETis the color to be recorded in the render target.
Shader compilation
ID3DBlob* VSBlob = nullptr;
ID3DBlob* PSBlob = nullptr;
ID3DBlob* ErrorBlob = nullptr;
D3DCompileFromFile(
L"Triangle.hlsl", nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE,
"VSMain", "vs_5_0", 0, 0, &VSBlob, &ErrorBlob
);
D3DCompileFromFile(
L"Triangle.hlsl", nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE,
"PSMain", "ps_5_0", 0, 0, &PSBlob, &ErrorBlob
);
Device->CreateVertexShader(
VSBlob->GetBufferPointer(), VSBlob->GetBufferSize(),
nullptr, &VertexShader
);
Device->CreatePixelShader(
PSBlob->GetBufferPointer(), PSBlob->GetBufferSize(),
nullptr, &PixelShader
);
If compilation failsErrorBlobYou can find out the cause by printing the string. It is difficult to debug by looking at the HRESULT without checking the file path or Entry Point typos.
Input Layout Connection
D3D11_INPUT_ELEMENT_DESC Elements[] =
{
{ "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 }
};
Device->CreateInputLayout(
Elements,
static_cast<UINT>(std::size(Elements)),
VSBlob->GetBufferPointer(),
VSBlob->GetBufferSize(),
&InputLayout
);
C++ VertexThe actual memory layout of the structure and the Format and Offset of the Input Layout must be the same. Since Position is 12 Bytes, Color Offset is 12.
The point of the DX11 triangle example is not to memorize API calls. The point is that the CPU's vertex structure, input layout, and vertex shader input must have exactly the same contract.