如何在opengl中使用二维纹理数组

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

我试图加载纹理到一个二维数组,然后应用它们。
但屏幕上只显示黑色。
这是我的密码。
创建纹理。

void int loadTexture(char const* path)
{
    glCreateTextures(GL_TEXTURE_2D_ARRAY, 1, &textureID);

    int width, height, nrComponents;
    unsigned char* data1 = stbi_load("C:\\Temp\\RED.png" , &width, &height, &nrComponents, 0);   // Load the first Image of size 512   X   512  (RGB)
    unsigned char* data2 = stbi_load("C:\\Temp\\BLUE.png", &width, &height, &nrComponents, 0);  // Load the second  Image of size 512   X   512   (RGB)
    glTextureStorage3D(textureID, 1, GL_RGB8, width, height, 2);

     GLenum format;
     format = GL_RGB;

     glTextureSubImage3D(textureID, 1 , 0 , 0 , 1 , width, height, 1, GL_RGB, GL_UNSIGNED_BYTE, data1);
     glTextureSubImage3D(textureID, 1 , 0, 0, 2, width, height, 1, GL_RGB, GL_UNSIGNED_BYTE, data2);

      glTextureParameteri(textureID, GL_TEXTURE_WRAP_S, GL_REPEAT);
      glTextureParameteri(textureID, GL_TEXTURE_WRAP_T, GL_REPEAT);
      glTextureParameteri(textureID, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
      glTextureParameteri(textureID, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

      stbi_image_free(data1);
      stbi_image_free(data2);

      glBindTextureUnit(0, textureID);
}

使用纹理。

while (!glfwWindowShouldClose(window))
    {
        glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

         Shader.use();
        Shader.setFloat("textureUnit", 1);   // Bind the first texture unit of the texture array
        glBindTextureUnit(0, textureID);  
        renderQuad();
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

顶点着色器。


# version 460 core

layout( location = 0)in vec2 aPos;
layout( location = 1 )in vec2 a_uv;
out vec2 f_uv;

void main() {
f_uv = a_uv;
gl_Position =   vec4(aPos ,0.0, 1.0 );
};

片段着色器。

版本460内核

uniform sampler2DArray u_tex;
in vec2 f_uv;
out vec4 FragColor;
uniform float textureUnit;

in vec2 TexCoord2;
void main() {

        vec3 texCoordTest = vec3( f_uv.x , f_uv.y , textureUnit);
        vec4 color = texture(u_tex  , texCoordTest);            
        FragColor = color ; 

    };
ahy6op9u

ahy6op9u1#

glTextureSubImage3D的第5个参数是 zoffset。对于第1个纹理,该参数为0;对于第2个纹理,该参数为1。第2个参数是 level,而不是层数:
glTextureSubImage3D(textureID, 1 , 0 , 0 , 1 , width, height, 1, GL_RGB, GL_UNSIGNED_BYTE, data1);
glTextureSubImage3D(textureID, 1 , 0, 0, 2, width, height, 1, GL_RGB, GL_UNSIGNED_BYTE, data2);

glTextureSubImage3D(textureID, 0, 0, 0, 0, width, height, 1, GL_RGB, GL_UNSIGNED_BYTE, data1);
glTextureSubImage3D(textureID, 0, 0, 0, 1, width, height, 1, GL_RGB, GL_UNSIGNED_BYTE, data2);

相关问题