如何将.pgm纹理文件加载到openGL中

How to load a .pgm texture file into openGL

本文关键字:加载 openGL 文件 纹理 pgm      更新时间:2023-10-16

到目前为止,我有以下代码:

ifstream textureFile;
char* fileName="BasketBall.pgm";
textureFile.open(fileName, ios::in);
if (textureFile.fail()) {
    displayMessage(ERROR_MESSAGE, "initTexture(): could not open file %s",fileName);
}
skipLine(textureFile); // skip the "P2" line in the Net.pgm file.
textureFile >> textureWidth; // read in the width
textureFile >> textureHeight; // read in the height
int maxGrayScaleValue;
textureFile >> maxGrayScaleValue; // read in the maximum gray value (255 in this case)
texture = new GLubyte[textureWidth*textureHeight];
int grayScaleValue;
for (int k = 0; k < textureHeight; k++) {
    for(int l = 0; l < textureWidth; l++) {
        textureFile >> grayScaleValue;
        texture[k * textureWidth + l]=(GLubyte) grayScaleValue;
    }
}
textureFile.close();
glBindTexture(GL_TEXTURE_2D, texName);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, textureWidth, textureHeight, 
            0, GL_RGBA, GL_UNSIGNED_BYTE, texture);

但当我在成功构建后尝试运行它时,它只是说我的项目已经"停止工作"。

这很可能是由于您正试图将灰度图像加载到RGBA容器中。

我可以想出两种方法来解决你的问题:

第一种是将texture放大3倍,并将灰度值加载到3个连续的空间中。因此:

texture = new GLubyte[textureWidth*textureHeight*3];

for (int k = 0; k < textureHeight; k++) {
    for(int l = 0; l < textureWidth; l+=3) {
        textureFile >> grayScaleValue;
        texture[k * textureWidth + l]=(GLubyte) grayScaleValue;
        texture[k * textureWidth + l + 1]=(GLubyte) grayScaleValue;
        texture[k * textureWidth + l + 2]=(GLubyte) grayScaleValue;
    }
}

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, textureWidth, textureHeight, 
        0, GL_RGB, GL_UNSIGNED_BYTE, texture);

第二个是尝试它只有一个单一的通道所以:

glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, textureWidth, textureHeight, 
        0, GL_RED, GL_UNSIGNED_BYTE, texture);

除此之外,我建议使用调试器和断点来遍历代码并找出崩溃的位置,但正如我上面提到的,这很可能是因为您正在将一个通道纹理传递到一个容器中,该容器需要4个通道。