Exemplo n.º 1
0
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;
}
Exemplo n.º 2
0
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!
}
Exemplo n.º 3
0
ILuint ImageManager::GenerateGradientImage(ILuint TextureDevILID, int16_t PrimaryColorID, int16_t SecondaryColorID, int16_t BorderColorID)
{
    ILuint TextureImageID;
    ilGenImages(1, &TextureImageID);
    ilBindImage(TextureImageID);
    ilCopyImage(TextureDevILID);
    ilConvertImage(IL_LUMINANCE, IL_UNSIGNED_BYTE);  //Load as IL_LUMINANCE to avoid convertion?

    uint8_t* TextureImageData = ilGetData();
    uint32_t width = ilGetInteger(IL_IMAGE_WIDTH);
    uint32_t height = ilGetInteger(IL_IMAGE_HEIGHT);

    ILuint MaskImageID;
    ilGenImages(1, &MaskImageID);
    ilBindImage(MaskImageID);
    ilTexImage(width, height, 1, 4, IL_BGRA, IL_UNSIGNED_BYTE, NULL);
    uint8_t* MaskImageData = ilGetData();

    ColorData* PrimaryColor = DATA->getColorData(PrimaryColorID);
    ColorData* SecondaryColor = DATA->getColorData(SecondaryColorID);

    uint32_t bpp = ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL);
    if(SecondaryColor != NULL)
    {
        for(uint32_t i = 0; i < width; i++)
        {
            for(uint32_t j = 0; j < height; j++)
            {
                MaskImageData[(i * width * bpp) + (j * bpp) + 0] = SecondaryColor->getBlue();     // Blue
                MaskImageData[(i * width * bpp) + (j * bpp) + 1] = SecondaryColor->getGreen();    // Green
                MaskImageData[(i * width * bpp) + (j * bpp) + 2] = SecondaryColor->getRed();      // Red
                MaskImageData[(i * width * bpp) + (j * bpp) + 3] = 255 - TextureImageData[(i * width) + j]; // Alpha
            }
        }
    }

    ILuint NewImageID;
    ilGenImages(1, &NewImageID);
    ilBindImage(NewImageID);
    ilTexImage(width, height, 1, 4, IL_BGRA, IL_UNSIGNED_BYTE, NULL);
    uint8_t* NewImageData = ilGetData();

    if(PrimaryColor != NULL)
    {
        for(uint32_t i = 0; i < width; i++)
        {
            for(uint32_t j = 0; j < height; j++)
            {
                NewImageData[(i * width * bpp) + (j * bpp) + 0] = PrimaryColor->getBlue(); // Blue
                NewImageData[(i * width * bpp) + (j * bpp) + 1] = PrimaryColor->getGreen(); // Green
                NewImageData[(i * width * bpp) + (j * bpp) + 2] = PrimaryColor->getRed(); // Red
                NewImageData[(i * width * bpp) + (j * bpp) + 3] = 255; // Alpha
            }
        }
    }

    ilOverlayImage(MaskImageID, 0, 0, 0);

    if (BorderColorID != -1)
    {
        ApplyBorder(NewImageID, BorderColorID);
    }

    return NewImageID;
}
Exemplo n.º 4
0
SMFMap::SMFMap(std::string smfname)
{
  std::vector<ILuint> tiles_images;
  std::vector<std::string> tile_files;
  metalmap = NULL;
  heightmap = NULL;
  typemap = NULL;
  minimap = NULL;
  vegetationmap = NULL;
  m_tiles = NULL;
  FILE * smffile = fopen(smfname.c_str(),"rb");
  if ( !smffile )
  {
    throw CannotLoadSmfFileException();
    
  }
  SMFHeader hdr;
  fread(&hdr,sizeof(hdr),1,smffile);
  if ( strncmp(hdr.magic,"spring map file",15) > 0 )
  {
    fclose(smffile);
    throw InvalidSmfFileException();
  }
  mapx = hdr.mapx;
  mapy = hdr.mapy;
  m_minh = hdr.minHeight;
  m_maxh = hdr.maxHeight;
  m_smfname = smfname;
  m_doclamp = true;
  m_th = 0;
  m_comptype = COMPRESS_REASONABLE;
  m_smooth = false;
  texture = new Image();
  texture->AllocateRGBA((mapx/128)*1024,(mapy/128)*1024);
  std::cout << "Loading metal map..." << std::endl;
  metalmap = new Image();
  metalmap->AllocateLUM(mapx/2,mapy/2);
  fseek(smffile,hdr.metalmapPtr,SEEK_SET);
  fread(metalmap->datapointer,mapx/2*mapy/2,1,smffile);
  
  
  std::cout << "Loading heightmap..." << std::endl;
  heightmap = new Image();
  heightmap->AllocateLUM(mapx+1,mapy+1);
  heightmap->ConvertToLUMHDR();//TODO: Allocate directly HDR
  fseek(smffile,hdr.heightmapPtr,SEEK_SET);
  fread(heightmap->datapointer,(mapx+1)*(mapy+1)*2,1,smffile);
  heightmap->FlipVertical();
  
  std::cout << "Loading type map..." << std::endl;
  typemap = new Image();
  typemap->AllocateLUM(mapx/2,mapy/2);
  fseek(smffile,hdr.typeMapPtr,SEEK_SET);
  fread(typemap->datapointer,mapx/2*mapy/2,1,smffile);
  typemap->FlipVertical();
  
  std::cout << "Loading minimap..." << std::endl;
  minimap = new Image();
  uint8_t * dxt1data = new uint8_t[699064];
  fseek(smffile,hdr.minimapPtr,SEEK_SET);
  fread(dxt1data,699064,1,smffile);
  ilBindImage(minimap->image);
  ilTexImageDxtc(1024,1024,1,IL_DXT1,dxt1data);
  ilDxtcDataToImage();
  std::cout << "Extracting main texture..." << std::endl;
  int *tilematrix = new int[mapx/4 * mapy/4];
  
  fseek(smffile,hdr.tilesPtr,SEEK_SET);
  MapTileHeader thdr;
  fread(&thdr,sizeof(thdr),1,smffile);
  while ( tile_files.size() < thdr.numTileFiles )
  {
    tile_files.push_back("");
    char byte;
    int numtiles;
    fread(&numtiles,4,1,smffile);
    fread(&byte,1,1,smffile);
    while ( byte != 0 )
    {
      tile_files[tile_files.size()-1].append(1,byte);
      fread(&byte,1,1,smffile);
    }
  }
  for ( std::vector<std::string>::iterator it = tile_files.begin(); it != tile_files.end(); it++ )
  {
    std::cout << "Opening " << *it << std::endl;
    FILE* smtfile = fopen((*it).c_str(),"rb");
    if ( !smtfile )
    {
      fclose(smffile);
      delete [] tilematrix;
      throw CannotOpenSmtFileException();
    }
    TileFileHeader smthdr;
    fread(&smthdr,sizeof(smthdr),1,smtfile);
    if ( strncmp(smthdr.magic,"spring tilefile",14) )
    {
      fclose(smffile);
      fclose(smtfile);
      delete [] tilematrix;
      throw InvalidSmtFileException();
    }
    for ( int i = 0; i < smthdr.numTiles; i++ )
    {
      ILuint tile = ilGenImage();
      fread(dxt1data,680,1,smtfile);
      ilBindImage(tile);
      ilTexImageDxtc(32,32,1,IL_DXT1,dxt1data);
      ilDxtcDataToImage();
      tiles_images.push_back(tile);
    }
    fclose(smtfile);
    
    
  }
  std::cout << "Tiles @ " << ftell(smffile) << std::endl;
  fread(tilematrix,mapx/4 * mapy/4 * 4,1,smffile);
  ilBindImage(texture->image);
  unsigned int * texdata = (unsigned int *)ilGetData();
  std::cout << "Blitting tiles..." << std::endl;
  for ( int y = 0; y < mapy/4; y++ )
  {
    std::cout << "Row " << y << " of " << mapy/4 << std::endl;
    for ( int x = 0; x < mapx/4; x++ )
    {
      if ( tilematrix[y*(mapx/4)+x] >= tiles_images.size() )
      {
	std::cerr << "Warning: tile " << tilematrix[y*(mapx/4)+x] << " out of range" << std::endl;
	continue;
      }
      //ilBlit(tiles_images[tilematrix[y*(mapx/4)+x]],x*32,y*32,0,0,0,0,32,32,1);
      ilBindImage(tiles_images[tilematrix[y*(mapx/4)+x]]);
      unsigned int * data = (unsigned int *)ilGetData();
      int r2 = 0;
      for ( int y2 = y*32; y2 < y*32+32; y2++ )//FAST blitting
      {
	/*for ( int x2 = y*32; x2 < y*32+32; x2++ )
	{
	  
	  
	}*/
	memcpy(&texdata[y2*texture->w+x*32],&data[r2*32],32*4);
	r2++;
      }
    }
    
  }
  texture->FlipVertical();
  
  
  std::cout << "Loading features..." << std::endl;
  
  fseek(smffile,hdr.featurePtr,SEEK_SET);
  MapFeatureHeader mfhdr;
  fread(&mfhdr,sizeof(mfhdr),1,smffile);
  //-32767.0f+f->rotation/65535.0f*360
  
  std::vector<std::string> feature_types;
  while ( feature_types.size() < mfhdr.numFeatureType )
  {
    feature_types.push_back("");
    char byte;
    fread(&byte,1,1,smffile);
    while ( byte != 0 )
    {
      feature_types[feature_types.size()-1].append(1,byte);
      fread(&byte,1,1,smffile);
    }
  }
  for ( int i = 0; i < mfhdr.numFeatures; i++ )
  {
    MapFeatureStruct f;
    fread(&f,sizeof(f),1,smffile);
    if ( f.featureType >= feature_types.size() )
    {
      std::cerr << "Warning: invalid feature type " << f.featureType << std::endl;
      continue;
    }
    AddFeature(feature_types[f.featureType],f.xpos,f.ypos,f.zpos,-32767.0f+f.rotation/65535.0f*360);
    
  }
  fclose(smffile);
  delete [] dxt1data;
  delete [] tilematrix;
}
Exemplo n.º 5
0
GLuint Renderer::loadTexture(const std::string &fname)
{
	ILuint imageID;
	GLuint textureID;
	ILboolean success;
	ILenum error;
	ilGenImages(1, &imageID); 
	ilBindImage(imageID); 
	success = ilLoadImage(fname.c_str());
	if (success)
	{
		ILinfo ImageInfo;
		iluGetImageInfo(&ImageInfo);
		if (ImageInfo.Origin == IL_ORIGIN_UPPER_LEFT)
		{
			iluFlipImage();
		}
	
		success = ilConvertImage(IL_RGB, IL_UNSIGNED_BYTE);

		if (!success)
		{
			error = ilGetError();
			return 0;
		}

		glGenTextures(1, &textureID);
		glBindTexture(GL_TEXTURE_2D, textureID);
		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_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexImage2D(GL_TEXTURE_2D, 0, ilGetInteger(IL_IMAGE_FORMAT), ilGetInteger(IL_IMAGE_WIDTH), ilGetInteger(IL_IMAGE_HEIGHT), 0, ilGetInteger(IL_IMAGE_FORMAT), GL_UNSIGNED_BYTE, ilGetData());
	}
	else
	{
		error = ilGetError();
		return 0;
	}

	ilDeleteImages(1, &imageID);
	return textureID;
}
Exemplo n.º 6
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;
}
Exemplo n.º 7
0
int GLText::LoadFont(char* fname, int Width, int Height)
{
	ScreenWidth = Width;
	ScreenHeight = Height;
	
	unsigned img;
	ilGenImages(1, &img);
	ilBindImage(img);
	if (ilLoadImage(fname) == false)
	{
		printf("Cannot load image file %s - %d\n", fname, ilGetError());
		return 1;
	}
	
	glGenTextures(1, &fontTexture);
	glBindTexture(GL_TEXTURE_2D, fontTexture);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, ilGetInteger(IL_IMAGE_WIDTH), ilGetInteger(IL_IMAGE_HEIGHT), 0, ilGetInteger(IL_IMAGE_FORMAT), GL_UNSIGNED_BYTE, ilGetData());
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	
	ilDeleteImages(1, &img);
	
	char data[256];
	memset(data, 0, 256);
	strcpy(data, fname);
	int len = strlen(data);
	
	data[len] = 0;
	data[len - 1] = 't';
	data[len - 2] = 'a';
	data[len - 3] = 'd';
	
	FILE* f = 0;
	f = fopen(data, "rb");
	if (!f)
	{
		printf("Cannot load character spacing file %s", data);
		return 1;
	}

	fread(charSpace, 1, 256, f);
	fclose(f);
	
	return 0;
}
Exemplo n.º 8
0
	void GraphicsCore::GenerateTexture(std::string path){
		ILuint texid;
		GLuint tex;
		ilGenImages(1,&texid);
		ilBindImage(texid);

		if(ilLoadImage(path.c_str())){
				std::cout<<"texture "<<path<<" loaded\n";
				ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);

		}else{
			std::cout << "Problems converting image" <<path<<"\n";
		}

		glGenTextures(1,&tex);
		glBindTexture(GL_TEXTURE_2D, tex);

		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

		glTexImage2D(GL_TEXTURE_2D, 0, ilGetInteger(IL_IMAGE_BPP), ilGetInteger(IL_IMAGE_WIDTH), ilGetInteger(IL_IMAGE_HEIGHT), 0, IL_RGBA,GL_UNSIGNED_BYTE, ilGetData());

		ilDeleteImage(texid);

		TextureDatabase.insert(std::pair<std::string,GLuint>(path,tex));
	}
GLuint ReadTexture()
{
	GLuint tex;
	glGenTextures(1, &tex);
	glBindTexture(GL_TEXTURE_2D, tex);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

	ILuint img;
	ilInit();
	ilGenImages(1, &img);
	ilBindImage(img);

	ILboolean success = ilLoadImage((const ILstring)"gv2.png");

	if(success)
	{
		success = ilConvertImage(IL_RGBA,IL_UNSIGNED_BYTE);
		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());
	}

	ilDeleteImages(1, &img);

	return tex;
}
Exemplo n.º 10
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;
}
Exemplo n.º 11
0
GLuint TextureUtils::createTexture(const GLchar *path){
   ilInit();
   ILuint image = ilGenImage();

   ilBindImage(image);

   ILboolean loadSuccess = ilLoadImage(path);
   if(!loadSuccess){
      std::cerr<<"Failed to load image: "<<path<<std::endl;
      ilBindImage(NULL);
      ilDeleteImage(image);
      return NULL;
   }

   ILboolean convertSuccess = ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
   if(!convertSuccess){
      std::cerr<<"Failed to convert image: "<<path<<std::endl;
      ilBindImage(NULL);
      ilDeleteImage(image);
      return NULL;
   }

   GLuint texture;
   glGenTextures(1, &texture);
   glBindTexture(GL_TEXTURE_2D, texture);

   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);


   glTexImage2D(GL_TEXTURE_2D, 0, ilGetInteger(IL_IMAGE_FORMAT), ilGetInteger(IL_IMAGE_WIDTH), ilGetInteger(IL_IMAGE_HEIGHT), 0, ilGetInteger(IL_IMAGE_FORMAT), ilGetInteger(IL_IMAGE_TYPE), ilGetData());
   glBindTexture(GL_TEXTURE_2D, NULL);

   ilBindImage(NULL);
   ilDeleteImage(image);

   return texture;
}
Exemplo n.º 12
0
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;
			}
		}
	}
}
Exemplo n.º 13
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;
}
Exemplo n.º 14
0
 bool Texture1D::loadFromFile(const std::string& filename, I32 filter, I32 wrapMode, bool mipmap)
 {
     UI32 image, texSize;
     
     // Load Image
     ILDEBUG(ilGenImages(1, &image));
     ILDEBUG(ilBindImage(image));
     bool success = ILDEBUG(ilLoadImage(filename.c_str()));
     
     if(success)
     {
         m_name = filename;
         
         UI32 texWidth = ILDEBUG(ilGetInteger(IL_IMAGE_WIDTH));
         UI32 texHeight = ILDEBUG(ilGetInteger(IL_IMAGE_HEIGHT));
         texSize = texWidth * texHeight;
         ILDEBUG(ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE));
         
         UI8 *textureData = ILDEBUG(ilGetData());
         
         I32 minFilter;
         if (filter == ODIN_LINEAR && mipmap)
         {
             minFilter = ODIN_LINEAR_MIPMAP_LINEAR;
         }
         else if (filter == ODIN_NEAREST && mipmap)
         {
             minFilter = ODIN_NEAREST_MIPMAP_LINEAR;
         }
         
         success = loadFromMemory(texSize,
                                  ODIN_RGBA,
                                  ODIN_RGBA,
                                  ODIN_UNSIGNED_BYTE,
                                  minFilter,
                                  filter,
                                  wrapMode,
                                  textureData,
                                  mipmap);
         
         UI32 bytesPerPixel = ILDEBUG(ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL));
         
         std::string imageFormat;
         UI32 imgFormat = ILDEBUG(ilGetInteger(IL_IMAGE_FORMAT));
         switch(imgFormat)
         {
             case IL_COLOR_INDEX      : imageFormat =  "IL_COLOR_INDEX"; break;
             case IL_ALPHA		     : imageFormat =  "IL_ALPHA"; break;
             case IL_RGB              : imageFormat =  "IL_RGB"; break;
             case IL_RGBA             : imageFormat =  "IL_RGBA"; break;
             case IL_BGR              : imageFormat =  "IL_BGR"; break;
             case IL_BGRA             : imageFormat =  "IL_BGRA"; break;
             case IL_LUMINANCE        : imageFormat =  "IL_LUMINANCE"; break;
             case  IL_LUMINANCE_ALPHA : imageFormat =  "IL_LUMINANCE_ALPHA"; break;
         }
         
         std::string imageType;
         UI32 imgType = ILDEBUG(ilGetInteger(IL_IMAGE_TYPE));
         switch(imgType)
         {
             case IL_BYTE           : imageType =  "IL_BYTE"; break;
             case IL_UNSIGNED_BYTE  : imageType =  "IL_UNSIGNED_BYTE"; break;
             case IL_SHORT          : imageType =  "IL_SHORT"; break;
             case IL_UNSIGNED_SHORT : imageType =  "IL_UNSIGNED_SHORT"; break;
             case IL_INT            : imageType =  "IL_INT"; break;
             case IL_UNSIGNED_INT   : imageType =  "IL_UNSIGNED_INT"; break;
             case IL_FLOAT          : imageType =  "IL_FLOAT"; break;
             case IL_DOUBLE         : imageType =  "IL_DOUBLE"; break;
             case IL_HALF           : imageType =  "IL_HALF"; break;
         }
         
         LOG_INFO("DEVIL: Image texture successfully loaded: %s\n"
                  "Width: %d, Height: %d, Bytes per Pixel: %d\n"
                  "Format: %s, Data type: %s"
                  , filename.c_str(), texWidth, texHeight, bytesPerPixel, imageFormat.c_str(), imageType.c_str());
     }
     else
     {
         m_name = "Default";
         
         LOG_ERROR("DEVIL: Could not load image: %s. Switching to default texture", filename.c_str());
         texSize = 1;
         
         UI8 data[] = {255,255,255,255};
         
         success = loadFromMemory(texSize,
                                  ODIN_RGBA,
                                  ODIN_RGBA,
                                  ODIN_UNSIGNED_BYTE,
                                  ODIN_NEAREST,
                                  ODIN_NEAREST,
                                  ODIN_CLAMP_TO_EDGE,
                                  data,
                                  false);
     }
     
     ILDEBUG(ilDeleteImages(1, &image));
     
     return success;
 }
