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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

base is used to hold the font display list.

swidth and sheight are used to grab the current window size. We use these two variable to help us calculate the scissor coordinates later in the code.

int scroll; // Used For Scrolling The Screen

int maxtokens; // Keeps Track Of The Number Of Extensions Supported

int swidth; // Scissor Width

int sheight; // Scissor Height

GLuint base; // Base Display List For The Font

Now we create a structure to hold the TGA information once we load it in. The first variable imageData will hold a pointer to the data that makes up the image. bpp will hold the bits per pixel used in the TGA file (this value should be 24 or 32 bits depending on whether or not there is an alpha channel). The third variable width will hold the width of the TGA image. height will hold the height of the image, and texID will be used to keep track of the textures once they are built. The structure will be called TextureImage.

The line just after the structure (TextureImage textures[1]) sets aside storage for the one texture that we will be using in this program.

typedef struct // Create A Structure

{

GLubyte *imageData; // Image Data (Up To 32 Bits)

GLuint bpp; // Image Color Depth In Bits Per Pixel

GLuint width; // Image Width

GLuint height; // Image Height

GLuint texID; // Texture ID Used To Select A Texture

} TextureImage; // Structure Name

TextureImage textures[1]; // Storage For One Texture

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); // Declaration For WndProc

Now for the fun stuff! This section of code will load in a TGA file and convert it into a texture for use in the program. One thing to note is that this code will only load 24 or 32 bit uncompressed TGA files. I had a hard enough time making the code work with both 24 and 32 bit TGA's :) I never said I was a genious. I'd like to point out that I did not write all of this code on my own. Alot of the really good ideas I got from reading through random sites on the net. I just took all the good ideas and combined them into code that works well with OpenGL. Not easy, not extremely difficult!

We pass two parameters to this section of code. The first parameter points to memory that we can store the texture in (*texture). The second parameter is the name of the file that we want to load (*filename).

The first variable TGAheader[ ] holds 12 bytes. We'll compare these bytes with the first 12 bytes we read from the TGA file to make sure that the file is indeed a Targa file, and not some other type of image.

TGAcompare will be used to hold the first 12 bytes we read in from the TGA file. The bytes in TGAcompare will then be compared with the bytes in TGAheader to make sure everything matches.

header[ ] will hold the first 6 IMPORTANT bytes from the header file (width, height, and bits per pixel).

The variable bytesPerPixel will store the result after we divide bits per pixel by 8, leaving us with the number of bytes used per pixel.

imageSize will store the number of bytes required to make up the image (width * height * bytes per pixel).

temp is a temporary variable that we will use to swap bytes later in the program.

The last variable type is a variable that I use to select the proper texture building params depending on whether or not the TGA is 24 or 32 bit. If the texture is 24 bit we need to use GL_RGB mode when we build the texture. If the TGA is 32 bit we need to add the Alpha component, meaning we have to use GL_RGBA (By default I assume the image is 32 bit by default that is why type is GL_RGBA).

bool LoadTGA(TextureImage *texture, char *filename) // Loads A TGA File Into Memory

{

GLubyte TGAheader[12]={0,0,2,0,0,0,0,0,0,0,0,0}; // Uncompressed TGA Header

GLubyte TGAcompare[12]; // Used To Compare TGA Header

GLubyte header[6]; // First 6 Useful Bytes From The Header

GLuint bytesPerPixel; // Holds Number Of Bytes Per Pixel Used In The TGA File

GLuint imageSize; // Used To Store The Image Size When Setting Aside Ram

GLuint temp; // Temporary Variable

GLuint type=GL_RGBA; // Set The Default GL Mode To RBGA (32 BPP)

The first line below opens the TGA file for reading. file is the handle we will use to point to the data within the file. the command fopen(filename, "rb") will open the file filename, and "rb" tells our program to open it for [r]eading in [b]inary mode!

The if statement has a few jobs. First off it checks to see if the file contains any data. If there is no data, NULL will be returned, the file will be closed with fclose(file), and we return false.

If the file contains information, we attempt to read the first 12 bytes of the file into TGAcompare. We break the line down like this: fread will read sizeof(TGAcompare) (12 bytes) from file into TGAcompare. Then we check to see if the number of bytes read is equal to sizeof(TGAcompare) which should be 12 bytes. If we were unable to read the 12 bytes into TGAcompare the file will close and false will be returned.

If everything has gone good so far, we then compare the 12 bytes we read into TGAcompare with the 12 bytes we have stored in TGAheader. If the bytes do not match, the file will close, and false will be returned.

Lastly, if everything has gone great, we attempt to read 6 more bytes into header (the important bytes). If 6 bytes are not available, again, the file will close and the program will return false.

FILE *file = fopen(filename, "rb"); // Open The TGA File

if (file==NULL || // Does File Even Exist?

fread(TGAcompare, 1, sizeof(TGAcompare), file) != sizeof(TGAcompare) || // Are There 12 Bytes To Read?

memcmp(TGAheader, TGAcompare, sizeof(TGAheader)) != 0 || // Does The Header Match What We Want?

fread(header, 1, sizeof(header), file) != sizeof(header)) // If So Read Next 6 Header Bytes

{

if (file == NULL) // Did The File Even Exist? *Added Jim Strong*

return false; // Return False

else {

fclose(file); // If Anything Failed, Close The File

return false; // Return False

}

}

If everything went ok, we now have enough information to define some important variables. The first variable we want to define is width. We want width to equal the width of the TGA file. We can find out the TGA width by multiplying the value stored in header[1] by 256. We then add the lowbyte which is stored in header[0].

The height is calculated the same way but instead of using the values stored in header[0] and header[1] we use the values stored in header[2] and header[3].

After we have calculated the width and height we check to see if either the width or height is less than or equal to 0. If either of the two variables is less than or equal to zero, the file will be closed, and false will be returned.

We also check to see if the TGA is a 24 or 32 bit image. We do this by checking the value stored at header[4]. If the value is not 24 or 32 (bit), the file will be closed, and false will be returned.

In case you have not realized. A return of false will cause the program to fail with the message "Initialization Failed". Make sure your TGA is an uncompressed 24 or 32 bit image!

texture->width = header[1] * 256 + header[0]; // Determine The TGA Width (highbyte*256+lowbyte)

texture->height = header[3] * 256 + header[2]; // Determine The TGA Height (highbyte*256+lowbyte)

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

Интервал:

Закладка:

Сделать

Похожие книги на «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