在 OpenGL 中重新组织图像/图片数组以适应 2 种纹理大小的幂

Reorganize image/picture arrays in OpenGL to fit power of 2 textures size

本文关键字:纹理 数组 OpenGL 新组织 图像      更新时间:2023-10-16

我在OpenGL中遇到了麻烦,因为在OpenGL中纹理必须是2的幂。我正在做的是以下内容:

我使用 PNGLIB 或 SOIL 将 PNG 文件加载到一个无符号字符数组中。这个想法是我可以运行这个数组并"选择"与我相关的部分。例如,想象我已经加载了一个人,但我只想将头部存储在单独的纹理中。因此,我循环遍历数组并仅选择必要的部分。

第一个问题:我相信数组中的数据是以 RGBA 模式存储的,但我还不确定数据是按行填充还是按列填充。是否有可能知道这些信息?

第二个问题:由于需要始终创建 2 个纹理的力量,因此我有一个宽度为 513 像素的图像,因此我需要宽度为 1024px 的纹理。所以正在发生的事情是,图片看起来完全被"破坏"了,因为像素不在它们应该在的地方 - 纹理的大小与数组中填充的相关数据不同。那么我如何设法重新组织数组以再次获取图像的内容呢?我尝试了以下方法,但它不起作用:

unsigned char* new_memory = 0;
    int index = 0;
    int new_index = 0;
    new_memory = new unsigned char[new_tex_width * new_tex_height * 4];
    for(int i=0; i<picture.width; i++) // WIDTH
    {
        for(int j=0; j<picture.height; j++) // HEIGHT
        {
            for(int k=0; k<4; k++) // DEPTH
                new_memory[new_index++] = picture.memory[index++];//picture.memory[i + picture.height * (j + 4 * k)];
        }
        new_index += new_tex_height - picture.height;
    }

    glGenTextures(1, &png_texture);
    glBindTexture(GL_TEXTURE_2D, png_texture);
    glTexImage2D(GL_TEXTURE_2D, 0, 3, new_tex_width, new_tex_height, 0 , GL_RGBA, GL_UNSIGNED_BYTE, new_memory);

自很久以前以来,就一直支持两种纹理的非幂。但是,创建纹理图集和重新排列纹理仍然有很多优点,我们这样做的方法是简单地使用 freeimage,因为它们会为您处理所有这些并支持一些压缩格式。

如果你想按照自己的方式做,并且知道它只是一个位图,那么我会按照(未经测试,不检查输入,但应该给你一个想法):

void Blit( int xOffset, int yOffset, int targetW, int sourceW, int sourceH, unsigned char* source, unsigned char* target, unsigned int bpp )
{
    for( unsigned int i = 0; i < sourceH; ++i )
    {
        memcpy( target + bpp * ( targetW * ( yOffset + i ) + xOffset ), source + sourceW * i * bpp, sourceW * bpp );
    }
}

基本上,只需将每一行都放在

上面。