Skip to content

Instantly share code, notes, and snippets.

@lqt0223
Created June 13, 2019 03:37
Show Gist options
  • Save lqt0223/68d1ff8cd793a3e36e8f4f52193fd9d5 to your computer and use it in GitHub Desktop.
Save lqt0223/68d1ff8cd793a3e36e8f4f52193fd9d5 to your computer and use it in GitHub Desktop.
37 perspective, view matrix derivation in vertex shader program
uniform mat4 u_modelMatrix;
uniform vec2 u_resolution;
uniform vec3 u_camera;
attribute vec4 a_position;
varying vec4 v_position;
attribute vec4 a_color;
varying vec4 v_color;
attribute vec3 a_normal;
varying vec3 v_normal;
attribute vec2 a_texcoord;
varying vec2 v_texcoord;
const float f = 0.1;
const float n = 100.;
const float fov = 0.707;
mat4 perspective() {
float fovv = fov;
float c = 1./tan(fovv/2.);
float ar = u_resolution.x/u_resolution.y;
float a = (f+n)/(f-n);
float b = 2.*f*n/(f-n);
return mat4(
c/ar,0.,0.,0.,
0.,c,0.,0.,
0.,0.,a,-1.,
0.,0.,b,0.
);
}
mat4 view() {
vec3 v = normalize(u_camera);
vec3 up = vec3(0.,1.,0.);
vec3 r = normalize(cross(up,v));
vec3 u = normalize(cross(v,r));
mat4 basis = mat4(
r.x,u.x,v.x,0.,
r.y,u.y,v.y,0.,
r.z,u.z,v.z,0.,
0.,0.,0.,1.
);
mat4 translate = mat4(
1.,0.,0.,0.,
0.,1.,0.,0.,
0.,0.,1.,0.,
-u_camera.x,-u_camera.y,-u_camera.z,1.
);
return basis * translate;
}
void main(void) {
v_position = a_position;
v_color = a_color;
v_normal = a_normal;
v_texcoord = a_texcoord;
gl_Position = perspective() * view() * u_modelMatrix * v_position;
}
@lqt0223
Copy link
Author

lqt0223 commented Jun 13, 2019

Some conventions about orders in GLSL:

  1. For the matrix data type, when using the constructor to fill in the matrix, pay attention to the column-major order.

For example, the matrix in mathematical notation:

should be initialized like this

mat4 T = mat4(
  1.,0.,0.,0., // 1st column
  0.,1.,0.,0., // 2nd column
  0.,0.,1.,0., // 3rd column
  tx,ty,tz,1.  // 4th column, for translation in this example
);
  1. When multiplying matrices together, the matrix on the right indicates that the transform represented by the matrix will perform earlier.
  2. When multiplying a matrix with a vector, the matrix should be on the left and the vector on the right.

For example, the code

 gl_Position = u_perspectiveMatrix * u_viewMatrix * u_modelMatrix * v_position;

can be interpreted as concatenate matrix operations such that model matrix operation is applied first, then view matrix operation, at last perspective matrix operation. Then the concatenated matrix is applied to the vector to be transformed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment