连续工作15小时,累了,睡觉。
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
若未特别说明,以下示例均假设矩阵/向量为四维
glm::mat4 mat;
glm::vec4 vec;
对于vec来说,第四位为1代表坐标,0代表方向
平移矩阵
| 1 0 0 X |
| 0 1 0 Y |
| 0 0 1 Z |
| 0 0 0 1 |
构造平移矩阵
glm::mat4 mat = glm::translate(X, Y, Z);
拉伸矩阵
| x 0 0 0 |
| 0 y 0 0 |
| 0 0 z 0 |
| 0 0 0 1 |
构造拉伸矩阵
glm:mat4 mat = glm::scale(x, y, z);
旋转矩阵
若转轴为 x, y, z, 角度为 a
X = x sin(a), Y = y sin(a), Z = z sin(a), W = cos(a)
| 1 - 2(Y*Y+Z*Z) | 2(X*Y+Z*W) | 2(X*Z-Y*W) | 0 |
| 2(X*Y-Z*W) | 1 - 2(X*X+Z*Z) | 2(Y*Z+X*W) | 0 |
| 2(X*Z+Y*W) | 2(Y*Z-X*W) | 1 - 2(X*X+Y*Y) | 0 |
| 0 | 0 | 0 | 1 |
构造旋转矩阵
glm::vec3 axis(x, y, z);
glm::mat4 transformedMatrix = glm::rotate(mat, a, axis);
初等变换矩阵与坐标相乘可得变换后的坐标
mat * vec (= vec)
glm::vec4 transformedVector = mat * vec;
构造模型矩阵
glm::mat4 mat = transmat3 * transmat2 * transmat1 * mat;
构造视图矩阵
glm::mat4 mat = glm::LookAt(CameraPos, CameraTarget, upVector);
若相机正置,则 upVector = glm:vec3(0, 1, 0)
构造投影矩阵
glm::mat4 mat = glm::perspective(FoV, AspectRatio, NearClipPlane, FarClipPlane);
模型矩阵 视图矩阵 投影矩阵
模型坐标 ----------> 绝对坐标 ----------> 相机坐标 ----------> 齐次坐标
最后一步是用仿射变换模拟人眼成像的过程
glm:mat3 MVP = projection * view * model;
循环前注册句柄
GLuint MatrixID = glGetUniformLocation(programID, "MVP");
循环中传递给GLSL
glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]);
GLSL vertex shader 末期处理
layout(location = 0) in vec3 vertexPosition_modelspace;
uniform mat4 MVP;
void main() {
vec4 v = vec4(vertexPosition_modelspace, 1);
gl_Position = MVP * v;
}