Search code examples
c++openglgraphicsglslshader

How will it be when in glTexImage2D I choose different internal format from how I sample it in shader?


For example, I write this in code:

glTexImage2D(GL_TEXTURE_2D, i, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);

and in shader:

glFragColor = texture2D(sampler, uv).rgba

what will happen, is there official definition for this situation?


Solution

  • The result will be the same, as if you would do the following:

    glFragColor = vec4( texture2D(sampler, uv).rgb, 1.0 );
    


    Because the Image Format specification of Khronos group says:

    Image formats do not have to store each component. When the shader samples such a texture, it will still resolve to a 4-value RGBA vector. The components not stored by the image format are filled in automatically. Zeros are used if R, G, or B is missing, while a missing Alpha always resolves to 1.


    See further OpenGL 4.6 API Core Profile Specification; 15.2. SHADER EXECUTION; page 487]:

    When a texture lookup is performed in a fragment shader, the GL computes the filtered texture value ... and converts it to a texture base color Cb as shown in table 15.1, ...

    Texture Base Texture base color Internal Format    Cb              Ab
    RED                                                (Rt, 0, 0)      1
    RG                                                 (Rt, Gt, 0)     1
    RGB                                                (Rt, Gt, Bt)    1
    RGBA                                               (Rt, Gt, Bt)    At
    

    Table 15.1: Correspondence of filtered texture components to texture base components.