Exemplo n.º 15
0
		//---------------------------------------------------------------------
		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());
			}
		}
Exemplo n.º 16
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;
}
Exemplo n.º 17
0
    //-----------------------------------------------------------------------
    void ILUtil::fromOgre(const PixelBox &src)
    {
		// ilTexImage http://openil.sourceforge.net/docs/il/f00059.htm
		ILFormat ifmt = OgreFormat2ilFormat( src.format );
		if(src.isConsecutive() && ifmt.isValid()) 
		{
			// The easy case, the buffer is laid out in memory just like 
			// we want it to be and is in a format DevIL can understand directly
			// We could even save the copy if DevIL would let us
			ilTexImage(static_cast<ILuint>(src.getWidth()), 
				static_cast<ILuint>(src.getHeight()), 
				static_cast<ILuint>(src.getDepth()), ifmt.numberOfChannels,
				ifmt.format, ifmt.type, src.data);
		} 
		else if(ifmt.isValid()) 
		{
			// The format can be understood directly by DevIL. The only 
			// problem is that ilTexImage expects our image data consecutively 
			// so we cannot use that directly.
			
			// Let DevIL allocate the memory for us, and copy the data consecutively
			// to its memory
			ilTexImage(static_cast<ILuint>(src.getWidth()), 
				static_cast<ILuint>(src.getHeight()), 
				static_cast<ILuint>(src.getDepth()), ifmt.numberOfChannels,
				ifmt.format, ifmt.type, 0);
			PixelBox dst(src.getWidth(), src.getHeight(), src.getDepth(), src.format, ilGetData());
			PixelUtil::bulkPixelConversion(src, dst);
		} 
		else 
		{
			// Here it gets ugly. We're stuck with a pixel format that DevIL
			// can't do anything with. We will do a bulk pixel conversion and
			// then feed it to DevIL anyway. The problem is finding the best
			// format to convert to.
			
			// most general format supported by OGRE and DevIL
			PixelFormat fmt = PixelUtil::hasAlpha(src.format)?PF_FLOAT32_RGBA:PF_FLOAT32_RGB; 

			// Make up a pixel format
			// We don't have to consider luminance formats as they have
			// straight conversions to DevIL, just weird permutations of RGBA an LA
			int depths[4];
			PixelUtil::getBitDepths(src.format, depths);
			
			// Native endian format with all bit depths<8 can safely and quickly be 
			// converted to 24/32 bit
			if(PixelUtil::isNativeEndian(src.format) && 
				depths[0]<=8 && depths[1]<=8 && depths[2]<=8 && depths[3]<=8) {
				if(PixelUtil::hasAlpha(src.format)) {
					fmt = PF_A8R8G8B8;
				} else {
					fmt = PF_R8G8B8;
				}
			}
			
			// Let DevIL allocate the memory for us, then do the conversion ourselves
			ifmt = OgreFormat2ilFormat( fmt );
			ilTexImage(static_cast<ILuint>(src.getWidth()), 
				static_cast<ILuint>(src.getHeight()), 
				static_cast<ILuint>(src.getDepth()), ifmt.numberOfChannels,
				ifmt.format, ifmt.type, 0);
			PixelBox dst(src.getWidth(), src.getHeight(), src.getDepth(), fmt, ilGetData());
			PixelUtil::bulkPixelConversion(src, dst);
		}
    }
