rendered paste bodytextures.h:
typedef struct {
unsigned int id;
int num;
char **data;
} mipmap;
extern int load_texture(char *data, int level, char *file);
extern int load_mipmap(mipmap *mip, char *basename, int size);
extern void free_mipmap(mipmap *mip);
----------------------------------------------------------------------
textures.c:
#include "main.h"
int load_texture(char *data, int level, char *file) {
FILE *src=fopen(file,"rb");
int temp;
char ctemp;
int size;
int bytespp;
int height;
int width;
int bpp;
if(!src) {
fprintf(stderr,"load_texture: Unable to open texture file \"%s\"\n",file);
return -1;
}
fseek(src,12,SEEK_SET);
//get texture width
temp=fgetc(src);
width=(fgetc(src)<<8)+temp;
//get texture height
temp=fgetc(src);
height=(fgetc(src)<<8)+temp;
bpp=fgetc(src);
if(bpp!=24 && bpp!=32) {
fprintf(stderr,"load_texture Texture file must be 24 or 32 bits per pixel\n");
fclose(src);
return -1;
}
fseek(src,1,SEEK_CUR);
bytespp=bpp/8;
size=width*height*bytespp;
data=malloc(size);
if(!data) {
fprintf(stderr,"load_texture: memory\n");
fclose(src);
return -1;
}
if(fread(data,1,size,src)!=size) {
fprintf(stderr,"load_texture: Error reading texture file\n");
free(data);
fclose(src);
return -1;
}
fclose(src);
//convert image data from BGR to RGB
for(temp=0;temp<size;temp+=bytespp) {
ctemp=data[temp];
data[temp]=data[temp+2];
data[temp+2]=ctemp;
}
temp=(bpp==24?GL_RGB:GL_RGBA);
//build the texture
glTexImage2D(GL_TEXTURE_2D,level,temp,width,height,0,temp,GL_UNSIGNED_BYTE,data);
return 0;
}
int load_mipmap(mipmap *mip, char *basename, int size) {
char *buffer=malloc(strlen(basename)+3);
int i;
int num=0;
for(i=size;i;i/=2)
num++;
mip->data=malloc(num*sizeof(char *));
if(!buffer) {
fprintf(stderr,"load_mipmap: memory\n");
return -1;
}
if(!mip->data) {
fprintf(stderr,"load_mipmap: memory\n");
free(buffer);
return -1;
}
mip->num=num;
glGenTextures(1,&mip->id);
glBindTexture(GL_TEXTURE_2D,mip->id);
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_NEAREST_MIPMAP_LINEAR);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
num=0;
for(i=size;i;i/=2,num++) {
sprintf(buffer,basename,i);
if(load_texture(mip->data[num],num,buffer)) {
fprintf(stderr,"load_mipmap: Unable to load mipmap\n",buffer);
free(buffer);
free(mip->data);
return -1;
}
free(mip->data[0]);
return 0;
}
free(buffer);
return 0;
}
void free_mipmap(mipmap *mip) {
int i=0;
for(;i<mip->num;i++) {
free(mip->data[i]);
}
free(mip->data);
}