'Why is my OpenGL texture black (in Dear ImGUI)?

In OpenGL 4.6, I (attempt to) create and initialize a solid color texture as follows:

glCreateTextures(GL_TEXTURE_2D, 1, &_textureHandle);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); // This doesn't change the outcome
std::vector<unsigned char> data(3 * WIDTH * HEIGHT, static_cast<unsigned char>(200));
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, WIDTH, HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, data.data());

I then use the texture in Dear ImGUI like this:

ImGui::Image((void*)(intptr_t) _textureHandle, ImVec2(WIDTH, HEIGHT));

However, this simply shows a black texture.

I also tried a different way of initialization (to no avail):

unsigned char* data = new unsigned char[3 * WIDTH * HEIGHT];
for (unsigned int i = 0; i < (int)(WIDTH * HEIGHT); i++) {
    data[i * 3] = (unsigned char)255;
    data[i * 3 + 1] = (unsigned char)50;
    data[i * 3 + 2] = (unsigned char)170;
}
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, WIDTH, HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, data);

Does anyone know what I'm doing wrong?



Solution 1:[1]

You created the texture by OpenGL 4.5 DSA, but didn't use DSA to set the texture parameters and image.
You have to use glTextureParameter, glTextureStorage2D and glTextureSubImage2D instead of glTexParameter and glTexImage2D.

glCreateTextures(GL_TEXTURE_2D, 1, &_textureHandle);
glTextureParameteri(_textureHandle, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTextureParameteri(_textureHandle, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTextureParameteri(_textureHandle, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTextureParameteri(_textureHandle, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
std::vector<unsigned char> data(3 * WIDTH * HEIGHT, static_cast<unsigned char>(200));
glTextureStorage2D(_textureHandle, 1, GL_RGB8, WIDTH, HEIGHT);
glTextureSubImage2D(_textureHandle, 0, 0, 0, WIDTH, HEIGHT, GL_RGB, GL_UNSIGNED_BYTE, data.data());

Solution 2:[2]

If don't generate mipmaps (with glGenerateMipmap) you must set GL_TEXTURE_MIN_FILTER to a non mipmap filter. The texture would be "Mipmap Incomplete" if you do not change the minifying function to GL_NEAREST or GL_LINEAR.

Eiter generate mipmaps:

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, WIDTH, HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, data.data());
glGenerateMipmap(GL_TEXTURE_2D);

Or use GL_LINEAR for the minifying function:

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Rabbid76