PDA

View Full Version : Loading images for textures under Linux



08-03-2001, 06:43 AM
Does somebody knows the name of a function (and the library in which this is) to load an image to use as texture? I haven't found such a function in GL, GLU, GLX, GLUT and other libraries I search for. Thanks for the help.

rts
08-03-2001, 09:07 AM
That's because it isn't the job of GL, GLU, GLUT, etc to do that.

Here is the absolute simplest function that can load a texture from an uncompressed PPM file (note: I wrote the following code, and it is GPL'ed, so if you use it, please respect the terms of license under which I am making it available):




#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <GL/gl.h>
#include <GL/glu.h>

/*
* Loads and binds a texture from a raw PPM file given by filename
*
* Returns the GL name in texName
*
* Return value: negative for failure, 0 for success
*
*/
int LoadTextureFromPPM(const char *filename, GLuint *texName)
{
/* Load the image */
FILE* fp;
int i, w, h, d;
unsigned char* image;
char head[70]; /* max line <= 70 in PPM (per spec). */

fp = fopen(filename, "rb");
if (!fp) {
perror(filename);
return -1;
}

/* grab first two chars of the file and make sure that it has the
correct magic cookie for a raw PPM file. */
fgets(head, 70, fp);

if (strncmp(head, "P6", 2)) {
fprintf(stderr, "%s is not a raw PPM file\n", filename);
return -1;
}

/* grab the three elements in the header (width, height, maxval). */
i = 0;
while (i < 3) {
fgets(head, 70, fp);
if (head[0] == '#') {
/* skip comments. */
continue;
}
switch (i) {
case 0:
i += sscanf(head, "%d %d %d", &amp;w, &amp;h, &amp;d);
break;
case 1:
i += sscanf(head, "%d %d", &amp;h, &amp;d);
break;
case 2:
i += sscanf(head, "%d", &amp;d);
break;
}
}

/* grab all the image data in one fell swoop. */
image = (unsigned char*)malloc(sizeof(unsigned char)*w*h*3);
fread(image, sizeof(unsigned char), w*h*3, fp);
fclose(fp);

/* Bind */
glGenTextures(1, texName);
glBindTexture(GL_TEXTURE_2D, *texName);

/* Set parameters */
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

/* Build mipmaps */
gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB,
w, h,
GL_RGB, GL_UNSIGNED_BYTE,
image);

free(image);
return 0;
}


I'm sure if you look hard enough, maybe at http://www.libsdl.org/ and http://plib.sourceforge.net/, you'll find lots of stuff to help you load textures of all kinds of various formats.

08-03-2001, 11:01 PM
Thank you very much.