fixed incorrect checking of the existence of GLX_EXT_swap_control and friends
[demo_prior] / src / texture.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include "opengl.h"
4 #include "texture.h"
5 #include "imago2.h"
6 #include "opt.h"
7
8 static unsigned int gl_ifmt[2][NUM_IMG_FMT] = {
9         /* opt.srgb == 0 */
10         {GL_LUMINANCE, GL_RGB, GL_RGBA, GL_LUMINANCE16F_ARB, GL_RGB16F, GL_RGBA16F, GL_RGBA, GL_RGB},
11         /* opt.srgb == 1 */
12         {GL_SLUMINANCE, GL_SRGB, GL_SRGB_ALPHA, GL_LUMINANCE16F_ARB, GL_RGB16F, GL_RGBA16F, GL_SRGB_ALPHA, GL_SRGB}
13 };
14 static unsigned int gl_fmt[] = {
15         GL_LUMINANCE, GL_RGB, GL_RGBA, GL_LUMINANCE, GL_RGB, GL_RGBA, GL_BGRA, GL_RGB
16 };
17 static unsigned int gl_type[] = {
18         GL_UNSIGNED_BYTE, GL_UNSIGNED_BYTE, GL_UNSIGNED_BYTE, GL_FLOAT, GL_FLOAT, GL_FLOAT, GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT_5_6_5
19 };
20
21
22 struct texture *load_texture(const char *fname)
23 {
24         struct img_pixmap img;
25         struct texture *tex;
26         int ifmt;
27
28         img_init(&img);
29         if(img_load(&img, fname) == -1) {
30                 fprintf(stderr, "failed to load texture: %s\n", fname);
31                 return 0;
32         }
33         ifmt = gl_ifmt[opt.srgb][img.fmt];
34
35         if(!(tex = malloc(sizeof *tex))) {
36                 img_destroy(&img);
37                 fprintf(stderr, "failed to allocate texture\n");
38                 return 0;
39         }
40
41         glGenTextures(1, &tex->id);
42         glBindTexture(GL_TEXTURE_2D, tex->id);
43         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
44         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
45         glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS, 1);
46         glTexImage2D(GL_TEXTURE_2D, 0, ifmt, img.width, img.height, 0, gl_fmt[img.fmt],
47                         gl_type[img.fmt], img.pixels);
48
49         tex->width = img.width;
50         tex->height = img.height;
51         tex->pixels = img.pixels;
52         return tex;
53 }
54
55 void free_texture(struct texture *tex)
56 {
57         if(!tex) return;
58
59         if(tex->id) {
60                 glDeleteTextures(1, &tex->id);
61         }
62
63         free(tex->pixels);
64         free(tex);
65 }