Search code examples
matrixopengl-esglslwebglcoordinate-transformation

Matrix Translation in GLSL is infinitely stretched


I work with webgl and modify the shaders (vs.glsls and fs.glsl) to understand the GLSL and graphic programming. I have a model that I want to scale, rotate and translate. Scaling and rotating works fine but when I multiply the translation matrix, the result is weird. I know this is a very basic question, but I am missing something and I need to find it out. my model is infinitely stretchered through the y axis.

The white area is supposed to be the eye of the model:

The white area is supposed to be the eye of the model

this is my vertex shader code:

mat4 rX = mat4 (
 1.0, 0.0, 0.0, 0.0,
 0.0, 0.0, -1.0, 0.0,
 0.0, 1.0, 0.0, 0.0,
 0.0, 0.0, 0.0, 1.0
 );

mat4 rZ = mat4 (
 0.0, 1.0, 0.0, 0.0,
 -1.0, 0.0, 0.0, 0.0,
 0.0, 0.0, 1.0, 0.0,
 0.0, 0.0, 0.0, 1.0
 );

mat4 eyeScale = mat4 (
 .50,0.0,0.0,0.0,
 0.0,.50,0.0,0.0,
 0.0,0.0,.50,0.0,
 0.0,0.0,0.0,1.0
 );
mat4 eyeTrans = mat4(
1.0,0.0,0.0,0.0,
0.0,1.0,0.0,4.0,
0.0,0.0,1.0,0.0,
0.0,0.0,0.0,1.0
);
 mat4 iR = eyeTrans*rZ*rX*eyeScale;
 gl_Position = projectionMatrix * modelViewMatrix  *iR* vec4(position, 1.0);
}

Solution

  • You swapped rows and columns, when you set up the translation matrix

    Change it to:

    mat4 eyeTrans = mat4(
        1.0, 0.0, 0.0, 0.0,
        0.0, 1.0, 0.0, 0.0,
        0.0, 0.0, 1.0, 0.0,
        0.0, 4.0, 0.0, 1.0
    );
    


    A 4*4 matrix looks like this:

      c0  c1  c2  c3            c0  c1  c2  c3
    [ Xx  Yx  Zx  Tx ]        [  0   4   8  12 ]     
    [ Xy  Yy  Zy  Ty ]        [  1   5   9  13 ]     
    [ Xz  Yz  Zz  Tz ]        [  2   6  10  14 ]     
    [  0   0   0   1 ]        [  3   7  11  15 ] 
    

    In GLSL the columns are addressed like this:

    vec4 c0 = eyeTrans[0].xyzw;
    vec4 c1 = eyeTrans[1].xyzw;
    vec4 c2 = eyeTrans[2].xyzw;
    vec4 c3 = eyeTrans[3].xyzw;
    

    And the memory image of a 4*4 matrix looks like this:

    [ Xx, Xy, Xz, 0, Yx, Yy, Yz, 0, Zx, Zy, Zz, 0, Tx, Ty, Tz, 1 ]
    

    See further: