]> git.lizzy.rs Git - shadowclad.git/blob - tga.c
11c8b5e8ef1518c1c0d9d740aab62ae7801a889e
[shadowclad.git] / tga.c
1 #include <GL/gl.h>
2
3 #include <stdlib.h>
4 #include <stdio.h>
5
6 #include "tga.h"
7
8 TgaImage* readTga(const char* path) {
9         FILE* tgaFile = fopen(path, "rb");
10         if (tgaFile == NULL) {
11                 return NULL;
12         }
13         
14         TgaHeader header;
15         
16         if (fread(&header, sizeof(TgaHeader), 1, tgaFile) != 1) {
17                 fclose(tgaFile);
18                 return NULL;
19         }
20         
21         GLenum imageFormat;
22         GLint imageComponents;
23         
24         switch (header.imageBpp) {
25                 case 32:
26                         imageFormat = GL_BGRA_EXT;
27                         imageComponents = GL_RGBA8;
28                         break;
29                 case 24:
30                         imageFormat = GL_BGR_EXT;
31                         imageComponents = GL_RGB8;
32                         break;
33                 case 8:
34                         imageFormat = GL_LUMINANCE;
35                         imageComponents = GL_LUMINANCE8;
36                         break;
37                 default:
38                         fclose(tgaFile);
39                         return NULL;
40         }
41         
42         unsigned long imageSize = header.imageWidth * header.imageHeight * (header.imageBpp >> 3);
43         
44         GLbyte* bytes = malloc(imageSize * sizeof(GLbyte));
45         if (bytes == NULL) {
46                 fclose(tgaFile);
47                 return NULL;
48         }
49         
50         if (fread(bytes, imageSize, 1, tgaFile) != 1) {
51                 free(bytes);
52                 fclose(tgaFile);
53                 return NULL;
54         }
55         
56         fclose(tgaFile);
57         
58         TgaImage* image = malloc(sizeof(TgaImage));
59         if (image == NULL) {
60                 return NULL;
61         }
62         
63         (*image).header = header;
64         (*image).imageFormat = imageFormat;
65         (*image).imageComponents = imageComponents;
66         (*image).bytes = bytes;
67         
68         return image;
69 }