第一个程序
视口
glViewport函数前两个参数控制窗口左下角的位置。第三个和第四个参数控制渲染窗口的宽度和高度(像素)。也可以将视口的维度设置为比GLFW的维度小,这样以后所有的渲染都会在一个更小的窗口中,周围就可以显示一些其他的元素。
用户改变窗口大小时候,调整:
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
// 并且还需要“注册”这个函数
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
渲染循环
双缓冲:OpenGL是一部分一部分绘制的,需要让他在缓冲区绘制完了再显示,绘制完了交换当前帧和绘制的那个缓冲区
// 渲染循环
while(!glfwWindowShouldClose(window))
{
// 输入
processInput(window);
// 渲染指令
...
// 检查并调用事件,交换缓冲
glfwPollEvents();
glfwSwapBuffers(window);
}
如果要输入的话,需要在渲染循环里加,比如按esc退出窗口,为保持整洁,加在void函数里,渲染循环里调用
整个程序:
#include<glad/glad.h>
#include<GLFW/glfw3.h>
#include<iostream>
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
void processInput(GLFWwindow *window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
}
int main()
{
//实例化GLFW窗口
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
//创建窗口对象
GLFWwindow* window = glfwCreateWindow(800, 600, "LearnOpenGL", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
//初始化GLAD管理指针,加载系统OpenGL函数指针
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to init GLAD" << std::endl;
return -1;
}
//视口
glViewport(0, 0, 800, 600);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
while (!glfwWindowShouldClose(window))
{
processInput(window);
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glfwSwapBuffers(window);
glfwPollEvents();
}
//关闭窗口
glfwTerminate();
return 0;
}
标签:窗口,入门,渲染,int,void,笔记,window,GLFW
From: https://www.cnblogs.com/IamIron-Man/p/16592395.html