在头文件中创建Shaders.h
#ifndef SHADER_H
#define SHADER_H
#include
#include
#include
#include
#include
class Shader
{
public:
unsigned int ID; //着色器程序ID
//构造器读取并构建着色器
Shader(const char* vertexPath, const char* fragmentPath)
{
//从文件路径中获取顶点/片段着色器
std::string vertexCode;
std::string fragmentCode;
std::ifstream vShaderFile;
std::ifstream fShaderFile;
//保证ifstream对象可以抛出异常
vShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
fShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
try
{
//打开文件
vShaderFile.open(vertexPath);
fShaderFile.open(fragmentPath);
std::stringstream vShaderStream, fShaderStream;
//读取文件的缓冲内容到数据流中
vShaderStream << vShaderFile.rdbuf();
fShaderStream << fShaderFile.rdbuf();
//关闭文件处理器
vShaderFile.close();
fShaderFile.close();
//转换数据流到string
vertexCode = vShaderStream.str();
fragmentCode = fShaderStream.str();
}
catch (std::ifstream::failure& e)
{
std::cout << "ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ: " << e.what() << std::endl;
}
const char* vShaderCode = vertexCode.c_str();
const char* fShaderCode = fragmentCode.c_str();
//编译着色器
unsigned int vertex, fragment;
//顶点着色器
vertex = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex, 1, &vShaderCode, NULL);
glCompileShader(vertex);
checkCompileErrors(vertex, "VERTEX");
//片段着色器
fragment = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment, 1, &fShaderCode, NULL);
glCompileShader(fragment);
checkCompileErrors(fragment, "FRAGMENT");
//着色器程序
ID = glCreateProgram();
glAttachShader(ID, vertex);
glAttachShader(ID, fragment);
glLinkProgram(ID);
checkCompileErrors(ID, "PROGRAM");
//删除着色器
glDeleteShader(vertex);
glDeleteShader(fragment);
}
激活着色器程序
void use()
{
glUseProgram(ID);
}
//uniform工具类
void setBool(const std::string& name, bool value) const
{
glUniform1i(glGetUniformLocation(ID, name.c_str()), (int)value);
}
void setInt(const std::string& name, int value) const
{
glUniform1i(glGetUniformLocation(ID, name.c_str()), value);
}
void setFloat(const std::string& name, float value) const
{
glUniform1f(glGetUniformLocation(ID, name.c_str()), value);
}
private:
//打印编译/链接错误
void checkCompileErrors(unsigned int shader, std::string type)
{
int success;
char infoLog[1024];
if (type != "PROGRAM")
{
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(shader, 1024, NULL, infoLog);
std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << type << "\n" << infoLog << std::endl;
}
}
else
{
glGetProgramiv(shader, GL_LINK_STATUS, &success);
if (!success)
{
glGetProgramInfoLog(shader, 1024, NULL, infoLog);
std::cout << "ERROR::PROGRAM_LINKING_ERROR of type: " << type << "\n" << infoLog << std::endl;
}
}
}
};
#endif
在资源文件中创建shader.vs和shader.fs
shader.vs代码
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aColor;
out vec3 ourColor;
void main()
{
gl_Position = vec4(aPos, 1.0);
ourColor = aColor;
}
shader.fs代码
#version 330 core
out vec4 FragColor;
in vec3 ourColor;
void main()
{
FragColor = vec4(ourColor, 1.0f);
}
将头文件目录添加进附加包含目录里
编写主程序
#include
#include
#include
#include
//视口调整函数
void framebuffer_size_callback(GLFWwindow* window, int width, int height) {
glViewport(0, 0, width, height); //设置窗口维度
}
//输入
void processInput(GLFWwindow* window) {
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) //如果按下ESC,关闭GLFW
glfwSetWindowShouldClose(window, true);
}
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); //使用的是核心模式
//创建窗口
GLFWwindow* window = glfwCreateWindow(800, 600, "MyWindow", NULL, NULL);
if (window == NULL) { //窗口创建失败
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate(); //释放/删除之前分配的资源
return -1;
}
glfwMakeContextCurrent(window); //将创建的窗口上下文设置为当前线程的主上下文
//初始化GLAD
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { //加载系统相关的OpenGL函数指针地址
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); //设置窗口大小调整的回调
//顶点数组:x,y,z轴,范围为-1.0到1.0
float vertices[] = {
// 位置 // 颜色
0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, // 右下
-0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, // 左下
0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f // 顶部
};
//创建VBO、VAO对象
unsigned int VBO,VAO;
glGenBuffers(1, &VBO);
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
//位置属性
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3*sizeof(float)));
glEnableVertexAttribArray(1);
Shader ourShader("shader.vs", "shader.fs"); //创建着色器
//渲染循环
while (!glfwWindowShouldClose(window)) { //判断是否退出
processInput(window); //输入
//渲染指令
glClearColor(0.2f, 0.3f, 0.3f, 1.0f); //清空屏幕所用颜色
glClear(GL_COLOR_BUFFER_BIT); //清空颜色缓冲
ourShader.use();
glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLES, 0, 3);
//检查并调用事件,交换缓冲
glfwSwapBuffers(window); //交换颜色缓冲
glfwPollEvents(); //检查触发事件、更新窗口状态
}
glDeleteBuffers(1, &VBO); //删除VBO对象
glDeleteVertexArrays(1, &VAO); //删除VAO对象
glfwTerminate(); //释放/删除之前分配的资源
return 0;
}