Alexandre GUIDET
Alexandre GUIDET

Reputation: 862

2D glsl shader transformation

I would like to create a shader to simulate a pseudo 3D water surface on a 2D scene build with libgdx. The idea is to recreate the following effect:

http://forums.tigsource.com/index.php?topic=40539.msg1104986#msg1104986

But I am stuck at creating the trapezoid shape, I think I didn't understand how texture coordinate are calculated on opengl shaders. May I modify the vertex in the vertex shader or may I displace the texture on the fragment shader?

here is a test I have done but that don't work as expected.

vertex shader:

attribute vec4 a_position;
attribute vec4 a_color;
attribute vec2 a_texCoord0;

uniform mat4 u_projTrans;

varying vec4 v_color;
varying vec2 v_texCoord0;

void main()
{
    v_color = a_color;
    float factor = (a_texCoord0.x - 0.5) * (a_texCoord0.y);
    v_texCoord0 = a_texCoord0;
    v_texCoord0.x += factor;
    gl_Position =  u_projTrans * a_position;
}

the fragment shader is just a passthrough

varying vec4 v_color;
varying vec2 v_texCoord0;

uniform sampler2D u_texture;

void main()
{
    gl_FragColor = v_color * texture2D(u_texture, v_texCoord0);
}

and the result image

the bad perspective result

I am sure that my approach is too naive.

Upvotes: 2

Views: 710

Answers (1)

Alexandre GUIDET
Alexandre GUIDET

Reputation: 862

Finally, I decided to use only the fragment shader to achieve the effect. Fake depth calculation is done by applying X displacement in regards of the Y axis.

Here is the snipet:

// simulate 3D surface
vec2 new_coord = v_texCoord0;
// calculate the stretching factor
float factor = ((0.5 - new_coord.x) * new_coord.y);
// apply the factor and stretch the image
new_coord.x += factor;

gl_FragColor = texture2D(u_texture, new_coord);

Upvotes: 0

Related Questions