AllenYuan

window - game loop

Apr 21st, 2020
328
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.29 KB | None | 0 0
  1. // import stdio and rendering libraries
  2. #include <cstdio>
  3. #include <GL/glew.h>
  4. #include <GLFW/glfw3.h>
  5.  
  6. // callback to print errors to console
  7. void error_callback(int error, const char *description)
  8. {
  9.   fprintf(stderr, "Error: %s\n", description);
  10. }
  11.  
  12. // play the game
  13. int main(int argc, char *argv[])
  14. {
  15.   // on error, print errors to console
  16.   glfwSetErrorCallback(error_callback);
  17.  
  18.   // initialize glfw. if it fails, exit the program.
  19.   if (!glfwInit())
  20.   {
  21.     return -1;
  22.   }
  23.  
  24.   // create a 640x480 window titled "Space Invaders"
  25.   GLFWwindow *window = glfwCreateWindow(640, 480, "Space Invaders", NULL, NULL);
  26.   // window doesn't render => close the program
  27.   if (!window)
  28.   {
  29.     glfwTerminate();
  30.     return -1;
  31.   }
  32.   // bind OpenGL calls to this window (allows us to draw on this window)
  33.   glfwMakeContextCurrent(window);
  34.  
  35.   // initialize GLEW so we can make OpenGL calls. Print an error and close the window if it fails
  36.   GLenum err = glewInit();
  37.   if (err != GLEW_OK)
  38.   {
  39.     fprintf(stderr, "Error initializing GLEW.\n");
  40.     glfwTerminate();
  41.     return -1;
  42.   }
  43.  
  44.   // if we see the below log statements, we've successfully attached OpenGL to the window
  45.   // query the openGL version
  46.   int glVersion[2] = {-1, 1};
  47.   glGetIntegerv(GL_MAJOR_VERSION, &glVersion[0]);
  48.   glGetIntegerv(GL_MINOR_VERSION, &glVersion[1]);
  49.  
  50.   // print some information about our version of OpenGL.
  51.   printf("Using OpenGL: %d.%d\n", glVersion[0], glVersion[1]);
  52.   printf("Renderer used: %s\n", glGetString(GL_RENDERER));
  53.   printf("Shading Language: %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
  54.  
  55.   // set the buffer clear color to red (rgba code)
  56.   glClearColor(1.0, 0.0, 0.0, 1.0);
  57.   // persist the window until user closes it
  58.   while (!glfwWindowShouldClose(window))
  59.   {
  60.     // 'buffer' means an image which can be displayed on the screen
  61.     // OpenGL has a 'front buffer' which is displayed on the screen and a 'back buffer'
  62.     // which is used for drawing.
  63.  
  64.     // every tick, clear the front buffer and swap in the back buffer
  65.     glClear(GL_COLOR_BUFFER_BIT);
  66.     glfwSwapBuffers(window);
  67.     // process pending events (for example, clicking the close button)
  68.     glfwPollEvents();
  69.   }
  70.  
  71.   // clean up our program and exit
  72.   glfwDestroyWindow(window);
  73.   glfwTerminate();
  74.   return 0;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment