istereo

annotate src/tex.c @ 17:4c20f10a7183

fixed the texture bug
author John Tsiombikas <nuclear@member.fsf.org>
date Wed, 07 Sep 2011 09:35:20 +0300
parents 32503603eb7d
children 206348366635
rev   line source
nuclear@14 1 #include <stdio.h>
nuclear@14 2 #include <stdlib.h>
nuclear@14 3 #include <string.h>
nuclear@14 4 #include <errno.h>
nuclear@14 5 #include "opengl.h"
nuclear@14 6 #include "tex.h"
nuclear@15 7 #include "config.h"
nuclear@14 8
nuclear@14 9 unsigned int load_texture(const char *fname)
nuclear@14 10 {
nuclear@14 11 unsigned int tex;
nuclear@14 12 FILE *fp;
nuclear@14 13 void *pixels;
nuclear@14 14 int xsz, ysz, sz;
nuclear@14 15 char buf[512];
nuclear@14 16
nuclear@14 17 if(!(fp = fopen(fname, "r"))) {
nuclear@14 18 fprintf(stderr, "failed to open texture: %s: %s\n", fname, strerror(errno));
nuclear@14 19 return 0;
nuclear@14 20 }
nuclear@14 21
nuclear@14 22 if(!fgets(buf, sizeof buf, fp) || buf[0] != 'P' || buf[1] != '6') {
nuclear@14 23 fprintf(stderr, "invalid format (1): %s\n", fname);
nuclear@14 24 fclose(fp);
nuclear@14 25 return 0;
nuclear@14 26 }
nuclear@14 27 if(!fgets(buf, sizeof buf, fp) || sscanf(buf, "%d %d", &xsz, &ysz) != 2) {
nuclear@14 28 fprintf(stderr, "invalid format (2): %s\n", fname);
nuclear@14 29 fclose(fp);
nuclear@14 30 return 0;
nuclear@14 31 }
nuclear@14 32 fgets(buf, sizeof buf, fp);
nuclear@14 33
nuclear@14 34 sz = xsz * ysz * 3;
nuclear@14 35 if(!(pixels = malloc(sz))) {
nuclear@14 36 fprintf(stderr, "failed to allocate %d bytes\n", sz);
nuclear@14 37 fclose(fp);
nuclear@14 38 return 0;
nuclear@14 39 }
nuclear@14 40 if(fread(pixels, 1, xsz * ysz * 3, fp) < sz) {
nuclear@14 41 fprintf(stderr, "partial read: %s\n", fname);
nuclear@14 42 free(pixels);
nuclear@14 43 fclose(fp);
nuclear@14 44 return 0;
nuclear@14 45 }
nuclear@14 46 fclose(fp);
nuclear@14 47
nuclear@14 48 glGenTextures(1, &tex);
nuclear@14 49 glBindTexture(GL_TEXTURE_2D, tex);
nuclear@14 50 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
nuclear@14 51 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
nuclear@14 52 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
nuclear@14 53 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
nuclear@17 54 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, xsz, ysz, 0, GL_RGB, GL_UNSIGNED_BYTE, pixels);
nuclear@14 55 free(pixels);
nuclear@14 56
nuclear@14 57 return tex;
nuclear@14 58 }
nuclear@15 59
nuclear@15 60 void bind_texture(unsigned int tex, int unit)
nuclear@15 61 {
nuclear@15 62 glActiveTexture(GL_TEXTURE0 + unit);
nuclear@15 63
nuclear@15 64 #ifndef IPHONE
nuclear@15 65 if(tex) {
nuclear@15 66 glEnable(GL_TEXTURE_2D);
nuclear@15 67 } else {
nuclear@15 68 glDisable(GL_TEXTURE_2D);
nuclear@15 69 }
nuclear@15 70 #endif
nuclear@15 71
nuclear@15 72 glBindTexture(GL_TEXTURE_2D, tex);
nuclear@15 73 }