Exemple #1
0
	virtual bool Load(const char* pathV){
		static bool hasInitIL = false;
		if(!hasInitIL){
			ilInit();
			ilutRenderer(ILUT_OPENGL);
			hasInitIL = true;
		}

		String path = pathV;
		FILE_SYS()->GetFullPath(path);
		ILuint ilTex;
		ilGenImages(1, &ilTex);
		ilBindImage(ilTex);
		if(!ilLoadImage(path)) return false;
		mWidth = ilGetInteger(IL_IMAGE_WIDTH);
		mHeight = ilGetInteger(IL_IMAGE_HEIGHT);
		iluFlipImage();

		mTexID = ilutGLBindTexImage();
		ilDeleteImages(1, &ilTex);

		return true;
	}
Exemple #2
0
GLuint loadTexture(const  char* theFileName)
{
	GLuint textureID;			// Create a texture ID as a GLuint
	ILuint imageID;				// Create an image ID as a ULuint
	ilInit();   //初始化IL
	ilGenImages(1, &imageID); 		// Generate the image ID
	ilBindImage(imageID); 			// Bind the image
	ILboolean success = ilLoadImage(theFileName); 	// Load the image file

	if (success) {
		glGenTextures(1, &textureID); //创建Opengl纹理接口
		glBindTexture(GL_TEXTURE_2D, textureID);
		//设置纹理的过滤和环绕模式
		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);
		//将加载的纹理数据转化为OpenGL格式
		ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
		//将数据传入纹理对象中
		glTexImage2D(GL_TEXTURE_2D, 				// Type of texture
			0,				// Pyramid level (for mip-mapping) - 0 is the top level
			ilGetInteger(IL_IMAGE_FORMAT),	// Internal pixel format to use. Can be a generic type like GL_RGB or GL_RGBA, or a sized type
			ilGetInteger(IL_IMAGE_WIDTH),	// Image width
			ilGetInteger(IL_IMAGE_HEIGHT),	// Image height
			0,				// Border width in pixels (can either be 1 or 0)
			ilGetInteger(IL_IMAGE_FORMAT),	// Format of image pixel data
			GL_UNSIGNED_BYTE,		// Image data type
			ilGetData());			// The actual image data itself
	}
	else 
		std::cout << "Fail to load the texture!" <<std::endl;

	ilDeleteImages(1, &imageID); // Because we have already copied image data into texture data we can release memory used by image.
	std::cout << "Load the texture:" << theFileName << std::endl;
	return textureID; // 返回加载纹理索引
}
void CBitmap::Save(string filename)
{
	if (type == BitmapTypeDDS) {
		ddsimage->save(filename);
		return;
	}

	ilInit();
	ilOriginFunc(IL_ORIGIN_UPPER_LEFT);
	ilEnable(IL_ORIGIN_SET);

	unsigned char* buf=new unsigned char[xsize*ysize*4];
	/* HACK Flip the image so it saves the right way up.
	   (Fiddling with ilOriginFunc didn't do anything?)
	   Duplicated with ReverseYAxis. */
	for(int y=0;y<ysize;++y){
		for(int x=0;x<xsize;++x){
			buf[((ysize-1-y)*xsize+x)*4+0]=mem[((y)*xsize+x)*4+0];
			buf[((ysize-1-y)*xsize+x)*4+1]=mem[((y)*xsize+x)*4+1];
			buf[((ysize-1-y)*xsize+x)*4+2]=mem[((y)*xsize+x)*4+2];
			buf[((ysize-1-y)*xsize+x)*4+3]=mem[((y)*xsize+x)*4+3];
		}
	}

	ilHint(IL_COMPRESSION_HINT, IL_USE_COMPRESSION);
	ilSetInteger (IL_JPG_QUALITY, 80);

	ILuint ImageName = 0;
	ilGenImages(1, &ImageName);
	ilBindImage(ImageName);

	ilTexImage(xsize,ysize,1,4,IL_RGBA,IL_UNSIGNED_BYTE,NULL);
	ilSetData(buf);
	ilSaveImage((char*)filename.c_str());
	ilDeleteImages(1,&ImageName);
	delete[] buf;
}
Exemple #4
0
bool Texture::loadTextureFromFile( std::string path )
{
    //Texture loading success
    bool textureLoaded = false;

    //Generate and set current image ID
    ILuint imgID = 0;
    ilGenImages( 1, &imgID );
    ilBindImage( imgID );

    //Load image
	ILboolean success = ilLoadImage( path.c_str() );

	//Image loaded successfully
	if( success == IL_TRUE ){
	//Convert image to RGBA
	success = ilConvertImage( IL_RGBA, IL_UNSIGNED_BYTE );

		if( success == IL_TRUE )
		{
			//Create texture from file pixels
			textureLoaded = loadTextureFromPixels32( (GLuint*)ilGetData(), (GLuint)ilGetInteger( IL_IMAGE_WIDTH ), (GLuint)ilGetInteger( IL_IMAGE_HEIGHT ) );
		}

		//Delete file from memory
		ilDeleteImages( 1, &imgID );
	}

	//Report error
	if( !textureLoaded )
	{
		mTextureID = 0;
	}

	return textureLoaded;
}
Exemple #5
0
void CreateGDI()
{
	ILuint CopyName, CurName, CurImg, CurMip;

	hDC = GetDC(HWnd);
	hMemDC = CreateCompatibleDC(hDC);
	CurName = ilGetInteger(IL_CUR_IMAGE);
	CurImg = ilGetInteger(IL_ACTIVE_IMAGE);
	CurMip = ilGetInteger(IL_ACTIVE_MIPMAP);
	CopyName = ilCloneCurImage();
	ilBindImage(CopyName);
	//ilConvertImage(IL_BGR, IL_UNSIGNED_BYTE);
	hBitmap = ilutConvertToHBitmap(hDC);
	ilutGetBmpInfo((BITMAPINFO*)&BmpInfo);
	DeleteObject(SelectObject(hMemDC, hBitmap));
	ilBindImage(CurName);
	if (CurImg)
		ilActiveImage(CurImg);//ilBindImage(Undos[0]);
	if (CurMip)
		ilActiveMipmap(CurMip);
	ilDeleteImages(1, &CopyName);

	return;
}
Exemple #6
0
unsigned int ilLoadImage(std::string filename) {

	ILboolean success;
	unsigned int imageID;
 
	// init DevIL. This needs to be done only once per application
	ilInit();
	// generate an image name
	ilGenImages(1, &imageID); 
	// bind it
	ilBindImage(imageID); 
	// match image origin to OpenGL’s
	ilEnable(IL_ORIGIN_SET);
	ilOriginFunc(IL_ORIGIN_LOWER_LEFT);
	// load  the image
	success = ilLoadImage((ILstring)filename.c_str());
	ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
	// check to see if everything went OK
	if (!success) {
		ilDeleteImages(1, &imageID); 
		return 0;
	}
	else return imageID;
}
void loadTexture(Midori::Texture* texture, const std::string& path)
{
    ILuint texID;
    ilGenImages(1,&texID);
    ilBindImage(texID);

    if(!ilLoadImage((const ILstring)path.c_str()))
        cerr << "Error loading image " << path << endl;

    if(!ilConvertImage(IL_RGBA,IL_UNSIGNED_BYTE))
        cerr << " Error converting image " << path << endl;

    glGenTextures(1,&texture->id);
    glBindTexture(GL_TEXTURE_RECTANGLE,texture->id);
    glTexParameteri(GL_TEXTURE_RECTANGLE,GL_TEXTURE_WRAP_S,GL_CLAMP);
    glTexParameteri(GL_TEXTURE_RECTANGLE,GL_TEXTURE_WRAP_T,GL_CLAMP);
    glTexParameteri(GL_TEXTURE_RECTANGLE,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_RECTANGLE,GL_TEXTURE_MAG_FILTER,GL_LINEAR);

    glTexImage2D(GL_TEXTURE_RECTANGLE,0,ilGetInteger(IL_IMAGE_BPP),ilGetInteger(IL_IMAGE_WIDTH),
                 ilGetInteger(IL_IMAGE_HEIGHT),0,ilGetInteger(IL_IMAGE_FORMAT),GL_UNSIGNED_BYTE,ilGetData());

    ilDeleteImages(1, &texID);
}
Exemple #8
0
bool Model::initMaterials(const char* fileName, const aiScene* scene){

  ILboolean success;

  /* initialization of DevIL */
  ilInit(); 

  //debug line to confirm material number
  //std::cout << "material number: " << materialNumber << "\n";

  //debug line to check number of materials
  //std::cout << "Materials found " << materialNumber << "\n";

    int texIndex = 0;
    aiString path;	// filename

    aiReturn texFound = scene->mMaterials[materialNumber]->GetTexture(aiTextureType_DIFFUSE, texIndex, &path);

    //very strange, but texFound seems to contain the opposite of what we'd expect
    if (texFound) {
      //std::cout << "No texture image found \n  Using default texture";
      textureIdMap["assets/models/textures/default.jpg"] = 0;
      //std::cout <<  path.data << "\n\n";
    }
    else {
      //fill map with textures, OpenGL image ids set to 0

      // Extract the file name out of the file path
      std::string file = path.data;
      std::string::size_type SlashIndex = file.find_last_of("/");
      file = file.substr(SlashIndex+1);
      //and prepend the directory we want to find texture images
      file.insert(0, "assets/models/textures/");

      textureIdMap[file.c_str()] = 0; 
    }

  //because we only have 1 texture per mesh, probably don't need this
  //given more time can strip this down to load our 1 texture for our object
  int numTextures = textureIdMap.size();

  /* create and fill array with DevIL texture ids */
  ILuint* imageIds = new ILuint[numTextures];
  ilGenImages(numTextures, imageIds); 

  /* create and fill array with GL texture ids */
  GLuint* textureIds = new GLuint[numTextures];
  glGenTextures(numTextures, textureIds); /* Texture name generation */

  /* get iterator */
  std::map<std::string, GLuint>::iterator itr = textureIdMap.begin();
  int i=0;
  for (; itr != textureIdMap.end(); ++i, ++itr)	{
    //save IL image ID
    std::string filename = (*itr).first;  // get filename
    (*itr).second = textureIds[i];	  // save texture id for filename in map

    ilBindImage(imageIds[i]); /* Binding of DevIL image name */
    ilEnable(IL_ORIGIN_SET);
    ilOriginFunc(IL_ORIGIN_LOWER_LEFT); 
    success = ilLoadImage((ILstring)filename.c_str());

    if (success) {
      /* Convert image to RGBA */
      ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE); 

      //save our texture data to be bound later
      width = ilGetInteger(IL_IMAGE_WIDTH);
      height = ilGetInteger(IL_IMAGE_HEIGHT); 
      texId = textureIds[i];
      ILubyte* texDataBytes = ilGetData();
      texData = new ILubyte [ilGetInteger(IL_IMAGE_SIZE_OF_DATA)];
      for (int i=0; i < ilGetInteger(IL_IMAGE_SIZE_OF_DATA); i++){
        texData[i] = texDataBytes[i];
      }
    }
    else 
    printf("Couldn't load Image: %s\n  Please make sure all texture images are located in assets/models/textures/ folder!", filename.c_str());
  }
  /* Because we have already copied image data into texture data
	we can release memory used by image. */
  ilDeleteImages(numTextures, imageIds); 

  //Cleanup
  delete [] imageIds;
  delete [] textureIds;

  return true;
}
Exemple #9
0
void CBitmap::Load(string const& filename, unsigned char defaultAlpha)
{
	delete[] mem;
	mem = NULL;

	ilOriginFunc(IL_ORIGIN_UPPER_LEFT);
	ilEnable(IL_ORIGIN_SET);

	if(mem != NULL) delete [] mem;

	CFileHandler file(filename);
	if(file.FileExists() == false)
	{
		xsize = 1;
		ysize = 1;
		mem=new unsigned char[4];
		memset(mem, 0, 4);
		return;
	}

	unsigned char *buffer = new unsigned char[file.FileSize()];
	file.Read(buffer, file.FileSize());

	ILuint ImageName = 0;
	ilGenImages(1, &ImageName);
	ilBindImage(ImageName);

	const bool success = ilLoadL(IL_TYPE_UNKNOWN, buffer, file.FileSize());
	delete [] buffer;

	if(success == false)
	{
		xsize = 1;
		ysize = 1;
		mem=new unsigned char[4];
		memset(mem, 0, 4);
		return;   
	}

	bool noAlpha=ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL)!=4;
