OpenGL:窗口

104 阅读1分钟
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <iostream>

void framebuffer_size_callback(GLFWwindow* window, int width, int height);	//窗口大小被调整的时候,视口大小也应该调整
void processInput(GLFWwindow* window);

int main()
{
	glfwInit();
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);	//第一个参数是GLFW的选项字段,是枚举类型;后一个字段为int,给选项字段设置值
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);	//选择核心模式

	GLFWwindow* window = glfwCreateWindow(800, 600, "LearnOpenGL", NULL, NULL);	//创建一个800*600的窗口
	if (window == NULL)
	{
		std::cout << "Failed to create GLFW window" << std::endl;
		glfwTerminate();
		return -1;
	}
	glfwMakeContextCurrent(window);	//将当前窗口的上下文设置为当前线程的主上下文

	if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))	//初始化GLAD,在使用任何GLFW函数之前,都需要先初始化GLAD
	{
		std::cout << "Failed to initialize window" << std::endl;
		return -1;
	}

	glViewport(0, 0, 800, 600);	//设置视口大小,视口中才会显示OpenGL的渲染,视口的大小可以小于窗口的大小

	glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);	//注册framebuffer_size_callback函数,每次窗口大小变化的时候进行调用

	while (!glfwWindowShouldClose(window))	//循环渲染,在没有收到关闭的通知时,保证窗口持续出现
	{
		//输入
		processInput(window);

		//渲染指令
		//........
		glClearColor(0.2f, 0.3f, 0.3f, 0.1f);	//设置清空屏幕所用的颜色
		glClear(GL_COLOR_BUFFER_BIT);	//清楚颜色缓冲;除了GL_COLOR_BUFFER_BIT,还有GL_DEPTH_BUFFER_BIT、GL_STENCIL_BUFFER_BIT

		//检查并调用事件,交换缓冲
		glfwSwapBuffers(window);	//交换颜色缓冲
		glfwPollEvents();	//检查有没有触发事件,例如鼠标移动、键盘点击
	}


	glfwTerminate();
	return 0;
}

void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
	glViewport(0, 0, width, height);
}
void processInput(GLFWwindow* window)		//判断键盘点击ESC后的函数
{
	if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
	{
		glfwSetWindowShouldClose(window, true);
	}
}