2016-11-21 259 views
1

我试图运行在C++中,打开一个窗口,我的第一个OpenGL图像,设置背景颜色,并给出了一个标题,从终端在Mac OS XOpenGL的glClearColor总是黑屏

的代码编译和链接很好。当我运行该程序时,窗口和标题可以正常打开,但背景颜色始终为黑色。

据我了解,功能glClearColor设置背景颜色。但是,无论我传递给函数的参数是什么,窗口的背景颜色都是黑色的。

如果有人能向我解释我所犯的错误,我将非常感激。感谢和下面是代码:

#include <iostream> 

#define GLEW_STATIC 
#include <GL/glew.h> 

#include <GLFW/glfw3.h> 

const GLint WIDTH = 800, HEIGHT = 600; 

int main() 
{ 
    glfwInit(); 

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); 
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); 
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); 
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); 
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); 

    GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "Learn OpenGL", nullptr, nullptr); 

    int screenWidth, screenHeight; 
    glfwGetFramebufferSize(window, &screenWidth, &screenHeight); 

    if(nullptr == window) 
    { 
     std::cout << "Failed to create GLFW window" << '\n'; 
     glfwTerminate(); 

     return -1; 
    } 

    glewExperimental = GL_TRUE; 
    GLenum err=glewInit(); 

    if(err != glewInit()) 
    { 
     std::cout << "Failed to initialize GLEW" << '\n'; 

     return -1; 
    } 

    glViewport(0, 0, screenWidth, screenHeight); 

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

     glClearColor(0.2f, 0.2f, 0.9f, 0.5f); 
     glClear(GL_COLOR_BUFFER_BIT); 

     glfwSwapBuffers(window); 
    } 

    glfwTerminate(); 

    return 0; 
} 

回答

5

glClearColor,像所有的OpenGL功能,适用于当前的OpenGL上下文。

您没有将窗口的上下文设置为您的调用线程的当前内容,因此您对glClearColor的调用在此处不起作用。添加:

glfwMakeContextCurrent(window); 

在循环之前。

glfwMakeContextCurrent从文档:

该功能调用线程上指定的窗口当前的OpenGL或OpenGL ES的上下文。一个上下文只能在单个线程上一次生成,而且每个线程一次只能有一个当前上下文。