视频:https://b23.tv/2Sl0JG
GLWindow.hpp
#include <glad/glad.h> // glad.h必须放在最前面
#include <GLFW/glfw3.h>
#include <iostream>
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
class GLWindow
{
public:
GLWindow(int w,int h,const char* title) {
glfwInit(); // 初始化GLFW
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
this->window = glfwCreateWindow(w,h, title, NULL, NULL); // 创建一个窗口
if (this->window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate(); // 销毁
exit(1);
}
glfwMakeContextCurrent(this->window);
glfwSetFramebufferSizeCallback(this->window, framebuffer_size_callback);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
std::cout << "Failed to initialize GLAD" << std::endl;
exit(1);
}
}
GLFWwindow *window;
~GLWindow() {
glfwTerminate();
}
void run() {
while(!glfwWindowShouldClose(this->window)) {
processInput(this->window);
this->paintGL();
glfwSwapBuffers(this->window);
glfwPollEvents();
}
}
private:
void paintGL() {
glClearColor(0.2f,0.3f,0.3f,0.1f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void processInput(GLFWwindow *window)
{
if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
}
};
main.cpp
#include "./GLWindow.hpp"
int main() {
GLWindow window(400,300,"OpenGL");
window.run();
return 0;
}
Makefile
Windows
path=./bin
projectName=OpenGL框架
main:main.cpp
g++ main.cpp $(path)/glfw3.dll glad.c -o $(path)/$(projectName) -lopengl32
Linux
path=./bin
projectName=OpenGL框架
main:main.cpp
g++ main.cpp glad.c -o $(path)/$(projectName) -lGLEW -lglfw3 -lGL -lX11 -lpthread -lXrandr -lXi -ldl