2

I want to light a flat surface at vertex level from the direction of the camera. I expect the lighting to not change when I rotate the view but it is brightest when I look slightly away. Is mvp[3] not a camera coordinate like I think it is?

#version 450
in vec3 vertex;
uniform mat4 mvp;
out vec4 color;

void main()
{
    gl_Position =  mvp * vec4(vertex,1.);
    vec3 n = vec3(0.,0.,1.);
    vec3 v = normalize( vec3(mvp[3])-vertex );
    //I tried the other direction in the mat4
    //vec3(mvp[0][3],mvp[1][3],mvp[2][3]);

    color = vec4( dot(v,n) );
}
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
spinning
  • 119
  • 1
  • 1
  • 10

1 Answers1

5

Is 4th column in the model view projection matrix the viewing position?

No, it is not. The 4th column of the view matrix would contain the camera position, but the model view projection matrix is the combination of the model matrix, the view matrix and the projection matrix.

A view matrix usually looks like this:

mat4 view;

view[0] : ( X-axis.x, X-axis.y, X-axis.z, 0 )
view[1] : ( Y-axis.x, Y-axis.y, Y-axis.z, 0 )
view[2] : ( Z-axis.x, Z-axis.y, Z-axis.z, 0 )
view[3] : ( trans.x,  trans.y,  trans.z,  1 ) 

A perspective projection matrix may look like this:

r = right, l = left, b = bottom, t = top, n = near, f = far 

mat4 projection;

projection[0] :     2*n/(r-l)      0              0                0
projection[1] :     0              2*n/(t-b)      0                0
projection[2] :     (r+l)/(r-l)    (t+b)/(t-b)    -(f+n)/(f-n)    -1    
projection[3] :     0              0              -2*f*n/(f-n)     0

A matrix multiplication works like this:

mat4 matA;
mat4 matB;{

mat4 matC;
for ( int i0 = 0; i0 < 4; ++ i0 )
    for ( int i1 = 0; i1 < 4; ++ i1 )
        matC[i0][i1] = matB[i0][0] * matA[0][i1] + matB[i0][1] * matA[1][i1] + matB[i0][2] * matA[2][i1] + matB[i0][3] * matA[3][i1];

This follows, that the 4th column of the view projection matrix contains the following:

mv[3][0] =  trans.x * 2*n/(r-l)   + trans.z * (r+l)/(r-l);
mv[3][1] =  trans.y * 2*n/(t-b)   + trans.z * (t+b)/(t-b);
mv[3][2] = -trans.z * (f+n)/(f-n) - 2*f*n/(f-n);
mv[3][3] = -trans.z;
Rabbid76
  • 202,892
  • 27
  • 131
  • 174