gpt4 book ai didi

c++ - 加载 TGA 文件并将其与 OpenGL 一起使用

转载 作者:太空狗 更新时间:2023-10-29 20:30:29 26 4
gpt4 key购买 nike

我目前正在尝试使用 C++ 加载标记文件并使用 OpenGL 渲染它。目前颜色都混合了(红色变成蓝色,绿色变成红色,蓝色变成绿色)。我目前将其放入显存的代码是。

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);

其中数据是像素数据,其余部分不言自明。文件以 24 位格式保存,没有压缩,是从 photoshop 保存的。

最佳答案

您的 glTexImage2D 是正确的,所以这不是问题所在。

我确实需要(在加载 TGA 文件时)交换颜色分量。试试这个:

typedef struct
{
unsigned char imageTypeCode;
short int imageWidth;
short int imageHeight;
unsigned char bitCount;
unsigned char *imageData;
} TGAFILE;

bool LoadTGAFile(char *filename, TGAFILE *tgaFile)
{
FILE *filePtr;
unsigned char ucharBad;
short int sintBad;
long imageSize;
int colorMode;
unsigned char colorSwap;

// Open the TGA file.
filePtr = fopen(filename, "rb");
if (filePtr == NULL)
{
return false;
}

// Read the two first bytes we don't need.
fread(&ucharBad, sizeof(unsigned char), 1, filePtr);
fread(&ucharBad, sizeof(unsigned char), 1, filePtr);

// Which type of image gets stored in imageTypeCode.
fread(&tgaFile->imageTypeCode, sizeof(unsigned char), 1, filePtr);

// For our purposes, the type code should be 2 (uncompressed RGB image)
// or 3 (uncompressed black-and-white images).
if (tgaFile->imageTypeCode != 2 && tgaFile->imageTypeCode != 3)
{
fclose(filePtr);
return false;
}

// Read 13 bytes of data we don't need.
fread(&sintBad, sizeof(short int), 1, filePtr);
fread(&sintBad, sizeof(short int), 1, filePtr);
fread(&ucharBad, sizeof(unsigned char), 1, filePtr);
fread(&sintBad, sizeof(short int), 1, filePtr);
fread(&sintBad, sizeof(short int), 1, filePtr);

// Read the image's width and height.
fread(&tgaFile->imageWidth, sizeof(short int), 1, filePtr);
fread(&tgaFile->imageHeight, sizeof(short int), 1, filePtr);

// Read the bit depth.
fread(&tgaFile->bitCount, sizeof(unsigned char), 1, filePtr);

// Read one byte of data we don't need.
fread(&ucharBad, sizeof(unsigned char), 1, filePtr);

// Color mode -> 3 = BGR, 4 = BGRA.
colorMode = tgaFile->bitCount / 8;
imageSize = tgaFile->imageWidth * tgaFile->imageHeight * colorMode;

// Allocate memory for the image data.
tgaFile->imageData = (unsigned char*)malloc(sizeof(unsigned char)*imageSize);

// Read the image data.
fread(tgaFile->imageData, sizeof(unsigned char), imageSize, filePtr);

// Change from BGR to RGB so OpenGL can read the image data.
for (int imageIdx = 0; imageIdx < imageSize; imageIdx += colorMode)
{
colorSwap = tgaFile->imageData[imageIdx];
tgaFile->imageData[imageIdx] = tgaFile->imageData[imageIdx + 2];
tgaFile->imageData[imageIdx + 2] = colorSwap;
}

fclose(filePtr);
return true;
}

关于c++ - 加载 TGA 文件并将其与 OpenGL 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7046270/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com