金属片段着色器中的测试属性

Test Attributes in Metal Fragment Shader

我正在尝试制作一个片段着色器,可以在某些 material 属性 是颜色类型或纹理的情况下使用。但是我遇到了很大的问题。 假设我有一个像这样的 Material 结构:

typedef struct {  
    vector_float4 diffuseColor;  
    bool useDiffuseTexture;  
} Material; 

和片段函数:

fragment float4 fragment_main(Vertex vert [[stage_in]],  
                              constant Constants &uniforms [[buffer(0)]],  
                              constant Material &material [[buffer(1)]],  
                              texture2d<float> diffuseTexture [[texture(0)]],  
                              sampler          diffuseTextureSampler [[sampler(0)]]  
                              )  
{...}

在片段主体中,我将有:

float4 diffuseColor = material.diffuseColor;

或者如果 material 有漫反射纹理:

float4 diffuseColor = diffuseTexture.sample(diffuseTextureSampler, float2(vert.textcoords));  

问题是我无法真正测试着色器中纹理的存在,所以我想我将把它作为参数传递到结构中:

bool useDiffuseTexture;

但出于某种原因,此代码:

float4 diffuseColor = material.diffuseColor;  
if (material.useDiffuseTexture == true ) {  
        diffuseColor = diffuseTexture.sample(diffuseTextureSampler, float2(vert.textcoords));  
}

总是调用 diffuseTexture 并引发错误:

diffuseTexture[0]

在索引 0 处缺少纹理绑定

我不确定我做错了什么。我不能绑定因为没有纹理。

提前致谢

即使您不在函数中使用它,每个纹理、缓冲区或采样器参数也必须在参数 table 中绑定一个相应的对象。在您的情况下,您可以绑定一个 "dummy"、1x1 纹理来满足此要求,或者您可以有两个着色器变体(因此有两个渲染管线状态),一个使用漫反射颜色,一个对漫反射纹理进行采样.