#if !defined(__APPLE__) // Temporary fix to allow testing of everything
						// else until i get a quicktime image loader written
	ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
	xsize = ilGetInteger(IL_IMAGE_WIDTH);
	ysize = ilGetInteger(IL_IMAGE_HEIGHT);

	mem = new unsigned char[xsize * ysize * 4];
	//	ilCopyPixels(0,0,0,xsize,ysize,0,IL_RGBA,IL_UNSIGNED_BYTE,mem);
	memcpy(mem, ilGetData(), xsize * ysize * 4);
#else
	xsize = 4;
	ysize = 4;

	mem = new unsigned char[xsize * ysize * 4];
#endif

	ilDeleteImages(1, &ImageName); 

	if(noAlpha){
		for(int y=0;y<ysize;++y){
			for(int x=0;x<xsize;++x){
			mem[(y*xsize+x)*4+3]=defaultAlpha;
			}
		}
	}
}
ColladaTexture::ColladaTexture(FCDImage * _image)
{
	image = _image;

	// Create an image container in DevIL.
	ILuint imageId;

	ilGenImages(1, &imageId);
	ilBindImage(imageId);

	// do it square
	// reduce it if it is necessaryt
	// test this
	//GL_MAX_TEXTURE_SIZE.

	// initializate some variables
	hasAlphaChannel = false;

	wchar_t orig[512];
	const size_t newsize = 256;
	char nstring[newsize];
#ifdef _WIN32
	// convert fstring to char*, amazing code based on http://msdn2.microsoft.com/en-us/library/ms235631(vs.80).aspx
	size_t convertedChars = 0;
	
	swprintf(orig, 512,L"%s", image->GetFilename().c_str() );
	size_t origsize = wcslen(orig) + 1;
	
	wcstombs_s(&convertedChars, nstring, origsize, orig, _TRUNCATE);
#else
	swprintf(orig, 512,L"%s", image->GetFilename().c_str() );
	const wchar_t * origTmp = &orig[0];
	wcsnrtombs( nstring, &origTmp, 512, 256, NULL);
#endif
	texturePathName =  nstring;
	
	wprintf(L"* added texture: %s", (wchar_t*)(image->GetFilename().c_str()));
	printf(" name: %s\n", image->GetDaeId().c_str());

	// Read in the image file into DevIL.
	if (!ilLoadImage(nstring))	
	{
		wchar_t error_message[256];
		swprintf(error_message, 256, L"This texture could not be opened: %s\n", (wchar_t*)(image->GetFilename().c_str()));
		wprintf(error_message);
        
        ILenum err = ilGetError();
        if (IL_NO_ERROR != err)
        {
            printf("- ilGetError() = %x", err);
        }
		
		ilDeleteImages(1, &imageId);
		textureId = -1;
	} else 
	{
		// resize if necessary
		ProcessDevilImage();


		// gl work
		glGenTextures(1, &textureId); /* Texture name generation */
		GLenum error;
		if ((error = glGetError()) != GL_NO_ERROR)
		{
			printf("OpenGL Error: %x\n", error);
		}

		glBindTexture(GL_TEXTURE_2D, textureId); /* Binding of texture name */

		// if 4 channels, the last one is the alpha channel
		if (ilGetInteger(IL_IMAGE_CHANNELS) == 4) 
			hasAlphaChannel = true;

		// create mipmaps and upload texture to video card memory
		gluBuild2DMipmaps
		(
			GL_TEXTURE_2D,
			ilGetInteger(IL_IMAGE_CHANNELS),
			ilGetInteger(IL_IMAGE_WIDTH),
			ilGetInteger(IL_IMAGE_HEIGHT), 
			ilGetInteger(IL_IMAGE_FORMAT), 
			GL_UNSIGNED_BYTE,
			ilGetData()
		); 




		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);
		glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);

		printf("texture size: %d x %d\n", ilGetInteger(IL_IMAGE_WIDTH), ilGetInteger(IL_IMAGE_HEIGHT));

		// release memory, now opengl have it !
		ilDeleteImages(1, &imageId); 
	}
	
}
Exemple #11
0
ILboolean GenSides()
{
	ILubyte	*Buffer, *Data, Bpp, Bpc;
	ILuint	TempImage;
	ILenum	Format, Type;
	ILint	SizePlane, Bps, c, y, z, i;

	ilActiveImage(ActiveImage);
	Bpp = ilGetInteger(IL_IMAGE_BPP);
	Bpc = ilGetInteger(IL_IMAGE_BPC);
	Format = ilGetInteger(IL_IMAGE_FORMAT);
	Type = ilGetInteger(IL_IMAGE_TYPE);

	// Front
	TexID1 = ilutGLBindTexImage();
	Width = ilGetInteger(IL_IMAGE_WIDTH);
	Height = ilGetInteger(IL_IMAGE_HEIGHT);
	Depth = ilGetInteger(IL_IMAGE_DEPTH);
	ilGenImages(1, &TempImage);

	SizePlane = ilGetInteger(IL_IMAGE_PLANESIZE);

	SizePlane = Width * Height * Bpp * Bpc;
	Bps = Width * Bpp * Bpc;
	Data = ilGetData();

	// Left
	i = 0;
	Buffer = (ILubyte*)malloc(Height * Depth * Bpp * Bpc);
	for (y = 0; y < Height; y++) {
		for (z = 0; z < Depth; z++) {
			for (c = 0; c < Bpp * Bpc; c++) {
				Buffer[i++] = Data[z * SizePlane + y * Bps + c];
			}
		}
	}
	ilBindImage(TempImage);
	ilTexImage(Depth, Height, 1, Bpp, Format, Type, Buffer);
	TexID2 = ilutGLBindTexImage();
	free(Buffer);

	// Right
	ilBindImage(ImgId);
	ilActiveImage(ActiveImage);
	i = 0;
	Buffer = (ILubyte*)malloc(Height * Depth * Bpp * Bpc);
	for (y = 0; y < Height; y++) {
		for (z = 0; z < Depth; z++) {
			for (c = 0; c < Bpp * Bpc; c++) {
				Buffer[i++] = Data[z * SizePlane + y * Bps + (Width - 1) * Bpp * Bpc + c];
			}
		}
	}
	ilBindImage(TempImage);
	ilTexImage(Depth, Height, 1, Bpp, Format, Type, Buffer);
	TexID3 = ilutGLBindTexImage();
	free(Buffer);

	// Back
	ilBindImage(ImgId);
	ilActiveImage(ActiveImage);
	Buffer = (ILubyte*)malloc(Width * Height * Bpp * Bpc);
	ilCopyPixels(0, 0, Depth-1, Width, Height, 1, Format, Type, Buffer);
	ilBindImage(TempImage);
	ilTexImage(Width, Height, 1, Bpp, Format, Type, Buffer);
	TexID4 = ilutGLBindTexImage();
	free(Buffer);

	//ilDeleteImages(1, &ImgId);
	ilDeleteImages(1, &TempImage);

	ilBindImage(ImgId);

	return IL_TRUE;
}
		//---------------------------------------------------------------------
		void LoadTexture(	const std::string& _filename,
							Texture2D& _texture,
							bool _srgb,
							bool _allocateMipmap,
							bool _verbose)
		{
			try
			{
				ilInit();
				
				ILuint imgH;
				ilGenImages(1, &imgH);
				ilBindImage(imgH);
				if(!ilLoadImage((const ILstring)_filename.c_str()))
				{
					Error("Load image error : file does not exist (%s)",_filename.c_str());
				}
				
				if(_verbose)
				{
					Info("Load image : %s",_filename.c_str());
				}

				// Convert all to RGBA. TODO Need improvement ...
				GLenum format;
				bool convert = false;
				ILenum target;
				switch(ilGetInteger(IL_IMAGE_FORMAT))
				{
					case IL_RGB  			: format = GL_RGBA; convert=true; target = IL_RGBA; break;
					case IL_RGBA 			: format = GL_RGBA; break;
					case IL_BGR  			: format = GL_RGBA; convert=true; target = IL_RGBA; break;
					case IL_BGRA 			: format = GL_RGBA; convert=true; target = IL_RGBA; break;
					case IL_LUMINANCE 		: format = GL_RGBA; convert=true; target = IL_RGBA; break;
					case IL_COLOUR_INDEX	: format = GL_RGBA; convert=true; target = IL_RGBA; break;
					case IL_ALPHA			: format = GL_RGBA; convert=true; target = IL_RGBA; break;
					case IL_LUMINANCE_ALPHA	: format = GL_RGBA; convert=true; target = IL_RGBA; break;
					default 				: Error("Load image error : unsupported format (%s)",_filename.c_str());
				}

				GLenum type;
				switch(ilGetInteger(IL_IMAGE_TYPE))
				{
					case IL_UNSIGNED_BYTE	: type = GL_UNSIGNED_BYTE; break;
					case IL_FLOAT			: type = GL_FLOAT; break;
					//case IL_BYTE			: type = GL_BYTE; break;
					//case IL_SHORT			: type = GL_SHORT; break;
					//case IL_UNSIGNED_SHORT: type = GL_UNSIGNED_SHORT; break;
					//case IL_INT			: type = GL_INTEGER; break;
					//case IL_UNSIGNED_INT	: type = GL_UNSIGNED_INT; break;
					//case IL_DOUBLE		: Error("Load image error : double data are not supported (%s)",_filename.c_str()); break;
					default 				: Error("Load image error : unsupported data (%s)",_filename.c_str());
				}

				if(convert)
					 ilConvertImage(target, ilGetInteger(IL_IMAGE_TYPE));

				// Flip image
				ILinfo ImageInfo;
				iluGetImageInfo(&ImageInfo);
				if( ImageInfo.Origin == IL_ORIGIN_UPPER_LEFT )
				{
					iluFlipImage();
					if(_verbose) Info("Flip image");
				}

				switch(type)
				{
					case GL_UNSIGNED_BYTE	:
					{
						if(_srgb)
						{
							_texture.Allocate( GL_SRGB8_ALPHA8, ilGetInteger(IL_IMAGE_WIDTH),ilGetInteger(IL_IMAGE_HEIGHT),_allocateMipmap);
							if(_verbose) Info("Allocate texture - format:GL_SRGB8_ALPHA8, w:%d, h:%d, mipmap:%s",ilGetInteger(IL_IMAGE_WIDTH),ilGetInteger(IL_IMAGE_HEIGHT), (_allocateMipmap?"TRUE":"FALSE") );
						}
						else
						{
							_texture.Allocate( GL_RGBA8, ilGetInteger(IL_IMAGE_WIDTH),ilGetInteger(IL_IMAGE_HEIGHT),_allocateMipmap);
							if(_verbose) Info("Allocate texture - format:GL_RGBA8, w:%d, h:%d, mipmap:%s",ilGetInteger(IL_IMAGE_WIDTH),ilGetInteger(IL_IMAGE_HEIGHT), (_allocateMipmap?"TRUE":"FALSE") );
						}
					}
					break;
					case GL_FLOAT			:
					{
						if(_srgb)
							Warning("Try to convert to SRGB, but texture format is not compatible");
						_texture.Allocate( GL_RGBA32F, ilGetInteger(IL_IMAGE_WIDTH),ilGetInteger(IL_IMAGE_HEIGHT),_allocateMipmap);
						if(_verbose) Info("Allocate texture - format:GL_RGBA32F, w:%d, h:%d, mipmap:%s",ilGetInteger(IL_IMAGE_WIDTH),ilGetInteger(IL_IMAGE_HEIGHT), (_allocateMipmap?"TRUE":"FALSE") );
					}
					break;
					default 				:
					{
						Error("Load image error : unsupported data (%s)",_filename.c_str());
					}
				}
				_texture.Fill(format,type,ilGetData());

				ilDeleteImages(1, &imgH);
				ilShutDown();
			}
			catch (const std::exception &e) 
			{
				Error("Unable to read image file \"%s\": %s",_filename.c_str(),e.what());
			}
		}
Exemple #13
0
int LoadGLTextures(const aiScene* sc)
{
	ILboolean success;
    
	//ilInit(); /* Initialization of DevIL */ //e' gia' inizializzato in InitGL nel main
    
	/* getTexture Filenames and Numb of Textures */
	for (unsigned int m=0; m<sc->mNumMaterials; m++)
	{
		int texIndex = 0;
        
		aiString path;	// filename
        
		aiReturn texFound = sc->mMaterials[m]->GetTexture(aiTextureType_DIFFUSE, texIndex, &path);
		while (texFound == AI_SUCCESS)
		{
			if (textureIdMap.find(path.data)==textureIdMap.end()) //la texture non e' ancora caricata nella mappa
			{
				textureIdMap[path.data] = NULL; //fill map with textures, pointers still NULL yet
			}
			texIndex++;
			texFound = sc->mMaterials[m]->GetTexture(aiTextureType_DIFFUSE, texIndex, &path);
		}
	}
    
	int numTextures = (int) textureIdMap.size();
    
	/* array with DevIL image IDs */
	ILuint* imageIds = NULL;
	imageIds = new ILuint[numTextures];
    
	/* generate DevIL Image IDs */
	ilGenImages(numTextures, imageIds); /* Generation of numTextures image names */
    
	/* create and fill array with GL texture ids */
	textureIds = new GLuint[numTextures];
	glGenTextures(numTextures, textureIds); /* Texture name generation */
    
	/* define texture path */
	//std::string texturepath = "../../../test/models/Obj/";
    

	/* get iterator */
	std::map<std::string, GLuint*>::iterator itr = textureIdMap.begin();
    int i=0;
    for (; itr != textureIdMap.end(); ++i, ++itr)
	{
		if (itr->second==NULL) //solo se la texture non e' ancora stata caricata
		{
			//save IL image ID
			std::string filename = (*itr).first;  // get filename
		
			(*itr).second =  &textureIds[i];	  // save texture id for filename in map        
        
			ilBindImage(imageIds[i]); /* Binding of DevIL image name */
			std::string fileloc = basepath + filename;	/* Loading of image */
			success = ilLoadImage((const char *)fileloc.c_str());
        
			//fprintf(stdout,"Loading Image: %s\n", fileloc.data());
        
			if (success) /* If no error occured: */
			{
				success = ilConvertImage(IL_RGB, IL_UNSIGNED_BYTE); /* Convert every colour component into
																	 unsigned byte. If your image contains alpha channel you can replace IL_RGB with IL_RGBA */
				if (!success)
				{
					/* Error occured */
					fprintf(stderr,"Couldn't convert image");
					return -1;
				}
				//glGenTextures(numTextures, &textureIds[i]); /* Texture name generation */
				glBindTexture(GL_TEXTURE_2D, textureIds[i]); /* Binding of texture name */
				//redefine standard texture values
				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); /* We will use linear
																				   interpolation for magnification filter */
				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); /* We will use linear
																				   interpolation for minifying filter */
				glTexImage2D(GL_TEXTURE_2D, 0, ilGetInteger(IL_IMAGE_BPP), ilGetInteger(IL_IMAGE_WIDTH),
							 ilGetInteger(IL_IMAGE_HEIGHT), 0, ilGetInteger(IL_IMAGE_FORMAT), GL_UNSIGNED_BYTE,
							 ilGetData()); /* Texture specification */
			}
			else
			{
				/* Error occured */
				fprintf(stderr,"Couldn't load Image: %s\n", fileloc.data());
			}
		}
	}
	ilDeleteImages(numTextures, imageIds); /* Because we have already copied image data into texture data
                                            we can release memory used by image. */
    
	//Cleanup
	delete [] imageIds;
	imageIds = NULL;
    
	//return success;
	return TRUE;
}
void CBitmap::Load(string filename, unsigned char defaultAlpha)
{
	if(mem!=0)
	{
		delete[] mem;
		mem = NULL;
	}

	if(filename.find(".dds")!=string::npos){
		ddsimage = new nv_dds::CDDSImage();
		ddsimage->load(filename);
		type = BitmapTypeDDS;
		return;
	}
	type = BitmapTypeStandar;

	ilInit();
	ilOriginFunc(IL_ORIGIN_UPPER_LEFT);
	ilEnable(IL_ORIGIN_SET);

	if(mem != NULL) delete [] mem;

	CFileHandler file(filename);
	if(file.FileExists() == false)
	{
		xsize = 1;
		ysize = 1;
		mem=new unsigned char[4];
		memset(mem, 0, 4);
		return;
	}

	unsigned char *buffer = new unsigned char[file.FileSize()];
	file.Read(buffer, file.FileSize());

	ILuint ImageName = 0;
	ilGenImages(1, &ImageName);
	ilBindImage(ImageName);

	const bool success = ilLoadL(IL_TYPE_UNKNOWN, buffer, file.FileSize());
	delete [] buffer;

	if(success == false)
	{
		xsize = 1;
		ysize = 1;
		mem=new unsigned char[4];
		memset(mem, 0, 4);
		return;   
	}

	bool noAlpha=ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL)!=4;
	ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
	xsize = ilGetInteger(IL_IMAGE_WIDTH);
	ysize = ilGetInteger(IL_IMAGE_HEIGHT);

	mem = new unsigned char[xsize * ysize * 4];