Exemplo n.º 18
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;
}
Exemplo n.º 19
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;
}
Exemplo n.º 20
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;
}
Exemplo n.º 21
0
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;
}
Exemplo n.º 22
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;
			}
		}
	}
}
Exemplo n.º 23
0
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); 
	}
	
}
Exemplo n.º 24
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;
}
Exemplo n.º 25
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;
}
Exemplo n.º 26
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;
    }
}
Exemplo n.º 27
0
uint8_t* ImageManager::getImageData(ILuint DevilImageID)
{
    ilBindImage(DevilImageID);
    return ilGetData();
}
Exemplo n.º 28
0
void init() {

    bancAlto  = new BancoAlto(0.6);
    bancBalc = new BancoBalcao(0.8);
    bar = Bar(1);
    copoV=copo_vinho(0.025);
    copoL=copo_largo(0.025);
    flt=flute(0.035);
    mesaQ=new MesaQuadrada(0.5,0.2);
    mesaR=new MesaRedonda(0.4);
    sofa=new Sofa(0.7,2);
    bil=new Bilhar(0.7);
    cBilhar=new CandeeiroBilhar(2,0.2);
    balcao=new Balcao(5,0.6,2);
    cLuz=new CandeeiroLuz(0.1);
    garr=new GarrafaAgua(0.2);
    garW=new GarrafaWhisky(0.2);
    porta=new Plano(0.5,1,10,20);

    GLfloat fLargest;
    glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &fLargest);

    ILuint ima[N_TEX];

    ilInit();
    ilGenImages(N_TEX,ima);
    glGenTextures(N_TEX,tex);

    int imagew,imageh;

    ilBindImage(ima[MADEIRA_TEX]);
    ilLoadImage((ILstring)"madeira_tex.jpg");
    ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
    imagew=ilGetInteger(IL_IMAGE_WIDTH);
    imageh=ilGetInteger(IL_IMAGE_HEIGHT);
    imageData[MADEIRA_TEX]=ilGetData();
    glBindTexture(GL_TEXTURE_2D,tex[MADEIRA_TEX]);
    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_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, fLargest);
    gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, imagew, imageh, GL_RGBA, GL_UNSIGNED_BYTE, imageData[MADEIRA_TEX]);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_BASE_LEVEL,0);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAX_LEVEL,10);

    ilBindImage(ima[TECIDO_SOFA_TEX]);
    ilLoadImage((ILstring)"tecido_sofa_tex.jpg");
    ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
    imagew=ilGetInteger(IL_IMAGE_WIDTH);
    imageh=ilGetInteger(IL_IMAGE_HEIGHT);
    imageData[TECIDO_SOFA_TEX]=ilGetData();
    glBindTexture(GL_TEXTURE_2D,tex[TECIDO_SOFA_TEX]);
    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_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, fLargest);
    gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, imagew, imageh, GL_RGBA, GL_UNSIGNED_BYTE, imageData[TECIDO_SOFA_TEX]);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_BASE_LEVEL,0);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAX_LEVEL,10);

    ilBindImage(ima[CHAO_TEX]);
    ilLoadImage((ILstring)"madeira_tex_alt.jpg");
    ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
    imagew=ilGetInteger(IL_IMAGE_WIDTH);
    imageh=ilGetInteger(IL_IMAGE_HEIGHT);
    imageData[CHAO_TEX]=ilGetData();
    glBindTexture(GL_TEXTURE_2D,tex[CHAO_TEX]);
    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_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, fLargest);
    gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, imagew, imageh, GL_RGBA, GL_UNSIGNED_BYTE, imageData[CHAO_TEX]);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_BASE_LEVEL,0);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAX_LEVEL,10);

    ilBindImage(ima[PAREDES_TEX]);
    ilLoadImage((ILstring)"parede_tex.jpg");
    ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
    imagew=ilGetInteger(IL_IMAGE_WIDTH);
    imageh=ilGetInteger(IL_IMAGE_HEIGHT);
    imageData[PAREDES_TEX]=ilGetData();
    glBindTexture(GL_TEXTURE_2D,tex[PAREDES_TEX]);
    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_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, fLargest);
    gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, imagew, imageh, GL_RGBA, GL_UNSIGNED_BYTE, imageData[PAREDES_TEX]);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_BASE_LEVEL,0);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAX_LEVEL,10);

    ilBindImage(ima[BALCAO_TAMPO_TEX]);
    ilLoadImage((ILstring)"balcao_tampo_tex.jpg");
    ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
    imagew=ilGetInteger(IL_IMAGE_WIDTH);
    imageh=ilGetInteger(IL_IMAGE_HEIGHT);
    imageData[BALCAO_TAMPO_TEX]=ilGetData();
    glBindTexture(GL_TEXTURE_2D,tex[BALCAO_TAMPO_TEX]);
    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_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, fLargest);
    gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, imagew, imageh, GL_RGBA, GL_UNSIGNED_BYTE, imageData[BALCAO_TAMPO_TEX]);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_BASE_LEVEL,0);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAX_LEVEL,10);

    ilBindImage(ima[BANCO_TAMPO_TEX]);
    ilLoadImage((ILstring)"banco_tampo_tex.png");
    ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
    imagew=ilGetInteger(IL_IMAGE_WIDTH);
    imageh=ilGetInteger(IL_IMAGE_HEIGHT);
    imageData[BANCO_TAMPO_TEX]=ilGetData();
    glBindTexture(GL_TEXTURE_2D,tex[BANCO_TAMPO_TEX]);
    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_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, fLargest);
    gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, imagew, imageh, GL_RGBA, GL_UNSIGNED_BYTE, imageData[BANCO_TAMPO_TEX]);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_BASE_LEVEL,0);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAX_LEVEL,10);

    ilBindImage(ima[PORTA_TEX]);
    ilLoadImage((ILstring)"porta_tex.jpg");
    ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
    imagew=ilGetInteger(IL_IMAGE_WIDTH);
    imageh=ilGetInteger(IL_IMAGE_HEIGHT);
    imageData[PORTA_TEX]=ilGetData();
    glBindTexture(GL_TEXTURE_2D,tex[PORTA_TEX]);
    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_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, fLargest);
    gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, imagew, imageh, GL_RGBA, GL_UNSIGNED_BYTE, imageData[PORTA_TEX]);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_BASE_LEVEL,0);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAX_LEVEL,10);

    //Create the shadow map texture
    glGenTextures(1, &shadowMapTexture);
    glBindTexture(GL_TEXTURE_2D, shadowMapTexture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    //Enable shadow comparison
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE_ARB, GL_COMPARE_R_TO_TEXTURE);
    //Shadow comparison should be true (ie not in shadow) if r<=texture
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC_ARB, GL_LEQUAL);
    glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE_ARB, GL_ALPHA);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, shadowMapSize, shadowMapSize, 0,GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);

    //Load identity modelview
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    //Shading states
    glShadeModel(GL_SMOOTH);
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);

    glGenFramebuffers(1,&mFBO);
    glBindFramebuffer(GL_DRAW_FRAMEBUFFER, mFBO);
    glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, shadowMapTexture, 0);

    glGenTextures(2, aaTexture);

    glBindTexture(GL_TEXTURE_2D, aaTexture[0]);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, AA_LEVEL*wWidth, AA_LEVEL*wHeight, 0,GL_RGBA, GL_UNSIGNED_BYTE, NULL);

    glBindTexture(GL_TEXTURE_2D, aaTexture[1]);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, AA_LEVEL*wWidth, AA_LEVEL*wHeight, 0,GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);

    glGenFramebuffers(1,&aaFBO);
    glBindFramebuffer(GL_DRAW_FRAMEBUFFER, aaFBO);
    glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, aaTexture[0], 0);
    glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER,GL_DEPTH_ATTACHMENT,GL_TEXTURE_2D, aaTexture[1],0);

    glGenTextures(1, &aaAuxTexture);
    glBindTexture(GL_TEXTURE_2D, aaAuxTexture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, AA_LEVEL*wWidth/2, AA_LEVEL*wHeight/2, 0,GL_RGBA, GL_UNSIGNED_BYTE, NULL);

    glGenFramebuffers(1,&aaAuxFBO);
    glBindFramebuffer(GL_DRAW_FRAMEBUFFER, aaAuxFBO);
    glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, aaAuxTexture, 0);

    // Disable writes to the color buffer
    glDrawBuffer(GL_NONE);

    //Depth states
    glClearDepth(1.0f);
    glDepthFunc(GL_LEQUAL);


    //We use glScale when drawing the scene
    glEnable(GL_NORMALIZE);

