首先,opengl api函数输入一些数据,包括顶点数据、纹理数据、矩阵变换数据,这些顶点数据到"顶点处理阶段"。
“顶点处理阶段”: 图形流水线会调用 vertex shader(顶点shader),对顶点进行处理,有多少个顶点就调用多少次vertex shader 程序。vertex shader主要做的工作是顶点变换(旋转,缩放,平移)、观察变换、投影变换、视口变换,最终把三维的顶点转换为二维的顶点。
顶点处理完后, 图形流水线走向图元装配、光栅化、片元处理阶段。
“片元处理阶段” :将对像素颜色进行处理,有多少个像素就调用多少次Fragment shader 程序。
总结:Fragment shader 程序执行次数往往远远多于vertex shader 程序,所以Fragment shader 程序对效率影响很大。
uniform修饰符,在shader中理解为全局变量
shader程序
uniform vec4 _color;
....
GLint _colorID = glGetUniformLocation(_program, "_color"); //获取shader中的uniform vec4 _color 地址,即建立shader中的变量和程序中变量关联
....
glUniform4f(_colorID, 0, 1, 0, 1); //通过_colorID 改变对应的shader中 _color 的值
shader.hpp
#pragma once
#include
#include
#include
#include
#include
using namespace std;
class Shader
{
public:
//传入的要么是shader路径,要么是code
Shader(const string vertexstr, const string fragmentstr, bool isCode = false);
int getShaderProgram();
// begin end之间就是这个shader程序的作用域
// 使用shader
void begin();
// 结束
void end();
//获取uniform 变量地址
GLint getUniformLocation(string attName);
private:
GLuint _program;
};
shader.cpp
#include "shader.hpp"
//根据shader 源文件 初始化
Shader::Shader(const string vertexstr, const string fragmentstr, bool isCode) {
string vertexCode;
string fragmentCode;
if(isCode) {
vertexCode = vertexstr;
fragmentCode = fragmentstr;
}
else {
ifstream vShaderFile;
ifstream fShaderFile;
vShaderFile.exceptions(std::ifstream::badbit);
fShaderFile.exceptions(std::ifstream::badbit);
try {
vShaderFile.open(vertexstr);
fShaderFile.open(fragmentstr);
std::stringstream vShaderStream, fShaderStream;
vShaderStream << vShaderFile.rdbuf();
fShaderStream << fShaderFile.rdbuf();
vShaderFile.close();
fShaderFile.close();
vertexCode = vShaderStream.str();
fragmentCode = fShaderStream.str();
}
catch(std::ifstream::failure e) {
cout << "读取失败" << endl;
}
}
const GLchar* vShaderCode = vertexCode.c_str();
const GLchar * fShaderCode = fragmentCode.c_str();
GLuint vertex, fragment;
GLint success;
GLchar infoLog[512];
// 1. 创建一个顶点shader对象
vertex = glCreateShader(GL_VERTEX_SHADER);
// 给shader vertex对象 指定源代码
glShaderSource(vertex, 1, &vShaderCode, NULL);
// 2. 编译shader
glCompileShader(vertex);
// 获取编译状态
glGetShaderiv(vertex, GL_COMPILE_STATUS, &success);
if(!success) {
//编译失败 下面获取编译日志
glGetShaderInfoLog(vertex, 512, NULL, infoLog);
cout << "顶点着色器编译错误: " << infoLog << endl;
}
// 3. 创建一个像素shader对象
fragment = glCreateShader(GL_FRAGMENT_SHADER);
// 给shader fragment对象 指定源代码
glShaderSource(fragment, 1, &fShaderCode, NULL);
// 4. 编译shader
glCompileShader(fragment);
// 获取编译状态
glGetShaderiv(fragment, GL_COMPILE_STATUS, &success);
if(!success) {
//编译失败 下面获取编译日志
glGetShaderInfoLog(fragment, 512, NULL, infoLog);
cout << "片元着色器编译错误:" << infoLog << std::endl;
}
// 5. 创建程序
this->_program = glCreateProgram();
// 把编译好的shader对象加入程序中
glAttachShader(this->_program, vertex);
glAttachShader(this->_program, fragment);
// 6. 链接程序
glLinkProgram(this->_program);
//获取链接状态
glGetProgramiv(this->_program, GL_LINK_STATUS, &success);
if(!success) {
//链接失败 下面获取链接日志
glGetProgramInfoLog(this->_program, 512, NULL, infoLog);
cout << "链接失败: " << infoLog << std::endl;
}
// 删除着色器对象
glDeleteShader(vertex);
glDeleteShader(fragment);
}
int Shader::getShaderProgram() {
return this->_program;
}
//使用
void Shader::begin() {
//使用shader程序
glUseProgram(this->_program);
}
void Shader::end() {
glUseProgram(0);
}
GLint Shader::getUniformLocation(string attName) {
return glGetUniformLocation(_program, attName.c_str());
}
main.cpp
/*
*
* 该实例演示shader程序的使用,及uniform变量在程序中赋值
*
*/
#define GLEW_STATIC
#include
#include
#include
#include
#include
#include
#include // glm::vec3
#include // glm::vec4
#include // glm::mat4
#include // glm::translate, glm::rotate, glm::scale
#include
#include "FreeImage.h"
#include "shader.hpp"
#pragma comment(linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"" ) //这行是取消显示控制台
char szTitle[64] = "opengl view";
//glm::vec4 vec(1.0f, 0.0f, 0.0f, 1.0f);//创建一个点
//glm::mat4 trans = glm::mat4(1.0f);//创建单位矩阵
//Window dimensions
const GLuint WIDTH = 800, HEIGHT = 600;
GLfloat ratio = 1.f;
GLfloat xpos, ypos;
glm::vec3 _eye(0, 0, 10);
glm::vec3 _lookAt(0, 0, 0);
glm::vec3 _up(0, 1, 0);
glm::mat4 _matProj = glm::mat4(1.0f);//创建单位矩阵
glm::mat4 _matView = glm::mat4(1.0f);//创建单位矩阵
float size = 100.0f;
//顶点数据
struct Vertex {
float x, y, z;
float u, v;
};
Vertex g_cubeVertices[] =
{
{ -1.0f, -1.0f, 1.0f, 0.0f, 0.0f },
{ 1.0f, -1.0f, 1.0f, 1.0f, 0.0f },
{ 1.0f, 1.0f, 1.0f, 1.0f, 1.0f },
{ -1.0f, 1.0f, 1.0f, 0.0f, 1.0f },
{ -1.0f, -1.0f, -1.0f, 1.0f, 0.0f },
{ -1.0f, 1.0f, -1.0f, 1.0f, 1.0f },
{ 1.0f, 1.0f, -1.0f, 0.0f, 1.0f },
{ 1.0f, -1.0f, -1.0f, 0.0f, 0.0f },
{ -1.0f, 1.0f, -1.0f, 0.0f, 1.0f },
{ -1.0f, 1.0f, 1.0f, 0.0f, 0.0f },
{ 1.0f, 1.0f, 1.0f, 1.0f, 0.0f },
{ 1.0f, 1.0f, -1.0f, 1.0f, 1.0f },
{ -1.0f, -1.0f, -1.0f, 1.0f, 1.0f },
{ 1.0f, -1.0f, -1.0f, 0.0f, 1.0f },
{ 1.0f, -1.0f, 1.0f, 0.0f, 0.0f },
{ -1.0f, -1.0f, 1.0f, 1.0f, 0.0f },
{ 1.0f, -1.0f, -1.0f, 1.0f, 0.0f },
{ 1.0f, 1.0f, -1.0f, 1.0f, 1.0f },
{ 1.0f, 1.0f, 1.0f, 0.0f, 1.0f },
{ 1.0f, -1.0f, 1.0f, 0.0f, 0.0f },
{ -1.0f, -1.0f, -1.0f, 0.0f, 0.0f },
{ -1.0f, -1.0f, 1.0f, 1.0f, 0.0f },
{ -1.0f, 1.0f, 1.0f, 1.0f, 1.0f },
{ -1.0f, 1.0f, -1.0f, 0.0f, 1.0f },
// 地面数据
{ -size, -1.0f, -size, 0.0f, 0.0f },
{ -size, -1.0f, size, 100.0f, 0.0f },
{ size, -1.0f, size, 100.0f, 100.0f },
{ size, 0.0f, -size, 0.0f, 100.0f }
};
//纹理ID
GLuint _texture;
GLuint _vbo;
//地面纹理
GLuint _texGround;
Shader* _shader = nullptr;
static void error_callback(int error, const char* description) {
fputs(description, stderr);
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
std::cout << "key " << key << std::endl;
switch(key) {
case GLFW_KEY_ESCAPE:
glfwSetWindowShouldClose(window, GL_TRUE);
break;
case GLFW_KEY_UP:
_eye.z -= 0.1f; //这里修改摄像机参数
break;
case GLFW_KEY_DOWN:
_eye.z += 0.1f;
break;
case GLFW_KEY_RIGHT:
_eye.x -= 1.0f;
break;
case GLFW_KEY_LEFT:
_eye.x += 1.0f;
break;
default:
break;
}
}
static void mouse_button_callback(GLFWwindow* window, int button, int action, int mods) {
if(action != GLFW_PRESS)
return;
switch(button) {
case GLFW_MOUSE_BUTTON_LEFT:
std::cout << "Mosue left button clicked!" << std::endl;
break;
case GLFW_MOUSE_BUTTON_MIDDLE:
std::cout << "Mosue middle button clicked!" << std::endl;
break;
case GLFW_MOUSE_BUTTON_RIGHT:
std::cout << "Mosue right button clicked!" << std::endl;
break;
default:
return;
}
return;
}
static void cursor_position_callback(GLFWwindow* window, double x, double y) {
//std::cout << "Mouse position move to X: " << x << " Y: " << y << std::endl;
xpos = float((x - WIDTH / 2) / WIDTH) * 2;
ypos = float(0 - (y - HEIGHT / 2) / HEIGHT) * 2;
return;
}
static void scroll_callback(GLFWwindow* window, double x, double y) {
return;
}
static unsigned createTexture(int w, int h, const void* data, GLenum type) {
unsigned texId;
glGenTextures(1, &texId);
glBindTexture(GL_TEXTURE_2D, texId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, type, w, h, 0, type, GL_UNSIGNED_BYTE, data);
return texId;
}
/**
* 使用FreeImage加载图片
*/
static unsigned createTextureFromImage(const char* fileName) {
//1 获取图片格式
FREE_IMAGE_FORMAT fifmt = FreeImage_GetFileType(fileName, 0);
if(fifmt == FIF_UNKNOWN) {
return 0;
}
//2 加载图片
FIBITMAP *dib = FreeImage_Load(fifmt, fileName, 0);
FREE_IMAGE_COLOR_TYPE type = FreeImage_GetColorType(dib);
//3 获取数据指针
FIBITMAP* temp = dib;
dib = FreeImage_ConvertTo32Bits(dib);
FreeImage_Unload(temp);
BYTE* pixels = (BYTE*)FreeImage_GetBits(dib);
int width = FreeImage_GetWidth(dib);
int height = FreeImage_GetHeight(dib);
for(int i = 0; i < width * height * 4; i += 4) {
BYTE temp = pixels[i];
pixels[i] = pixels[i + 2];
pixels[i + 2] = temp;
}
unsigned res = createTexture(width, height, pixels, GL_RGBA);
FreeImage_Unload(dib);
return res;
}
static GLint _colorID;
static void onInit() {
_texture = createTextureFromImage("../res/1.jpg");
_texGround = createTextureFromImage("../res/dimian.jpg");
glGenBuffers(1, &_vbo);
glBindBuffer(GL_ARRAY_BUFFER, _vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(g_cubeVertices), g_cubeVertices, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
string vsCode = "void main()\
{\
gl_Position = ftransform();\
}";
string psCode = "uniform vec4 _color; \
void main()\
{\
gl_FragColor = _color;\
}";
//uniform 理解为shader程序中的全局变量
//gl_Position 内置变量 表示输出顶点
//gl_FragColor 内置变量 表示输出颜色
//ftransform() 内置函数
//_shader = new Shader("../res/shader/vertShader1.vert", "../res/shader/fragShader1.frag");
_shader = new Shader(vsCode, psCode, true);
//获取shader中的uniform vec4 _color 地址,即建立shader中的变量和程序中变量关联
_colorID = _shader->getUniformLocation("_color");
}
static void onDestory() {
glDeleteTextures(1, &_texture);
glDeleteTextures(1, &_texGround);
glDeleteBuffers(1, &_vbo); //删除VBO 显存中释放VBO内存
}
// 绘制
static void render(GLFWwindow * window) {
glClearColor(0, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
glEnable(GL_TEXTURE_2D);
glMatrixMode(GL_MODELVIEW);
_matView = glm::lookAt(_eye, _lookAt, _up); //使用glm数学库 根据公式计算得到视图矩阵 这公式可以推倒出来
//摄像机围绕目标旋转
static float angle = 0; //旋转角度
float r = 10; //旋转半径
_eye.x = cos(angle * glm::pi<double>() / 180) * r;
_eye.z = sin(angle * glm::pi<double>() / 180) * r;
angle += 1; //角度每帧加一
glm::mat4 matVP = _matProj * _matView;
glLoadMatrixf(&matVP[0][0]);
glBindTexture(GL_TEXTURE_2D, _texture);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
//开始使用ID为 _vbo 的buffer 接下来的操作针对这个VBO
glBindBuffer(GL_ARRAY_BUFFER, _vbo);
float* addrVertex = (float*)0;
float* uvAddress = (float*)12;
glVertexPointer(3, GL_FLOAT, sizeof(Vertex), addrVertex);
glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), uvAddress);
// 绘制 立方体
_shader->begin(); //使用 shader 对绘制立方体起作用
//先begin 使用这个shader 然后才能修改
glUniform4f(_colorID, 0, 1, 0, 1); //通过_colorID 改变对应的shader中 _color 的值
glDrawArrays(GL_QUADS, 0, 24); //shader 只在针对 glDrawArrays 这类绘制函数其作用,顶点处理阶段调用顶点shader 光栅化处理阶段调用片元shader
_shader->end(); //结束 如果不掉用这个函数 glUseProgram设置为0,这个shader程序会对后面的绘制产生影响
//绘制地面
//glLoadIdentity(); //这里打开 地面就不会跟着旋转 说明摄像机操作的是模型矩阵
glBindTexture(GL_TEXTURE_2D, _texGround);
glDrawArrays(GL_QUADS, 24, 4);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glBindTexture(GL_TEXTURE_2D, 0);
glfwSwapBuffers(window);
glfwPollEvents();
}
int main(void) {
GLFWwindow * window;
glfwSetErrorCallback(error_callback);
if(!glfwInit())
return -1;
window = glfwCreateWindow(WIDTH, HEIGHT, szTitle, NULL, NULL);
if(!window) {
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwSetKeyCallback(window, key_callback);
glfwSetMouseButtonCallback(window, mouse_button_callback);
glfwSetCursorPosCallback(window, cursor_position_callback);
glfwSetScrollCallback(window, scroll_callback);
glfwMakeContextCurrent(window);
glewExperimental = GL_TRUE;
glewInit();
onInit();
glViewport(0, 0, WIDTH, HEIGHT); //设置opengl视口 即看到的显示区域
_matProj = glm::perspective(glm::radians(60.0f), float(WIDTH) / float(HEIGHT), 0.1f, 1000.0f);//使用glm数学库 根据公式计算得到投影矩阵 这公式可以推倒出来
while(!glfwWindowShouldClose(window)) {
render(window);
}
onDestory();
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}