Jeff Molofee - NeHe's OpenGL Tutorials

Здесь есть возможность читать онлайн «Jeff Molofee - NeHe's OpenGL Tutorials» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

NeHe's OpenGL Tutorials: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «NeHe's OpenGL Tutorials»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

NeHe's OpenGL Tutorials — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «NeHe's OpenGL Tutorials», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

}

Thats all there is to loading an uncompressed TGA file. Loading a RLE compressed one is only slightly harder. We read the header and collect height/width/bpp as usual, sme as the uncompressed version, so i will just post the code, you can look in the previous pages for a complete explanation.

bool LoadCompressedTGA(Texture * texture, char * filename, FILE * fTGA) {

if (fread(tga.header, sizeof(tga.header), 1, fTGA) == 0) {

…Error code here…

}

texture->width = tga.header[1] * 256 + tga.header[0];

texture->height = tga.header[3] * 256 + tga.header[2];

texture->bpp = tga.header[4];

tga.Width = texture->width;

tga.Height = texture->height;

tga.Bpp = texture->bpp;

if ((texture->width <= 0) || (texture->height <= 0) || ((texture->bpp != 24) && (texture->bpp !=32))) {

…Error code here…

}

tga.bytesPerPixel = (tga.Bpp / 8);

tga.imageSize = (tga.bytesPerPixel * tga.Width * tga.Height);

Now we need to allocate the amount of storage for the image to use AFTER we uncompress it, we will use malloc. If memory fails to be allocated, run error code, and return false.

// Allocate Memory To Store Image Data

texture->imageData = (GLubyte *)malloc(tga.imageSize);

if (texture->imageData == NULL) // If Memory Can Not Be Allocated…

{

…Error code here…

return false; // Return False

}

Next we need to determine how many pixels make up the image. We will store it in the variable "pixelcount"

We also need to store which pixel we are currently on, and what byte of the imageData we are writing to, to avoid overflows and overwriting old data.

We will allocate enough memory to store one pixel.

GLuint pixelcount = tga.Height * tga.Width; // Number Of Pixels In The Image

GLuint currentpixel = 0; // Current Pixel We Are Reading From Data

GLuint currentbyte = 0; // Current Byte We Are Writing Into Imagedata

// Storage For 1 Pixel

GLubyte * colorbuffer = (GLubyte *)malloc(tga.bytesPerPixel);

Next we have a big loop.

Lets break it down into more manageable chunks.

First we declare a variable in order to store the chunk header. A chunk header dictates wheather the following section is RLE, or RAW, and how long it is. If the one byte header is less than or equal to 127, then it is a RAW header. The value of the header is the number of colors, minus one, that we read ahead and copy into memory, before we hit another header byte. So we add one to the value we get, and then read that many pixels and copy them into the ImageData, just like we did with the uncompressed ones. If the header is ABOVE 127, then it is the number of times that the next pixel value is repeated consequtively. To get the actual number of repetitions we take the value returned and subtract 127 to get rid of the one bit header identifier. Then we read the next one pixel and copy it the said number of times consecutively into the memory.

On to the code. First we read the one byte header.

do // Start Loop

{

GLubyte chunkheader = 0; // Variable To Store The Value Of The Id Chunk

if (fread(&chunkheader, sizeof(GLubyte), 1, fTGA) == 0) // Attempt To Read The Chunk's Header

{

…Error code…

return false; // If It Fails, Return False

}

Next we will check to see if it a RAW header. If it is, we need to add one to the value to get the total number of pixels following the header.

if (chunkheader < 128) // If The Chunk Is A 'RAW' Chunk

{

chunkheader++; // Add 1 To The Value To Get Total Number Of Raw Pixels

We then start another loop to read all the color information. It will loop the amout of times specified in the chunk header, and will read and store one pixel each loop.

First we read and verify the pixel data. The data for one pixel will be stored in the colorbuffer variable. Next we will check to see if it a RAW header. If it is, we need to add one to the value to get the total number of pixels following the header.

// Start Pixel Reading Loop

for (short counter = 0; counter < chunkheader; counter++) {

// Try To Read 1 Pixel

if (fread(colorbuffer, 1, tga.bytesPerPixel, fTGA) != tga.bytesPerPixel) {

…Error code…

return false; // If It Fails, Return False

}

The next part in our loop will take the color values stored in colorbuffer and writing them to the imageData varable to be used later. In the process it will flip the data from BGR format to RGB or from BGRA to RGBA depending on the number of bits per pixel. When we are done we increment the current byte, and current pixel counters.

texture->imageData[currentbyte] = colorbuffer[2]; // Write The 'R' Byte

texture->imageData[currentbyte + 1 ] = colorbuffer[1]; // Write The 'G' Byte

texture->imageData[currentbyte + 2 ] = colorbuffer[0]; // Write The 'B' Byte

if (tga.bytesPerPixel == 4) // If It's A 32bpp Image…

{

texture->imageData[currentbyte + 3] = colorbuffer[3]; // Write The 'A' Byte

}

// Increment The Byte Counter By The Number Of Bytes In A Pixel

currentbyte += tga.bytesPerPixel;

currentpixel++; // Increment The Number Of Pixels By 1

The next section deals with the chunk headers that represent the RLE sections. First thing we do is subtract 127 from the chunkheader to get the amount of times the next color is repeated.

else // If It's An RLE Header

{

chunkheader –= 127; // Subtract 127 To Get Rid Of The ID Bit

The we attempt to read the next color value.

// Read The Next Pixel

if (fread(colorbuffer, 1, tga.bytesPerPixel, fTGA) != tga.bytesPerPixel) {

…Error code…

return false; // If It Fails, Return False

}

Next we begin a loop to copy the pixel we just read into memory multiple times, as dictated by the value from the RLE header.

Then we copy the the color values into the image data, preforming the R and B value switch.

Then we increment the current bytes, and current pixel, so we are in the right spot when we write the values again.

// Start The Loop

for (short counter = 0; counter < chunkheader; counter++) {

// Copy The 'R' Byte

texture->imageData[currentbyte] = colorbuffer[2];

// Copy The 'G' Byte

texture->imageData[currentbyte + 1 ] = colorbuffer[1];

// Copy The 'B' Byte

texture->imageData[currentbyte + 2 ] = colorbuffer[0];

if (tga.bytesPerPixel == 4) // If It's A 32bpp Image

{

// Copy The 'A' Byte

texture->imageData[currentbyte + 3] = colorbuffer[3];

}

currentbyte += tga.bytesPerPixel; // Increment The Byte Counter

currentpixel++; // Increment The Pixel Counter

Then we contiune the main loop, as long as we still have pixels left to read.

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «NeHe's OpenGL Tutorials»

Представляем Вашему вниманию похожие книги на «NeHe's OpenGL Tutorials» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Jeff Jacobson - Sleep Tight
Jeff Jacobson
Jeff Salyards - Veil of the Deserters
Jeff Salyards
Jeff LaSala - The Darkwood Mask
Jeff LaSala
Jeff Lindsay - Dexter's Final Cut
Jeff Lindsay
libcat.ru: книга без обложки
Неизвестный Автор
libcat.ru: книга без обложки
Неизвестный Автор
libcat.ru: книга без обложки
Неизвестный Автор
libcat.ru: книга без обложки
Неизвестный Автор
Отзывы о книге «NeHe's OpenGL Tutorials»

Обсуждение, отзывы о книге «NeHe's OpenGL Tutorials» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x