Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the pixel color in a specific coordinate from a sampler2D using GLSL

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?

like image 869
Luke B. Avatar asked Feb 29 '12 20:02

Luke B.


1 Answers

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

like image 98
emackey Avatar answered Oct 02 '22 22:10

emackey