Ejemplo n.º 1
0
WzConfig::WzConfig(const QString &name, WzConfig::warning warning, QObject *parent)
	: WzConfigHack(name, (int)warning), m_settings(QString("wz::") + name, QSettings::IniFormat, parent), m_overrides()
{
	if (m_settings.status() != QSettings::NoError && (warning != ReadOnly || PHYSFS_exists(name.toUtf8().constData())))
	{
		debug(LOG_FATAL, "Could not open \"%s\"", name.toUtf8().constData());
	}
	char **diffList = PHYSFS_enumerateFiles("diffs");
	char **i;
	int j;
	for (i = diffList; *i != NULL; i++) 
	{
		std::string str(std::string("diffs/") + *i + std::string("/") + name.toUtf8().constData());
		if (!PHYSFS_exists(str.c_str())) 
			continue;
		QSettings tmp(QString("wz::") + str.c_str(), QSettings::IniFormat);
		if (tmp.status() != QSettings::NoError)
		{
			debug(LOG_FATAL, "Could not read an override for \"%s\"", name.toUtf8().constData());
		}
		QStringList keys(tmp.allKeys());
		for (j = 0; j < keys.length(); j++)
		{
			m_overrides.insert(keys[j],tmp.value(keys[j]));
		}
	}
	PHYSFS_freeList(diffList);
}
Ejemplo n.º 2
0
WzConfig::WzConfig(const QString &name, WzConfig::warning warning, QObject *parent)
{
	UDWORD size;
	char *data;
	QJsonParseError error;

	mFilename = name;
	mStatus = true;
	mWarning = warning;

	if (!PHYSFS_exists(name.toUtf8().constData()))
	{
		if (warning == ReadOnly)
		{
			mStatus = false;
			debug(LOG_ERROR, "IGNORED %s", name.toUtf8().constData());
			return;
		}
		else if (warning == ReadAndWrite)
		{
			mJson = QJsonDocument();
			mObj = mJson.object();
			debug(LOG_ERROR, "PREPARED %s", name.toUtf8().constData());
			return;
		}
	}
	if (!loadFile(name.toUtf8().constData(), &data, &size))
	{
		debug(LOG_FATAL, "Could not open \"%s\"", name.toUtf8().constData());
	}
	mJson = QJsonDocument::fromJson(QByteArray(data, size), &error);
	ASSERT(!mJson.isNull(), "JSON document from %s is invalid: %s", name.toUtf8().constData(), error.errorString().toUtf8().constData());
	ASSERT(mJson.isObject(), "JSON document from %s is not an object. Read: \n%s", name.toUtf8().constData(), data);
	mObj = mJson.object();
#if 0
	char **diffList = PHYSFS_enumerateFiles("diffs");
	char **i;
	int j;
	for (i = diffList; *i != NULL; i++) 
	{
		std::string str(std::string("diffs/") + *i + std::string("/") + name.toUtf8().constData());
		if (!PHYSFS_exists(str.c_str())) 
			continue;
		QSettings tmp(QString("wz::") + str.c_str(), QSettings::IniFormat);
		if (tmp.status() != QSettings::NoError)
		{
			debug(LOG_FATAL, "Could not read an override for \"%s\"", name.toUtf8().constData());
		}
		QStringList keys(tmp.allKeys());
		for (j = 0; j < keys.length(); j++)
		{
			m_overrides.insert(keys[j],tmp.value(keys[j]));
		}
	}
	PHYSFS_freeList(diffList);
#endif
}
Ejemplo n.º 3
0
int PHYSFSX_exists(const char *filename, int ignorecase)
{
	char filename2[PATH_MAX];

	if (!ignorecase)
		return PHYSFS_exists(filename);

	snprintf(filename2, sizeof(filename2), "%s", filename);
	PHYSFSEXT_locateCorrectCase(filename2);

	return PHYSFS_exists(filename2);
}
Ejemplo n.º 4
0
File::File(const MountedFilePath& mountedFilePath, DataStream::OpenMode openMode)
   : impl(std::make_unique<File_Impl>()), mountedFilePath(mountedFilePath)
{
   const char* path = mountedFilePath.path.c_str();

   int fileExists = PHYSFS_exists(path);

   if (fileExists == 0)
   {
      throw Exception(std::string("File ") + path + " does not exist in the search path");
   }

   switch (openMode)
   {
   case OpenMode::Read:
      impl->physfsFileHandle = PHYSFS_openRead(path);
      break;

   case OpenMode::Write:
      impl->physfsFileHandle = PHYSFS_openWrite(path);
      break;

   case OpenMode::Append:
      impl->physfsFileHandle = PHYSFS_openAppend(path);
      break;
   }

   if (impl->physfsFileHandle == nullptr)
   {
      throw Exception(std::string("Failed to open file ") + path + "\n" + PHYSFS_getLastError());
   }
}
Ejemplo n.º 5
0
bool j1Physfs::OpenFile(const char* file)
{
	if (0 == PHYSFS_exists(file))
	{
		return false; //file doesn't exist
	}

	PHYSFS_file* myfile = PHYSFS_openRead(file);

	// Get the lenght of the file
	file_lenght = PHYSFS_fileLength(myfile);

	// Get the file data.
	file_data = new Uint32[file_lenght];

	int length_read = PHYSFS_read(myfile, file_data, 1, file_lenght);

	if (length_read != (int)file_lenght)
	{
		delete[] file_data;
		file_data = 0;
		return false;
	}

	PHYSFS_close(myfile);


	return true;
}
Ejemplo n.º 6
0
static bool loadLevFile(const char* filename, searchPathMode datadir, bool ignoreWrf, char const *realFileName)
{
	char *pBuffer;
	UDWORD size;

	if (realFileName == NULL)
	{
		debug(LOG_WZ, "Loading lev file: \"%s\", builtin\n", filename);
	}
	else
	{
		debug(LOG_WZ, "Loading lev file: \"%s\" from \"%s\"\n", filename, realFileName);
	}

	if (!PHYSFS_exists(filename) || !loadFile(filename, &pBuffer, &size))
	{
		debug(LOG_ERROR, "loadLevFile: File not found: %s\n", filename);
		return false; // only in NDEBUG case
	}
	if (!levParse(pBuffer, size, datadir, ignoreWrf, realFileName))
	{
		debug(LOG_ERROR, "loadLevFile: Parse error in %s\n", filename);
		return false;
	}
	free(pBuffer);

	return true;
}
Ejemplo n.º 7
0
//==================================================
//! Load a file from the VFS into memory, can throw a FileIOException
//==================================================
void System::VFS::LoadRaw( const string& strFilename, vector<byte>& data ) {
	// Check to see if it exists
	if( !PHYSFS_exists(strFilename.c_str()) ) {
		THROW_EXCEPTION( FileReadException() << FileIOExceptionFilename(strFilename) );
	}
	
	// Open the file
	shared_ptr<PHYSFS_file> pFile( PHYSFS_openRead(strFilename.c_str()), PHYSFS_close );
	if( pFile.get() == NULL ) {
		THROW_EXCEPTION( FileReadException() << FileIOExceptionFilename(strFilename) );
	}

	// Try to read the number of bytes, fail if we can't
	PHYSFS_sint64 nBytes= PHYSFS_fileLength( pFile.get() );
	if( nBytes < 0 ) {
		THROW_EXCEPTION( FileReadException() << FileIOExceptionFilename(strFilename) );
	}
	data.resize( unsigned(nBytes) );

	// Try to read the data
	PHYSFS_sint64 nBytesRead= PHYSFS_read( pFile.get(), &data[0], sizeof(byte), data.size() );
	// Check for unexpected length
	if( nBytesRead != nBytes ) {
		data.resize( unsigned(nBytesRead) );
		THROW_EXCEPTION( FileReadException() << FileIOExceptionFilename(strFilename) );
	}
}
Ejemplo n.º 8
0
bool ResourceManager::exists(const std::string &path, bool lookInSearchPath)
{
    if (!lookInSearchPath)
        return fileExists(path);

    return PHYSFS_exists(path.c_str());
}
Ejemplo n.º 9
0
Block::Block(const ReaderMapping& lisp, const std::string& sprite_file) :
  sprite(),
  sprite_name(),
  default_sprite_name(),
  bouncing(false),
  breaking(false),
  bounce_dir(0),
  bounce_offset(0),
  original_y(-1)
{
  lisp.get("x", bbox.p1.x);
  lisp.get("y", bbox.p1.y);

  std::string sf;
  lisp.get("sprite", sf);
  if (sf.empty() || !PHYSFS_exists(sf.c_str())) {
    sf = sprite_file;
  }
  sprite = SpriteManager::current()->create(sf);
  sprite_name = sf;
  default_sprite_name = sprite_name;

  bbox.set_size(32, 32.1f);
  set_group(COLGROUP_STATIC);
  SoundManager::current()->preload("sounds/upgrade.wav");
  SoundManager::current()->preload("sounds/brick.wav");
}
Ejemplo n.º 10
0
int FS_loadFile(lua_State *L, const char *filename) {
	char *buffer;		/* buffer for the file */
	char *entryPoint;	/* entry point of file (differs from buffer, if "#!" in the first line is skipped */
	int err;
	PHYSFS_file *Hndfile = NULL;
	PHYSFS_sint64 fileLength, size;

	if (PHYSFS_exists(filename) == 0) {
		lua_pushfstring(L, "Error loading '%s': file not found.", filename);
		return FILEIO_ERROR;
	}

	Hndfile = PHYSFS_openRead(filename); /* open file to read! */
	if (Hndfile == NULL) {
		lua_pushfstring(L, "Error while reading from '%s': %s", filename, PHYSFS_getLastError());
		return FILEIO_ERROR;
	}

	size = PHYSFS_fileLength(Hndfile);
	if (size == -1) {
		lua_pushfstring(L, "Error while determining the size of %s.", filename);
		return FILEIO_ERROR;
	}

	buffer = (char *)malloc((unsigned int)size);
	if (buffer == NULL) {
		lua_pushfstring(L, "Error loading %s: Insufficient memory available.", filename);
		return FILEIO_ERROR;
	}

	fileLength = PHYSFS_read(Hndfile, buffer, 1, (unsigned int)size);
	if (fileLength < size) {
		free(buffer);
		lua_pushfstring(L, "Error while reading from %s: %s", filename, PHYSFS_getLastError());
		return FILEIO_ERROR;
	}
	/* close the file */
	err = PHYSFS_close(Hndfile);
	if (err == 0) {
		free(buffer);
		lua_pushfstring(L, "Error closing %s: %s", filename, PHYSFS_getLastError());
		return FILEIO_ERROR;
	}
	/* skip #! if nescessary */
	entryPoint = buffer;
	if (buffer[0] == '#') {
		while ((*entryPoint != 0x0D) && (*entryPoint != 0x0A) && (*entryPoint != EOF)) {
			entryPoint++;
			fileLength--;
		}
	}
	err = luaL_loadbuffer(L, entryPoint, (size_t)fileLength, filename);
	free(buffer);
	if (err != 0) {
		/* error message is on the stack */
		return FILEIO_ERROR;
	}

	return FILEIO_SUCCESS;
}
Ejemplo n.º 11
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;
}
Ejemplo n.º 12
0
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());
    }
}
Ejemplo n.º 13
0
bool physfsDrive::FileOpen(DOS_File * * file,const char * name,Bit32u flags) {
	char newname[CROSS_LEN];
	strcpy(newname,basedir);
	strcat(newname,name);
	CROSS_FILENAME(newname);
	dirCache.ExpandName(newname);
	normalize(newname,basedir);

	PHYSFS_file * hand;
	
	if (!PHYSFS_exists(newname)) return false;
	if ((flags&0xf) == OPEN_READ) {
		hand = PHYSFS_openRead(newname);
	} else {

		/* open for reading, deal with writing later */
		hand = PHYSFS_openRead(newname);
	}

	if (!hand) { 
		if((flags&0xf) != OPEN_READ) {
			PHYSFS_file *hmm = PHYSFS_openRead(newname);
			if (hmm) {
				PHYSFS_close(hmm);
				LOG_MSG("Warning: file %s exists and failed to open in write mode.\nPlease mount a write directory (see docs).",newname);
			}
		}
		return false;
	}
   
	*file=new physfsFile(name,hand,0x202,newname,false);
	(*file)->flags=flags;  //for the inheritance flag and maybe check for others.
	return true;
}
Ejemplo n.º 14
0
char* physfs_addmappath(char *path)
{
    char *p_path, *p_result;
    char *result;
    int length;

    result = (char *)malloc(PATH_MAX * sizeof(char));
    result[0] = '\0';
    p_result = result;
    
    length = strlen(path);
    if (length >= 3 && strcmp(&path[length-3], ".wz")==0)
    {
        PHYSFS_mount(path, NULL, 1);
            
        strcat(p_result, "multiplay/maps/");
        p_result += strlen("multiplay/maps/");        
        
        p_path = strrchr(path, PHYSFS_getDirSeparator()[0]);
        if (p_path)
        {
            // Remove the path
            p_path++;
            strcpy(p_result, p_path);

			path[strlen(path) - strlen(result) - 1] = '\0';
			PHYSFS_mount(path, NULL, 1);
        }
        else
        {
            strcpy(p_result, path);
        }

        // remove ".wz" from end
        length = strlen(result);
        result[length-3] = '\0';
    }
    else
    {
        if (PHYSFS_exists("multiplay/maps"))
        {
            strcat(p_result, "multiplay/maps/");
            p_result += strlen("multiplay/maps/");
        }

        p_path = strrchr(path, PHYSFS_getDirSeparator()[0]);
        if (p_path)
        {
            // Remove the path
            p_path++;
            strcpy(p_result, p_path);
        }
        else
        {
            strcpy(p_result, path);
        }        
    }

    return result;
}
Ejemplo n.º 15
0
Sp<AIOStream> ZipFileSystem::open(const String& uri, AIOStream::Mode mode){
	if(!PHYSFS_exists(uri.c_str())){
		LOGW("File \"%s\" does not exist in zip archive", uri.c_str());
	}

	return new ZipInputStream(PHYSFS_openRead(uri.c_str()));
}
Ejemplo n.º 16
0
boost::shared_ptr<ResourceInfo> Resource::LoadResource(const std::string& name)
{
    boost::shared_ptr<ResourceInfo> resource_info = m_resources.LoadResource(name);

    if (resource_info.get() == NULL)
    {
        const char* name_cstr = name.c_str();

        // Check if resource exists
        if (PHYSFS_exists(name_cstr) && !PHYSFS_isDirectory(name_cstr))
        {
            // Load the resource
            PHYSFS_File* fp = PHYSFS_openRead(name_cstr);

            // Load file data into ResourceInfo class
            Sint64 length = (Sint64)PHYSFS_fileLength(fp);
            char* data = new char[length];
            PHYSFS_read(fp, (void*)data, (PHYSFS_uint32)length, 1);
            resource_info = m_resources.Construct(name, data, length);

            // Close PHYSFS_File
            PHYSFS_close(fp);
            fp = NULL;
        }
        else
        {
            BOOST_THROW_EXCEPTION(ResourceNotFoundException()
                                  << StringErrorInfo("The requested resource could not be found: " + name));
        }
    }

    return resource_info;
}
Ejemplo n.º 17
0
// ////////////////////////////////////////////////////////////////////////////
// Load Player Stats
bool loadMultiStats(char *sPlayerName, PLAYERSTATS *st)
{
	char				fileName[255];
	UDWORD				size;
	char				*pFileData;

	memset(st, 0, sizeof(PLAYERSTATS));	// clear in case we don't get to load

	// Prevent an empty player name (where the first byte is a 0x0 terminating char already)
	if (!*sPlayerName)
	{
		strcpy(sPlayerName, _("Player"));
	}

	snprintf(fileName, sizeof(fileName), "%s%s.sta", MultiPlayersPath, sPlayerName);

	debug(LOG_WZ, "loadMultiStats: %s", fileName);

	// check player already exists
	if ( !PHYSFS_exists( fileName ) )
	{
		PLAYERSTATS			blankstats;

		memset(&blankstats, 0, sizeof(PLAYERSTATS));
		saveMultiStats(sPlayerName,sPlayerName,&blankstats);		// didnt exist so create.
	}
	else
	{
		int num = 0;

		loadFile(fileName,&pFileData,&size);

		if (strncmp(pFileData, "WZ.STA.v3", 9) != 0)
		{
			return false; // wrong version or not a stats file
		}

		num = sscanf(pFileData, "WZ.STA.v3\n%u %u %u %u %u",
		             &st->wins, &st->losses, &st->totalKills, &st->totalScore, &st->played);
		if (num < 5)
		{
			st->played = 0;	// must be old, buggy format still
		}
		free(pFileData);
	}

	// reset recent scores
	st->recentKills = 0;
	st->recentScore = 0;

	// clear any skirmish stats.
	for(size = 0;size<MAX_PLAYERS;size++)
	{
		ingame.skScores[size][0] =0;
		ingame.skScores[size][1] =0;
	}

	return true;
}
Ejemplo n.º 18
0
AddonManager::AddonManager(const std::string& addon_directory,
                           std::vector<Config::Addon>& addon_config) :
  m_downloader(),
  m_addon_directory(addon_directory),
  m_repository_url("https://raw.githubusercontent.com/SuperTux/addons/master/index-0_5.nfo"),
  m_addon_config(addon_config),
  m_installed_addons(),
  m_repository_addons(),
  m_has_been_updated(false),
  m_transfer_status()
{
  if(!PHYSFS_mkdir(m_addon_directory.c_str()))
  {
    std::ostringstream msg;
    msg << "Couldn't create directory for addons '"
        << m_addon_directory << "': " << PHYSFS_getLastError();
    throw std::runtime_error(msg.str());
  }

  add_installed_addons();

  // FIXME: We should also restore the order here
  for(auto& addon : m_addon_config)
  {
    if (addon.enabled)
    {
      try
      {
        enable_addon(addon.id);
      }
      catch(const std::exception& err)
      {
        log_warning << "failed to enable addon from config: " << err.what() << std::endl;
      }
    }
  }

  if(PHYSFS_exists(ADDON_INFO_PATH))
  {
    try
    {
        m_repository_addons = parse_addon_infos(ADDON_INFO_PATH);
    }
    catch(const std::exception& err)
    {
        log_warning << "parsing repository.nfo failed: " << err.what() << std::endl;
    }
  }
  else
  {
    log_info << "repository.nfo doesn't exist, not loading" << std::endl;
  }

  if (!g_config->repository_url.empty() &&
      g_config->repository_url != m_repository_url)
  {
    m_repository_url = g_config->repository_url;
  }
}
Ejemplo n.º 19
0
bool CResourceManager::DirectoryExists(const std::string& directory)
{
    if (PHYSFS_isInit())
    {
        return PHYSFS_exists(CleanPath(directory).c_str()) && PHYSFS_isDirectory(CleanPath(directory).c_str());
    }
    return false;
}
Ejemplo n.º 20
0
bool Filesystem::exists(const std::string &filename)
{
    if (PHYSFS_exists(filename.c_str())) {
        return true;
    } else {
        return false;
    }
}
Ejemplo n.º 21
0
bool CResourceManager::Exists(const std::string &filename)
{
    if (PHYSFS_isInit())
    {
        return PHYSFS_exists(CleanPath(filename).c_str());
    }
    return false;
}
Ejemplo n.º 22
0
bool physfsDrive::FileExists(const char* name) {
	char newname[CROSS_LEN];
	strcpy(newname,basedir);
	strcat(newname,name);
	CROSS_FILENAME(newname);
	dirCache.ExpandName(newname);
	normalize(newname,basedir);
	return PHYSFS_exists(newname) && !PHYSFS_isDirectory(newname);
}
Ejemplo n.º 23
0
	bool VFS::DoesExist(const std::string& fileName)
	{
		// Return true if Physfs_exists returns non-zero number.
		if (PHYSFS_exists(fileName.c_str())) {
			return true;
		} else {
			return false;
		}
	}
