OpenGL采样器2D阵列

jxct1oxe  于 2022-11-04  发布在  其他
关注(0)|答案(1)|浏览(165)

我有一个sampler2D数组,如下所示:uniform sampler2D u_Textures[2];。我希望能够在同一个drawcall中渲染更多的纹理(在本例中为2个)。在我的片段着色器中,如果我将颜色输出值设置为红色之类的值,它会显示2个红色方块,这让我相信我在绑定纹理时做错了什么。我的代码:
第一个
这是我的片段着色器:


# version 450 core

layout(location = 0) out vec4 color;

in vec2 v_TexCoord;
in float v_texIndex;

uniform sampler2D u_Textures[2];

void main() 
{
    int index = int(v_texIndex);
    vec4 texColor = texture(u_Textures[index], v_TexCoord);
    if (texColor.a == 0.0) {
        // this line fills the a = 0.0f pixels with the color red  
        color = vec4(1.0f, 0.0f, 0.0f, 1.0f);
    }
    else color = texColor;
}

另外,它只在屏幕上绘制tex2纹理。这是我的verticia属性:

float pos[24 * 2] = {
        // position xy z    texture coordinate, texture index
        -2.0f, -1.5f, 0.0f,     0.0f, 0.0f, 0.0f,
        -1.5f, -1.5f, 0.0f,     1.0f, 0.0f, 0.0f,
        -1.5f, -2.0f, 0.0f,     1.0f, 1.0f, 0.0f, // right side bottom
        -2.0f, -2.0f, 0.0f,     0.0f, 1.0f, 0.0f,

        0.5f, 0.5f, 0.0f,   0.0f, 0.0f, 1.0f,
        1.5f, 0.5f, 0.0f,   1.0f, 0.0f, 1.0f, 
        1.5f, 1.5f, 0.0f,   1.0f, 1.0f, 1.0f,
        0.5f, 1.5f, 0.0f,   0.0f, 1.0f, 1.0f
    };

无论我如何改变纹理指数,它只画这2个纹理之一。

1dkrff03

1dkrff031#

不能使用片段着色器输入变量来索引纹理采样器数组。必须使用sampler2DArrayGL_TEXTURE_2D_ARRAY),而不是sampler2DGL_TEXTURE_2D)数组。

int index = int(v_texIndex);
vec4 texColor = texture(u_Textures[index], v_TexCoord);

是未定义的行为,因为v_texIndex是片段着色器输入变量,因此不是动态统一表达式。请参见GLSL 4.60规范- 4.1.7。不透明类型
[...]结合纹理的采样器类型是不透明类型[...]。在着色器内聚合到数组中时,只能使用动态统一整数表达式对它们进行索引,否则结果未定义
使用sampler2DArray的示例:


# version 450 core

layout(location = 0) out vec4 color;

in vec2 v_TexCoord;
in float v_texIndex;

uniform sampler2DArray u_Textures;

void main() 
{
    color = texture(u_Textures, vec3(v_TexCoord.xy, v_texIndex));
}

texture对于所有采样器类型都是重载的。纹理坐标和纹理层不需要动态统一,但采样器数组的索引必须动态统一。
要明确的是,问题不在于采样器阵列(问题不在于sampler2D u_Textures[2];)。问题在于索引。问题在于v_texIndex不是动态统一的(问题是in float v_texIndex;)。它在索引是动态统一的情况下工作(eidogg. uniform float v_texIndex;将工作)。而且规范只是说结果是未定义的。所以可能有一些系统在那里它工作。

相关问题