OpenGL创建一个GLFW窗口
先上图,再解答。
完整主要的源代码
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <iostream>
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow *window);
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_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);
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // uncomment this statement to fix compilation on OS X
#endif
GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "it_xiangqiang", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
while (!glfwWindowShouldClose(window))
{
processInput(window);
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
return 0;
}
void processInput(GLFWwindow *window)
{
if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
}
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
源代码剖析
void framebuffer_size_callback(GLFWwindow* window, int width, int height)//每当窗口大小更改(通过操作系统或用户调整大小)时,此回调函数就会执行
void processInput(GLFWwindow *window)//查询GLFW是否在此帧中按下/释放了相关的按键并做出相应的反应
glfwTerminate();//终止,清除所有先前分配的GLFW资源
glfwSwapBuffers(window);//交换缓冲区和轮询IO事件(按下/释放键,移动鼠标等)
gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)//加载所有OpenGL函数指针
GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, “it_xiangqiang”, NULL, NULL);//glfw窗口创建
glfwInit();//初始化和配置
while (!glfwWindowShouldClose(window)){}//渲染循环
glViewport(0, 0, width, height);//确保视口与新窗口尺寸匹配; 请注意,宽度和高度将大大大于视网膜显示器上指定的宽度和高度。