Search code examples
copenglvertex-shader

working with mat4 in the VertexShader


Why does the first code work, but not the second? The Code is in the Vertex-Shader.

First Code:

gl_Position = ProjectionMatrix * ViewMatrix * ModelMatrix * vec4(Position, 1.0);

Second Code:

mat4 View = mat4(
        ViewMatrix[0][0], ViewMatrix[1][0], ViewMatrix[2][0], ViewMatrix[3][0],
        ViewMatrix[0][1], ViewMatrix[1][1], ViewMatrix[2][1], ViewMatrix[3][1],
        ViewMatrix[0][2], ViewMatrix[1][2], ViewMatrix[2][2], ViewMatrix[3][2],
        ViewMatrix[0][3], ViewMatrix[1][3], ViewMatrix[2][3], ViewMatrix[3][3]
    );

gl_Position = ProjectionMatrix * View * ModelMatrix * vec4(Position, 1.0);

Solution

  • From the GLSL spec about matrix constructors:

    Matrix components will be constructed and consumed in column major order.

    The first 4 floats define the first colum of the new matrix, but you specify the first row of it. You are setting View to the transposed ViewMatrix.

    Note that this absolutely mirros the C syntax and array conventions.