创建窗口
#include <iostream>
#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>
int main()
{
glfwInit(); //初始化GLFW
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);//设置主版本号3
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);//设置次版本号3
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);//设置用什么配置文件Profile,可编程化流水线
//glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);//Mac OS X系统,明确前项兼容性
//创建窗口。宽,高,窗口名称
GLFWwindow* window = glfwCreateWindow(800, 600, "LearnOpenGL", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
/************************************/
glewExperimental = true;
//初始化glew,和用GLAD没有多少区别
if (glewInit()!= GLEW_OK)
{
std::cout << "glew init failed." << std::endl;
glfwTerminate();
return EXIT_FAILURE;
}
//glViewport函数前两个参数控制窗口左下角的位置。第三个和第四个参数控制渲染窗口的宽度和高度(像素)
glViewport(0, 0,800, 800);
while (!glfwWindowShouldClose(window))
{
glfwSwapBuffers(window);
glfwPollEvents();
}
//渲染循环结束后我们需要正确释放/删除之前的分配的所有资源
glfwTerminate();
return 0;
}
会得到以下结果,只是一个黑窗口。
输入
其实就是一个回调函数,循环不断扫描有没有相应的标志:
while (!glfwWindowShouldClose(window))
{
//处理上文window对象的输入
processInput(window);
glfwSwapBuffers(window);
glfwPollEvents();
}
//获取状态,做出相应的相应
void processInput(GLFWwindow *window)
{
if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
}
这里是按下空格键改变窗口大小的例子:
#include <iostream>
#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>
void processInput(GLFWwindow* window);
int main()
{
glfwInit(); //初始化GLFW
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);//设置主版本号3
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);//设置次版本号3
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);//设置用什么配置文件Profile,可编程化流水线
//glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);//Mac OS X系统,明确前项兼容性
GLFWwindow* window = glfwCreateWindow(800, 600, "LearnOpenGL", NULL, NULL); //创建窗口。宽,高,窗口名称
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
/************************************/
glewExperimental = true;
//初始化glew,和用GLAD没有多少区别
if (glewInit()!= GLEW_OK)
{
std::cout << "glew init failed." << std::endl;
glfwTerminate();
return EXIT_FAILURE;
}
//设置渲染窗口的尺寸大小.前两个参数控制窗口左下角的位置。第三个和第四个参数控制渲染窗口的宽度和高度(像素)
glViewport(0, 0,800, 800);
// 渲染循环
while (!glfwWindowShouldClose(window))
{
// 输入
processInput(window);
// 渲染指令
//设置清空屏幕所用的颜色rgba模式
glClearColor(0.5f, 0.3f, 0.3f, 1.0f);
//清空颜色缓冲
glClear(GL_COLOR_BUFFER_BIT);//每次渲染迭代开始时清屏,否则上次的渲染结果会叠加
// 检查并调用事件,交换缓冲
glfwPollEvents();
glfwSwapBuffers(window);
}
//渲染循环结束后我们需要正确释放/删除之前的分配的所有资源
glfwTerminate();
return 0;
}
void processInput(GLFWwindow* window)
{
//按下ESC键关闭窗口
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
{
glfwDestroyWindow(window);
}//按下空格键改变窗口大小
else if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS)
{
glfwSetWindowSize(window, 640, 999);
}
}