如何进行无分支丢弃?

问题描述 投票:0回答:1

我有一个相当基本的片段着色器,它可以从纹理中采样并根据样本更改分配的固定颜色。如果我从纹理中采样,我会进行 alpha 检查并丢弃低 alpha 值。有没有办法让这个过程无分支?

#version 460 core
layout (location = 0) out vec4 FragColor;

uniform vec4 color;
uniform sampler2D tex;
uniform bool useTex;
in vec2 texCoords;

void main() {
   vec4 tex = texture(tex, texCoords);
   if(useTex && tex.a < 0.1) { discard; }
   vec4 outColor = mix(color, color * tex, int(useTex));
   FragColor = outColor;
}
opengl glsl shader fragment-shader branchless
1个回答
3
投票

我建议始终绑定纹理,至少是带有颜色 (1, 1, 1, 1) 的 1x1 纹理。通过这种方法,您可以完全省略

useTex
并且着色器更简单:

#version 460 core

layout (location = 0) out vec4 FragColor;

uniform vec4 color;
uniform sampler2D tex;
in vec2 texCoords;

void main() 
{
    vec4 outColor = color * texture(tex, texCoords);
    if (outColor.a < 0.1)
        discard;
    FragColor = outColor;
}

如果你可以使用Blending代替

discard
,着色器可以进一步简化:

#version 460 core

layout (location = 0) out vec4 FragColor;

uniform vec4 color;
uniform sampler2D tex;
in vec2 texCoords;

void main() 
{
    FragColor = color * texture(tex, texCoords);
}
© www.soinside.com 2019 - 2024. All rights reserved.