前面绘制了一个三角形,虽然比较简单,但我还是想让他有一些可设置的变化,于是这里就开始需要变换矩阵了。不过先抛掉一些枯燥乏味的理论知识,直接使用专门为OpenGl
定制的glm
库了,有了它,做个什么矩阵变换就轻轻松松,事半功倍了。
glm
连接:http://glm.g-truc.net/0.9.5/index.html
将glm
下载下来后放在自己引用的include
的目录即可
常用三个头文件:
#include
#include
#include
//三角形的变换矩阵
glm::mat4 trans;
//缩放0.5倍
trans = glm::scale(trans, glm::vec3(0.5, 0.5, 0.5));
//逆时针旋转90度
trans = glm::rotate(trans, 90.0f, glm::vec3(0.0, 0.0, 1.0));
//向x轴位移1.5
trans = glm::translate(trans, glm::vec3(1.2, 0.0f, 0.0));
uniform
矩阵变量,并用矩阵*位置数据(vec4)
const char* vertexShaderSource = "#version 330 core\n"
"layout(location = 0) in vec3 aPos;\n"
"layout(location = 1) in vec3 aColor;\n"
"out vec3 vertextColor;\n"
"uniform mat4 model;\n"
"void main()\n"
"{\n"
"gl_Position = model * vec4(aPos, 1.0);\n"
"vertextColor =aColor;\n"
"}\n";
OpenGL
的函数设置Uniform
变量,切记在设置变量前,先调用一下glUseProgram
//使用当前激活的着色其
glUseProgram(shaderProgram);
//赋值给shader的model变量
unsigned int loc = glGetUniformLocation(shaderProgram, "model");
glUniformMatrix4fv(loc, 1, GL_FALSE, glm::value_ptr(trans));
Model
(模型矩阵):其实模型矩阵在上面已经演示了,它主要就是控制本身的模型的数据,比如位置、缩放、旋转View
(视图矩阵):视图矩阵完全可以理解为一个摄像机,走到哪儿就看到什么东西Projection
(投影矩阵):投影矩阵暂时被分为正射投影
&透视投影
,主要区别在与正射投影
会将你所看到的东西老老实实的绘制到屏幕上,而透视投影
会根据人眼看物体越远越小的体验而进行模拟//正射投影矩阵
glm::ortho(0.0f, 800.0f, 0.0f, 600.0f, 0.1f, 100.0f);
//透视投影矩阵
glm::mat4 proj = glm::perspective(glm::radians(45.0f), (float)width/(float)height, 0.1f, 100.0f);
gl_Position =projection* view* model*vec4(aPos,1.0);
const char* vertexShaderSource = "#version 330 core\n"
"layout(location = 0) in vec3 aPos;\n"
"layout(location = 1) in vec3 aColor;\n"
"out vec3 vertextColor;\n"
"uniform mat4 model;\n"
"uniform mat4 view;\n"
"uniform mat4 projection;\n"
"void main()\n"
"{\n"
"gl_Position = projection * view * model * vec4(aPos, 1.0);\n"
"vertextColor =aColor;\n"
"}\n";
View
&Projection
矩阵,并给顶点shader进行设置glm::mat4 view;
// 注意,我们将矩阵向我们要进行移动场景的反方向移动。
view = glm::translate(view, glm::vec3(0.0f, 0.0f, -5.0f));
glm::mat4 projection;
projection = glm::perspective(45.0f, _glViewWidth / (float)_glViewHegiht, 0.1f, 100.0f);
//三角形的变换矩阵
glm::mat4 trans;
//缩放0.5倍
trans = glm::scale(trans, glm::vec3(0.5, 0.5, 0.5));
//逆时针旋转90度
trans = glm::rotate(trans, 90.0f, glm::vec3(0.0, 0.0, 1.0));
//向x轴位移1.5
trans = glm::translate(trans, glm::vec3(1.2, 0.0f, 0.0));
//使用当前激活的着色其
glUseProgram(shaderProgram);
//赋值给shader的model变量
unsigned int loc = glGetUniformLocation(shaderProgram, "model");
glUniformMatrix4fv(loc, 1, GL_FALSE, glm::value_ptr(trans));
unsigned int locView = glGetUniformLocation(shaderProgram, "view");
glUniformMatrix4fv(locView, 1, GL_FALSE, glm::value_ptr(view));
unsigned int locPro = glGetUniformLocation(shaderProgram, "projection");
glUniformMatrix4fv(locPro, 1, GL_FALSE, glm::value_ptr(projection));