]> git.lizzy.rs Git - shadowclad.git/blob - tga.c
Add and fix header guards
[shadowclad.git] / tga.c
1 #include <GL/gl.h>
2 #include <stdlib.h>
3 #include <stdio.h>
4
5 #include "tga.h"
6
7 TGAimage* read_tga(const char* path) {
8         FILE* tga_file = fopen(path, "rb");
9         if (tga_file == NULL) {
10                 return NULL;
11         }
12         
13         TGAheader header;
14         
15         if (fread(&header, sizeof(TGAheader), 1, tga_file) != 1) {
16                 fclose(tga_file);
17                 return NULL;
18         }
19         
20         GLenum image_format;
21         GLint image_components;
22         
23         if (header.image_bpp == 32) {
24                 image_format = GL_BGRA_EXT;
25                 image_components = GL_RGBA8;
26         }
27         else if (header.image_bpp == 24) {
28                 image_format = GL_BGR_EXT;
29                 image_components = GL_RGB8;
30         }
31         else if (header.image_bpp == 8) {
32                 image_format = GL_LUMINANCE;
33                 image_components = GL_LUMINANCE8;
34         }
35         else {
36                 fclose(tga_file);
37                 return NULL;
38         }
39         
40         unsigned long image_size = header.image_width * header.image_height * (header.image_bpp >> 3);
41         
42         GLbyte* bytes = malloc(image_size * sizeof(GLbyte));
43         if (bytes == NULL) {
44                 fclose(tga_file);
45                 return NULL;
46         }
47         
48         if (fread(bytes, image_size, 1, tga_file) != 1) {
49                 free(bytes);
50                 fclose(tga_file);
51                 return NULL;
52         }
53         
54         fclose(tga_file);
55         
56         TGAimage* image = malloc(sizeof(TGAimage));
57         if (image == NULL) {
58                 return NULL;
59         }
60         
61         (*image).header = header;
62         (*image).image_format = image_format;
63         (*image).image_components = image_components;
64         (*image).bytes = bytes;
65         
66         return image;
67 }