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

How to use a 2d texture array in opengl

我正在尝试将纹理加载到二维数组中然后应用它们。

但是屏幕只显示黑色

这是我的代码。

创建纹理。

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 ; 
                                
    };

glTextureSubImage3D 的第 5 个参数是 zoffset。第一个纹理为 0,第二个纹理为 1。第二个参数是 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);