LearnOpenGL 总结记录 Camera , View Matrix

// camera/view transformation
        glm::mat4 view = glm::mat4(1.0f); // make sure to initialize matrix to identity matrix first
        float radius = 10.0f;
        float camX   = sin(glfwGetTime()) * radius;
        float camZ   = cos(glfwGetTime()) * radius;
        view = glm::lookAt(glm::vec3(camX, 0.0f, camZ), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
        ourShader.setMat4("view", view);

细节

1. Camera Direction

The next vector required is the camera’s direction e.g. at what direction it is pointing at. For now we let the camera point to the origin of our scene: (0,0,0). Remember that if we subtract two vectors from each other we get a vector that’s the difference of these two vectors? Subtracting the camera position vector from the scene’s origin vector thus results in the direction vector. Since we know that the camera points towards the negative z direction we want the direction vector to point towards the camera’s positive z-axis. If we switch the subtraction order around we now get a vector pointing towards the camera’s positive z-axis:

glm::vec3 cameraTarget = glm::vec3(0.0f, 0.0f, 0.0f);
glm::vec3 cameraDirection = glm::normalize(cameraPos - cameraTarget);

The name direction vector is not the best chosen name, since it is actually pointing in the reverse direction of what it is targeting.

2.

上面的 view 矩阵就是一个 lookAt 函数:

A great thing about matrices is that if you define a coordinate space using 3 perpendicular (or non-linear) axes you can create a matrix with those 3 axes plus a translation vector and you can transform any vector to that coordinate space by multiplying it with this matrix. This is exactly what the LookAt matrix does and now that we have 3 perpendiclar axes and a position vector to define the camera space we can create our own LookAt matrix:

Where R is the right vector, U is the up vector, D is the direction vector and P is the camera’s position vector. Note that the position vector is inverted since we eventually want to translate the world in the opposite direction of where we want to move. Using this LookAt matrix as our view matrix effectively transforms all the world coordinates to the view space we just defined. The LookAt matrix then does exactly what it says: it creates a view matrix that looks at a given target.

(为什么上面的 LookAt 是 等于 View 矩阵,可以参考:

https://blog.csdn.net/popy007/article/details/5120158

个人理解:

要将顶点变换到相机空间,那么理解为就是,把相机的位置移到原点,旋转相机的自身的3个轴都与世间坐标空间的 x,y,z 轴 重合,顶点是相对于Camera的,所以当顶点执行同样的操作之后,顶点就在相机空间了。

1. 相机平移到原点,也就是 执行(平移 -P,P就是相机位置)。

2. 相机坐标轴与世界坐标空间 x,y,z 轴 重合。(利用坐标转换公式))

M-c * P-c = M-w * P-w = P. (同一个点P,世界空间(M-w * P-w) 和 相机空间(M-c * P-c) 的 表示 )

变换:

P-c = M-c ^ (-1) * P-w. (M-w 是世界空间矩阵,单位矩阵)

M-c:

[R-x  U-x  D-x  0]

[R-y  U-y  D-y  0]   

[R-z  U-z  D-z 0]

[0  0  0  0]

M-c ^ (-1) :

M-c 的转置 得到上面的 LookAt 的 左边的 矩阵。

猜你喜欢

转载自blog.csdn.net/aa20274270/article/details/86658559
今日推荐