Search code examples
glsl

Can I access the spare floats in a mat3 in GLSL?


I'm using a mat3 uniform in a GLSL shader.

layout (std140)
struct UNI {
    mat3 mat;
} u;

A mat3 is stored as 3 rows of vec4 in GLSL so that means there's 3 unused floats in there.

Is there any way to access those floats? I want to to pack some more data in there.

nb. I tried using u.mat[0][3] but it says "array index out of bounds" when I compile it.


Solution

  • I think you are mixing two things here:

    1. the actual memory layout of the data
    2. the API that GLSL provides you to access the data

    When you are using Uniform Buffer Objects (UBO) to back the storage of the mat3 and are using the std140 layout, then yes, a mat3 is layed out in exactly the same way as 3 vec4 values. So, essentially, under std140 layout there is no difference in the memory layout between a mat3x4 (three columns each with 4 rows/elements) and a mat3 or mat3x3.

    However, you cannot access the fourth row of each column when using a mat3 as the API type in the GLSL shader.

    What you could do instead is simply use the mat3x4 type, which would give you access to the fourth row. And when you need a mat3 you can cast it with mat3(theMat3x4Value).