6
votes

I'm in the process of learning C++ and DirectX, and I'm noticing a lot of duplication in trying to keep structs in my HLSL shaders and C++ code in sync. I'd like to share the structs, since both languages have the same #include semantics and header file structure. I met success with

// ColorStructs.h
#pragma once

#ifdef __cplusplus

#include <DirectXMath.h>
using namespace DirectX;

using float4 = XMFLOAT4;

namespace ColorShader
{

#endif

    struct VertexInput
    {
        float4 Position;
        float4 Color;
    };

    struct PixelInput
    {
        float4 Position;
        float4 Color;
    };

#ifdef __cplusplus
}
#endif

The problem, though, is during the compilation of these shaders, FXC tells me input parameter 'input' missing sematics on the main function of my Pixel shader:

#include "ColorStructs.h"

void main(PixelInput input)
{
    // Contents elided
}

I know that I need to have the semantics like float4 Position : POSITION but I can't come up with a way to do this that wouldn't violate C++'s syntax.

Is there a way I can keep the structs common between HLSL and C++? Or is it unfeasible, and requires duplicating the structs between the two source trees?

1
Note that it's generally considered a bad idea to put "using namespace" in an unrelated header file (since it makes accidental name collisions more likely).user253751
That's a good point! This started out as a C++ header, and I forgot to remove it. Thanks for pointing that out!berwyn

1 Answers

5
votes

You could use a function macro to remove the semantic specifiers while compiling C++

#ifdef __cplusplus
#define SEMANTIC(sem) 
#else
#define SEMANTIC(sem) : sem
#endif

struct VertexInput
{
    float4 Position SEMANTIC(POSITION0);
    float4 Color SEMANTIC(COLOR0);
};