在openGL中。如何将纹理的一部分复制到另一个纹理

时间:2013-07-16 17:06:10

标签: c++ opengl textures

我正在尝试创建一个空白(没有alpha的白色)纹理,我可以在其中加载其他纹理并编写其中的一部分。我试着只需要获得纹理的一部分,并使用glTexSubImage2D将它放在那里它似乎不能正常工作。任何人都知道如何做到这一点?我做错了什么?

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);

1 个答案:

答案 0 :(得分:6)

如果您可以访问OpenGL 4.3 or the ARB_copy_image extension(或其旧版本,NV_copy_image),则可以use glCopyImageSubData

否则,您可以使用FBO blitting。您将源纹理附加到an FBO,将目标纹理附加到FBO(可能是同一个,但如果是这样,那么显然不是相同的附着点),设置read buffers和{{3 FBO从源附件中读取并绘制到目标附件,然后draw buffers

你尝试做的伎俩不行,BTW,因为你从未为新纹理分配存储。除非已分配blit from one framebuffer to the other,否则无法为纹理中的图像调用<{1}} 。这可以通过storage for that image“SubImage”功能全部用于上传到现有存储,而不是用于创建新存储。