00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023 #include "texture.h"
00024 #include "common/math/real.h"
00025
00026 #include <cassert>
00027 #include <GL/glut.h>
00028 #include <IL/il.h>
00029
00030 using namespace sheep;
00031 using namespace std;
00032
00033 Texture::Texture(int width, int height, const unsigned char *texels) {
00034 assert(texels);
00035 set_texture(width, height, texels);
00036 }
00037
00038 Texture::Texture(const string &filename) {
00039 ILuint image_id;
00040
00041 ilGenImages(1, &image_id);
00042 ilBindImage(image_id);
00043
00044 const ILboolean success = ilLoadImage(( ILstring)filename.c_str());
00045 assert(success);
00046
00047 const int width = ilGetInteger(IL_IMAGE_WIDTH);
00048 const int height = ilGetInteger(IL_IMAGE_HEIGHT);
00049
00050 GLubyte *texels = new GLubyte[width * height * 3];
00051
00052 ilCopyPixels(0, 0, 0, width, height, 1, IL_RGB, IL_UNSIGNED_BYTE, texels);
00053 ilDeleteImages(1, &image_id);
00054
00055 set_texture(width, height, texels);
00056
00057 delete [] texels;
00058 }
00059
00060 Texture::~Texture() {
00061 glDeleteTextures(1, &m_name);
00062 }
00063
00064 void Texture::set_texture(int img_width, int img_height, const unsigned char *img_bits) {
00065 glGenTextures(1, &m_name);
00066 glBindTexture(GL_TEXTURE_2D, m_name);
00067
00068 GLint max_tex_size;
00069 glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_tex_size);
00070
00071 int tex_width = min(max_tex_size, NextPowerOfTwo(img_width));
00072 int tex_height = min(max_tex_size, NextPowerOfTwo(img_height));
00073
00074 while(true) {
00075 GLint format = 0;
00076
00077 glTexImage2D(GL_PROXY_TEXTURE_2D, 0, GL_RGB, tex_width, tex_height, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
00078 glGetTexLevelParameteriv(GL_PROXY_TEXTURE_2D, 0, GL_TEXTURE_INTERNAL_FORMAT, &format);
00079
00080 if(format == GL_RGB)
00081 break;
00082
00083
00084
00085 if(tex_width > tex_height) {
00086 assert(tex_width > 1);
00087 tex_width /= 2;
00088 } else {
00089 assert(tex_height > 1);
00090 tex_height /= 2;
00091 }
00092 }
00093
00094 unsigned char *tex_bits = new unsigned char[tex_width * tex_height * 3];
00095
00096
00097 gluScaleImage(
00098 GL_RGB,
00099 img_width, img_height, GL_UNSIGNED_BYTE, img_bits,
00100 tex_width, tex_height, GL_UNSIGNED_BYTE, tex_bits);
00101
00102 glTexImage2D(GL_TEXTURE_2D, 0, 3, tex_width, tex_height, 0, GL_RGB, GL_UNSIGNED_BYTE, tex_bits);
00103
00104
00105 delete [] tex_bits;
00106
00107 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
00108
00109 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
00110 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
00111
00112 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
00113 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
00114
00115
00116 }