#include "Texture.h" #include "glInterface.h" #include "common.h" #include #include #include namespace CHCDemoEngine { using namespace std; void startil() { ilInit(); assert(ilGetError() == IL_NO_ERROR); } void stopil() { ilShutDown(); assert(ilGetError() == IL_NO_ERROR); } Texture::Texture(const std::string &filename): mWidth(0), mHeight(0), mFormat(0), mImage(NULL), mTexId(-1), mName(filename), mBoundaryModeS(REPEAT), mBoundaryModeT(REPEAT), mUseMipMap(true) { startil(); if (!ilLoadImage(ILstring(filename.c_str()))) { cerr << "Image load error " << ilGetError() << ": " << filename << endl; } else { mWidth = ilGetInteger(IL_IMAGE_WIDTH); mHeight = ilGetInteger(IL_IMAGE_HEIGHT); mFormat = FORMAT_RGBA; mByteSize = mHeight * GetRowLength(); mImage = malloc(GetByteSize()); Debug << "loaded texture " << filename << " w " << mWidth << " h " << mHeight << endl; //cout << "loaded texture " << filename << " w " << mWidth << " h " << mHeight << endl; ilCopyPixels(0, 0, 0, mWidth, mHeight, 1, IL_RGBA, IL_UNSIGNED_BYTE, mImage); assert(ilGetError() == IL_NO_ERROR); } stopil(); } static int GetGlWrapMode(int mode) { switch (mode) { case Texture::REPEAT: return GL_REPEAT; case Texture::CLAMP: return GL_CLAMP_TO_EDGE; case Texture::BORDER: return GL_CLAMP_TO_BORDER; default: return GL_CLAMP_TO_EDGE; } return GL_CLAMP_TO_EDGE; } void Texture::Create() { glEnable(GL_TEXTURE_2D); glGenTextures(1, &mTexId); glBindTexture(GL_TEXTURE_2D, mTexId); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 4); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GetGlWrapMode(mBoundaryModeS)); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GetGlWrapMode(mBoundaryModeT)); if (mUseMipMap) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } if (!mUseMipMap) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, mWidth, mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, mImage); else gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, mWidth, mHeight, GL_RGBA, GL_UNSIGNED_BYTE, mImage); glBindTexture(GL_TEXTURE_2D, 0); } int Texture::GetFormat() const { return mFormat; } int Texture::GetWidth() const { return mWidth; } int Texture::GetHeight() const { return mHeight; } void *Texture::GetImage() const { return mImage; } Texture::~Texture() { glDeleteTextures(1, &mTexId); free(mImage); } std::string Texture::GetName() const { return mName; } int Texture::GetRowLength() const { if (mFormat == FORMAT_RGBA) return mWidth * 4 * sizeof (unsigned char); else return mWidth * 3 * sizeof (unsigned char); } int Texture::GetPixelSize() const { if (mFormat == FORMAT_RGBA) return 4 * sizeof(unsigned char); else return 3 * sizeof(unsigned char); } void Texture::Bind() const { glBindTexture(GL_TEXTURE_2D, mTexId); } }