Search code examples
openglglsltextures

GLSL texture layout


How does the layout of the matrix (row-major vs column-major) affect the GLSL texture that it creates? Does the access to that texture changes in the shader? In case of the column-major matrix should I first change the matrix to row-major and then upload it to GPU as a texture?


Solution

  • See The OpenGL Shading Language 4.6, 5.4.2 Vector and Matrix Constructors, page 101:

    To initialize a matrix by specifying vectors or scalars, the components are assigned to the matrix elements in column-major order.

    mat4(float, float, float, float,  // first column
         float, float, float, float,  // second column
         float, float, float, float,  // third column
         float, float, float, float); // fourth column
    


    This means if you store the matrices (mat4) in the lines of a 2 dimensional 4*N, RGBA texture, like this:

             0           1           2           3
    mat4 m0  m0[0].xyzw  m0[1].xyzw  m0[2].xyzw  m0[3].xyzw
    mat4 m1  m1[0].xyzw  m1[1].xyzw  m1[2].xyzw  m1[3].xyzw
    mat4 m2  m2[0].xyzw  m2[1].xyzw  m2[2].xyzw  m2[3].xyzw
    mat4 m3  .....
    

    mat4 matArray[N]; // possibly std::vector<glm::mat4>( N );
    
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, 4, N, 0, GL_RGBA, GL_FLOAT, matArray);
    

    then you can read the matrices from the texture in the shader like this:

    uniform sampler2D matSampler; 
    
    void main()
    {
        mat4 m0 = mat4(
            texelFetch( matSampler, ivec(0, 0), 0),
            texelFetch( matSampler, ivec(1, 0), 0),
            texelFetch( matSampler, ivec(2, 0), 0),
            texelFetch( matSampler, ivec(3, 0), 0) );
    
        mat4 m1 = mat4(
            texelFetch( matSampler, ivec(0, 1), 0),
            texelFetch( matSampler, ivec(1, 1), 0),
            texelFetch( matSampler, ivec(2, 1), 0),
            texelFetch( matSampler, ivec(3, 1), 0) );
    
       .....      
    }