//	ilCopyPixels(0,0,0,xsize,ysize,0,IL_RGBA,IL_UNSIGNED_BYTE,mem);
	memcpy(mem, (unsigned char *) ilGetData() , xsize * ysize * 4);

	ilDeleteImages(1, &ImageName); 

	if(noAlpha){
		for(int y=0;y<ysize;++y){
			for(int x=0;x<xsize;++x){
				mem[(y*xsize+x)*4+3]=defaultAlpha;
			}
		}
	}
}
Exemple #15
0
bool CBitmap::Load(std::string const& filename, unsigned char defaultAlpha)
{
	bool noAlpha = true;

	delete[] mem;
	mem = NULL;

#ifndef BITMAP_NO_OPENGL
	textype = GL_TEXTURE_2D;
#endif // !BITMAP_NO_OPENGL

	if (filename.find(".dds") != std::string::npos) {
		type = BitmapTypeDDS;
		xsize = 0;
		ysize = 0;
		channels = 0;
#ifndef BITMAP_NO_OPENGL
		ddsimage = new nv_dds::CDDSImage();
		bool status = ddsimage->load(filename);
		if (status) {
			xsize = ddsimage->get_width();
			ysize = ddsimage->get_height();
			channels = ddsimage->get_components();
			switch (ddsimage->get_type()) {
				case nv_dds::TextureFlat :
					textype = GL_TEXTURE_2D;
					break;
				case nv_dds::Texture3D :
					textype = GL_TEXTURE_3D;
					break;
				case nv_dds::TextureCubemap :
					textype = GL_TEXTURE_CUBE_MAP;
					break;
				case nv_dds::TextureNone :
				default :
					break;
			}
		}
		return status;
#else
		return false;
#endif // !BITMAP_NO_OPENGL
	}
	type = BitmapTypeStandardRGBA;
	channels = 4;

	CFileHandler file(filename);
	if (file.FileExists() == false) {
		Alloc(1, 1);
		return false;
	}

	unsigned char* buffer = new unsigned char[file.FileSize() + 2];
	file.Read(buffer, file.FileSize());

	boost::mutex::scoped_lock lck(devilMutex);
	ilOriginFunc(IL_ORIGIN_UPPER_LEFT);
	ilEnable(IL_ORIGIN_SET);

	ILuint ImageName = 0;
	ilGenImages(1, &ImageName);
	ilBindImage(ImageName);

	const bool success = !!ilLoadL(IL_TYPE_UNKNOWN, buffer, file.FileSize());
	ilDisable(IL_ORIGIN_SET);
	delete[] buffer;

	if (success == false) {
		xsize = 1;
		ysize = 1;
		mem = new unsigned char[4];
		mem[0] = 255; // Red allows us to easily see textures that failed to load
		mem[1] = 0;
		mem[2] = 0;
		mem[3] = 255; // Non Transparent
		return false;
	}

	noAlpha = (ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL) != 4);
	ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
	xsize = ilGetInteger(IL_IMAGE_WIDTH);
	ysize = ilGetInteger(IL_IMAGE_HEIGHT);

	mem = new unsigned char[xsize * ysize * 4];
	//ilCopyPixels(0, 0, 0, xsize, ysize, 0, IL_RGBA, IL_UNSIGNED_BYTE, mem);
	memcpy(mem, ilGetData(), xsize * ysize * 4);

	ilDeleteImages(1, &ImageName);

	if (noAlpha) {
		for (int y=0; y < ysize; ++y) {
			for (int x=0; x < xsize; ++x) {
				mem[((y*xsize+x) * 4) + 3] = defaultAlpha;
			}
		}
	}

	return true;
}
Exemple #16
0
void
Config::readSetOfSlices( const std::vector<std::string>& files,
						 unsigned int downx,
						 unsigned int downy,
						 unsigned int downz )
{
	ILuint image;
	ilGenImages( 1, &image );
	ilBindImage( image);

	ILenum type, bpp;
	switch( m_function_format )
	{
	case FUNC_FLOAT:
		m_function_iso_min = 0;
		m_function_iso_max = 0xfff;
		m_function_isovalue = 0x200;
		type = IL_FLOAT;
		bpp = 4;
		break;
	case FUNC_UNSIGNED_BYTE:
		m_function_iso_min = 0;
		m_function_iso_max = 0xff;
		m_function_isovalue = 0x20;
		type = IL_UNSIGNED_BYTE;
		bpp = 1;
		break;
	case FUNC_UNSIGNED_SHORT:
		m_function_iso_min = 0;
		m_function_iso_max = 0xfff;
		m_function_isovalue = 0x200;
		type = IL_UNSIGNED_SHORT;
		bpp = 2;
		break;
	}

	int w, h;
	for(int i=0; i<files.size(); i++) {
		std::vector<char> filename(files[i].begin(), files[i].end());
		filename.push_back('\0');

		if( ilLoadImage( &filename[0] ) == IL_FALSE ) {
			std::cerr << __func__ << ": failed to read image " << files[i] << "\n";
			exit( EXIT_FAILURE );
		}
		std::cerr << __func__ << ": read " << files[i] << "\n";		

		if( i==0 ) {
			w = ilGetInteger( IL_IMAGE_WIDTH );
			h = ilGetInteger( IL_IMAGE_HEIGHT );
			std::cerr << __func__ << ": input = [ " << w << " x " << h << "]\n";
			std::cerr << __func__ << ": type = " << type << "\n";
			std::cerr << __func__ << ": bpp = " << bpp << "\n";
			m_function_tsize_log2 = (unsigned int)ceilf(log2(max(w,h)));
			m_function_tsize = 1<<m_function_tsize_log2;
			m_function_slices = files.size();
			allocFuncMem();
		}

		ilCopyPixels(0, 0, 0, m_function_tsize, m_function_tsize, 1, IL_LUMINANCE, type, (unsigned char*)m_function_data_ + bpp*m_function_tsize*m_function_tsize*i );
	}
	ilDeleteImages( 1, &image );
}
Texture* DevILImageCodec::load(const RawDataContainer& data, Texture* result)
{
    ilPushAttrib(IL_ORIGIN_SET);
    ilOriginFunc(IL_ORIGIN_UPPER_LEFT);
    ilEnable(IL_ORIGIN_SET);

    ILuint imgName;
    ilGenImages(1, &imgName);
    ilBindImage(imgName);

    if (ilLoadL(IL_TYPE_UNKNOWN, (ILvoid*)data.getDataPtr(), data.getSize()) != IL_FALSE)
    {
        // get details about size of loaded image
        ILinfo imgInfo;
        memset(&imgInfo, 0, sizeof(ILinfo));
        iluGetImageInfo(&imgInfo);
        // set dimensions of texture
        size_t width = imgInfo.Width;
        size_t height = imgInfo.Height;
        // allocate temp buffer to receive image data
        uchar* tmpBuff = new uchar[width * height * 4];

        // get image data in required format
        Texture::PixelFormat cefmt;
        ILenum ilfmt;
        switch (imgInfo.Format)
        {
        case IL_RGBA:
        case IL_BGRA:
            ilfmt = IL_RGBA;
            cefmt = Texture::PF_RGBA;
            break;
        default:
            ilfmt = IL_RGB;
            cefmt = Texture::PF_RGB;
            break;
        };
        ilCopyPixels(0, 0, 0, width, height, 1, ilfmt, IL_UNSIGNED_BYTE, (ILvoid*)tmpBuff);

        // delete DevIL image
        ilDeleteImages(1, &imgName);
        ilPopAttrib();

        // create cegui texture
        try
        {
            result->loadFromMemory(tmpBuff, width, height, cefmt);
        }
        catch(...)
        {
            delete [] tmpBuff;
            throw;
        }

        // free temp buffer
        delete [] tmpBuff;

        return result;
    }
	// failed to load image properly.
	else
	{
		// delete DevIL image
		ilDeleteImages(1, &imgName);
		ilPopAttrib();
        return 0;
    }
}
int main(int argc, char *argv[])
{
    e_epiphany_t Epiphany, *pEpiphany;
    e_mem_t      DRAM,     *pDRAM;
    unsigned int msize;
    int          row, col, cnum;



    ILuint  ImgId;
//	ILenum  Error;
    ILubyte *imdata;
    ILuint  imsize, imBpp;



    unsigned int addr;
    size_t sz;
    struct timespec timer[4];
    uint32_t time_p[TIMERS];
    uint32_t time_d[TIMERS];
    FILE *fo;
//	FILE *fi;
    int  result;


    pEpiphany = &Epiphany;
    pDRAM     = &DRAM;
    msize     = 0x00400000;

    //get_args(argc, argv);
    strcpy(ar.ifname,argv[1]);
    strcpy(ar.elfFile,argv[2]);
    strcpy(ar.ofname, ar.ifname);
    printf("------------------------------------------------------------\n");
    fo = fopen("matprt.m", "w");
    if ((fo == NULL)) // || (fi == NULL))
    {
        fprintf(stderr, "Could not open Octave file \"%s\" ...exiting.\n", "matprt.m");
        exit(4);
    }
//	fo = stderr;


    // Connect to device for communicating with the Epiphany system
    // Prepare device
    e_set_host_verbosity(ar.verbose);
    e_init(NULL);
    e_reset_system();
    e_get_platform_info(&platform);
    if (e_open(pEpiphany, 0, 0, platform.rows, platform.cols))
    {
        fprintf(fo, "\nERROR: Can't establish connection to Epiphany device!\n\n");
        exit(1);
    }
    if (e_alloc(pDRAM, 0x00000000, msize))
    {
        fprintf(fo, "\nERROR: Can't allocate Epiphany DRAM!\n\n");
        exit(1);
    }

    // Initialize Epiphany "Ready" state
    addr = offsetof(shared_buf_t, core.ready);
    Mailbox.core.ready = 0;
    e_write(pDRAM, 0, 0, addr, (void *) &(Mailbox.core.ready), sizeof(Mailbox.core.ready));

    result = e_load_group(ar.elfFile, pEpiphany, 0, 0, platform.rows, platform.cols, (e_bool_t) (ar.run_target));
    if (result == E_ERR) {
        printf("Error loading Epiphany program.\n");
        exit(1);
    }


    // Check if the DevIL shared lib's version matches the executable's version.
    if (ilGetInteger(IL_VERSION_NUM) < IL_VERSION)
    {
        fprintf(stderr, "DevIL version is different ...exiting!\n");
        exit(2);
    }

    // Initialize DevIL.
    ilInit();
#ifdef ILU_ENABLED
    iluInit();
#endif



    // create the coreID list
    init_coreID(pEpiphany, coreID, _Nside, _Nside, 0x808);


    // Generate the main image name to use, bind it and load the image file.
    ilGenImages(1, &ImgId);
    ilBindImage(ImgId);
    if (!ilLoadImage(ar.ifname))//ar.ifname
    {
        fprintf(stderr, "Could not open input image file \"%s\" ...exiting.\n", ar.ifname);
        exit(3);
    }


    // Display the image's dimensions to the end user.
    /*
    printf("Width: %d  Height: %d  Depth: %d  Bpp: %d\n\n",
           ilGetInteger(IL_IMAGE_WIDTH),
           ilGetInteger(IL_IMAGE_HEIGHT),
           ilGetInteger(IL_IMAGE_DEPTH),
           ilGetInteger(IL_IMAGE_BITS_PER_PIXEL));
    */
    imdata = ilGetData();
    imsize = ilGetInteger(IL_IMAGE_WIDTH) * ilGetInteger(IL_IMAGE_HEIGHT);
    imBpp  = ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL);

    if (imsize != (_Sfft * _Sfft))
    {
        printf("Image file size is different from %dx%d ...exiting.\n", _Sfft, _Sfft);
        exit(5);
    }


    // Extract image data into the A matrix.
    for (unsigned int i=0; i<imsize; i++)
    {
        Mailbox.A[i] = (float) imdata[i*imBpp] + 0.0 * I;
    }

    fprintf(fo, "\n");


    // Generate operand matrices based on a provided seed
    matrix_init(0);

#ifdef _USE_DRAM_
    // Copy operand matrices to Epiphany system
    addr = DRAM_BASE + offsetof(shared_buf_t, A[0]);
    sz = sizeof(Mailbox.A);
    fprintf(fo, "%% Writing A[%ldB] to address %08x...\n", sz, addr);
    e_write(addr, (void *) Mailbox.A, sz);

    addr = DRAM_BASE + offsetof(shared_buf_t, B[0]);
    sz = sizeof(Mailbox.B);
    fprintf(fo, "%% Writing B[%ldB] to address %08x...\n", sz, addr);
    e_write(addr, (void *) Mailbox.B, sz);
#else
    // Copy operand matrices to Epiphany cores' memory
    fprintf(fo, "%% Writing image to Epiphany\n");

    sz = sizeof(Mailbox.A) / _Ncores;
    for (row=0; row<(int) platform.rows; row++)
        for (col=0; col<(int) platform.cols; col++)
        {
            addr = BankA_addr;
            fflush(stdout);
            cnum = e_get_num_from_coords(pEpiphany, row, col);
//			 printf(       "Writing A[%uB] to address %08x...\n", sz, addr);
            fprintf(fo, "%% Writing A[%uB] to address %08x...\n", sz, (coreID[cnum] << 20) | addr);
            fflush(fo);
            e_write(pEpiphany, row, col, addr, (void *) &Mailbox.A[cnum * _Score * _Sfft], sz);
        }
#endif



    // Call the Epiphany fft2d() function
    fprintf(fo, "%% GO!\n");
    fflush(stdout);
    fflush(fo);
    clock_gettime(CLOCK_MONOTONIC, &timer[0]);
    fft2d_go(pDRAM);
    clock_gettime(CLOCK_MONOTONIC, &timer[1]);
    fprintf(fo, "%% Done!\n\n");
    fflush(stdout);
    fflush(fo);

    // Read time counters
//	 printf(       "Reading time count...\n");
    fprintf(fo, "%% Reading time count...\n");
    addr = 0x7128+0x4*2 + offsetof(core_t, time_p[0]);
    sz = TIMERS * sizeof(uint32_t);
    e_read(pEpiphany, 0, 0, addr, (void *) (&time_p[0]), sz);

