Search code examples
openglshadervertex-shader

OpenGL In-shader Vertex Matrix Creation


I am trying to generate up my projection and transform matrix functions inside my vertex shader, e.g. defining my transform, rotation, and perspective matrix functions in terms of GLSL. I am doing this in order to increase readability of my program by bypassing all the loading/importing etc. of matrices into the shader, apart from camera position, rotation and FOV.

My only concern is that the matrix is being calculated each shader call or each vertex calculation.

Which, if either of the two, is what actually happens in the shader?

Is it better to deal with the clutter and import the matrix from my program, or is my short-cut of creating the matrix in-shader acceptable/recommended?

*update with code*

#version 400

in vec4 position;
uniform vec3 camPos;
uniform vec3 camRot;

mat4 calcMatrix(
    vec3 pos,
    vec3 rot,
) {
    float foo=1;
    float bar=0;
    return mat4(pos.x,pos.y,pos.z,0,
                rot.x,rot.y,rot.z,0,
                foo,bar,foo,bar,
                0,0,0,1);
}

void main()
{
    gl_Position = calcMatrix(camPos, camRot) * position;
}

versus:

#version 400

in vec4 position;
uniform mat4 viewMatrix;

void main()
{
    gl_Position = viewMatrix * position;
}

Which method is recommended?


Solution

  • If you need a different matrix for each vertex, well, fairly do it in the shader. I can't imagine a case where that's needed.

    Otherwise, it's much more faster to pass the matrix as a uniform. Don't overload the GPU computing again and again the same matrix.