【OpenGL】代码记录01创建窗口

时间:2023-03-09 19:29:33
【OpenGL】代码记录01创建窗口

创建空窗口:

#include<iostream>
// GLEW
#define GLEW_STATIC
#include <GL/glew.h>
// GLFW
#include <glfw3.h> //set key_callback
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode);
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
// When a user presses the escape key, we set the WindowShouldClose property to true,
// closing the application
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
} int main()
{
//instantiate the GLFW window
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, );
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, );//3为版本号
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);//设置为GL_TRUE就可以调整窗口大小 //initial GLFW window
GLFWwindow* window = glfwCreateWindow(, , "LLapuras", nullptr, nullptr);
if (window == nullptr)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -;
}
//通知GLFW将window的上下文设置为当前线程的主上下文
glfwMakeContextCurrent(window); //initial GLEW
//GLEW用来管理OpenGL的函数指针,在调用任何OpenGL的函数之要先初始化GLEW //设置glewExperimental为TRUE可以让GLEW在管理OpenGL的函数指针时更多地使用现代化的技术,
//如果把它设置为GL_FALSE的话可能会在使用OpenGL的核心模式时出现一些问题。
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK)
{
std::cout << "Failed to initialize GLEW" << std::endl;
return -;
} //viewpoint
//告诉opengl需要渲染窗口的尺寸
int width, height; //获取窗口的width和height in pixels,要以屏幕坐标衡量用glfwGetWindowSize()
glfwGetFramebufferSize(window, &width, &height); //OpenGL坐标范围为(-1,1),需要映射为屏幕坐标,
//OpenGL幕后使用glViewport中定义的位置和宽高进行2D坐标的转换
glViewport(, , width, height); //这句去掉也没事??是个输入回馈函数
glfwSetKeyCallback(window, key_callback); // Program loop
//在退出前保持循环
while (!glfwWindowShouldClose(window))
{
// Check and call events
glfwPollEvents(); // Rendering commands here
glClearColor(0.9f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT); // Swap the buffers
glfwSwapBuffers(window);
} //释放GLFW分配的内存
glfwTerminate();
return ;
}

运行:

【OpenGL】代码记录01创建窗口