//	for (int i=0; i<TIMERS; i++)
//		printf("time_p[%d] = %u\n", i, time_p[i]);

    time_d[2] = time_p[7] - time_p[2]; // FFT setup
    time_d[3] = time_p[2] - time_p[3]; // bitrev (x8)
    time_d[4] = time_p[3] - time_p[4]; // FFT-1D (x8)
    time_d[5] = time_p[4] - time_p[5]; // corner-turn
    time_d[6] = time_p[7] - time_p[8]; // FFT-2D
    time_d[7] = time_p[6] - time_p[7]; // LPF
    time_d[9] = time_p[0] - time_p[9]; // Total cycles
    fprintf(fo, "%% Finished calculation in %u cycles (%5.3f msec @ %3.0f MHz)\n\n", time_d[9], (time_d[9] * 1000.0 / eMHz), (eMHz / 1e6));

    printf(       "FFT2D         - %7u cycles (%5.3f msec)\n", time_d[6], (time_d[6] * 1000.0 / eMHz));
    printf(       "  FFT Setup   - %7u cycles (%5.3f msec)\n", time_d[2], (time_d[2] * 1000.0 / eMHz));
    printf(       "  BITREV      - %7u cycles (%5.3f msec)\n", time_d[3], (time_d[3] * 1000.0 / eMHz));
    printf(       "  FFT1D       - %7u cycles (%5.3f msec x2)\n", time_d[4], (time_d[4] * 1000.0 / eMHz));
    printf(       "  Corner Turn - %7u cycles (%5.3f msec)\n", time_d[5], (time_d[5] * 1000.0 / eMHz));
    printf(       "LPF           - %7u cycles (%5.3f msec)\n", time_d[7], (time_d[7] * 1000.0 / eMHz));
    fprintf(fo, "%% Reading processed image back to host\n");



    // Read result matrix
#ifdef _USE_DRAM_
    addr = DRAM_BASE + offsetof(shared_buf_t, B[0]);
    sz = sizeof(Mailbox.B);
    printf(       "Reading B[%ldB] from address %08x...\n", sz, addr);
    fprintf(fo, "%% Reading B[%ldB] from address %08x...\n", sz, addr);
    blknum = sz / RdBlkSz;
    remndr = sz % RdBlkSz;
    for (i=0; i<blknum; i++)
    {
        fflush(stdout);
        e_read(addr+i*RdBlkSz, (void *) ((long unsigned)(Mailbox.B)+i*RdBlkSz), RdBlkSz);
    }
    fflush(stdout);
    e_read(addr+i*RdBlkSz, (void *) ((long unsigned)(Mailbox.B)+i*RdBlkSz), remndr);
#else
    // Read result matrix from Epiphany cores' memory
    sz = sizeof(Mailbox.A) / _Ncores;
    for (row=0; row<(int) platform.rows; row++)
        for (col=0; col<(int) platform.cols; col++)
        {
            addr = BankA_addr;
            fflush(stdout);
            cnum = e_get_num_from_coords(pEpiphany, row, col);
//			printf(        "Reading A[%uB] from address %08x...\n", sz, addr);
            fprintf(fo, "%% Reading A[%uB] from address %08x...\n", sz, (coreID[cnum] << 20) | addr);
            fflush(fo);
            e_read(pEpiphany, row, col, addr, (void *) &Mailbox.B[cnum * _Score * _Sfft], sz);
        }
#endif

    // Convert processed image matrix B into the image file date.
    for (unsigned int i=0; i<imsize; i++)
    {
        for (unsigned int j=0; j<imBpp; j++)
            imdata[i*imBpp+j] = cabs(Mailbox.B[i]);
    }

    // Save processed image to the output file.
    ilEnable(IL_FILE_OVERWRITE);
    if (!ilSaveImage(ar.ofname))
    {
        fprintf(stderr, "Could not open output image file \"%s\" ...exiting.\n", ar.ofname);
        exit(7);
    }

    // We're done with the image, so let's delete it.
    ilDeleteImages(1, &ImgId);

    // Simple Error detection loop that displays the Error to the user in a human-readable form.
//	while ((Error = ilGetError()))
//		PRINT_ERROR_MACRO;

    // Close connection to device
    if (e_close(pEpiphany))
    {
        fprintf(fo, "\nERROR: Can't close connection to Epiphany device!\n\n");
        exit(1);
    }
    if (e_free(pDRAM))
    {
        fprintf(fo, "\nERROR: Can't release Epiphany DRAM!\n\n");
        exit(1);
    }

    fflush(fo);
    fclose(fo);

    //Returnin success if test runs expected number of clock cycles
    //Need to add comparison with golden reference image!
    printf("------------------------------------------------------------\n");
    if(time_d[9]>50000) {
        printf( "TEST \"fft2d\" PASSED\n");
        return EXIT_SUCCESS;
    }
    else {
        printf( "TEST \"fft2d\" FAILED\n");
        return EXIT_FAILURE;
    }
}
		//----------------------------------------------------------------------
		void SaveTexture(	const std::string& _filename,
							Texture2D& _texture,
							bool _verbose)
		{
			#ifdef ENABLE_OPEN_EXR
			float* data = new float[_texture.size.x * _texture.size.y * 4];
			glBindTexture(_texture.target,_texture.id);
			glGetTexImage(_texture.target,0,GL_RGBA,GL_FLOAT,data);
			SaveTexture(_filename,data,_texture.size.x,_texture.size.y,_verbose);
			delete[] data;
			#else
			try
			{
				ilInit();
				
				ILuint imgH;
				ilGenImages(1, &imgH);
				ilBindImage(imgH);

				float* data = new float[_texture.size.x * _texture.size.y * 4];
				glBindTexture(_texture.target,_texture.id);
				glGetTexImage(_texture.target,0,GL_RGBA,GL_FLOAT,data);

				ILboolean result;
				result = ilTexImage(_texture.size.x, _texture.size.y, 1, 4, IL_RGBA, IL_FLOAT, data);
				assert(result);

				ilEnable(IL_FILE_OVERWRITE);
//				result = ilSave(IL_EXR, _filename.c_str());
//				result = ilSave(IL_TYPE_UNKNOWN, _filename.c_str());
				#if WIN32
				result = ilSaveImage(s2ws(_filename).c_str());			
				#else
				result = ilSaveImage(_filename.c_str());
				#endif

				if(!result)
				{
					ILenum errorID = ilGetError();
					if(errorID != IL_NO_ERROR)
					{
						Error("Save image error :  %s",_filename.c_str());
						Error("Error ID :  %d",errorID);
					}
				}
				assert(result);

				delete[] data;

				if(_verbose)
				{
					Info("Save image : %s",_filename.c_str());
				}

				ilDeleteImages(1, &imgH);
				ilShutDown();
			}
			catch (const std::exception &e) 
			{
				Error("Unable to write texture \"%s\": %s",_filename.c_str(),e.what());
			}
			#endif
		}
