OpenGL 纹理会导致 ImGUI 窗口永久失焦

OpenGL Texture cause ImGUI windows to be permanently out of focus

本文关键字:窗口 ImGUI 纹理 OpenGL      更新时间:2023-10-16

我正在遵循TheCherno在OpenGL上的教程(不过我已经修改了一些东西(。我使用的是MacOS mojave,并且拥有OpenGL 2.1。但是,当我进入教程的ImGui部分时,事情开始变得奇怪。

由于我使用的是旧版本的 OpenGL,因此我使用的是 ImGui 的glfw_opengl2_impl,并且 https://github.com/ocornut/imgui/blob/master/examples/example_glfw_opengl2/main.cpp 的示例代码有效,但除了 .h 文件之外,我还必须包含一些其他 cpp 文件(见我的代码顶部(。

当我用自己的代码尝试此操作时,我发现在调用ImGui_ImplOpenGL2_RenderDrawData(ImGui::GetDrawData());之前,我必须取消绑定着色器、顶点缓冲区/索引缓冲区和顶点数组 这实际上按预期工作过一次,但是在关闭并重新启动程序时,窗口拒绝聚焦,文本显示为矩形。喜欢 这。

我的代码:

#include "imgui.h"
#include "imgui_impl_opengl2.h"
#include "imgui_impl_glfw.h"
#include "imgui.cpp"
#include "imgui_impl_glfw.cpp"
#include "imgui_impl_opengl2.cpp"
#include "imgui_draw.cpp"
#include "imgui_widgets.cpp"
#include "imgui_demo.cpp"
// other includes
// Init GLEW, GLFW, etc
// Removing this chunk of code fixes the problem
localBuf = stbi_load(path.c_str(), &width, &height, &bits, 4); 
glGenTextures(1, &id);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, id);
setRenderHints({{GL_TEXTURE_MIN_FILTER, GL_NEAREST}, {GL_TEXTURE_MAG_FILTER, GL_NEAREST}});
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, localBuf);
if (localBuf) {
stbi_image_free(localBuf);
}
glGenerateMipmap(GL_TEXTURE_2D);

IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
ImGui::StyleColorsClassic();
ImGui_ImplGlfw_InitForOpenGL(window, true);
ImGui_ImplOpenGL2_Init();
while (!glfwWindowShouldClose(win)) {
// some logic for the camera ...
ImGui_ImplOpenGL2_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
{
ImGui::Begin("Hello, world!");
ImGui::ColorEdit3("Tint: ", (float *) &tint);
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate,
ImGui::GetIO().Framerate);
ImGui::Text("Count: %iu", counter);
ImGui::End();
}

ImGui::Render();
glClearColor(0.25f, 0.25f, 1, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDrawElements(GL_QUADS, 24, GL_UNSIGNED_INT, nullptr);
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glUseProgram(0);
ImGui_ImplOpenGL2_RenderDrawData(ImGui::GetDrawData());
glUseProgram(shader);
glBindVertexArray(vao);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
ImGui_ImplOpenGL2_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
// terminate glfw.

编辑:我刚刚发现完全删除所有纹理可以解决问题。在绘制之前取消绑定纹理不会执行任何操作。

编辑2:显然有多个纹理是问题所在?!!有一个纹理很好,但有多个纹理会导致这个问题。同样,解除绑定没有任何作用。

知道了!出于某种原因,使用多个纹理插槽会让ImGui感到不安。我只用了一个插槽,一切都按预期工作!