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

时间:2015-03-11 06:54:55

标签: c++ opengl volume-rendering

我尝试将.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;

1 个答案:

答案 0 :(得分:4)

非Power-of-2是没有问题的,因为OpenGL-2.0删除了这个约束。为了将每个图像切片读入纹理,请使用带有NULL指针的glTexImage3D来初始化纹理,然后在循环中迭代文件,读取每个文件,解码并使用glTexSubImage3D将其加载到正确的切片中。另外,请勿使用明确的newdelete[],而应使用std::vector

正确实现“foreach文件”循环和“ImageFileReader”留给读者练习。我建议查看一个特定候选人(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);