1

I have a problem with mapping of texture in fragment shader. I have a texture that has same size as window (I use part of scene rendered in previous pass, but I use brick texture in the example below) and I need to map it as in 2D. Is it somehow possible ? I tried different ways, but nothing worked.

Could you please advice me how should the fragment shader looks like ? Please any advice will be helpfull. Thank you!

tepaot with plain mapping

Bhiefer
  • 1,613
  • 4
  • 16
  • 31

1 Answers1

3

I have a texture that has same size as window (…) and I need to map it as in 2D.

So if I understand you correctly, then you want to use the previously generated texture as if it was some kind of "layer", where texture pixels map 1:1 to viewport pixels, and the texture has the very same size like the viewport?

If so then this is very easy (as of GLSL version 1.30). There is the function texelFetch, which takes a pixel index as coordinate (unlike texture which takes a value in the range [0; 1]). The built in variable gl_FragCoord gives the window coordinates of the currently processed fragment. So by using the coordinates in gl_FragCoord for texelFetch you get the desired result.

datenwolf
  • 159,371
  • 13
  • 185
  • 298
  • 2
    As a little remark, if the `texelFetch` function is not availabe (on GL2/DX9 hardware, I think) you can just use the usual `texture2D`, but have to divide `gl_FragCoord` by the size of the screen/texture before using it as texture coordinate. – Christian Rau Dec 11 '11 at 13:40
  • 1
    @ChristianRau: It's not that easy as simply deviding by the testure size, because 0 and 1 coordinates are not at texel centers. I explained it in detail here http://stackoverflow.com/a/5879551/524368 – datenwolf Dec 11 '11 at 15:25
  • Yes, I know that (0,0) is not the texel center. But shouldn't the `gl_FragCoord` be at pixel centers, too? So the `gl_FragCoord` of, say the lower left pixel should be (0.5, 0.5) instead of (0, 0) anyway, shoudn't it? So you should indeed get texel centers from `gl_FragCoord`. – Christian Rau Dec 11 '11 at 15:29
  • 1
    I haven't really found it in the GLSL spec yet, but [this extension](http://www.opengl.org/registry/specs/ARB/fragment_coord_conventions.txt) (which should already be core) states that `gl_FragCoord` indeed gives x.5 values instead of integers by default. So it is really as easy as a division by the texture size. – Christian Rau Dec 11 '11 at 15:50