openGL 子贴图

2021-12-19 00:00:00 opengl c++

我有图像数据,我想获得它的子图像以用作 opengl 纹理.

I have image data and i want to get a sub image of that to use as an opengl texture.

glGenTextures(1, &m_name);
glGetIntegerv(GL_TEXTURE_BINDING_2D, &oldName);
glBindTexture(GL_TEXTURE_2D, m_name);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_width, m_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_data);

如何获取作为纹理加载的图像的子图像.我认为这与使用 glTexSubImage2D 有关,但我不知道如何使用它来创建我可以加载的新纹理.调用:

How can i get a sub image of that image loaded as a texture. I think it has something to do with using glTexSubImage2D, but i have no clue how to use it to create a new texture that i can load. Calling:

glTexSubImage2D(GL_TEXTURE_2D, 0, xOffset, yOffset, xWidth, yHeight, GL_RGBA, GL_UNSIGNED_BYTE, m_data);

不做任何我能看到的事情,调用 glCopyTexSubImage2D 只会占用我的帧缓冲区的一部分.谢谢

does nothing that i can see, and calling glCopyTexSubImage2D just takes part of my framebuffer. Thanks

推荐答案

使用 glPixelStorei.您可以使用它来将 GL_UNPACK_ROW_LENGTH 设置为整个图像的宽度(以像素为单位).然后调用 glTexImage2D(或其他),将指针传递给子图像的第一个像素以及子图像的宽度和高度.

Use glPixelStorei. You use it to set GL_UNPACK_ROW_LENGTH to the width (in pixels) of the entire image. Then you call glTexImage2D (or whatever), passing it a pointer to the first pixel of the subimage and the width and height of the subimage.

完成后不要忘记将 GL_UNPACK_ROW_LENGTH 恢复为 0.

Don't forget to restore GL_UNPACK_ROW_LENGTH to 0 when you're finished with it.

即:

glPixelStorei( GL_UNPACK_ROW_LENGTH, img_width );
char *subimg = (char*)m_data + (sub_x + sub_y*img_width)*4;
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, sub_width, sub_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, subimg );
glPixelStorei( GL_UNPACK_ROW_LENGTH, 0 );

或者,如果您对指针数学过敏:

Or, if you're allergic to pointer maths:

glPixelStorei( GL_UNPACK_ROW_LENGTH, img_width );
glPixelStorei( GL_UNPACK_SKIP_PIXELS, sub_x );
glPixelStorei( GL_UNPACK_SKIP_ROWS, sub_y );

glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, sub_width, sub_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_data );

glPixelStorei( GL_UNPACK_ROW_LENGTH, 0 );
glPixelStorei( GL_UNPACK_SKIP_PIXELS, 0 );
glPixelStorei( GL_UNPACK_SKIP_ROWS, 0 );

Edit2:为了完整起见,我应该指出,如果您使用 OpenGL-ES,那么您将不会获得 GL_UNPACK_ROW_LENGTH.在这种情况下,您可以 (a) 自己将子图像提取到新的缓冲区中,或者 (b)...

For the sake of completeness, I should point out that if you're using OpenGL-ES then you don't get GL_UNPACK_ROW_LENGTH. In which case, you could either (a) extract the subimage into a new buffer yourself, or (b)...

glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, sub_width, sub_height, 0, GL_RGBA, GL_UNSIGNED_BYTES, NULL );

for( int y = 0; y < sub_height; y++ )
{
    char *row = m_data + ((y + sub_y)*img_width + sub_x) * 4;
    glTexSubImage2D( GL_TEXTURE_2D, 0, 0, y, sub_width, 1, GL_RGBA, GL_UNSIGNED_BYTE, row );
}

相关文章