summaryrefslogtreecommitdiffstats
path: root/texture.c
blob: 276fc94f7c0e0bd80839e282edec285854bb57ea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <GL/gl.h>
#include <zoom/texture.h>


#pragma pack(push,2)
typedef struct _TEXHEADER {
	unsigned char t;
	unsigned char x;
	unsigned long w;
	unsigned long h;
} TEXHEADER;
#pragma pack(pop)


int nTex;
TEXLIST *texlist;

GLuint LoadTexture(char *filename) {
	GLuint tex;
	FILE *file;
	TEXHEADER txh;
	unsigned char *data;
	int i;
	char name[100];
	
	for(i = 0; i < nTex; i++) {
		if(strcasecmp(filename, texlist[i].name) == 0) return texlist[i].id;
	}
	
	strcpy(name, "tex/");
	strcat(name, filename);
	file = fopen(name, "rb");
	if(!file) return 0;
	
	fread(&txh, sizeof(txh), 1, file);
	if(txh.t != 'T' || txh.x != 'X') {
		fclose(file);
		return 0;
	}
	
	data = malloc(txh.w*txh.h*4);
	if(!data) {
		fclose(file);
		return 0;
	}
	fread(data, txh.w*txh.h*4, 1, file);
	
	glGenTextures(1, &tex);
	glBindTexture(GL_TEXTURE_2D, tex);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexImage2D(GL_TEXTURE_2D, 0, 4, txh.w, txh.h, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
	
	free(data);
	fclose(file);
	
	nTex++;
	
	if(nTex == 1) texlist = malloc(sizeof(TEXLIST));
	else texlist = realloc(texlist, sizeof(TEXLIST)*nTex);
	
	strcpy(texlist[nTex-1].name, filename);
	texlist[nTex-1].id = tex;
	
	return tex;
}