2016-08-25 109 views
0

我正在通過http://learnopengl.com/學習OpenGL,但是當我試圖綁定本教程的'hello triangle'部分中的緩衝區時,我崩潰了。我有C++編程經驗,但我無法弄清楚什麼是錯的。調用glGenBuffers時openGL崩潰

我的代碼:

#include <iostream> 

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

using namespace std; 



const GLuint WIDTH = 800, HEIGHT = 600; 

void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode); 
int initializeWindow(GLFWwindow* window); 
int main() { 

    GLFWwindow* window; 

    cout << "Creating Triangles" << endl; 
    GLfloat triangles[] = { 
      -0.5f, -0.5f, 0.0f, 
      0.5f, -0.5f, 0.0f, 
      0.5f, 0.5f, 0.0f 
    }; 

    cout << "Initialising GLFW" << endl; 
    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); 

    cout << "Initialising Window..." << endl; 
    window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", NULL, NULL); 

    cout << "Setting Callback Functions..." << endl; 
    glfwSetKeyCallback(window, key_callback); 

    cout << "Binding Buffers" << endl; 
    GLuint VBO; 
    glGenBuffers(1, &VBO); // <--- Crashing here 
    glBindBuffer(GL_ARRAY_BUFFER, VBO); 
    glBufferData(GL_ARRAY_BUFFER, sizeof(triangles), triangles, GL_STATIC_DRAW); 

    if (initializeWindow(window) == -1) { 
     return -1; 
    } 

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

     glClearColor(0.2f, 0.3f, 0.3f, 1.0f); 
     glClear(GL_COLOR_BUFFER_BIT); 

     glfwSwapBuffers(window); 
    } 

    cout << "Terminating..." << endl; 
    glfwTerminate(); 
    return 0; 
} 

int initializeWindow(GLFWwindow* window) { 

     if (window == NULL) { 
      cout << "Failed to create GLFW window... exiting" << endl; 
      glfwTerminate(); 
      return -1; 
     } 

     glfwMakeContextCurrent(window); 

     glewExperimental = GL_TRUE; 
     if(glewInit() != GLEW_OK) { 
      cout << "Failed to initialize GLEW... exiting" << endl; 
      return -1; 
     } 

     int width, height; 
     glfwGetFramebufferSize(window, &width, &height); 
     glViewport(0, 0, width, height); 

     return 0; 
} 

void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) { 
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) { 
     glfwSetWindowShouldClose(window, GL_TRUE); 
    } 
} 

我得到只是一個通用的「不響應」的一聲,在控制檯中沒有錯誤。任何幫助將不勝感激,謝謝。

回答

2

您需要在窗口創建之後和任何調用gl函數之前調用initializeWindow。這是必要的,以使當前窗口活動並初始化(這些操作都在initializewindow內完成)

+0

ahh的原因,我完全忘記了我在if語句中初始化窗口。謝謝! –