Exemple #20
0
int main(int argc, char **argv)
{
	ILuint	ImgId;
	ILenum	Error;

	// We use the filename specified in the first argument of the command-line.
	if (argc < 2) {
		printf("Please specify a file to open.\n");
		return 1;
	}

	// Check if the shared lib's version matches the executable's version.
	if (ilGetInteger(IL_VERSION_NUM) < IL_VERSION) {
		printf("DevIL version is different...exiting!\n");
		return 2;
	}

	// Initialize DevIL.
	ilInit();


	// Set the loading function here.
	ilRegisterLoad("xxx", LoadFunction);


	// Generate the main image name to use.
	ilGenImages(1, &ImgId);
	// Bind this image name.
	ilBindImage(ImgId);
	// Loads the image specified by File into the image named by ImgId.
	if (!ilLoadImage(argv[1])) {
		printf("Could not open file...exiting.\n");
		return 3;
	}

	// Display the image's dimensions to the end user.
	printf("Width: %d  Height: %d  Depth: %d  Bpp: %d\n", ilGetInteger(IL_IMAGE_WIDTH),
		ilGetInteger(IL_IMAGE_HEIGHT), ilGetInteger(IL_IMAGE_DEPTH), ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL));

	// Enable this to let us overwrite the destination file if it already exists.
	ilEnable(IL_FILE_OVERWRITE);

	// If argv[2] is present, we save to this filename, else we save to test.tga.
	if (argc > 2)
		ilSaveImage(argv[2]);
	else
		ilSaveImage("test.tga");


	// Remove the loading function when we're done using it or want to change it.
	//  This isn't required here, since we're exiting, but here's how it's done:
	ilRemoveLoad("xxx");


	// We're done with the image, so let's delete it.
	ilDeleteImages(1, &ImgId);

	// Simple Error detection loop that displays the Error to the user in a human-readable form.
	while ((Error = ilGetError())) {
		PRINT_ERROR_MACRO;
	}

	return 0;
}
Exemple #21
0
// loads image
bool CImage::Load(const char *fname)
{
 assert(fname != NULL);
 
 //printf(">>> %s\n", fname);
 
 // unload old image
 Unload();
 
 // init devil
 ilInit();
 
 // create image
 ILuint img;
 ilGenImages(1, &img);
 ilBindImage(img);
 
 // correct origin
 ilOriginFunc(IL_ORIGIN_LOWER_LEFT);
 ilEnable(IL_ORIGIN_SET);
 
 // convert palette
 ilEnable(IL_CONV_PAL);
 //ilutEnable(ILUT_OPENGL_CONV);
 
 // load image
 if (!ilLoadImage(fname)) {
  ilDeleteImages(1, &img);
  g_errmsg = "Format not recognised or file corrupted.";
  return false;
 } else {
  
  // copy info
  width = ilGetInteger(IL_IMAGE_WIDTH);
  height = ilGetInteger(IL_IMAGE_HEIGHT);
  frags = ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL);
  
  
  GLint maxsize;
  glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxsize);
  if (width > maxsize || height > maxsize) {
   g_errmsg = "Image dimension larger than ";
   char shitstream[10];
   sprintf(shitstream, "%i", (int)maxsize );
   g_errmsg += shitstream;
   g_errmsg += " not supported by graphics driver!";
   return false;
  }
  
  //printf(">>> %ix%i*%i\n", width, height, frags);
  
  int  ilfmt;
  switch (frags) {
  case 1:  ilfmt = IL_LUMINANCE;       break;
  case 2:  ilfmt = IL_LUMINANCE_ALPHA; break;
  case 3:  ilfmt = IL_RGB;             break;
  case 4:  ilfmt = IL_RGBA;            break;
  default: ilfmt = IL_RGB;             break;
  }
  
  // convert
  if (!ilConvertImage(ilfmt, IL_UNSIGNED_BYTE)) {
   ilDeleteImages(1, &img);
   g_errmsg = "Failed to convert image!";
   return false;
  }
  
  // opengl texture
  target = GL_TEXTURE_2D;
  //target = GL_TEXTURE_RECTANGLE_ARB; // todo: for compat mode?
  intformat = ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL);
  format = ilGetInteger(IL_IMAGE_FORMAT);
  type = GL_UNSIGNED_BYTE;
 }
 
 // create texture
 glGenTextures(1, &texname);
 glBindTexture(target, texname);
 
 // load image
 glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
 glTexImage2D(target, 0, intformat, width, height, 0, format, type, ilGetData() );
 
 // generate mipmaps
 if (g_genmipmaps) {
  glGenerateMipmap(GL_TEXTURE_2D);
  mipmaps = CountMipmaps( width, height );
 } else {
  mipmaps = 1;
 }
 
 // set texture params
 Refresh();
 
 // unload image
 ilDeleteImages(1, &img);
 
 /*
 // determine target & images
 int images = 0;
 if (cubemap) {
  target = GL_TEXTURE_CUBE_MAP;
 } else {
  target = GL_TEXTURE_2D;
 }
 
 // determine texture format
 GLint intformat;
 switch (frags)
 {
  case 1:
   format = GL_ALPHA;
   intformat = GL_ALPHA8;
   break;
  case 3:
   format = GL_BGR;
   intformat = GL_RGB8;
   break;
  case 4:
   format = GL_BGRA;
   intformat = GL_RGBA8;
   break;
 }
 
  // mipmapping
  if (mipmap) {
   glTexParameteri(target, GL_GENERATE_MIPMAP, GL_TRUE);
  } else {
   glTexParameteri(target, GL_GENERATE_MIPMAP, GL_FALSE);
  }
  
  // determine upload target
  int uptarget = 0;
  if (cubemap) {
   if (i == 5) uptarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X;
   if (i == 4) uptarget = GL_TEXTURE_CUBE_MAP_NEGATIVE_X;
   if (i == 2) uptarget = GL_TEXTURE_CUBE_MAP_POSITIVE_Y;
   if (i == 3) uptarget = GL_TEXTURE_CUBE_MAP_NEGATIVE_Y;
   if (i == 1) uptarget = GL_TEXTURE_CUBE_MAP_POSITIVE_Z;
   if (i == 0) uptarget = GL_TEXTURE_CUBE_MAP_NEGATIVE_Z;
  } else {
   uptarget = GL_TEXTURE_2D;
  }
  
  // upload texture image
  glTexImage2D(uptarget, 0, intformat, width, height, 0, format, GL_UNSIGNED_BYTE, data);
 }
 */
 
 // copy filename
 filename = fname;
 
 // set flag
 loaded = true;
 
 // success
 return true;
}
Exemple #22
0
// helper function for derived classes
// loads an image and defines an 8-bit RGBA texture
unsigned int
VSResourceLib::loadRGBATexture(std::string filename, 
						bool mipmap, bool compress, 
						GLenum aFilter, GLenum aRepMode) {

	ILboolean success;
	unsigned int imageID;
	GLuint textureID = 0;

	// Load Texture Map
	ilGenImages(1, &imageID); 
	
	ilBindImage(imageID); /* Binding of DevIL image name */
	ilEnable(IL_ORIGIN_SET);
	ilOriginFunc(IL_ORIGIN_LOWER_LEFT); 
	success = ilLoadImage((ILstring)filename.c_str());

	if (!success) {
		VSLOG(sLogError, "Couldn't load texture: %s", 
							filename.c_str());
		// The operation was not sucessfull 
		// hence free image and texture 
		ilDeleteImages(1, &imageID); 
		return 0;
	}

	// add information to the log

	VSLOG(sLogInfo, "Texture Loaded: %s", filename.c_str());
	printf("Width: %d, Height %d, Bytes per Pixel %d", 
				ilGetInteger(IL_IMAGE_WIDTH),
				ilGetInteger(IL_IMAGE_HEIGHT),
				ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL));

	std::string s;
	switch(ilGetInteger(IL_IMAGE_FORMAT)) {
		case IL_COLOR_INDEX      : s =  "IL_COLOR_INDEX"; break;     
		case IL_ALPHA		     : s =  "IL_ALPHA"; break;	
		case IL_RGB              : s =  "IL_RGB"; break;     
		case IL_RGBA             : s =  "IL_RGBA"; break;     
		case IL_BGR              : s =  "IL_BGR"; break;     
		case IL_BGRA             : s =  "IL_BGRA"; break;     
		case IL_LUMINANCE        : s =  "IL_LUMINANCE"; break;     
		case  IL_LUMINANCE_ALPHA : s =  "IL_LUMINANCE_ALPHA"; break;
	}
	printf(" Format %s", s.c_str());
	
	switch(ilGetInteger(IL_IMAGE_TYPE)) {
		case IL_BYTE           : s =  "IL_BYTE"; break;     
		case IL_UNSIGNED_BYTE  : s =  "IL_UNSIGNED_BYTE"; break;	
		case IL_SHORT          : s =  "IL_SHORT"; break;     
		case IL_UNSIGNED_SHORT : s =  "IL_UNSIGNED_SHORT"; break;     
		case IL_INT            : s =  "IL_INT"; break;     
		case IL_UNSIGNED_INT   : s =  "IL_UNSIGNED_INT"; break;     
		case IL_FLOAT          : s =  "IL_FLOAT"; break;     
		case IL_DOUBLE         : s =  "IL_DOUBLE"; break;
		case IL_HALF           : s =  "IL_HALF"; break;
	}
	printf(" Data type:  %s\n", s.c_str());

	/* Convert image to RGBA */
	ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE); 
	// Set filters
	GLenum minFilter = aFilter;
	if (aFilter == GL_LINEAR && mipmap) {
		minFilter = GL_LINEAR_MIPMAP_LINEAR;
	}
	else if (aFilter == GL_NEAREST && mipmap){
		minFilter = GL_NEAREST_MIPMAP_LINEAR;
	}
	GLenum type;
	if (compress)
		type = GL_RGBA;
	else
		type = GL_COMPRESSED_RGBA;


	/* Create and load textures to OpenGL */
	glGenTextures(1, &textureID); /* Texture name generation */
	glBindTexture(GL_TEXTURE_2D, textureID); 
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, aFilter); 
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, aRepMode);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, aRepMode);
	glTexImage2D(GL_TEXTURE_2D, 0, type, 
					ilGetInteger(IL_IMAGE_WIDTH),
					ilGetInteger(IL_IMAGE_HEIGHT), 
					0, GL_RGBA, GL_UNSIGNED_BYTE,
					ilGetData()); 

	// Mipmapping?
	if (mipmap)
		glGenerateMipmap(GL_TEXTURE_2D);

	glBindTexture(GL_TEXTURE_2D,0);

	/* Because we have already copied image data into texture data
	we can release memory used by image. */
	ilDeleteImages(1, &imageID); 


	return textureID;
}
int LoadGLTextures(const aiScene* scene)
{
	ILboolean success;

	/* Before calling ilInit() version should be checked. */
	if (ilGetInteger(IL_VERSION_NUM) < IL_VERSION)
	{
		ILint test = ilGetInteger(IL_VERSION_NUM);
		/// wrong DevIL version ///
		std::string err_msg = "Wrong DevIL version. Old devil.dll in system32/SysWow64?";
		char* cErr_msg = (char *) err_msg.c_str();
		abortGLInit(cErr_msg);
		return -1;
	}

	ilInit(); /* Initialization of DevIL */

	if (scene->HasTextures()) abortGLInit("Support for meshes with embedded textures is not implemented");

	/* getTexture Filenames and Numb of Textures */
	for (unsigned int m=0; m<scene->mNumMaterials; m++)
	{
		int texIndex = 0;
		aiReturn texFound = AI_SUCCESS;

		aiString path;	// filename

		while (texFound == AI_SUCCESS)
		{
			texFound = scene->mMaterials[m]->GetTexture(aiTextureType_DIFFUSE, texIndex, &path);
			textureIdMap[path.data] = NULL; //fill map with textures, pointers still NULL yet
			texIndex++;
		}
	}

	int numTextures = textureIdMap.size();

	/* array with DevIL image IDs */
	ILuint* imageIds = NULL;
	imageIds = new ILuint[numTextures];

	/* generate DevIL Image IDs */
	ilGenImages(numTextures, imageIds); /* Generation of numTextures image names */

	/* create and fill array with GL texture ids */
	textureIds = new GLuint[numTextures];
	glGenTextures(numTextures, textureIds); /* Texture name generation */

	/* define texture path */
	//std::string texturepath = "../../../test/models/Obj/";

	/* get iterator */
	std::map<std::string, GLuint*>::iterator itr = textureIdMap.begin();

	for (int i=0; i<numTextures; i++)
	{

		//save IL image ID
		std::string filename = (*itr).first;  // get filename
		(*itr).second =  &textureIds[i];	  // save texture id for filename in map
		itr++;								  // next texture


		ilBindImage(imageIds[i]); /* Binding of DevIL image name */
		std::string fileloc = basepath + filename;	/* Loading of image */
		success = ilLoadImage(fileloc.c_str());

		if (success) /* If no error occured: */
		{
			success = ilConvertImage(IL_RGB, IL_UNSIGNED_BYTE); /* Convert every colour component into
			unsigned byte. If your image contains alpha channel you can replace IL_RGB with IL_RGBA */
			if (!success)
			{
				/* Error occured */
				abortGLInit("Couldn't convert image");
				return -1;
			}
			//glGenTextures(numTextures, &textureIds[i]); /* Texture name generation */
			glBindTexture(GL_TEXTURE_2D, textureIds[i]); /* Binding of texture name */
			//redefine standard texture values
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); /* We will use linear
			interpolation for magnification filter */
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); /* We will use linear
			interpolation for minifying filter */
			glTexImage2D(GL_TEXTURE_2D, 0, ilGetInteger(IL_IMAGE_BPP), ilGetInteger(IL_IMAGE_WIDTH),
				ilGetInteger(IL_IMAGE_HEIGHT), 0, ilGetInteger(IL_IMAGE_FORMAT), GL_UNSIGNED_BYTE,
				ilGetData()); /* Texture specification */
		}
		else
		{
			/* Error occured */
			MessageBox(NULL, ("Couldn't load Image: " + fileloc).c_str() , "ERROR", MB_OK | MB_ICONEXCLAMATION);
		}


	}

	ilDeleteImages(numTextures, imageIds); /* Because we have already copied image data into texture data
	we can release memory used by image. */

	//Cleanup
	delete [] imageIds;
	imageIds = NULL;

	//return success;
	return TRUE;
}
Exemple #24
0
bool CBitmap::Load(std::string const& filename, unsigned char defaultAlpha)
{
#ifndef BITMAP_NO_OPENGL
	ScopedTimer timer("Textures::CBitmap::Load");
#endif

	bool noAlpha = true;

	delete[] mem;
	mem = NULL;

#ifndef BITMAP_NO_OPENGL
	textype = GL_TEXTURE_2D;
#endif // !BITMAP_NO_OPENGL

	if (filename.find(".dds") != std::string::npos) {
#ifndef BITMAP_NO_OPENGL
		type = BitmapTypeDDS;
		xsize = 0;
		ysize = 0;
		channels = 0;

		ddsimage = new nv_dds::CDDSImage();
		bool status = ddsimage->load(filename);

		if (status) {
			xsize = ddsimage->get_width();
			ysize = ddsimage->get_height();
			channels = ddsimage->get_components();
			switch (ddsimage->get_type()) {
				case nv_dds::TextureFlat :
					textype = GL_TEXTURE_2D;
					break;
				case nv_dds::Texture3D :
					textype = GL_TEXTURE_3D;
					break;
				case nv_dds::TextureCubemap :
					textype = GL_TEXTURE_CUBE_MAP;
					break;
				case nv_dds::TextureNone :
				default :
					break;
			}
		}
		return status;
#else // !BITMAP_NO_OPENGL
		AllocDummy(); //allocate a dummy texture, as dds aren't supported in headless
		return true;
#endif // !BITMAP_NO_OPENGL
	}

	type = BitmapTypeStandardRGBA;
	channels = 4;

	CFileHandler file(filename);
	if (file.FileExists() == false) {
		AllocDummy();
		return false;
	}

	unsigned char* buffer = new unsigned char[file.FileSize() + 2];
	file.Read(buffer, file.FileSize());

	boost::mutex::scoped_lock lck(devilMutex);
	ilOriginFunc(IL_ORIGIN_UPPER_LEFT);
	ilEnable(IL_ORIGIN_SET);

	ILuint ImageName = 0;
	ilGenImages(1, &ImageName);
	ilBindImage(ImageName);

	{
		// do not signal floating point exceptions in devil library
		ScopedDisableFpuExceptions fe;

		const bool success = !!ilLoadL(IL_TYPE_UNKNOWN, buffer, file.FileSize());
		ilDisable(IL_ORIGIN_SET);
		delete[] buffer;

		if (success == false) {
			AllocDummy();
			return false;
		}
	}

	noAlpha = (ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL) != 4);
	ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
	xsize = ilGetInteger(IL_IMAGE_WIDTH);
	ysize = ilGetInteger(IL_IMAGE_HEIGHT);

	mem = new unsigned char[xsize * ysize * 4];
	//ilCopyPixels(0, 0, 0, xsize, ysize, 0, IL_RGBA, IL_UNSIGNED_BYTE, mem);
	memcpy(mem, ilGetData(), xsize * ysize * 4);

	ilDeleteImages(1, &ImageName);

	if (noAlpha) {
		for (int y=0; y < ysize; ++y) {
			for (int x=0; x < xsize; ++x) {
				mem[((y*xsize+x) * 4) + 3] = defaultAlpha;
			}
		}
	}

	return true;
}
Exemple #25
0
// helper function for derived classes
// loads an image and defines an 8-bit RGBA texture
unsigned int
VSResourceLib::loadCubeMapTexture(	std::string posX, std::string negX, 
									std::string posY, std::string negY, 
									std::string posZ, std::string negZ) {

	ILboolean success;
	unsigned int imageID;
	GLuint textureID = 0;

	std::string files[6];

	files[0] = posX;
	files[1] = negX;
	files[2] = posY;
	files[3] = negY;
	files[4] = posZ;
	files[5] = negZ;

	glGenTextures(1, &textureID); /* Texture name generation */
	glBindTexture(GL_TEXTURE_CUBE_MAP, textureID); 

	// Load Textures for Cube Map

	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 
	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S,  GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T,  GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R,  GL_CLAMP_TO_EDGE);

	ilGenImages(1, &imageID); 
	ilBindImage(imageID); /* Binding of DevIL image name */

	for (int i = 0; i < 6; ++i) {
		ilEnable(IL_ORIGIN_SET);
		ilOriginFunc(IL_ORIGIN_LOWER_LEFT); 
		success = ilLoadImage((ILstring)files[i].c_str());

		if (!success) {
			VSLOG(sLogError, "Couldn't load texture: %s", 
								files[i].c_str());
			// The operation was not sucessfull 
			// hence free image and texture 
			ilDeleteImages(1, &imageID); 
			return 0;
		}
		
		/* Convert image to RGBA */
		ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE); 

		/* Create and load textures to OpenGL */
		glTexImage2D(faceTarget[i], 0, GL_RGBA, 
						ilGetInteger(IL_IMAGE_WIDTH),
						ilGetInteger(IL_IMAGE_HEIGHT), 
						0, GL_RGBA, GL_UNSIGNED_BYTE,
						ilGetData()); 

		VSLOG(sLogInfo, "Texture Loaded: %s", files[i].c_str());
	}

	VSLOG(sLogInfo, "Cube Map Loaded Successfully");

	glBindTexture(GL_TEXTURE_CUBE_MAP,0);

	/* Because we have already copied image data into texture data
	we can release memory used by image. */
	ilDeleteImages(1, &imageID); 

	// add information to the log

	return textureID;
}
Exemple #26
0
bool Texture::LoadTexDataFromFile(const std::string &srcFilename)
{
    /*--------------------------------------------------------------------------
     * Load image from file
     */
    unsigned int imageID = 0; // DevIL name for image to load
    ilGenImages(1, &imageID); // Generate 1 slot for image
    ilBindImage(imageID);     // Set slot as current

    if (!ilLoadImage(srcFilename.c_str()))
    {
        std::fprintf(stdout, "Texture::LoadTexDataFromFile: Failed to load texture image for %s from file %s\n", texname_.c_str(), srcFilename.c_str());
        ilDeleteImages(1, &imageID);
        return false;
    }
    if (!ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE))
    {
        std::fprintf(stdout, "Texture::LoadTexDataFromFile: Failed to load convert image for %s from file %s to suitable format\n", texname_.c_str(), srcFilename.c_str());
        ilDeleteImages(1, &imageID);
        return false;
    }

    filename_ = srcFilename;
    // Save image dimensions
    bytedepth_ = ilGetInteger(IL_IMAGE_BPP);
    width_     = ilGetInteger(IL_IMAGE_WIDTH);
    height_    = ilGetInteger(IL_IMAGE_HEIGHT);
    imgFormat_ = ilGetInteger(IL_IMAGE_FORMAT);
    imgType_   = ilGetInteger(IL_IMAGE_TYPE);

    // Massage data if file format is TARGA
    if (filename_.find(".tga", filename_.size() - std::strlen(".tga")) != std::string::npos)
    {
        // Open targa file to read its header
        std::FILE *pFile = fopen(filename_.c_str(), "r");
        if (!pFile)
        {
            std::fprintf(stdout, "Texture::LoadTexDataFromFile: Failed to read TARGA header for %s from file %s\n", texname_.c_str(), filename_.c_str());
            ilDeleteImages(1, &imageID);
            return false;
        }

        // Read targa header
        unsigned char buffer[32] = {0};
        std::fread(buffer, 1, sizeof(buffer), pFile);
        fclose(pFile);

        // Allocate memory for data massaging
        unsigned char* pImgData = new unsigned char[bytedepth_ * width_ * height_];

        /*
         * 18th byte is origin location info. OpenGL expects origin to be at the top left of the image,
         * so the data needs to be massaged if it is located otherwise.
         */
        if (buffer[17] & (1 << 4)) // origin at right side
        {
            std::fprintf(stdout, "origin at right side");
        }
        if (!(buffer[17] & (1 << 5))) // origin at bottom
        {
            unsigned char *pSrc = ilGetData();
            for (size_t i = 0; i < height_; ++i)
            {
                std::memcpy(
                    pImgData + i * width_ * bytedepth_,
                    pSrc + (height_ - i - 1) * width_ * bytedepth_,
                    bytedepth_ * width_);
            }
        }
        else
        {
            std::memcpy(pImgData, ilGetData(), bytedepth_ * width_ * height_);
        }

        // Free any existing texel array
        if (pTexels_)
        {
            delete[] pTexels_;
        }
        pTexels_ = pImgData;
    }
    else
    {
        pTexels_ = new unsigned char[bytedepth_ * width_ * height_];
        std::memcpy(pTexels_, ilGetData(), bytedepth_ * width_ * height_);
    }

    ilDeleteImages(1, &imageID);
    return true;
}
unsigned int sceneLoader::loadTexture(const char* filename)
{
	ILuint imageID;				// Create an image ID as a ULuint
 
	GLuint textureID;			// Create a texture ID as a GLuint
 
	ILboolean success;			// Create a flag to keep track of success/failure
 
	ILenum error;				// Create a flag to keep track of the IL error state
 
	ilGenImages(1, &imageID); 		// Generate the image ID
 
	ilBindImage(imageID); 			// Bind the image
 
	std::stringstream sstm;
	sstm <<  filename;
	//sstm << "../Source/Models/house/" << filename;
	//sstm << "../Source/Models/Thor/" << filename;	
	success = ilLoadImage((const ILstring) &sstm.str()[0]); 	// Load the image file
 
	// If we managed to load the image, then we can start to do things with it...
	if (success)
	{
		// If the image is flipped (i.e. upside-down and mirrored, flip it the right way up!)
	/*	ILinfo ImageInfo;
		iluGetImageInfo(&ImageInfo);
		if (ImageInfo.Origin == IL_ORIGIN_UPPER_LEFT)
		{
			iluFlipImage();
		}*/

		// Convert the image into a suitable format to work with
		// NOTE: If your image contains alpha channel you can replace IL_RGB with IL_RGBA
		success = ilConvertImage(IL_RGB, IL_UNSIGNED_BYTE);
 
		// Quit out if we failed the conversion
		if (!success)
		{
			error = ilGetError();
			std::cout << "Image conversion failed - IL reports error: " << error << " - " << iluErrorString(error) << std::endl;
			exit(-1);
		}
 
		// Generate a new texture
		glGenTextures(1, &textureID);
 
		// Bind the texture to a name
		glBindTexture(GL_TEXTURE_2D, textureID);
 
		// Set texture clamping method
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
 
		// Set texture interpolation method to use linear interpolation (no MIPMAPS)
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
 
		// Specify the texture specification
		glTexImage2D(GL_TEXTURE_2D, 				// Type of texture
					 0,				// Pyramid level (for mip-mapping) - 0 is the top level
					 ilGetInteger(IL_IMAGE_FORMAT),	// Internal pixel format to use. Can be a generic type like GL_RGB or GL_RGBA, or a sized type
					 ilGetInteger(IL_IMAGE_WIDTH),	// Image width
					 ilGetInteger(IL_IMAGE_HEIGHT),	// Image height
					 0,				// Border width in pixels (can either be 1 or 0)
					 ilGetInteger(IL_IMAGE_FORMAT),	// Format of image pixel data
					 GL_UNSIGNED_BYTE,		// Image data type
					 ilGetData());			// The actual image data itself
 	}
  	else // If we failed to open the image file in the first place...
  	{
		error = ilGetError();
		std::cout << "Image load failed - IL reports error: " << error << " - " << iluErrorString(error) << std::endl;
		exit(-1);
  	}
 
 	ilDeleteImages(1, &imageID); // Because we have already copied image data into texture data we can release memory used by image.
 
	std::cout << "Texture creation successful." << std::endl;
 
	return textureID; // Return the GLuint to the texture so you can use it!
}
Exemple #28
0
/*
=================
- Destructor.
=================
*/
cTexture::~cTexture()
{
	ilDeleteImages(1, &ilTextureID);
}
Texture* TextureReaderDevil::loadTexture(const std::string& filename, Texture::Filter filter,
                                         bool compress, bool keepPixels, bool createOGLTex,
                                         bool textureRectangle)
{

#ifndef GL_TEXTURE_RECTANGLE_ARB
    if (textureRectangle){
        LERROR("Texture Rectangles not supported!");
        textureRectangle = false;
    }
#endif

    File* file = FileSys.open(filename);

    // check if file is open
    if (!file || !file->isOpen()) {
        delete file;
        return 0;
    }

    size_t len = file->size();

    // check if file is empty
    if (len == 0) {
        delete file;
        return 0;
    }

    // allocate memory
    char* imdata = new char[len];

    if (imdata == 0) {
        delete file;
        return 0;   // allocation failed
    }

    file->read(imdata, len);

    file->close();
    delete file;

    /*
        FIXME: I think the keepPixels option does not work properly
        -> I don't see why...afaik keepPixels has been used in some project (stefan)
    */
    ILuint ImageName;
    ilGenImages(1, &ImageName);
    ilBindImage(ImageName);
    Texture* t = new Texture();
    t->setName(filename);

    if (!ilLoadL(IL_TYPE_UNKNOWN, imdata, static_cast<ILuint>(len))) {
        LERROR("Failed to open via ilLoadL " << filename);
        delete[] imdata;
        delete t;
        return 0;
    }
    delete[] imdata;
    imdata = 0;

    t->setBpp(ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL));

    // determine image format
    ILint devilFormat;
    switch (ilGetInteger(IL_IMAGE_FORMAT)) {
        case IL_LUMINANCE:         // intensity channel only
            devilFormat = IL_LUMINANCE;
            t->setFormat(GL_LUMINANCE);
            break;
        case IL_LUMINANCE_ALPHA:   // intensity-alpha channels
            devilFormat = IL_LUMINANCE_ALPHA;
            t->setFormat(GL_LUMINANCE_ALPHA);
            break;
        case IL_RGB:
            devilFormat = IL_RGB;  // three color channels
            t->setFormat(GL_RGB);
            break;
        case IL_RGBA:
            devilFormat = IL_RGBA; // color-alpha channels
            t->setFormat(GL_RGBA);
            break;
        case IL_BGR:
            devilFormat = IL_RGB;  // B-G-R ordered color channels, convert to RGB
            t->setFormat(GL_RGB);
            break;
        case IL_BGRA:
            devilFormat = IL_RGBA; // R-G-B-A ordered color channels, convert to RGBA
            t->setFormat(GL_RGBA);
            break;
        default:
            LERROR("unsupported format: " << ilGetInteger(IL_IMAGE_FORMAT) << " (" << filename << ")");
            delete t;
            return 0;
    }

    // determine data type
    ILint devilDataType;
    switch (ilGetInteger(IL_IMAGE_TYPE)) {
    case IL_UNSIGNED_BYTE:
        devilDataType = IL_UNSIGNED_BYTE;
        t->setDataType(GL_UNSIGNED_BYTE);
        break;
    case IL_BYTE:
        devilDataType = IL_BYTE;
        t->setDataType(GL_BYTE);
        break;
    case IL_UNSIGNED_SHORT:
        devilDataType = IL_UNSIGNED_SHORT;
        t->setDataType(GL_UNSIGNED_SHORT);
        break;
    case IL_SHORT:
        devilDataType = IL_SHORT;
        t->setDataType(GL_SHORT);
        break;
    case IL_UNSIGNED_INT:
        devilDataType = IL_UNSIGNED_INT;
        t->setDataType(GL_UNSIGNED_INT);
        break;
    case IL_INT:
        devilDataType = IL_INT;
        t->setDataType(GL_INT);
        break;
    case IL_FLOAT:
        devilDataType = IL_FLOAT;
        t->setDataType(GL_FLOAT);
        break;
    default:
        LERROR("unsupported data type: " << ilGetInteger(IL_IMAGE_TYPE) << " (" << filename << ")");
        delete t;
        return 0;
    }

    if (!ilConvertImage(devilFormat, devilDataType)) {
        LERROR("failed to convert loaded image: " << filename);
        delete t;
        return 0;
    }

    tgt::ivec3 dims;
    dims.x = ilGetInteger(IL_IMAGE_WIDTH);
    dims.y = ilGetInteger(IL_IMAGE_HEIGHT);
    dims.z = ilGetInteger(IL_IMAGE_DEPTH);
    t->setDimensions(dims);
    LDEBUG("Image dimensions: " << t->getDimensions());
    tgtAssert( dims.z == 1, "depth is not equal 1");

