在godot的canvas_item着色器中构建逆投影矩阵和逆视图矩阵
使用canvas_item着色器进行后期处理时,可能会需要用到对应相机的逆投影矩阵和逆视图矩阵,但是在canvas_item着色器内显然无法直接获取,因此需要传入相机的参数手动构建。防止遗忘,记录一下。
逆投影矩阵
传入参数:
uniform float _fov; //视场角,Camera.Fov(注意转为弧度制)uniform float _aspect; //窗口宽高比uniform float _near; //近裁剪平面,Camera.Nearuniform float _far; //远裁剪平面,Camera.Far
构建函数:
mat4 get_inv_projection_matrix(float fov, float aspect, float near, float far){float mat11 = 1.0 / (tan(fov / 2.0) * aspect);float mat22 = 1.0 / tan(fov / 2.0);float mat33 = (near + far) / (near - far);float mat34 = 2.0 * near * far / (near - far);mat4 projection_matrix = mat4(vec4(mat11, 0, 0, 0),vec4(0, mat22, 0, 0),vec4(0, 0, mat33, -1),vec4(0, 0, mat34, 0));return inverse(projection_matrix);}
逆视图矩阵
从视图空间转换到世界空间的矩阵
传入参数:
uniform vec3 UpD3D; //相机的向上向量,Camera.Transform.basis.yuniform vec3 DirectionD3D; //相机的朝向,即视图坐标系的z轴的反方向, -Camera.Transform.basis.zuniform vec3 camera_position; //相机的位置, Camera.Translation
构建函数:
mat4 get_camera_matrix(vec3 up, vec3 direction, vec3 camera_position){vec3 N = normalize(-direction);vec3 U = normalize(cross(up, N));vec3 V = normalize(cross(N, U));mat4 inv_camera_matrix = mat4(vec4(U.x, V.x, N.x, 0),vec4(U.y, V.y, N.y, 0),vec4(U.z, V.z, N.z, 0),vec4(-dot(U, camera_position), -dot(V, camera_position), -dot(N, camera_position), 1));return inverse(inv_camera_matrix);}