弃用的 glBegin & glEnd
环境:glfw 3.3.8 + glad core
OpenGL 初学者在尝试使用 glBegin 和 glEnd 函数来绘制三角形时,有可能找到使用这些函数的文章、代码文献
但许多这些函数已经在OpenGL的核心规范中被弃用
应该使用新的 API 来绘制图形
- 顶点缓冲对象:Vertex Buffer Objects,VBOs
- 顶点数组对象:Vertex Array Objects,VAOs
glBegin(GL_TRIANGLES);
glColor3f(1.0f, 0.0f, 0.0f); // 设置颜色为红色
glVertex2f(-0.6f, -0.4f); // 顶点1
glColor3f(0.0f, 1.0f, 0.0f); // 设置颜色为绿色
glVertex2f(0.6f, -0.4f); // 顶点2
glColor3f(0.0f, 0.0f, 1.0f); // 设置颜色为蓝色
glVertex2f(0.0f, 0.6f); // 顶点3
glEnd();
使用新 API 的示例
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <iostream>
// 窗口大小
const int WINDOW_WIDTH = 800;
const int WINDOW_HEIGHT = 600;
// 顶点着色器源码
const char* vertexShaderSource = R"(
#version 330 core
layout (location = 0) in vec3 aPos;
uniform float rotation;
mat3 getRotationMatrix(float angle) {
float s = sin(angle);
float c = cos(angle);
return mat3(
c, -s, 0.0,
s, c, 0.0,
0.0, 0.0, 1.0
);
}
void main()
{
mat3 rotationMatrix = getRotationMatrix(rotation);
gl_Position = vec4(rotationMatrix * aPos, 1.0);
}
)";
// 片段着色器源码
const char* fragmentShaderSource = R"(
#version 330 core
out vec4 FragColor;
uniform float time;
void main()
{
float red = sin(time);
float green = cos(time);
float blue = 0.5 + 0.5 * sin(2.0 * time);
FragColor = vec4(red, green, blue, 1.0);
}
)";
int main() {
// 初始化GLFW
if (!glfwInit(