Ejemplo n.º 24
0
	bool ClientOptions::LoadFromFile(const std::string &filename, bool default_if_missing)
	{
		clan::MutexSection mutexSection(&m_Mutex);
		try
		{
			// Load the document
			ticpp::Document doc;
			if (PHYSFS_exists(filename.c_str()))
			{
				doc = OpenXml_PhysFS(filename);
			}
			else if (default_if_missing)
			{				
				// Copy the default config file
				try
				{
					PhysFSHelp::copy_file("Data/default-" + filename, filename);

					// Parse the xml
					doc = OpenXml_PhysFS(filename);
				}
				catch (FileSystemException&)
				{
					return false;
				}
			}

			ticpp::Element* pElem = doc.FirstChildElement();

			if (pElem->Value() != m_Type)
				FSN_EXCEPT(FileTypeException, filename + " is not a " + m_Type + " file");

			ticpp::Iterator< ticpp::Element > child;
			for ( child = child.begin( pElem ); child != child.end(); child++ )
			{
				if (child->Value() == "var")
				{
					std::string name = child->GetAttribute("name");
					if (name.empty()) continue;
					std::string value = child->GetAttribute("value");
					m_Variables[name] = value;
				}
				else if (child->Value() == "playeroptions")
				{
					loadPlayerOptions(child.Get());
				}
			}
		}
		catch (ticpp::Exception &ex)
		{
			FSN_EXCEPT(FileSystemException, ex.what());
		}

		m_LastFile = filename;

		return true;
	}
Ejemplo n.º 25
0
// Load labels
bool loadLabels(const char *filename)
{
	if (!PHYSFS_exists(filename))
	{
		debug(LOG_SAVE, "No %s found -- use fallback method", filename);
		return false;
	}
	WzConfig ini(filename);
	if (ini.status() != QSettings::NoError)
	{
		debug(LOG_ERROR, "No label file %s", filename);
		return false;
	}
	labels.clear();
	QStringList list = ini.childGroups();
	for (int i = 0; i < list.size(); ++i)
	{
		ini.beginGroup(list[i]);
		labeltype p;
		QString label(ini.value("label").toString());
		if (labels.contains(label))
		{
			debug(LOG_ERROR, "Duplicate label found");
		}
		else if (list[i].startsWith("position"))
		{
			p.p1 = ini.vector2i("pos");
			p.p2 = p.p1;
			p.type = POSITION;
			p.player = -1;
			p.id = -1;
			labels.insert(label, p);
		}
		else if (list[i].startsWith("area"))
		{
			p.p1 = ini.vector2i("pos1");
			p.p2 = ini.vector2i("pos2");
			p.type = AREA;
			p.player = -1;
			p.id = -1;
			labels.insert(label, p);
		}
		else if (list[i].startsWith("object"))
		{
			p.id = ini.value("id").toInt();
			p.type = ini.value("type").toInt();
			p.player = ini.value("player").toInt();
			labels.insert(label, p);
		}
		else
		{
			debug(LOG_ERROR, "Misnamed group in %s", filename);
		}
		ini.endGroup();
	}
	return true;
}
Ejemplo n.º 26
0
bool FS_Exists(const char *file) {
	if (PHYSFS_exists(file)) {
		if (!PHYSFS_isDirectory(file)) {
			return true;
		}
	}
	
	return false;
}
Ejemplo n.º 27
0
		bool FolderExists(std::string path) {
            if (!IsLoaded()) {
                Logger::begin("Filesystem", Logger::LogLevel_Error) << "FS not loaded" << Logger::end();
                assert(false);
                return false;
            }
			const char* pathC = path.c_str();
			return PHYSFS_exists(pathC) && PHYSFS_isDirectory(pathC);
		}
PhysFSInputStream::PhysFSInputStream( std::string filePath )
{
	File = NULL;
	
	if ( PHYSFS_exists(filePath.c_str()) )
	{
		File = PHYSFS_openRead(filePath.c_str());
	}
}
Ejemplo n.º 29
0
void
VideoSystem::do_take_screenshot()
{
  SDLSurfacePtr surface = make_screenshot();
  if (!surface) {
    log_warning << "Creating the screenshot has failed" << std::endl;
    return;
  }

  const std::string screenshots_dir = "/screenshots";
  if (!PHYSFS_exists(screenshots_dir.c_str())) {
    if (!PHYSFS_mkdir(screenshots_dir.c_str())) {
      log_warning << "Creating '" << screenshots_dir << "' failed" << std::endl;
      return;
    }
  }

  auto find_filename = [&]() -> boost::optional<std::string>
    {
      for (int num = 0; num < 1000000; ++num)
      {
        std::ostringstream oss;
        oss << "screenshot" << std::setw(6) << std::setfill('0') << num << ".png";
        const std::string screenshot_filename = FileSystem::join(screenshots_dir, oss.str());
        if (!PHYSFS_exists(screenshot_filename.c_str())) {
          return screenshot_filename;
        }
      }
      return boost::none;
    };

  auto filename = find_filename();
  if (!filename)
  {
    log_info << "Failed to find filename to save screenshot" << std::endl;
  }
  else
  {
    if (SDLSurface::save_png(*surface, *filename)) {
      log_info << "Wrote screenshot to \"" << *filename << "\"" << std::endl;
    }
  }
}
Ejemplo n.º 30
0
static int l_filesystem_isFile(lua_State* state) {
  if (!PHYSFS_isInit())
    return 0;

  const char* name = l_tools_toStringOrError(state, 1);
  if(!PHYSFS_isDirectory(name) && PHYSFS_exists(name))
    lua_pushboolean(state, 1);
  else
    lua_pushboolean(state, 0);
  return 1;
}