Rotating a texture on a Fragment Shader in GLSL ES

PerracoLabs picture PerracoLabs · Jan 21, 2015 · Viewed 11.2k times · Source

I'm trying to rotate a texture in a fragment shader, instead of using the vertex shader and matrix transformations.

The rotation has the pivot at the center.

The algorithm works fine when rendering in a quad with a square shape, but when the quad has a rectangular shape the render result gets messed up. Anyone can spot the problem?

Thank you

    varying vec2 v_texcoord;
    uniform sampler2D u_texture;
    uniform float u_angle;

    void main()
    {
        vec2 coord = v_texcoord;
        float sin_factor = sin(u_angle);
        float cos_factor = cos(u_angle);
        coord = (coord - 0.5) * mat2(cos_factor, sin_factor, -sin_factor, cos_factor);
        coord += 0.5;

        gl_FragColor = texture2D(u_texture, coord);
    }

Answer

Tobias Grothmann picture Tobias Grothmann · May 24, 2016

The following line of code which was provided in the question:

coord = vec2(coord.x - (0.5 * Resolution.x / Resolution.y), coord.y - 0.5) * mat2(cos_factor, sin_factor, -sin_factor, cos_factor);

is not quite right. There are some bracketing errors.

The correct version would be:

coord = vec2((coord.x - 0.5) * (Resolution.x / Resolution.y), coord.y - 0.5) * mat2(cos_factor, sin_factor, -sin_factor, cos_factor);