#ifdef GL_TEXTURE_RECTANGLE_ARB
    if (textureRectangle)
        t->setType( GL_TEXTURE_RECTANGLE_ARB );
    else
#endif
        t->setType( GL_TEXTURE_2D );

    t->alloc();
    memcpy(t->getPixelData(), ilGetData(), t->getArraySize());

    bool success;
    if (textureRectangle)
        success = createRectangleTexture(t, filter, compress, createOGLTex);
    else {
        if (dims.y == 1)
            success = create1DTexture(t, filter, compress, createOGLTex);
        else
            success = create2DTexture(t, filter, compress, createOGLTex);
    }
    if (!success) {
        ilDeleteImages(1, &ImageName);
        if (!keepPixels)
            t->setPixelData(0);
        delete t;
        return 0;
    }

    ilDeleteImages(1, &ImageName);

    if (!keepPixels) {
        delete[] t->getPixelData();
        t->setPixelData(0);
    }

    return t;
}
Exemple #30
0
int NMS_TextureManager::LoadTexture (const char* sFilename,char* textureName) {
	if(_DEBUG)
	{
		sprintf_s (m_Singleton->m_sMessage, m_Singleton->m_iMessageSize, "NMS_TextureManager::Trying to load [%s]\n", sFilename);
		LOG.write(m_sMessage,LOG_DEBUG);
	}
	if (ilGetInteger(IL_VERSION_NUM) < IL_VERSION)
	  {
		  LOG.write("NMS_TextureManager::Wrong DevIL version!\n",LOG_ERROR);
		  return -1;
	  }
	 
	  //Create the hash on which to compare to see if we have loaded the same two file twice
	  shaMap hash;

	  //Open the file provided and check for the SHA1 hash to see if we have already another texture like this
	  FILE	*fp=NULL;
	  ILubyte *Lump;

	  //Open the texture file
	  fopen_s(&fp,sFilename,"rb");
	  if (!fp)
	  {
		LOG.write("NMS_TextureManager::Cannot open the texture file!\n",LOG_ERROR);
		return -1;
	  }
	 

	  //Calculate the size of the file
	  long fileSize= nmsFileManagement::FileSize(fp);
	  if (fileSize<=0)
	  {
		  LOG.write("NMS_TextureManager::Negative file size for the texture!\n",LOG_ERROR);
		  return -1;
	  }

	  //Convert the file read to a Lump file to be used by DevIL
	  Lump = (ILubyte*)LEVEL_ALLOC->allocMem(fileSize, MEM_TEXTURE);
	  fseek(fp, 0, SEEK_SET);
	  fread(Lump, 1, fileSize, fp);
	  fclose(fp);
	  if(_DEBUG)
			LOG.write("NMS_TextureManager::Lump created correctly!\n",LOG_DEBUG);



	  //Create the sha1
	  hash=nmsSha1::returnSha1(Lump,fileSize);
	  textStruct imageToBeAdded=checkForHash(hash,textureName);

	  GLuint image=NULL;
	  ILuint texid=NULL;
	  //Just a basic check. If both the textID AND the hash are different from NULL that means that 
	  //we have already the texture and we just want to change the name into the map
	  if(imageToBeAdded.textID!=NULL && imageToBeAdded.hash!=NULL)
	  {
		  textureMap[textureName]=imageToBeAdded;
		  image=textureMap[textureName].textID;
	  }
	  else
	  {
		  //It's the same texture with the same name, do nothing!
		  if(imageToBeAdded.textID==NULL && imageToBeAdded.hash!=NULL)
		  {
			  image=textureMap[textureName].textID;
		  }
		  //It's a different texture with the same name, warn the user and exit
		  else if(imageToBeAdded.textID==-1)
			    {throw 0;}
		  else
			  {
				  //It's a new image, load it
				  ILboolean success;
				  ilInit(); // Initialization of DevIL 
				  ilGenImages(1, &texid); // Generation of one image name 
				  ilBindImage(texid); // Binding of image name
				  success = ilLoadL(IL_TYPE_UNKNOWN,Lump,fileSize); // Loading of image "image.jpg"   //USA iLoadImageF
				  //free(Lump);
				  

				  if (success) // If no error occured: 
				  {
					success = ilConvertImage(IL_RGB, IL_UNSIGNED_BYTE); // Convert every colour component into
					  // unsigned byte. If your image contains alpha channel you can replace IL_RGB with IL_RGBA 
					if (!success)
					{
						LOG.write("NMS_TextureManager::Error in converting the texture in the proper format!\n",LOG_ERROR);
						ilDeleteImages(1, &texid);					 
						// Error occured 
						return -1;
					}


					//Create the new image
					glGenTextures(1, &image); // Texture name generation 
					
					 glBindTexture(GL_TEXTURE_2D, image);
					glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 
					// We will use linear interpolation for magnification filter 
					glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 
					// We will use linear interpolation for minifying filter 
					glTexImage2D(GL_TEXTURE_2D, 0, ilGetInteger(IL_IMAGE_BPP), ilGetInteger(IL_IMAGE_WIDTH),
					ilGetInteger(IL_IMAGE_HEIGHT), 0, ilGetInteger(IL_IMAGE_FORMAT), GL_UNSIGNED_BYTE,
					ilGetData()); // Texture specification 


					if(_DEBUG)
						LOG.write("NMS_TextureManager::Texture loaded from Lump!\n",LOG_DEBUG);
				  }
				  else
				  {
					// Error occured 
					LOG.write("NMS_TextureManager::Error in loading the texture from the Lump!\n",LOG_ERROR);
					ilDeleteImages(1, &texid);
					return -1;
				  }
			  }
	  }
	  //Pick the image that has been created to be used in our context
	  textureMap[textureName].textID=image;
	  textureMap[textureName].hash=hash;

	  if(_DEBUG)
	  {
		 sprintf_s (m_Singleton->m_sMessage, m_Singleton->m_iMessageSize, "NMS_TextureManager::Loaded [%s] without issues!\n", sFilename);
		 LOG.write(m_sMessage,LOG_DEBUG);
	  }
	 

	  //glBindTexture(GL_TEXTURE_2D, image); // Binding of texture name 
      ilDeleteImages(1, &texid);
	  //Close the file we are done with it
	  fclose(fp);
	  cerr << "Texture id" << textureMap[textureName].textID;
	  return textureMap[textureName].textID;
	  
	  return textureMap[textureName].textID;
}