Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotating a texture on a Fragment Shader in GLSL ES

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);
    }
like image 382
PerracoLabs Avatar asked Jan 21 '15 19:01

PerracoLabs


People also ask

How do you rotate textures in shader?

To rotate a texture in a shader, you have to rotate its texture coordinates. This solution should work for both 2D and 3D. uv is the texture coordinate you're initially using. pivot is the point the uv will rotate about.

Can you send data from fragment shader to vertex shader?

All shader stages can pass data between them by using input and output variables. If in the vertex shader we create an output variable, we will be able to read it on the fragment shader as an input variable.

Is fragment shader same as pixel shader?

A fragment shader is the same as pixel shader. One main difference is that a vertex shader can manipulate the attributes of vertices. which are the corner points of your polygons. The fragment shader on the other hand takes care of how the pixels between the vertices look.


1 Answers

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);
like image 142
Tobias Grothmann Avatar answered Nov 18 '22 12:11

Tobias Grothmann