OpenGL的运行结构
着色器(Shader):用来实现图像渲染的,用来替代固定渲染管线的可编辑程序。
着色器代替了传统的固定渲染管线,可以实现3D图形学的相关计算,由于其可编辑性,可以实现各种各样的图像效果,而不用受显卡的固定渲染管线限制。
入门只学习顶点着色器(负责顶点的集合关系等的运算)和片段着色器(负责片源颜色等的计算)
OpenGL上下文窗口(GLFW库):C语言库,支持多窗口、多显示器和高分辨率显示,支持键盘、鼠标、游戏手柄、Windows事件的输入
一、改变OpenGL的初始化环境
#include <glad/glad.h>
#include <GLFW/glfw3.h> //GLAD、GLFW文件
#include <iostream>
int winWidth = 600, winHeight = 600;
int main(int nargs, char *args[])
{
// initialization
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// window creation
GLFWwindow* window = glfwCreateWindow(winWidth, winHeight, args[0], NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
// load all OpenGL function pointers
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
//在循环前加入代码
// render loop
while (!glfwWindowShouldClose(window))
{
//在循环中加入代码
// rendering
// swap buffers and poll IO events
glfwSwapBuffers(window);
glfwPollEvents();
}
//在循环后加入代码
// terminate, clearing all previously allocated GLFW resources.
glfwTerminate();
return 0;
}
二、基本图形的绘制
1、设置图形(主循环前):定义顶点数组变量,定义并设置顶点缓存对象,设置顶点数组对象,设置着色器
2、绘制图形(主循环中):绘制顶点缓存对象中的图元
3、删除图形(主循环后):删除顶点缓存/数组对象以及着色器变量
(一)定义顶点数组(如位置、颜色、法向量、纹理坐标、其他属性等)
float trianglePositions[] = {
-0.866f, -0.5f, 0.0f,