Advertisement
xerpi

OpenGL + GLFW simple

Nov 25th, 2013
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.26 KB | None | 0 0
  1. #include <iostream>
  2. #include <GL/glew.h>
  3. #include <GLFW/glfw3.h>
  4. #include <glm/glm.hpp>
  5. using namespace std;
  6.  
  7. void error_callback(int error, const char *description);
  8. void key_callback(GLFWwindow *window, int key, int scancode, int action, int mods);
  9. void framebuffer_size_callback(GLFWwindow *window, int w, int h);
  10.  
  11. GLFWwindow *window = NULL;
  12. int width, height;
  13. void init_glfw();
  14.  
  15. const GLfloat vertex_data[] = {
  16.     -0.75f, -0.75f, 0.0f, 1.0f,
  17.      0.0f,   0.75f, 0.0f, 1.0f,
  18.      0.75f, -0.75f, 0.0f, 1.0f
  19. };
  20.  
  21. int main()
  22. {
  23.     init_glfw();
  24.  
  25.     GLuint positionBO;
  26.     glGenBuffers(1, &positionBO);
  27.     glBindBuffer(GL_ARRAY_BUFFER, positionBO);
  28.     glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_data), vertex_data, GL_STATIC_DRAW);
  29.     glBindBuffer(GL_ARRAY_BUFFER, 0);
  30.  
  31.     while(!glfwWindowShouldClose(window)) {
  32.         glClear(GL_COLOR_BUFFER_BIT);
  33.         glViewport(0, 0, width, height);
  34.  
  35.         glBindBuffer(GL_ARRAY_BUFFER, positionBO);
  36.         glEnableVertexAttribArray(0);
  37.         glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
  38.  
  39.         glDrawArrays(GL_TRIANGLES, 0, 3);
  40.  
  41.  
  42.         glfwSwapBuffers(window);
  43.         glfwPollEvents();
  44.     }
  45.  
  46.     glfwDestroyWindow(window);
  47.     glfwTerminate();
  48.     return 0;
  49. }
  50.  
  51. void key_callback(GLFWwindow *window, int key, int scancode, int action, int mods)
  52. {
  53.     if (key == GLFW_KEY_ESCAPE and action == GLFW_PRESS)
  54.         glfwSetWindowShouldClose(window, GL_TRUE);
  55. }
  56.  
  57. void init_glfw()
  58. {
  59.     glfwSetErrorCallback(error_callback);
  60.     if (!glfwInit())
  61.         exit(EXIT_FAILURE);
  62.  
  63.     window = glfwCreateWindow(640, 480, "OpenGL", NULL, NULL);
  64.     if (!window) {
  65.         glfwTerminate();
  66.         exit(EXIT_FAILURE);
  67.     }
  68.  
  69.     glfwMakeContextCurrent(window);
  70.     glewInit();
  71.     glfwSetKeyCallback(window, key_callback);
  72.     glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
  73.     glfwGetFramebufferSize(window, &width, &height);
  74.     glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
  75. }
  76.  
  77. void framebuffer_size_callback(GLFWwindow *window, int w, int h)
  78. {
  79.     cout << "Resized to: " << w << "x" << h << endl;
  80.     width  = w;
  81.     height = h;
  82.     //glViewport(0, 0, width, height);
  83. }
  84.  
  85. void error_callback(int error, const char *description)
  86. {
  87.     cerr << description;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement