int main(int argc, char * argv[])
{
	//Load the config and apply
		//Load the configs of screen
	win_w = cfg.Load(KEY_WINWIDTH);
	win_h = cfg.Load(KEY_WINHEIGHT);
		//Load the volumn and apply
	snd.ApplyCfg(BGMCN, cfg.Load(BGMCN));
	snd.ApplyCfg(SECN,  cfg.Load(SECN));
	snd.ApplyCfg(VCECN, cfg.Load(VCECN));

	//Init
	SDL_Init(SDL_INIT_EVENTS);
	win = SDL_CreateWindow("MaikazeSekai", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, win_w, win_h, SDL_WINDOW_OPENGL);
	ren = SDL_CreateRenderer(win, -1, 0);
	SDL_RenderSetLogicalSize(ren, 1280, 720);
	blk = SDL_CreateTexture(ren, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, win_w, win_h);
		//sent the renderer to Class Image as a stage and init them with the FileMgr
	img.Init(ren, &file);
	snd.Init(&file);

    
    auto *rw = SDL_RWFromFile("z:/star.png", "r");
    auto sur = IMG_Load_RW(rw, AUTOFREE);
    auto tex = SDL_CreateTextureFromSurface(ren, sur);
    SDL_FreeSurface(sur);
    SDL_Rect rt = { 0, 0, 2362, 7087 };
    SDL_RenderCopy(ren, tex, NULL, &rt);
    SDL_RenderPresent(ren);
    SDL_DestroyTexture(tex);

    auto *rw2 = SDL_RWFromFile("z:/1.png", "r");
    auto sur2 = IMG_Load_RW(rw2, AUTOFREE);
    auto tex2 = SDL_CreateTextureFromSurface(ren, sur2);
    SDL_FreeSurface(sur2);
    SDL_Rect rt2 = { 0, 0, 800, 900 };
    SDL_RenderCopy(ren, tex2, NULL, &rt2);
    SDL_RenderPresent(ren);
    //SDL_DestroyTexture(tex);
    
	
	//
	BGM("yui.wav", 1, 0);
	BG("sample.png");
	img.OnDraw();

	//Refresh the textures on renderer
	SDL_RenderPresent(ren);
    UnLoadBG();
    //SDL_DestroyTexture()
	//Logo();
	//Title();
	SDL_Quit();
	return 0;
}
Beispiel #2
0
surface get_no_cache(const std::string& key)
{
	std::string fname = path + key;
#if defined(__ANDROID__)
	if(fname[0] == '.' && fname[1] == '/') {
		fname = fname.substr(2);
	}
	SDL_RWops *rw = sys::read_sdl_rw_from_asset(module::map_file(fname).c_str());
	surface surf;
	if(rw) {
		surf = surface(IMG_Load_RW(rw,1));
	} else {
		surf = surface(IMG_Load(module::map_file(fname).c_str()));
	}
#else
	surface surf = surface(IMG_Load(module::map_file(fname).c_str()));
#endif // ANDROID
	//std::cerr << "loading image '" << fname << "'\n";
	if(surf.get() == false || surf->w == 0) {
		std::cerr << "failed to load image '" << key << "'\n";
		throw load_image_error();
	}

	//std::cerr << "IMAGE SIZE: " << (surf->w*surf->h) << "\n";
	return surf;
}
Beispiel #3
0
/**
* @brief Needs Debug 
* @param file_name name of the image file to load, relative to the base directory specified
* @param base_directory the base directory to use
*/
Surface::Surface(const std::string& file_name, ImageDirectory base_directory): Drawable(), internal_surface_created(true)
{
	std::string prefix = "";
	bool language_specific = false;
	
	if(base_directory == DIR_SPRITES)
	{
		prefix = "sprites/";
	}
	
	std::string prefixed_file_name = prefix + file_name;
	std::cout << prefixed_file_name << std::endl;
	size_t size;
	char* buffer;
	FileTools::data_file_open_buffer(prefixed_file_name, &buffer, &size);
	SDL_RWops* rw = SDL_RWFromMem(buffer, int(size));
	if(rw == NULL)
		std::cout << "rw didn't load\n";
	this->internal_surface = IMG_Load_RW(rw, 0);
	if(!internal_surface)
	{
		printf( "IMG_Load: %s\n", IMG_GetError());
		return;
	}
	FileTools::data_file_close_buffer(buffer);
	SDL_RWclose(rw);

	//Debug assertion
	
}
Beispiel #4
0
Image::Image(const char *filename) {
	SDL_RWops *image = SDL_RWFromFile(filename, "rb");
	m_surface = IMG_Load_RW(image, 1);
	
	if(!m_surface) {
		fprintf(stderr, "Failed to load image \"%s\": %s\n", filename, IMG_GetError());
		exit(EXIT_FAILURE);
	}
	
	m_width = m_surface->w;
	m_height = m_surface->h;
	
	m_texture = SDL_CreateTextureFromSurface(Window::main->renderer(), m_surface);
	if(!m_texture) {
		fprintf(stderr, "Failed to create texture from image: %s", SDL_GetError());
		exit(EXIT_FAILURE);
	}
	
	m_clipRect.x = 0;
	m_clipRect.y = 0;
	m_clipRect.w = m_width;
	m_clipRect.h = m_height;
	
	m_posRect.x = 0;
	m_posRect.y = 0;
	m_posRect.w = m_width;
	m_posRect.h = m_height;
}
gcn::Image* InfraellyImageLoader::load(unsigned char *buffer, long bufferLength, bool convertToDisplayFormat){
    //make rWop out of character buffer
    SDL_RWops *source_Rwop = SDL_RWFromMem(buffer, bufferLength);

    //load the rWop into a SDL Surface
    SDL_Surface *loadedSurface = IMG_Load_RW(source_Rwop, 1);

    if (loadedSurface == NULL)
    {
        throw GCN_EXCEPTION( std::string("Unable to load image file: ") );
    }

    SDL_Surface *surface = convertToStandardFormat(loadedSurface);
    SDL_FreeSurface(loadedSurface);

    if (surface == NULL)
    {
        throw GCN_EXCEPTION( std::string("Not enough memory to load: ") );
    }

    gcn::Image *image = new gcn::SDLImage(surface, true);

    if (convertToDisplayFormat)
    {
        image->convertToDisplayFormat();
    }

    return image;
}
Beispiel #6
0
gSurface *gLoadImage(const char *name)
{
   gSurface    *ret;
   SDL_RWops   *ops;

   if(!PHYSFS_exists(name))
   {
      gSetError("gLoadImage was unable to load the image %s", name);
      return NULL;
   }

   ops = PHYSFSRWOPS_openRead(name);
   if(!ops)
   {
      gSetError("gLoadImage was unable to load the image %s: failed _openRead", name);
      return NULL;
   }

   if(!(ret = IMG_Load_RW(ops, true)))
   {
      gSetError("gLoadImage was unable to load the image %s: %s", name, SDL_GetError());
      return NULL;
   }

   return ret;
}
void SetWindowIcon(photon_window &window, const std::string &filename){
    if(PHYSFS_exists(filename.c_str())){
        auto fp = PHYSFS_openRead(filename.c_str());
        intmax_t length = PHYSFS_fileLength(fp);
        if(length > 0){
            uint8_t *buffer = new uint8_t[length];

            PHYSFS_read(fp, buffer, 1, length);

            PHYSFS_close(fp);

            SDL_RWops *rw = SDL_RWFromMem(buffer, length);
            SDL_Surface *icon = IMG_Load_RW(rw, 1);

            if(icon == nullptr){
                PrintToLog("ERROR: icon loading failed! %s", IMG_GetError());
            }

            SDL_SetWindowIcon(window.window_SDL, icon);

            SDL_FreeSurface(icon);
            delete[] buffer;
        }else{
            PrintToLog("ERROR: Unable to open image file \"%s\"!");
        }
    }else{
        PrintToLog("ERROR: Image file \"%s\" does not exist!", filename.c_str());
    }
}
Beispiel #8
0
SDL_Surface *WadImageCache::image_from_desc(WadImageDescriptor& desc)
{
	SDL_Surface *surface = NULL;
	OpenedFile wad_file;
	if (open_wad_file_for_reading(desc.file, wad_file))
	{
		struct wad_header header;
		if (read_wad_header(wad_file, &header))
		{
			struct wad_data *wad;
			wad = read_indexed_wad_from_file(wad_file, &header, desc.index, true);
			if (wad)
			{
				void *data;
				size_t length;
				data = extract_type_from_wad(wad, desc.tag, &length);
				if (data && length)
				{
					SDL_RWops *rwops = SDL_RWFromConstMem(data, length);
#ifdef HAVE_SDL_IMAGE
					surface = IMG_Load_RW(rwops, 1);
#else
					surface = SDL_LoadBMP_RW(rwops, 1);
#endif
				}
				free_wad(wad);
			}
		}
		close_wad_file(wad_file);
	}
	clear_game_error();
	return surface;
}
Beispiel #9
0
int img_read(char *filein) {

	SDL_PixelFormat *fmt;   // we need that to determine which BPP
	SDL_RWops *rw;

	if (g_statics.debug) {
		printf("Reading from %s\n", filein);
		fflush(stdout);
	}

	if (!strcmp(filein, "-")) { // stdin as input. Shouldn't work but we try anyways
		rw = SDL_RWFromFP(stdin, 0);
	} else { // a regular file name
		rw = SDL_RWFromFile(filein, "rb");
	}

	g_statics.image_in = IMG_Load_RW(rw, 0);
	if (g_statics.image_in == NULL) {
		fprintf(stderr, "ERROR: %s\n", SDL_GetError());
		SDL_FreeRW(rw);
		return(-1);
	}

	// check if image is in 8bpp format
	fmt = g_statics.image_in->format;
	if (fmt->BitsPerPixel != 8) {
		fprintf(stderr, "ERROR: the image file is not in 8 bpp. Please convert it.\n");
		SDL_FreeSurface(g_statics.image_in);
		SDL_FreeRW(rw);
		return(-1);
	}

	if (g_statics.image_in->w != 192 || g_statics.image_in->h != 192) {
		fprintf(stderr, "ERROR: The image file is not 192x192 pixels. Please modify it.\n");
		SDL_FreeSurface(g_statics.image_in);
		SDL_FreeRW(rw);
		return(-1);
	}

	if (g_statics.debug > 1) {
		printf("The image file uses %d colours\n", fmt->palette->ncolors);
		fflush(stdout);
	}

	if ((g_variables.image_out = SDL_CreateRGBSurfaceFrom(g_statics.image_in->pixels, g_statics.image_in->w, g_statics.image_in->h, g_statics.image_in->pitch, g_statics.image_in->format->BitsPerPixel, 0, 0, 0, 0)) == NULL) {
		fprintf(stderr, "ERROR: %s", SDL_GetError());
		return(-1);
	}

	// need to convert the image using proper values for format, since there is a strong likelyhood to have more colours in the palette than for image_in.
	// algo: create proper palette, retrieve number of colours
	//       update image_in->format->palette with new info
	//       launch SDL_ConvertSurface

	g_variables.image_out = SDL_ConvertSurface(g_variables.image_out, g_statics.image_in->format, SDL_SWSURFACE);

	// a bit of clean up
	SDL_FreeRW(rw);
	return(0);
}
Beispiel #10
0
//
// TextureResourceLoader::VLoadResource				- Chapter 14, page 492
//
bool TextureResourceLoader::VLoadResource( char *rawBuffer, unsigned int rawSize, shared_ptr<ResHandle> handle )
   {
 	Renderer renderer = EngineApp::GetRendererImpl();
	if ( renderer == Renderer::Renderer_OpenGL )
	   {
		
      SDL_RWops* p_RWops = SDL_RWFromMem( rawBuffer, rawSize );
      if( !p_RWops )
         {
         ENG_ERROR( SDL_GetError() );
         return false;
         }
      SDL_Surface* p_Surface = IMG_Load_RW( p_RWops, 0 );
      if( SDL_RWclose( p_RWops ) )
         {
         ENG_WARNING( SDL_GetError() );
         }
      if( !p_Surface )
         {
         ENG_ERROR( SDL_GetError() );
         return false;
         }
      shared_ptr<SDLTextureResourceExtraData> extra = shared_ptr<SDLTextureResourceExtraData>( ENG_NEW SDLTextureResourceExtraData() );
      extra->m_pSurface = p_Surface;
      handle->SetExtraData( extra );
      handle->SetSize( extra->m_pSurface->w * extra->m_pSurface->h * extra->m_pSurface->format->BytesPerPixel );
	   }

	return true;
   }
gcn::Image* InfraellyImageLoader::load(SDL_RWops *source_Rwop, bool freeRWOP, bool convertToDisplayFormat){
    //load the rWop into a SDL Surface
    SDL_Surface *loadedSurface = IMG_Load_RW(source_Rwop, freeRWOP);

    if (loadedSurface == NULL)
    {
        throw GCN_EXCEPTION( std::string("Unable to load image file: ") );
    }

    SDL_Surface *surface = convertToStandardFormat(loadedSurface);
    SDL_FreeSurface(loadedSurface);

    if (surface == NULL)
    {
        throw GCN_EXCEPTION( std::string("Not enough memory to load: ") );
    }

    gcn::Image *image = new gcn::SDLImage(surface, true);

    if (convertToDisplayFormat)
    {
        image->convertToDisplayFormat();
    }

    return image;
}
Beispiel #12
0
SDL_Texture* LoadTextureFromFile(const String &file, SDL_Renderer *renderer)
{
	SDL_Texture *texture = nullptr;
	SDL_Surface *loadedImage = nullptr;

	//android
	#if defined(__ANDROID__)
		SDL_RWops *f = SDL_RWFromFile(file.c_str(), "rb");
		loadedImage = IMG_Load_RW(f , 1);

		if(f > 0)
			__android_log_write(ANDROID_LOG_INFO, "Chain Drop", "File Loaded");
	#elif defined(_WIN32)
		loadedImage = IMG_Load(file.c_str());
	#endif

	//If the loading went ok, convert to texture and return the texture
	if (loadedImage != nullptr)
	{
		texture = SDL_CreateTextureFromSurface(renderer, loadedImage);
		SDL_FreeSurface(loadedImage);
		//Make sure converting went ok too
		if (texture == nullptr)
			logSDLError(std::cout, "LoadTextureFromFile");
	}
	else
		logSDLError(std::cout, "LoadTextureFromFile");

	return texture;
}
Beispiel #13
0
void ResourceFile::load(std::string source)
{
	std::ifstream is(source.c_str(), std::ifstream::binary);
	ResourceMarker marker = ResourceMarker();

	while(!is.eof())
	{
		is.read( (char*) &marker, sizeof(ResourceMarker) );
		int rlength = marker.length;
		std::string rname = marker.name;

		char * buffer = new char[rlength];

		is.read(buffer, rlength);

		SDL_RWops *rw = SDL_RWFromMem(buffer, rlength);

		SDL_Surface *sdlSurface = IMG_Load_RW(rw, 1);

		Surface *surface = new Surface(sdlSurface);
		surface->setReleaseSurface(true);
		std::cout << IMG_GetError() << std::endl;

		//some error handling to do here

		delete buffer;

		resources.insert(std::make_pair(rname, surface));
	}

	is.close();
}
Beispiel #14
0
/**\brief Load image from buffer
 */
bool Image::Load( char *buf, int bufSize ) {
	SDL_RWops *rw;
	SDL_Surface *s = NULL;

	rw = SDL_RWFromMem( buf, bufSize );
	if( !rw ) {
		LogMsg(WARN, "Image loading failed. Could not create RWops" );
		return( false );
	}

	s = IMG_Load_RW( rw, 0 );
	SDL_FreeRW(rw);

	if( !s ) {
		LogMsg(WARN, "Image loading failed. Could not load image from RWops" );
		return( false );
	}

	w = s->w;
	h = s->h;

	if( ConvertToTexture( s ) == false ) {
		LogMsg(WARN, "Failed to load image from buffer" );
		SDL_FreeSurface( s );
		return( false );
	}


	return( true );
}
Beispiel #15
0
GLuint Graphic::LoadTexture( const char* src, GLfloat *texcoord, Uint32* width, Uint32* height) {
    static std::pair<GLuint, TexCoordArray> dat;
    tex_iter iter = texMap.find(src);
    GLuint texture;
    if (iter != texMap.end()) {
        texture = iter->second.first;
        memcpy(texcoord, iter->second.second.data, 4 * sizeof(GLfloat));
        *width = iter->second.second.w;
        *height = iter->second.second.h;
    } else {
        SDL_Surface *surface = IMG_Load_RW(Storage::GetInstance()->OpenIFile(src), 1);
        if (!surface) {
            char buf[256];
            snprintf(buf, sizeof(buf), "Load file failed: %s", src);
            throw Exception(buf);
        }
        texture = SDL_GL_LoadTexture(surface, texcoord);
        if (texture == 0) {
            throw Exception("failed create texture.");
        }
        dat.first = texture;
        memcpy(dat.second.data, texcoord, 4*sizeof(GLfloat));
        dat.second.w = *width = surface->w;
        dat.second.h = *height = surface->h;
        texMap[src] = dat;
        SDL_FreeSurface(surface);

    }
    return texture;
}
Beispiel #16
0
int PLEXT_Window_SetIconImageFile(const DXCHAR *filename) {
    SDL_Surface *surface;
    SDL_RWops *file;
    
    file = PL_File_OpenStream(filename);
    if (file == NULL) {
        return -1;
    }

    surface = IMG_Load_RW(file, SDL_TRUE);
    if (surface == NULL) {
        return -1;
    }
    
    if (s_windowIcon != NULL) {
        SDL_FreeSurface(s_windowIcon);
    }
    s_windowIcon = surface;
    
    if (s_initialized == DXTRUE) {
        SDL_SetWindowIcon(s_window, s_windowIcon);
    }
    
    return 0;
}
Beispiel #17
0
	surface surface::load(std::streambuf* buf,string type) {
		surface surface;
		SDL_RWops* wop = build_rwops_stream(buf);
		struct noname {
            SDL_RWops* woop;
            ~noname() {
                if(woop!=NULL)
                    SDL_RWclose(woop);
            }
        } destroyer;
        destroyer.woop = wop;
		if(type=="auto")
			surface.build(IMG_Load_RW(wop,false));
		else
			surface.build(IMG_LoadTyped_RW(wop,false,(char*)type.c_str()));
        return surface;
		/*int beg = strea.tellg();
		strea.seekg(0,ios::end);
		int size = ((int)strea.tellg())-beg;
		strea.seekg(beg,ios::beg);
		vector<char> vec(size);
		strea.read(&vec[0],size);
		SDL_RWops* wop = SDL_RWFromConstMem(&vec[0],size);
		if(wop == NULL)
			throw exception_sdl();
		if(type=="auto")
			surface.build(IMG_Load_RW(wop,true));
		else
			surface.build(IMG_LoadTyped_RW(wop,true,(char*)type.c_str()));
		return surface;*/
	}
Beispiel #18
0
/**
 * \brief Creates a surface from the specified image file name.
 *
 * An assertion error occurs if the file cannot be loaded.
 *
 * \param file_name Name of the image file to load, relative to the base directory specified.
 * \param base_directory The base directory to use.
 */
Surface::Surface(const std::string& file_name, ImageDirectory base_directory):
  Drawable(),
  internal_surface(NULL),
  owns_internal_surface(true),
  with_colorkey(false),
  colorkey(0) {

  std::string prefix = "";
  bool language_specific = false;

  if (base_directory == DIR_SPRITES) {
    prefix = "sprites/";
  }
  else if (base_directory == DIR_LANGUAGE) {
    language_specific = true;
    prefix = "images/";
  }
  std::string prefixed_file_name = prefix + file_name;

  size_t size;
  char* buffer;
  FileTools::data_file_open_buffer(prefixed_file_name, &buffer, &size, language_specific);
  SDL_RWops* rw = SDL_RWFromMem(buffer, int(size));
  this->internal_surface = IMG_Load_RW(rw, 0);
  FileTools::data_file_close_buffer(buffer);
  SDL_RWclose(rw);

  Debug::check_assertion(internal_surface != NULL, StringConcat() <<
      "Cannot load image '" << prefixed_file_name << "'");
    
  with_colorkey = SDL_GetColorKey(internal_surface, &colorkey) == 0;
}
Beispiel #19
0
SDL_Texture* LoadData::LoadImages(char *filename)
{
	SDL_RWops* RW_src = NULL;
	SDL_Texture* ret = NULL;
	
	//RW_src = LoadFile_RW(filename);
	RW_src = loadFile_PHYSFS(filename);
	if (RW_src != NULL)
	{
		SDL_Surface* toLoadSurface = IMG_Load_RW(RW_src, 1);
		if (toLoadSurface == NULL)
		{
			LOG("Failed to load IMG from RW! ERROR: %s", IMG_GetError());
		}
		else
		{
			//ret = SDL_CreateTextureFromSurface(App->render->renderer, toLoadSurface);
			//App->tex->textures.add(ret);
			ret = App->tex->LoadSurface(toLoadSurface);
			SDL_FreeSurface(toLoadSurface);
			if (ret == NULL)
			{
				LOG("Failed to load IMG from RW! ERROR: %s", IMG_GetError());
			}
		}
	}
	return ret;
}
Beispiel #20
0
static SDL_Surface* IMG_Load_istream(std::istream* stream, int freesrc) {
    SDL_RWops* irwops = reinterpret_cast<SDL_RWops*>(malloc(sizeof SDL_RWops));
    SimKit::construct_istream_rwops_adapter(irwops, i);
    
    SDL_Surface* out = IMG_Load_RW(irwops, freesrc);
    if (freesrc == 0) free(irwops);
    return out;
};
Beispiel #21
0
SDL_Surface*
Texture::loadImage(unsigned dsize, const char* data, const char *extension, const char *mimeType)
{
  SDL_RWops* rw = SDL_RWFromMem((void *)data,dsize);
  SDL_Surface* s=IMG_Load_RW(rw,true);
  if (!s) JGACHINE_FATAL("Could not load image");
  return s;
};
Beispiel #22
0
	void ImageLoader::load(IResource* res) {
		VFS* vfs = VFS::instance();

		Image* img = dynamic_cast<Image*>(res);

		//Have to save the images x and y shift or it gets lost when it's
		//loaded again.
		int32_t xShiftSave = img->getXShift();
		int32_t yShiftSave = img->getYShift();

		if(!img->isSharedImage()) {
			const std::string& filename = img->getName();
			boost::scoped_ptr<RawData> data (vfs->open(filename));
			size_t datalen = data->getDataLength();
			boost::scoped_array<uint8_t> darray(new uint8_t[datalen]);
			data->readInto(darray.get(), datalen);
			SDL_RWops* rwops = SDL_RWFromConstMem(darray.get(), static_cast<int>(datalen));

			SDL_Surface* surface = IMG_Load_RW(rwops, false);

			if (!surface) {
				throw SDLException(std::string("Fatal Error when loading image into a SDL_Surface: ") + SDL_GetError());
			}

			RenderBackend* rb = RenderBackend::instance();
			// in case of SDL we don't need to convert the surface
			if (rb->getName() == "SDL") {
				img->setSurface(surface);
			// in case of OpenGL we need a 32bit surface
			} else {
				SDL_PixelFormat dst_format = rb->getPixelFormat();
				SDL_PixelFormat src_format = *surface->format;
				uint8_t dstbits = dst_format.BitsPerPixel;
				uint8_t srcbits = src_format.BitsPerPixel;

				if (srcbits != 32 || dst_format.Rmask != src_format.Rmask || dst_format.Gmask != src_format.Gmask ||
					dst_format.Bmask != src_format.Bmask || dst_format.Amask != src_format.Amask) {
					dst_format.BitsPerPixel = 32;
					SDL_Surface* conv = SDL_ConvertSurface(surface, &dst_format, 0);
					dst_format.BitsPerPixel = dstbits;

					if (!conv) {
						throw SDLException(std::string("Fatal Error when converting surface to the screen format: ") + SDL_GetError());
					}

					img->setSurface(conv);
					SDL_FreeSurface(surface);
				} else {
					img->setSurface(surface);
				}
			}

			SDL_FreeRW(rwops);
		}
		//restore saved x and y shifts
		img->setXShift(xShiftSave);
		img->setYShift(yShiftSave);
	}
Beispiel #23
0
 boost::intrusive_ptr<Image> loadImage(Stream *stream)
 {
     SDL_Surface *surface = IMG_Load_RW(stream->rwops(), 0);
     if (surface == 0) {
         throw std::runtime_error(std::string("Failed to load image: ") +
                                  SDL_GetError());
     }
     return adoptImage(surface);
 }
void PictureBank::loadArchive(const std::string &filename)
{
  std::cout << "reading image archive: " << filename << std::endl;
  struct archive *a;
  struct archive_entry *entry;
  int rc;

  a = archive_read_new();
  archive_read_support_compression_all(a);
  archive_read_support_format_all(a);
  rc = archive_read_open_filename(a, filename.c_str(), 16384); // block size
  
  if (rc != ARCHIVE_OK) 
  {
    THROW("Cannot open archive " << filename);
  }

  SDL_Surface *surface;
  SDL_RWops *rw;

  const Uint32 bufferSize = 10000000;  // allocated buffer
  std::auto_ptr< Uint8 > buffer( new Uint8[ bufferSize ] );
   
  if( buffer.get() == 0 ) 
    THROW("Memory error, cannot allocate buffer size " << bufferSize);

  std::string entryname;
  while( archive_read_next_header(a, &entry) == ARCHIVE_OK )
  {
    // for all entries in archive
    entryname = archive_entry_pathname(entry);
    if ((archive_entry_stat(entry)->st_mode & S_IFREG) == 0)
    {
      // not a regular file (maybe a directory). skip it.
      continue;
    }

    if (archive_entry_stat(entry)->st_size >= bufferSize) 
    {
      THROW("Cannot load archive: file is too big " << entryname << " in archive " << filename);
    }
      
    int size = archive_read_data(a, buffer.get(), bufferSize);  // read data into buffer
    rw = SDL_RWFromMem(buffer.get(), size);
    surface = IMG_Load_RW(rw, 0);
    SDL_SetAlpha( surface, 0, 0 );

    setPicture(entryname, *surface);
    SDL_FreeRW(rw);
  }

  rc = archive_read_finish(a);
  if (rc != ARCHIVE_OK)
  {
    THROW("Error while reading archive " << filename);
  }
}
std::shared_ptr<SDL_Surface> ImageLoader_SDL_image::load(vfs_FILE *file) const
{
    SDL_Surface *surface = IMG_Load_RW(vfs_openRWops(file, false), 1);
    if (!surface)
    {
        return nullptr;
    }
    return std::shared_ptr<SDL_Surface>(surface, [](SDL_Surface *surface) { SDL_FreeSurface(surface); });
}
void
TileDescription::load(TileFactory* factory)
{  
  if (debug)
    std::cout << "Loading tiles: " << filename << std::endl;

  SDL_Surface* image = IMG_Load_RW(get_physfs_SDLRWops(filename), 1);
  if(!image) 
    {
      std::ostringstream msg;
      msg << "Couldn't load image '" << filename << "': " << SDL_GetError();
      throw std::runtime_error(msg.str());
    }
  else
    {
      try 
        {
          int num_tiles = width * height; //(image->w/TILE_RESOLUTION) * (image->h/TILE_RESOLUTION);
          if (int(colmap.size()) != num_tiles)
            {
              std::ostringstream str;
              str << "'colmap' information and num_tiles mismatch (" 
                  << colmap.size() << " != " << num_tiles << ") for image '" << filename << "'";
              throw std::runtime_error(str.str());
            }

          if (int(ids.size()) != num_tiles)
            {
              std::ostringstream str;
              str << "'ids' information and num_tiles mismatch (" 
                  << ids.size() << " != " << num_tiles << ") for image '" << filename << "'";
              throw std::runtime_error(str.str());
            }
    
          int i = 0;
          for (int y = 0; y < height*TILE_RESOLUTION; y += TILE_RESOLUTION)
            {
              for (int x = 0; x < width*TILE_RESOLUTION; x += TILE_RESOLUTION)
                {
                  if(ids[i] != -1)
                    {
                      factory->pack(ids[i], colmap[i], image,
                                    Rect(x, y, x+TILE_RESOLUTION, y+TILE_RESOLUTION));
                    }

                  i += 1; 
                }
            }
        } 
      catch(...) 
        {
          SDL_FreeSurface(image);
          throw;
        }
      SDL_FreeSurface(image);
    }
}
Beispiel #27
0
	GraphicsPrivate(RGSSThreadData *rtData)
	    : scRes(DEF_SCREEN_W, DEF_SCREEN_H),
	      scSize(scRes),
	      winSize(rtData->config.defScreenW, rtData->config.defScreenH),
	      screen(scRes.x, scRes.y),
	      threadData(rtData),
	      glCtx(SDL_GL_GetCurrentContext()),
	      frameRate(DEF_FRAMERATE),
	      frameCount(0),
	      brightness(255),
	      fpsLimiter(frameRate),
	      frozen(false)
	{
		recalculateScreenSize(rtData);
		updateScreenResoRatio(rtData);

		TEXFBO::init(frozenScene);
		TEXFBO::allocEmpty(frozenScene, scRes.x, scRes.y);
		TEXFBO::linkFBO(frozenScene);

		TEXFBO::init(currentScene);
		TEXFBO::allocEmpty(currentScene, scRes.x, scRes.y);
		TEXFBO::linkFBO(currentScene);

		FloatRect screenRect(0, 0, scRes.x, scRes.y);
		screenQuad.setTexPosRect(screenRect, screenRect);

		TEXFBO::init(transBuffer);
		TEXFBO::allocEmpty(transBuffer, scRes.x, scRes.y);
		TEXFBO::linkFBO(transBuffer);

		fpsLimiter.resetFrameAdjust();
		
		const std::string &olImage = rtData->config.touchOverlay.image;
		if (!olImage.empty())
		{
			SDL_RWops *ops = SDL_RWFromFile(olImage.c_str(), "rb");
			SDL_Surface *surf = IMG_Load_RW(ops, 1);

			if (surf)
			{
				overlayTex = TEX::gen();

				TEX::bind(overlayTex);
				TEX::setRepeat(false);
				TEX::setSmooth(true);
				TEX::uploadImage(surf->w, surf->h, surf->pixels, GL_RGBA);

				overlayTexSize = Vec2i(surf->w, surf->h);
			}
			else
			{
				Debug() << "failed to load overlay image:" << SDL_GetError();
			}
		}
	}
Beispiel #28
0
	void Texture::LoadTexture_fromMemoryPage(const MemoryPage& input_page, const ScreenVideo& makerVideo) throw(Error){
		this->Clean();
		if(makerVideo.m_renderer==nullptr)
			throw Error("Texture","LoadTexture_fromMemoryPage","Impossibile caricare una texture con uno specifico renderer nullo!");
		if(makerVideo.m_renderer!=m_render) m_render = makerVideo.m_renderer;
		if(input_page.GetSize()==0) return;
		if(m_render==nullptr) 
			throw Error("Texture","LoadTexture_fromMemoryPage","Impossibile caricare la texture richiesta!\nRenderer non inizializzato!");

		SDL_RWops* data_access = SDL_RWFromConstMem(input_page.Get_PtrMemory(),input_page.GetSize());
		if(data_access==nullptr){
			throw Error("Texture","LoadTexture_fromMemoryPage","Pagina di memoria corrotta!\n%s",SDL_GetError());
		}else{
			SDL_Surface* image_load = IMG_Load_RW(data_access,1);
			if(image_load==nullptr){
				throw Error("Texture","LoadTexture_fromMemoryPage","Impossibile caricare correttamente la texture richiesta\n%s",SDL_GetError());
			}else{
				SDL_Surface* image_opt = SDL_ConvertSurfaceFormat(image_load,SDL_PIXELFORMAT_RGBA8888,0);
				SDL_FreeSurface(image_load);
				image_load=nullptr;
				if(image_opt==nullptr){
					throw Error("Texture","LoadTexture_fromMemoryPage","Impossibile ottimizzare correttamente la texture richiesta\n%s",SDL_GetError());
				}

				this->m_texture = SDL_CreateTexture(m_render,SDL_PIXELFORMAT_RGBA8888,SDL_TEXTUREACCESS_STREAMING,image_opt->w,image_opt->h);
				if(this->m_texture==nullptr){
					SDL_FreeSurface(image_opt);
					throw Error("Texture","LoadTexture_fromMemoryPage","Impossibile creare una texture grafica!\n%s",SDL_GetError());
				}

				void* data_pixel_texture;
				int pitch_pixel_texture;

				if(SDL_LockTexture(m_texture,NULL,&data_pixel_texture,&pitch_pixel_texture)!=0){
					SDL_FreeSurface(image_opt);
					SDL_DestroyTexture(m_texture);
					throw Error("Texture","LoadTexture_fromMemoryPage","Impossibile scrivere la texture grafica!\n%s",SDL_GetError());
				}
				memcpy(data_pixel_texture,image_opt->pixels,image_opt->pitch * image_opt->h);
				SDL_UnlockTexture(m_texture);
				data_pixel_texture=nullptr;

				m_w_size = image_opt->w;
				m_h_size = image_opt->h;
				m_w_size_scaled = image_opt->w;
				m_h_size_scaled = image_opt->h;
				m_drawnable_area.Set_AllComponent(0,0,image_opt->w,image_opt->h);
				m_alpha_mod = SDL_ALPHA_OPAQUE;
				
				SDL_FreeSurface(image_opt);
				image_opt=nullptr;

				SDL_SetTextureBlendMode(m_texture,SDL_BLENDMODE_BLEND);
			}
		}
	}
Beispiel #29
0
surface get_no_cache(data_blob_ptr blob)
{
	ASSERT_LOG(blob != NULL, "Invalid data_blob in surface::get_no_cache");
	surface surf = surface(IMG_Load_RW(blob->get_rw_ops(), 0));
	if(surf.get() == false || surf->w == 0) {
		std::cerr << "failed to load image '" << (*blob)() << "'\n";
		throw load_image_error();
	}
	return surf;
}
Beispiel #30
0
static void LoadArchivePics(
	PicManager *pm, const char *archive, const char *dirname)
{
	char *buf = NULL;

	char path[CDOGS_PATH_MAX];
	sprintf(path, "%s/%s", archive, dirname);
	tinydir_dir dir;
	if (tinydir_open(&dir, path) != 0)
	{
		LOG(LM_MAP, LL_DEBUG, "no pic dir(%s): %s", path, strerror(errno));
		goto bail;
	}
	while (dir.has_next)
	{
		tinydir_file file;
		if (tinydir_readfile(&dir, &file) != 0)
		{
			LOG(LM_MAP, LL_WARN, "cannot read file: %s", strerror(errno));
			break;
		}
		if (!file.is_reg) goto nextFile;
		long len;
		buf = ReadFileIntoBuf(file.path, "rb", &len);
		if (buf == NULL) goto nextFile;
		SDL_RWops *rwops = SDL_RWFromMem(buf, len);
		bool isPng = IMG_isPNG(rwops);
		if (isPng)
		{
			SDL_Surface *data = IMG_Load_RW(rwops, 0);
			if (data != NULL)
			{
				char nameBuf[CDOGS_FILENAME_MAX];
				PathGetBasenameWithoutExtension(nameBuf, file.path);
				PicManagerAdd(&pm->customPics, &pm->customSprites, nameBuf, data);
			}
		}
		rwops->close(rwops);
	nextFile:
		CFREE(buf);
		buf = NULL;
		if (tinydir_next(&dir) != 0)
		{
			printf(
				"Could not go to next file in dir %s: %s\n",
				path, strerror(errno));
			goto bail;
		}
	}

bail:
	CFREE(buf);
	tinydir_close(&dir);
}