将两个图像堆栈的非幂加载到 3d 纹理 OpenGL C++

Load non power of two image stack into 3d texture OpenGL C++

我已尝试将一堆 .png 图像文件加载到 glTexImage3D 中以用于体积渲染。但是,我无法让它工作,因为它一直在崩溃。顺便说一句,这个问题似乎与 pData.

有关

以下代码供您参考:

GLubyte * pData = new GLubyte[XDIM*YDIM*ZDIM];
ifstream volumeData;

getFileNameWithSpecificExtension(dir_path);
sort(begin(fileIndex), end(fileIndex));

for (int i = 0; i < 201; i ++)
{
    volumeData.open(FrontPart + to_string(fileIndex[i]) + ".png", ios::binary);
}

volumeData.read(reinterpret_cast<char*>(pData), XDIM*YDIM*ZDIM*sizeof(GLubyte));
volumeData.close();


glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_3D, textureID);

// set the texture parameters
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);

//set the mipmap levels (base and max)
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_BASE_LEVEL, 0);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAX_LEVEL, 4);

//allocate data with internal format and foramt as (GL_RED) 
glTexImage3D(GL_TEXTURE_3D, 0, GL_RED, XDIM, YDIM, ZDIM, 0, GL_RED, GL_UNSIGNED_BYTE, pData);
GL_CHECK_ERRORS

//generate mipmaps
glGenerateMipmap(GL_TEXTURE_3D);

//delete the volume data allocated on heap
delete[] pData;

非 2 的幂不是问题,因为 OpenGL-2.0 删除了该约束。为了将每个图像切片读入纹理,使用带有 NULL 指针的 glTexImage3D 来初始化纹理,然后在循环中遍历文件,读取每个文件,对其进行解码并使用 glTexSubImage3D 将其加载到正确的切片中。也不要使用明确的 newdelete[],而是 std::vector.

正确实现 "foreach file" 循环和 "ImageFileReader" 留作 reader 的练习。我建议查看 one 特定候选人 (http://sourceforge.net/adobe/genimglib/home/Home/) 的通用图像库。另请记住,将任何图像尺寸硬编码到您的代码中是一个非常糟糕的主意。

glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_3D, textureID);

// set the texture parameters
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);

//set the mipmap levels (base and max)
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_BASE_LEVEL, 0);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAX_LEVEL, 4);

//allocate data with internal format and foramt as (GL_RED) 
glTexImage3D(GL_TEXTURE_3D, 0, GL_RED, XDIM, YDIM, ZDIM, 0, GL_RED, GL_UNSIGNED_BYTE, NULL);
GL_CHECK_ERRORS

GLubyte * pData = new GLubyte[XDIM*YDIM*ZDIM];
std::vector<GLubyte> vData(XDIM*YDIM*ZDIM);
foreach file in filenames (...)
{
    ImageFileReader ifr(FrontPart + to_string(fileIndex[i]) + ".png")
    ifr.decode(vData);
    glTexSubImage3D(GL_TEXTURE_3D, 0,
        0 /* x offset */,
        0 /* y offset */,
        z,
        XDIM, YDIM, 1,
        GL_RED, GL_UNSIGNED_BYTE,
        &vData[0] );
}

//generate mipmaps
glGenerateMipmap(GL_TEXTURE_3D);