opengl - how to rotate and translate rectangle texture in shader -
i'm trying handle transform of texture in fragment shader. resolution of window (640,360), rotation 30 degree, , scale vec2(0.5,0.5).
this want: here fragment shader:
precision mediump float; varying vec2 v_texcoord; uniform sampler2d s_texture; mat3 maketranslation(vec2 t) { mat3 m = mat3(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, t.x, t.y, 1.0); return m; } mat3 makerotation( float angleinradians ){ float c = cos(angleinradians); float s = sin(angleinradians); mat3 m = mat3(c, -s, 0, s, c, 0, 0, 0, 1); return m; } mat3 makescale(vec2 s) { mat3 m = mat3( s.x, 0, 0, 0, s.y, 0, 0, 0, 1); return m; } void main(){ vec2 position = vec2(0.0,0.0); vec2 scale = vec2(0.5,0.5); float rotation = 30.0; float r = rotation/180.0*3.14159; vec2 size = vec2(640.0,480.0); mat3 mt = maketranslation( translation ); mat3 mr = makerotation( r ); mat3 ms = makescale( 1.0/scale ); //transform vec3 newcoord = vec3(v_texcoord.xy,1.0); newcoord = mt*newcoord; newcoord = mr*ms*vec3(newcoord.x - 0.5, newcoord.y - 0.5,0.0) + vec3(0.5, 0.5, 0.0); gl_fragcolor = texture2d(s_texture, vec2(newcoord.x, newcoord.y) ); }
the result is:
can see, result incorrect.
so, apply ratio of rectangle size texcoord.y:
//transform float fy = 0.5*(1.0 - size.y*1.0/size.x); newcoord.y = (newcoord.y-0.5)*size.y/size.x+fy; newcoord = mt*newcoord; \n" newcoord = mr*ms*vec3(newcoord.x - 0.5, newcoord.y - 0.5,0.0) + vec3(0.5, 0.5, 0.0); newcoord.y = (newcoord.y+0.5)*size.x/size.y-fy;
what i've got: rectangle correct, position of center point incorrect.
so, how right result? thanks.
getting right order of operations important.
when receive texture coordinates, in range [0, 1]. however, need translate them, in [-0.5, 0.5], before rotate them, rotating around center of texture. apply scale, , translation.
Comments
Post a Comment