Search code examples
glslsizetexel

GLSL Texel Size


Why people use this equation to specify the size of a single texel?

vec2 tex_offset = 1.0 / textureSize(image, 0);

In my opinion, this should be:

whole texels -> whole texture size
single texel -> single texel size

So

singleTexelSize = (singleTexel * wholeTextureSize) / wholeTexel = wholeTextureSize / wholeTexel

This is the whole version of the fragment shader of the Bloom lesson about OpenGL of Joey de Vries:

#version 330 core
out vec4 FragColor;
  
in vec2 TexCoords;

uniform sampler2D image;
  
uniform bool horizontal;
uniform float weight[5] = float[] (0.227027, 0.1945946, 0.1216216, 0.054054, 0.016216);

void main()
{             
    vec2 tex_offset = 1.0 / textureSize(image, 0); // gets size of single texel
    vec3 result = texture(image, TexCoords).rgb * weight[0]; // current fragment's contribution
    if(horizontal)
    {
        for(int i = 1; i < 5; ++i)
        {
            result += texture(image, TexCoords + vec2(tex_offset.x * i, 0.0)).rgb * weight[i];
            result += texture(image, TexCoords - vec2(tex_offset.x * i, 0.0)).rgb * weight[i];
        }
    }
    else
    {
        for(int i = 1; i < 5; ++i)
        {
            result += texture(image, TexCoords + vec2(0.0, tex_offset.y * i)).rgb * weight[i];
            result += texture(image, TexCoords - vec2(0.0, tex_offset.y * i)).rgb * weight[i];
        }
    }
    FragColor = vec4(result, 1.0);
}

Solution

  • I can't follow your proposed way of calculating texel size but maybe this makes it more clear:

    Texture coordinates (also referred to as UVs) are normalized, so they're fractions between 0 and 1 no matter the size of the texture, meaning that a coordinate of 1 can be 256 pixels or 2048 pixels. To calculate how to get from one dedicated value to the next in a normalized space you need to divide 1 by the number of individual values.

    To put in in a different context: Assume I have 10 apples, so that's 100%, how much percent make up one apple? 100(%) / 10(apples) = 10(%) = 1(apple). So if you now want only whole apples from me you know that you have to ask for a multiple of 10%. Convert this to fractions by dividing by 100 and you're back to UVs.

    For further reading check out this answer, it also has a nice diagram: Simulate OpenGL texture wrap + interpolation on canvas?