istereo
diff 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 diff
1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/src/tex.c Wed Sep 07 09:03:51 2011 +0300 1.3 @@ -0,0 +1,57 @@ 1.4 +#include <stdio.h> 1.5 +#include <stdlib.h> 1.6 +#include <string.h> 1.7 +#include <errno.h> 1.8 +#include "opengl.h" 1.9 +#include "tex.h" 1.10 + 1.11 +unsigned int load_texture(const char *fname) 1.12 +{ 1.13 + unsigned int tex; 1.14 + FILE *fp; 1.15 + void *pixels; 1.16 + int xsz, ysz, sz; 1.17 + char buf[512]; 1.18 + 1.19 + if(!(fp = fopen(fname, "r"))) { 1.20 + fprintf(stderr, "failed to open texture: %s: %s\n", fname, strerror(errno)); 1.21 + return 0; 1.22 + } 1.23 + 1.24 + if(!fgets(buf, sizeof buf, fp) || buf[0] != 'P' || buf[1] != '6') { 1.25 + fprintf(stderr, "invalid format (1): %s\n", fname); 1.26 + fclose(fp); 1.27 + return 0; 1.28 + } 1.29 + if(!fgets(buf, sizeof buf, fp) || sscanf(buf, "%d %d", &xsz, &ysz) != 2) { 1.30 + fprintf(stderr, "invalid format (2): %s\n", fname); 1.31 + fclose(fp); 1.32 + return 0; 1.33 + } 1.34 + fgets(buf, sizeof buf, fp); 1.35 + 1.36 + sz = xsz * ysz * 3; 1.37 + if(!(pixels = malloc(sz))) { 1.38 + fprintf(stderr, "failed to allocate %d bytes\n", sz); 1.39 + fclose(fp); 1.40 + return 0; 1.41 + } 1.42 + if(fread(pixels, 1, xsz * ysz * 3, fp) < sz) { 1.43 + fprintf(stderr, "partial read: %s\n", fname); 1.44 + free(pixels); 1.45 + fclose(fp); 1.46 + return 0; 1.47 + } 1.48 + fclose(fp); 1.49 + 1.50 + glGenTextures(1, &tex); 1.51 + glBindTexture(GL_TEXTURE_2D, tex); 1.52 + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); 1.53 + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); 1.54 + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 1.55 + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 1.56 + glTexImage2D(GL_TEXTURE_2D, 0, 4, xsz, ysz, 0, GL_RGB, GL_UNSIGNED_BYTE, pixels); 1.57 + free(pixels); 1.58 + 1.59 + return tex; 1.60 +}