0
votes

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?

2
Your vertex shader uniform inputs and matrix calculation code might help to give a better idea of what you're referring to.MuertoExcobito
Performance-wise it's not a good idea to calculate those in a shader. What do you mean by "clutter"? Creating the transform matrix should be a pretty simple function. Like the previous comment says, let's see some code.vesan
Okay, added some sample codeilcj

2 Answers

2
votes

Whats wrong with doing

float[16] matrix;
calculate_transform(matrix, args);
glUniformMatrix4fv(mvp, 1, false, matrix);

Or even

set_matrix_uniform_using(mvp, args);

which then does what the previous bit of code does.


If you are worried about clutter then extract a function and give it a good name.

To do this in the shader there are several consequences: you would need multiple varaibles to express what the single matrix expresses, leading to clutter at shader load and uniform upload, shader debugging is much more difficult than making sure your own cope does what it needs to do. If you hardcode the movement code you cannot replace it with a free moving camera without changing the shader.

All that doesn't even touch on performance costs. The GPU is much better at loading a matrix from uniform memory and multiplying a it with a vector than it is at doing the trig function needed for the frustum and rotate.

1
votes

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.