最近在学opengl,使用的《OpenGL编程指南》第9版,其中第一个例子,就是基于glfw库创建的,所以先了解一下glfw这个库,对于后续OpenGL开发是有帮助的。
GLFW 简介
GLFW 是一个开源的,跨平台的库,可以用于桌面环境的OpenGL, OpenGL ES和Vulkan开发。它提供了简单的API,用来创建窗口,上下文和Surface,接收输入和事件。
GLFW是用c语言编写的,支持Windows, macOS, X11和Wayland。
以上翻译自glfw官网,想了解更多的,请移步到该网址。
GLFW开发环境搭建
搭建方式有两种,一种是通过ubuntu系统自带的apt安装,另一种就是通过GLFW官网上的源码,自己编译安装。我是通过apt安装的,我也没啥定制化的需求,怎么省事怎么来。
通过如下命令,安装glfw
sudo apt install libglfw3-dev
GLFW的Hello world
搭建好开发环境之后,就可以写代码了。
下面代码,展示如何使用GLFW编写一个Hello world程序。我把这个程序,放在了hello.c中。
#include <GLFW/glfw3.h>
int main(void)
{
GLFWwindow* window;
/* Initialize the library */
if (!glfwInit())
return -1;
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}
/* Make the window's context current */
glfwMakeContextCurrent(window);
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
/* Render here */
glClear(GL_COLOR_BUFFER_BIT);
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
glfwTerminate();
return 0;
}
然后使用如下命令编译
gcc hello.c -lglfw -lGL -o hello
然后运行./hello,就出来如下窗口,程序运行成功。
GLFW的Hello world的解析
上面代码,比较简单,主要就是分成3步:
- 创建窗口
- 显示窗口
- 销毁窗口
这是常用的窗口程序的操作步骤。
创建窗口
创建窗口,是通过函数glfwCreateWindow进行的,不过在调用glfw的函数之前,我们需要先对glfw进行初始化,也就是调用 glfwInit。
/* Initialize the library */
if (!glfwInit())
return -1;
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}
显示窗口
由于显示的窗口,假如用户按下了窗口的“叉叉”,关闭了窗口,应用程序应该响应关闭事件。
那么程序中需要接收事件,并判断事件是否为关闭事件。接收事件,是通过glfwPollEvents来进行的。判断是否是关闭事件,是通过函数glfwWindowShouldClose进行的。如果是一个普通的窗口程序,那么只需要glfwPollEvents 和 glfwWindowShouldClose 函数就行了。
但是我们这里,窗口系统跟OpenGL结合了,还需要3个OpenGL相关的函数,
glfwMakeContextCurrent, glClear, glfwSwapBuffers。 这3个函数,分别是把当前窗口设置成OpenGL的绘制上下文,清除窗口,交换前后缓冲区。
/* Make the window's context current */
glfwMakeContextCurrent(window);
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
/* Render here */
glClear(GL_COLOR_BUFFER_BIT);
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
销毁窗口
销毁窗口,同时销毁glfw分配的其他资源。
glfwTerminate();
至此,GLFW的hello world,解析完成。