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