一、shader:
是一段程序,分为顶点着色、片元着色两种。分别在顶点着色阶段和片元着色阶段使用。
二、相关函数:
// 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;
}
// 5. 创建程序
this->_program = glCreateProgram();
// 把编译好的shader对象加入程序中
glAttachShader(this->_program, vertex);
// 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);
...
//使用shader程序
glUseProgram(this->_program);
三、代码:
vertShader1.vert
void main()
{
gl_Position = ftransform();
};
fragShader1.frag
void main()
{
gl_FragColor = vec4(1,0,0,1);
};
shader 类封装了shader的使用
shader.hpp
#pragma once
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <GL/glew.h>
using namespace std;
class Shader
{
public:
Shader(const GLchar* vertexPath, const GLchar* fragmentPath);
int getShaderProgram();
// begin end之间就是这个程序的作用域
// 使用shader
void begin();
// 结束
void end();
private:
GLuint _program;
};
shader.cpp
#include "shader.hpp"
//根据shader 源文件 初始化
Shader::Shader(const GLchar* vertexPath, const GLchar* fragmentPath) {
string vertexCode;
string fragmentCode;
ifstream vShaderFile;
ifstream fShaderFile;
vShaderFile.exceptions(std::ifstream::badbit);
fShaderFile.exceptions(std::ifstream::badbit);
try {
vShaderFile.open(vertexPath);
fShaderFile.open(fragmentPath);
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);
}
main.cpp
/*
* shader
* shader就是一个代码 --->编写 --->编译 --->链接 --->使用
* shader分为两种:
* vs shader: 对顶点进行处理
* ps shader: 对像素进行处理
*/
#define GLEW_STATIC
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <iostream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/vec3.hpp> // glm::vec3
#include <glm/vec4.hpp> // glm::vec4
#include <glm/mat4x4.hpp> // glm::mat4
#include <glm/ext/matrix_transform.hpp> // glm::translate, glm::rotate, glm::scale
#include <glm/ext/matrix_clip_space.hpp>
#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 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);
_shader = new Shader("../res/shader/vertShader1.vert", "../res/shader/fragShader1.frag");
}
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 对绘制立方体起作用
glDrawArrays(GL_QUADS, 0, 24);
_shader->end(); //结束
//绘制地面
//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;
}
四、运行结果:
五、Shader开发环境:
为了方便shader开发。这里推荐使用一个shader开发编辑器 ShaderDesigner
官网地址为:
https://www.opengl.org/sdk/tools/ShaderDesigner/
国内官方下载较慢,这里提供一个下载地址,免费、完整、可用。