istereo

view src/tex.c @ 14:b39d8607f4bb

added textures
author John Tsiombikas <nuclear@mutantstargoat.com>
date Wed, 07 Sep 2011 09:03:51 +0300
parents
children 32503603eb7d
line source
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <errno.h>
5 #include "opengl.h"
6 #include "tex.h"
8 unsigned int load_texture(const char *fname)
9 {
10 unsigned int tex;
11 FILE *fp;
12 void *pixels;
13 int xsz, ysz, sz;
14 char buf[512];
16 if(!(fp = fopen(fname, "r"))) {
17 fprintf(stderr, "failed to open texture: %s: %s\n", fname, strerror(errno));
18 return 0;
19 }
21 if(!fgets(buf, sizeof buf, fp) || buf[0] != 'P' || buf[1] != '6') {
22 fprintf(stderr, "invalid format (1): %s\n", fname);
23 fclose(fp);
24 return 0;
25 }
26 if(!fgets(buf, sizeof buf, fp) || sscanf(buf, "%d %d", &xsz, &ysz) != 2) {
27 fprintf(stderr, "invalid format (2): %s\n", fname);
28 fclose(fp);
29 return 0;
30 }
31 fgets(buf, sizeof buf, fp);
33 sz = xsz * ysz * 3;
34 if(!(pixels = malloc(sz))) {
35 fprintf(stderr, "failed to allocate %d bytes\n", sz);
36 fclose(fp);
37 return 0;
38 }
39 if(fread(pixels, 1, xsz * ysz * 3, fp) < sz) {
40 fprintf(stderr, "partial read: %s\n", fname);
41 free(pixels);
42 fclose(fp);
43 return 0;
44 }
45 fclose(fp);
47 glGenTextures(1, &tex);
48 glBindTexture(GL_TEXTURE_2D, tex);
49 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
50 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
51 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
52 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
53 glTexImage2D(GL_TEXTURE_2D, 0, 4, xsz, ysz, 0, GL_RGB, GL_UNSIGNED_BYTE, pixels);
54 free(pixels);
56 return tex;
57 }