可视化 如何在 C++/DirectX 和 HLSL 之间共享结构

visual How to share a struct between C++/DirectX and HLSL?

本文关键字:HLSL 之间 共享 结构 DirectX C++ 可视化      更新时间:2023-10-16

我正在学习C++和DirectX,我注意到在尝试保持HLSL着色器和C++代码中的结构同步时存在很多重复。我想分享结构,因为两种语言具有相同的#include语义和头文件结构。我遇到了成功

// 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

但是,问题在于在这些着色器的编译过程中,FXC告诉我input parameter 'input' missing sematics了像素着色器的主要功能:

#include "ColorStructs.h"
void main(PixelInput input)
{
    // Contents elided
}

我知道我需要像float4 Position : POSITION这样的语义,但我无法想出一种不违反C++语法的方法。

有没有办法使 HLSL 和 C++ 之间的结构保持通用?还是不可行,需要在两个源树之间复制结构?

您可以使用函数宏在编译时删除语义说明符C++

#ifdef __cplusplus
#define SEMANTIC(sem) 
#else
#define SEMANTIC(sem) : sem
#endif
struct VertexInput
{
    float4 Position SEMANTIC(POSITION0);
    float4 Color SEMANTIC(COLOR0);
};