In openGL. How to copy part of a texture to another texture

I am trying to create an empty (white without alpha) texture where I can load other textures and record some of them. I tried just getting a part of the texture, and using glTexSubImage2D to put it there, it doesn't seem to work correctly. Does anyone know how to do this? What am I doing wrong?

int sourceTextWidth; int sourceTextHeight; int sourceFormat; int formatOffset = 0; //bind the texture glBindTexture( GL_TEXTURE_2D, textureID ); //get its params glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_COMPONENTS, &sourceFormat); glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &sourceTextWidth); glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &sourceTextHeight); switch (sourceFormat) { case GL_RGB: { formatOffset = 3; } break; case GL_RGBA: { formatOffset = 4; } break; } if (formatOffset == 0) { return false; } unsigned char * sourceData = (unsigned char *)malloc(sourceTextWidth * sourceTextHeight * formatOffset); glGetTexImage(GL_TEXTURE_2D, 0, GL_RGB, GL_UNSIGNED_BYTE, sourceData); glBindTexture( GL_TEXTURE_2D, m_currentTextureId ); unsigned char * destData = (unsigned char *)malloc(width * height * 3); glGetTexImage(GL_TEXTURE_2D, 0, GL_RGB, GL_UNSIGNED_BYTE, sourceData); for (int i = 0; i < height; ++i) { memcpy(&destData[(i * width * 3) ], &sourceData[((i + y) * sourceTextWidth * 3) + (x * 3)], width * 3); } //glDeleteTextures (1, m_currentTextureId); glBindTexture( GL_TEXTURE_2D, m_currentTextureId ); glTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGB,GL_UNSIGNED_BYTE, destData ); free(destData); free(sourceData); 
+4
c ++ opengl textures
source share
1 answer

If you have access to OpenGL 4.3 or the ARB_copy_image extension (or its older cousin, NV_copy_image), you can use glCopyImageSubData .

Otherwise, you can use BLP. You attach the source texture to the FBO , attach the destination texture to the FBO (perhaps the same thing, but if it is, then obviously not at the same anchor point) set the reading buffers and draw buffers so that the FBOs read from the source attachments and painted to the destination, and then blit from one framebuffer to another .

The trick you are trying to do does not work, BTW, because you never allocated storage for your new texture. glTexSubImage cannot be called for an image in a texture if no storage has been allocated for this image . This may be caused by calling glTexImage or one of several other functions. The "SubImage" functions are intended to be loaded into existing storage, and not to create new storage.

+6
source share

All Articles