// alguns settings para OpenGL
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    glEnable(GL_TEXTURE_2D);

    glBindTexture(GL_TEXTURE_2D,0);
}
Exemplo n.º 29
0
ILuint ImageManager::GeneratedOverLayImage(ILuint TextureDevILID, int16_t PrimaryColorID, int16_t BorderColorID)
{
    ILuint TextureImageID;
    ilGenImages(1, &TextureImageID);
    ilBindImage(TextureImageID);
    ilCopyImage(TextureDevILID);
    ilConvertImage(IL_LUMINANCE_ALPHA, IL_UNSIGNED_BYTE);

    uint8_t* TextureImageData = ilGetData();
    uint32_t width = ilGetInteger(IL_IMAGE_WIDTH);
    uint32_t height = ilGetInteger(IL_IMAGE_HEIGHT);

    ColorData* PrimaryColor = DATA->getColorData(PrimaryColorID);

    ILuint NewImageID;
    ilGenImages(1, &NewImageID);
    ilBindImage(NewImageID);
    ilTexImage(width, height, 1, 4, IL_BGRA, IL_UNSIGNED_BYTE, NULL);
    uint8_t* NewImageData = ilGetData();

    uint32_t bpp = ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL);

    if(PrimaryColor != NULL)
    {
        for(uint32_t i = 0; i < width; i++)
        {
            for(uint32_t j = 0; j < height; j++)
            {
                float Base  = TextureImageData[(i * width * 2) + (j * 2) + 0];
                uint8_t Alpha =  TextureImageData[(i * width * 2) + (j * 2) + 1];
                Base /= 255.0;

                float OriginalBlue = PrimaryColor->getBlue();
                OriginalBlue /= 255.0;

                float OriginalGreen = PrimaryColor->getGreen();
                OriginalGreen /= 255.0;

                float OriginalRed = PrimaryColor->getRed();
                OriginalRed /= 255.0;

                // coloring using overlay mode
                if(Base >= 0.5)
                {
                    NewImageData[(i * width * bpp) + (j * bpp) + 0] = (1.0 - 2.0 * (1.0 - OriginalBlue) * (1.0 - Base)) * 255; // Blue
                    NewImageData[(i * width * bpp) + (j * bpp) + 1] = (1.0 - 2.0 * (1.0 - OriginalGreen) * (1.0 - Base)) * 255; // Green
                    NewImageData[(i * width * bpp) + (j * bpp) + 2] = (1.0 - 2.0 * (1.0 - OriginalRed) * (1.0 - Base)) * 255; // Red
                    NewImageData[(i * width * bpp) + (j * bpp) + 3] = Alpha;
                }
                else
                {
                    NewImageData[(i * width * bpp) + (j * bpp) + 0] = (2.0 * OriginalBlue * Base) * 255; // Blue
                    NewImageData[(i * width * bpp) + (j * bpp) + 1] = (2.0 * OriginalGreen * Base) * 255; // Green
                    NewImageData[(i * width * bpp) + (j * bpp) + 2] = (2.0 * OriginalRed * Base) * 255; // Red
                    NewImageData[(i * width * bpp) + (j * bpp) + 3] = Alpha;
                }
            }
        }
    }

    if (BorderColorID != -1)
    {
        ApplyBorder(NewImageID, BorderColorID);
    }

    return NewImageID;
}
Exemplo n.º 30
0
	GLuint
	loadCubemap(string filebase)
	{
	    glActiveTexture(GL_TEXTURE0);
	    GLuint imageID;
        ilGenImages(1, &imageID);
        ilBindImage(imageID);

        glGenTextures(1, &imageID);
        glBindTexture(GL_TEXTURE_CUBE_MAP, imageID);

	    string suffixes[] = {"right","left","top", "bottom","back","front"};
	    GLuint targets[] = {
                GL_TEXTURE_CUBE_MAP_POSITIVE_X,
                GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
                GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
                GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
                GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
                GL_TEXTURE_CUBE_MAP_NEGATIVE_Z
	    };
	    bool success;
	    ILenum error;
	    for (int i = 0; i < 6; i++) {
	        string texName = filebase + "_" + suffixes[i] + ".png";

	        success = ilLoadImage(texName.c_str());     // Load the image file
	        printf("LOADED %s\n", texName.c_str());

	        // 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);
	            }

	            glTexImage2D(targets[i],                 // Type of texture
	                         0,             // Pyramid level (for mip-mapping) - 0 is the top level
	                         ilGetInteger(IL_IMAGE_FORMAT),    // Internal image format
	                         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), // Image format (i.e. RGB, RGBA, BGR etc.)
	                         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

	    }

        // Set texture clamping method
        glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);

        // Set texture interpolation method to use linear interpolation (no MIPMAPS)
        glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

	    return imageID;
	}