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