3
votes

I have created a classic 2D a texture, and rendered into some values, in my case depth. In the c++ code I use the glGenerateMipmap() function to auto generate mipmaps. In fragment shader I can access the texture, like a normal sampler2D uniform, and I would like to write into the given mipmap level, specifically I want to calculate values on r+1 level, according to values on level r, and write in it. Is there some useful tool to achieve that? Using GLSL 4.30

For example:

// That's how I get the value, I need some kind of method to set
float current_value = textureLod(texture, tex_coords, MIP_LVL).y;
1

1 Answers

5
votes

Yes, use the function glFramebufferTexture2D and on the last parameter specify the mipmap level.

After you attached everything you need, render the image you want to be at the specific mipmap.

Note: Don't forget to change to glViewport so it will render to the appropriate mipmap size!

Here is a simple example:

unsigned int Texture = 0;
int MipmapLevel = 0;
glGenFramebuffers(1, &FBO);
glGenRenderbuffers(1, &RBO);
glGenTextures(1, &Texture);

glBindTexture(GL_TEXTURE_2D, Texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, TextureWidth, TextureHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr);
// glTexParameteri here

// Use shader and setup uniforms

glViewport(0, 0, TextureWidth, TextureHeight);

glBindFramebuffer(GL_FRAMEBUFFER, FBO);
glBindRenderbuffer(GL_RENDERBUFFER, RBO);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, TextureWidth, TextureHeight);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, Texture, MipmapLevel); // Here, change the last parameter to the mipmap level you want to write to
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// Render to texture

// Restore all states (glViewport, Framebuffer, etc..)

EDIT:

If you want to modify a generated mipmap (generated with glGenerateMipmap or externally), you can use the same method, use glFramebufferTexture2D and choose the mipmap you want to modify.

After you have done all the setup stuff (like the above sample), you can either completely render a new mipmap, or you can send the original texture, and modify it in the fragment shader.