# Computing derivatives with finite difference

Hi,

i have some problems with computing the laplacian with texture lookups, my following fragment code is

uniform sampler2D u_tex;
uniform float h; // 1.0/BUFF_DIM

void main ()
{
vec4 u = texture2D(u_tex, gl_TexCoord[0].xy);

vec4 u_ip = texture2D(u_tex, gl_TexCoord[0].xy + vec2(0.0,h));
vec4 u_im = texture2D(u_tex, gl_TexCoord[0].xy - vec2(0.0,h));

vec4 u_fx = u - u_ip; // forward difference
vec4 u_xx = texture2D(u_tex, u_fx.xy - vec2(0.0,h)) - u_fx; // backward difference of u_fx

gl_FragColor = u_xx;
//gl_FragColor = u_ip - 2*u + u_im; this one gives the correct laplacian
}

so gl_FragColor = u_xx; is calculating the backward difference of a forward difference operator giving the laplacian in one direction and this does not gives the correct result.

While gl_FragColor = u_ip - 2*u + u_im; gives the correct laplacian.

I think the problem is that the lookup texture2D(u_tex, u_fx.xy - vec2(0.0,h)) is wrong but I don’t know how I can lookup the u_fx texture?

Regards,
Christoffer

your texture lookup texture2D(u_tex, u_fx.xy - vec2(0.0,h)) does indeed look wrong.
I’m a little stumped by your question. You know how to get the correct result…what exactly is the issue?

That aside, in terms of the lookup above, remember that the first lookups you are doing use the fragment position (which I assume is how you’ve set up your texcoords) and lookup values spatially around that fragment (forwards and backwards)

Then with your problem texture2D(u_tex, u_fx.xy - vec2(0.0,h)) the u_fx isn’t relative to the fragment anymore. I’d guess, not knowing the specifics of this problem, that you want to be adding or subracting that u_fx from the current fragment position, or the next position to the right or left.

hth

Are you entirely sure of your algorithm? I have never did that in a glsl shader. But I find doubtful your way of using returned texel colors by texture2D as texture coordinates latter. Please correct me if I am mistaken.

If I had to compute laplacian in a texture, I would first compute gradient and then divergence of these gradient vectors. But your method may be faster.

This topic was automatically closed 183 days after the last reply. New replies are no longer allowed.