How do you access the individual elements of a glsl mat4?
Is it possible to access the individual elements of a glsl mat4 type matrix? How?
Solution 1:
The Section 5.6 of the GLSL reference manual says you can access mat4
array elements using operator[][]
style syntax in the following way:
mat4 m;
m[1] = vec4(2.0); // sets the second column to all 2.0
m[0][0] = 1.0; // sets the upper left element to 1.0
m[2][3] = 2.0; // sets the 4th element of the third column to 2.0
Remember, OpenGL defaults to column major matrices, which means access is of the format mat[col][row]
. In the example, m[2][3]
sets the 4th ROW (index 3) of the 3rd COLUMN (index 2) to 2.0. In the example m[1]=vec4(2.0)
, it is setting an entire column at once (because m[1]
refers to column #2, when only ONE index is used it means that COLUMN. m[1]
refers to the SECOND COLUMN VECTOR).