new: Set up a window

Nehe的教程确实太老了,不过我认为它也能够让我了解OpenGL3.2以前的管线渲染模式,即使它在现在已经不常见了。因为想要了解,所以我还是会看完Nehe的教程。

现在这是一个新的教程 - JoeyDeVries的教程,可以说是网上最好的OpenGL教程,现在一步一步地来学习。我会在每个新的教程标题前面附加new,旧的教程标题前面附加outdated。

glfw的函数都可以在这里找到

在运行代码前,需要先在项目属性-链接器-输入-附加依赖项中添加glew32s.lib、glfw3.lib、opengl32.lib。

代码如下:

 1 #include <iostream>
 2 
 3 // GLEW
 4 #define GLEW_STATIC
 5 #include <GL/glew.h>
 6 
 7 // GLFW
 8 #include <GLFW/glfw3.h>
 9 
10 // Window dimensions
11 const GLuint WIDTH = 800, HEIGHT = 600;
12 
13 void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
14 {
15     std::cout << key << std::endl;
16     // When a user presses the escape key, we set the WindowSouldlose propert to ture
17     // closing the application
18     if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
19         glfwSetWindowShouldClose(window, GLFW_TRUE);
20 }
21 
22 // The MAIN function, from here we start the application and run the game loop
23 int main()
24 {
25     // Init GLFW
26     glfwInit();
27     // Set all the required options for GLFW
28     glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
29     glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
30     glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
31     glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
32 
33     // Create a GLFWwindow object that we can use for GLFW's functions
34     GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "OpenGL", nullptr, nullptr);
35     if (window == nullptr)
36     {
37         std::cout << "Failed to create GLFW window" << std::endl;
38         glfwTerminate();
39         return -1;
40     }
41     glfwMakeContextCurrent(window);
42     // Set the required callback function
43     glfwSetKeyCallback(window, key_callback);
44     // Set this to true so GLEW knows to use a modern approach to retrieving 
45     // function pointers and extensions
46     glewExperimental = GL_TRUE;
47     // Initialize GLEW to setup the OpenGL Function pointers
48     if (glewInit() != GLEW_OK)
49     {
50         std::cout << "Failed to initialize GLEW" << std::endl;
51         return -1;
52     }
53 
54     // Define the viewport dimensions
55     int width, height;
56     glfwGetFramebufferSize(window, &width, &height);
57     glViewport(0, 0, width, height);
58 
59     // Game loop
60     while (!glfwWindowShouldClose(window))
61     {
62         // Check if any events have been activiated (key pressed, mouse moved etc.) 
63         // and call corresponding response functions
64         glfwPollEvents();
65 
66         glClearColor(0.2, 0.3, 0.4, 1.0f);
67         glClear(GL_COLOR_BUFFER_BIT);
68 
69         // Swap the screen buffers
70         glfwSwapBuffers(window);
71     }
72 
73     // Terminate GLFW, clearing any resources allocated by GLFW.
74     glfwTerminate();
75     return 0;
76 }
原文地址:https://www.cnblogs.com/clairvoyant/p/5575129.html