# Should the modelview and projection matrices be calculated in the shader or on the CPU?

At minimum I would have a camera with rotation and world position; projections parameters such as angle of view and perspective vs. orthographic; and meshes with scale, angle, and world position.

When rendering a mesh I am wondering if I should calculate the final transformation matrix on the CPU and pass it to my shader, or if I should calculate the transformation matrix inside my shader.

## 2 Answers

There is no reason to calculate transformation matrix in shader, it would be just waste of resources, because you would need to calculate it for every vertex and that's not good idea.

If you calculate matrix in cpu, it would cost you few instructions and 16 * float size data transfer to GPU.

If you calculate matrix in gpu, it would cost you few instructions * vertices count and 9 * float size transfer to GPU - position, rotation, scale.

• I forgot about the shader running for every vertex. Oops. I actually got the idea about calculating matrices in the shader because that's what this tutorial appears to be doing. – Aaron Jul 2 '12 at 20:13
• It's possible to calculate a matrix in a shader and sometimes it can be faster than uploading via a new glUniform (another example might be a transform via position only) but as a general rule that only applies to very special cases where full CPU-side matrix transforms and full matrix uploads are benchmarked and determined to be a bottleneck - otherwise don't do it unless you absolutely know for certain that you need to. – Maximus Minimus Jul 3 '12 at 0:28
• ...also note what it says in the Conclusion of that tutorial... – Maximus Minimus Jul 3 '12 at 0:33
• And that's why one shouldn't skim. – Aaron Jul 3 '12 at 15:13

You should most definitely calculate the matrices in client cod, since the matrices do not change on a vertex-to-vertex basis. You are essentially repeating one calculation - of which you know the answer will be the same - for every time the vertex program is run.