Question

I have a 3D object in my scene and the fragment shader for this object receives a texture that has the same size of the screen. I want to get the coordinates from the current fragment and find the color information on the image in the same position. Is this possible? Can someone point me to the right direction?

Was it helpful?

Solution

The fragment shader has a built-in value called gl_FragCoord that supplies the pixel coordinates of the target fragment. You must divide this by the width and height of the viewport to get the texture coordinates for lookup. Here's a short example:

uniform vec2 resolution;
uniform sampler2D backbuffer;

void main( void ) {
    vec2 position = ( gl_FragCoord.xy / resolution.xy );
    vec4 color = texture2D(backbuffer, position);
    // ... do something with it ...
}

For a complete working example, try this in a WebGL-capable browser:

http://glslsandbox.com/e#375.15

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top