繁体   English   中英

OpenGL 采样器二维数组

[英]OpenGL sampler2D array

我有一个 sampler2D 数组,看起来像这样: uniform sampler2D u_Textures[2]; . 我希望能够在同一个绘图调用中渲染更多纹理(在本例中为 2)。 在我的片段着色器中,如果我将颜色 output 值设置为类似红色的值,它确实显示了 2 个红色方块,女巫让我相信我在绑定纹理时做错了。 我的代码:

Texture tex1("Texture/lin.png");
tex1.Bind(0);
Texture tex2("Texture/font8.png");
tex2.Bind(1);

auto loc = glGetUniformLocation(sh.getRendererID(), "u_Textures");
GLint samplers[2] = { 0, 1 };
glUniform1iv(loc, 2, samplers);
void Texture::Bind(unsigned int slot) const {
    glActiveTexture(slot + GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, m_RendererID);
}

这是我的片段着色器:

#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 纹理。 这是我的顶点属性:

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 个纹理中的 1 个。

您不能使用片段着色器输入变量来索引纹理采样器数组。 您必须使用sampler2DArray ( GL_TEXTURE_2D_ARRAY ) 而不是sampler2D ( GL_TEXTURE_2D ) 的数组。

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

是未定义的行为,因为v_texIndex是片段着色器输入变量,因此不是动态统一表达式 请参阅GLSL 4.60 规范 - 4.1.7。 不透明类型

[...] 纹理组合采样器类型是不透明类型,[...]。 当在着色器中聚合成数组时,只能使用动态统一的积分表达式对它们进行索引,否则结果为 undefined


使用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; )。 它在索引是动态统一的时候起作用(例如uniform float v_texIndex;会起作用)。 此外,规范只是说结果是未定义的。 所以可能有一些系统可以工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM