尝试在打开GL中创建空白窗口时出现异常输出

时间:2016-08-06 11:47:13

标签: c++ c opengl graphics glfw

我试图在GLFW的帮助下在OpenGL中创建一个空白窗口。下面是我的代码

#include <stdio.h>
#include <stdlib.h>

#include <GL/glew.h>

#include <glfw3.h>
GLFWwindow* window;

#include <glm/glm.hpp>
using namespace glm;

int main( void )
{

    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
    window = glfwCreateWindow(800,600,"learnopengl",NULL,NULL);
    if (window == NULL)
    {
        fprintf(stderr,"there is a problem with window creation\n");
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);

    glewExperimental = GL_TRUE;
    if (glewInit() != GLEW_OK)
    {
        fprintf(stderr,"Failed to initialize GLEW\n");
        return -1;
    }
    int width, height;
    glfwGetFramebufferSize(window,&width,&height);

    glViewport(0,0,width,height);

while(!glfwWindowShouldClose(window))
{
    glfwPollEvents();
    glfwSwapBuffers(window);
}


    glfwTerminate();
}

但是当我尝试运行上面的代码而不是黑色空白时,它会在新创建的窗口中显示当前屏幕的实例。

2 个答案:

答案 0 :(得分:5)

为什么您希望此代码导致空白窗口?

根据规范,交换缓冲区后,后台缓冲区内容变为 undefined (最初,它们当然也是未定义的)。因此,您应该得到的输出也是未定义的,基本上任何东西都可能出现。

如果需要一些已定义的输出,请在渲染循环中添加glClear(GL_COLOR_BUFFER_BIT)

答案 1 :(得分:0)

我知道答案很晚,但是可能会涉及到其他人并帮助他们,我运行了这段代码,它运行良好,但是问题不在您的代码中,而是您的视频卡驱动程序,那么这是怎么回事? OpenGL具有所谓的“默认帧缓冲区”,它是用来创建OpenGL的帧缓冲区(缓冲区将包含您将看到的内容)。它与OpenGL上下文一起创建。像帧缓冲对象一样,默认的帧缓冲是一系列图像。与FBO不同,这些图像之一通常代表您实际在屏幕的某个部分看到的图像。换句话说,默认的帧缓冲区是操作系统用于渲染桌面和其他应用程序窗口的缓冲区,因此您的应用程序使用默认的帧缓冲区,因为该帧缓冲区未由您的应用程序编辑,因此您可能需要使用以下命令清除帧缓冲区:其他一些值,例如颜色。这是使用颜色使用缓冲区清除功能编辑的代码。

#include <stdio.h>
#include <stdlib.h>
#include <GL/glew.h>
#include <glfw3.h>

GLFWwindow* window;

#include <glm/glm.hpp>
using namespace glm;

int main( void )
{

 glfwInit();
 glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
 glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
 glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
 glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
 window = glfwCreateWindow(800,600,"learnopengl",NULL,NULL);
 if (window == NULL)
 {
     fprintf(stderr,"there is a problem with window creation\n");
     glfwTerminate();
     return -1;
 }
 glfwMakeContextCurrent(window);

 glewExperimental = GL_TRUE;
 if (glewInit() != GLEW_OK)
 {
     fprintf(stderr,"Failed to initialize GLEW\n");
     return -1;
 }
 int width, height;
 glfwGetFramebufferSize(window,&width,&height);

 glViewport(0,0,width,height);
 
 //this is an added line
 glClearColor(1, 1, 1, 1); //the RGBA color we will clear with
 
 while(!glfwWindowShouldClose(window))
 {
   glfwPollEvents();
   //this is an added line
   glClear(GL_COLOR_BUFFER_BIT); //the buffer used to clear with

   glfwSwapBuffers(window);
 }


  glfwTerminate();
 } 

希望这个答案,此代码可以帮助其他可能遇到这种情况的人。 有关帧缓冲区的更多信息,请检查以下链接:https://learnopengl.com/Advanced-OpenGL/Framebuffers