Search code examples
openglglsl

Rotate texture using vertex shader


I'm trying to rotate a texture inside vertex shader. I have a pointer to a texture that, for my purpose, is rotated counterclockwise by 90 degrees. I don't want to manually rotate the texture before calling glTexImage2D().

I can use #version 120 only.

This is my original vertex shader:

#version 120

attribute vec4 a_position;
attribute vec2 a_texCoord;

varying vec2 v_texCoord;

void main()
{
    gl_Position = a_position;
    v_texCoord = a_texCoord;
}

For testing purpose only, I modified the vertex shader in this way but I get a black screen:

#version 120

const float w = 0.76;
float mat3 A = ( 1, 0, 0,
                 0,  1, 0,
                 0,  0, 1 );

attribute vec3 a_position;
attribute vec2 a_texCoord;

varying vec2 v_texCoord;

void main()
{
    A = ( cos(w), -sin(w), 0,
          sin(w),  cos(w), 0,
               0,       0, 1 );
    gl_Position = A * vec4(a_position, 1.0f);
    v_texCoord = a_texCoord;
}

Solution

  • You get compile errors. The assignment doesn't work:

    A = (cos(w), -sin(w), 0,
         sin(w),  cos(w), 0,
         0,       0, 1 );
    

    You have to construct a mat3. Then you can assign that matrix (also see GLSL Programming/Vector and Matrix Operations):

    A = mat3(cos(w), -sin(w), 0.0,
             sin(w),  cos(w), 0.0,
             0.0,     0.0,    1.0);
    

    You cannot multiply a vec4 and a mat3. You have to multiply the vec3 with the mat3

    gl_Position = vec4(A * a_position, 1.0f);
    

    And I even cant imagin what you expect with this line:

    float mat3 A = ( 1, 0, 0,
                    0,  1, 0,
                    0,  0, 1 );
    

    Correct would be:

    mat3 A = mat3(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0);
    

    This is the same as:

    mat3 A = mat3(1.0);
    

    Correct vertex shader:

    #version 120
    
    attribute vec3 a_position;
    attribute vec2 a_texCoord;
    varying vec2 v_texCoord;
    
    void main()
    {
        const float w = 0.76;
        mat3 A = mat3(cos(w), -sin(w), 0.0,
                      sin(w),  cos(w), 0.0,
                      0.0,     0.0,    1.0);
        gl_Position = vec4(A * a_position, 1.0);
        v_texCoord = a_texCoord;
    }