Search code examples
shaderrenderingvulkanhlsl

Understanding how to setup simple HLSL vertex and fragment shaders


I'm trying to understand how to use the HLSL shading language to output my simple vulkan triangle. I'm compiling my shader files with google's glslc compiler and not getting any complaints when compiling the shaders but no triangle is being produced. I know my HLSL files are wrong because I was able to output a triangle via GLSL. I've been trying to piece together my HLSL shaders from various tutorials and here are my current vert.hlsl and pixel.hlsl files:

vert.hlsl

struct vertex_info
{
    float2 position : POSITION;
    float3 color : COLOR;
};

struct vertex_to_pixel
{
    float4 position : POSITION;
    float3 color : COLOR;
};

void main(in vertex_info IN, out vertex_to_pixel OUT)
{
    OUT.position = float4(IN.position, 0.0, 1.0);
    OUT.color = IN.color;
};

pixel.hlsl

struct vertex_to_pixel
{
    float4 position : POSITION;
    float3 color : COLOR;
};

float4 main(in vertex_to_pixel IN) : COLOR
{
    return float4(IN.color, 1.0);   
};

In my cpp program with vulkan I try and pass a single vertex buffer containing 3 vertices which contain float2 positions and float3 colors:

struct vec2 {
    float x{};
    float y{};
};

struct vec3 {
    float r{};
    float g{};
    float b{};
};

struct vertex {
    vec2 pos;
    vec3 color;
};

vertex vertices[3] = {
        {{0.0f, -0.5f},   {1.0f, 0.0f, 0.0f}},
        {{0.5f, 0.5f},    {0.0f, 1.0f, 0.0f}},
        {{-0.5f, 0.5f},   {0.0f, 0.0f, 1.0f}}
    };

Solution

  • I think the main issue was I wasn't using the SV_POSITION semantic. I also changed up the shader code slightly and everything worked. The changed shader code was the following:

    vert.hlsl

    struct vertex_info
    {
        float2 position : POSITION;
        float3 color : COLOR;
    };
    
    struct vertex_to_pixel
    {
        float4 position : SV_POSITION;
        float3 color : COLOR;
    };
    
    vertex_to_pixel main(in vertex_info IN)
    {
        vertex_to_pixel OUT;
    
        OUT.position = float4(IN.position, 0.0, 1.0);
        OUT.color = IN.color;
    
        return OUT;
    };
    

    pixel.hlsl

    struct input_from_vertex
    {
        float3 color : COLOR;
    }
    
    float4 main(in input_from_vertex IN) : COLOR
    {
        return float4(IN.color, 1.0);
    };