使用 OpenGL 在二维对象上看不到我的纹理

Can't see my texture on 2d object using OpenGL

我正在尝试在我的迷你 OpenGL 程序中使用纹理。由于使用 OpenGL 需要大量重复代码,因此我将代码抽象为 class。但是我在 window 上看不到任何东西。 OpenGL 不会抛出任何错误。我正在使用 stb_image.h from https://github.com/nothings/stb/ 来处理图像文件。我做错了什么?我正在使用 Ubuntu 20.04.

Class声明:

class texture {
protected:
    unsigned int textureid;
    unsigned char* localbuf;
    int length, width, pixelbit;
    std::string srcpath;
public:
    texture(std::string file);
    ~texture();
    int getwidth() const;
    int getlength() const;
    void bind(unsigned int slot = 0) const;
    void unbind() const;
};

Class 实施:

texture::texture(std::string file) {
    srcpath = file;

    stbi_set_flip_vertically_on_load(1);
    localbuf = stbi_load(file.c_str(), &width, &length, &pixelbit, 4);

    glcall(glGenTextures(1, &textureid));
    glcall(glBindTexture(GL_TEXTURE_2D, textureid));

    glcall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
    glcall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
    glcall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
    glcall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));

    glcall(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, length, 0, GL_RGBA, GL_UNSIGNED_BYTE, localbuf))

    glcall(glBindTexture(GL_TEXTURE_2D, 0));

    if (localbuf) stbi_image_free(localbuf);
}

texture::~texture() {
    glcall(glDeleteTextures(1, &textureid));
}

void texture::bind(unsigned int slot) const {
    glcall(glActiveTexture(GL_TEXTURE0 + slot));
    glcall(glBindTexture(GL_TEXTURE_2D, textureid));
}

void texture::unbind() const {
    glcall(glBindTexture(GL_TEXTURE_2D, 0));
}

int texture::getwidth() const {
    return width;
}

int texture::getlength() const {
    return length;
}

顶点着色器:

#version 330 core
layout(location = 0) in vec4 position;
layout(location = 1) in vec2 texpos;
out vec2 v_texpos;
void main() {
    gl_Position = position;
    v_texpos = texpos;
};

片段着色器:

#version 330 core
layout(location = 0) out vec4 color;
in vec2 v_texpos; 
uniform sampler2D u_texture;
void main() {
    vec4 texcolor = texture2D(u_texture, v_texpos);
    color = texcolor;
};

main 函数:

int main() {
    ...
    texture mytexture("path/to/image/file.png");
    texture.bind();
    glUniform1i(glGetUniformLocation(shader, "u_texture"), 0);
    ...
    while (window_open) {
        ...
        glDrawElements(...);
        ...
    }
    ...
}

我正在使用 class 来处理顶点的布局。在那个class的实现中,有一个这样的循环:

for (int i = 0; i < ...; i++) {
    ...
    glEnableVertexAttribArray(i);
    ...
}

上面一个是正确的,但我之前输入 0 而不是 i 是这样的:

glEnableVertexAttribArray(0);

当我不处理纹理时,这个循环是 运行 一次并且 i 的值是 0 。但是当开始处理纹理时,这个循环是 运行 两次并且 i 并不总是 0 ,导致错误。