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);
}
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With