相同的 opngl texture2d 在 GTK 中变成全黑但在过剩中工作

Same opngl texture2d become all black in GTK but works in glut

我有一个程序使用 OpenGL + GLUT 从相机捕获图像并将其用作 2D 纹理。然后在 window 中显示具有该纹理的点云。它在 GLUT window 时工作正常。但是当我切换到 GTK opengl 区域时。点云(或顶点)显示但全黑。仅更改 window 相关代码,可能会出现什么问题?

代码如下。我只 post 关于纹理的代码,因为整个代码确实在 GLUT 中工作。所以我相信代码是正确的。也许 GTK 需要一些额外的设置?

生成纹理

  glGenTextures(1, &TEXTURE);
  glBindTexture(GL_TEXTURE_2D, TEXTURE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

更新纹理内容

    glBindTexture(GL_TEXTURE_2D, TEXTURE);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, frame.get_width(), frame.get_height(), 0, GL_RGB, GL_UNSIGNED_BYTE, frame.get_data());

更新顶点及其纹理坐标

for (int i = 0; i < points.size(); i++)
{
    if (rsVertices[i].z)
    {
        vertices[count * 3] = rsVertices[i].x * 0.5f;
        vertices[count * 3 + 1] = rsVertices[i].y * -0.5f;
        vertices[count * 3 + 2] = rsVertices[i].z - 1.5f;
        textureCoord[count * 2] = rsTextureCoord[i].u;
        textureCoord[count * 2 + 1] = rsTextureCoord[i].v;
        count++;
    }
}
glBindBuffer(GL_ARRAY_BUFFER, VBO_VERTEX);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * count * 3, vertices, GL_DYNAMIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void *)0);

glBindTexture(GL_TEXTURE_2D, TEXTURE);
glBindBuffer(GL_ARRAY_BUFFER, VBO_TEX);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * count * 2, textureCoord, GL_DYNAMIC_DRAW);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void *)0);

顶点着色器

#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 2) in vec2 aTexCoord;
uniform mat4 model;
uniform mat4 view;
uniform mat4 proj;
out vec2 TexCoord;
void main()
{
    gl_Position = proj * view * model * vec4(aPos.x, aPos.y, aPos.z, 1.0);
    TexCoord = aTexCoord;
};

片段着色器

#version 330 core
out vec4 FragColor;
in vec2 TexCoord;
uniform sampler2D ourTexture;
void main(){
    FragColor = texture(ourTexture, TexCoord);
}

问题已解决。我在不同的线程中更新纹理。所以,每次更新纹理缓冲区之前。 gdk_gl_context_make_current() 应该被调用。 (因为 GTK window 是由第三方代码控制的。也许它以某种方式改变了上下文)

gdk_gl_context_make_current(gdkContext);
glBindTexture(GL_TEXTURE_2D, TEXTURE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, frame.get_width(), frame.get_height(), 0, GL_RGB, GL_UNSIGNED_BYTE, frame.get_data());