bool FileSystem::awake(pugi::xml_node &node) { bool ret = true; for (pugi::xml_node path = node.child("path"); path ; path = path.next_sibling("path")) addSearchPath(path.child_value()); char *write_dir = SDL_GetPrefPath("Carlos", "Game_development"); if (PHYSFS_setWriteDir(write_dir) == 0) { LOG("%s,%s","Error on setting Write Dir. Error:", PHYSFS_getLastError()); ret = false; } else { LOG("%s %s", "Write directory is ", write_dir); addSearchPath(write_dir, getSaveDirectory()); } SDL_free(write_dir); return ret; }
void addToSearchPath(const char* directory, bool append) { if(!PHYSFS_addToSearchPath(directory, append)) throw Exception("Couldn't add '%s' to searchpath: %s", directory, PHYSFS_getLastError()); }
static void getPlatformUserDir(char * const tmpstr, size_t const size) { #if defined(WZ_OS_WIN) // When WZ_PORTABLE is passed, that means we want the config directory at the same location as the program file DWORD dwRet; wchar_t tmpWStr[MAX_PATH]; #ifndef WZ_PORTABLE if ( SUCCEEDED( SHGetFolderPathW( NULL, CSIDL_PERSONAL|CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, tmpWStr ) ) ) { #else if (dwRet = GetCurrentDirectoryW(MAX_PATH, tmpWStr)) { if(dwRet > MAX_PATH) { debug(LOG_FATAL, "Buffer exceeds maximum path to create directory. Exiting."); exit(1); } #endif if (WideCharToMultiByte(CP_UTF8, 0, tmpWStr, -1, tmpstr, size, NULL, NULL) == 0) { debug(LOG_FATAL, "Config directory encoding conversion error."); exit(1); } strlcat(tmpstr, PHYSFS_getDirSeparator(), size); } else #elif defined(WZ_OS_MAC) FSRef fsref; OSErr error = FSFindFolder(kUserDomain, kApplicationSupportFolderType, false, &fsref); if (!error) error = FSRefMakePath(&fsref, (UInt8 *) tmpstr, size); if (!error) strlcat(tmpstr, PHYSFS_getDirSeparator(), size); else #endif if (PHYSFS_getUserDir()) { strlcpy(tmpstr, PHYSFS_getUserDir(), size); // Use PhysFS supplied UserDir (As fallback on Windows / Mac, default on Linux) } // If PhysicsFS fails (might happen if environment variable HOME is unset or wrong) then use the current working directory else if (getCurrentDir(tmpstr, size)) { strlcat(tmpstr, PHYSFS_getDirSeparator(), size); } else { debug(LOG_FATAL, "Can't get UserDir?"); abort(); } } static void initialize_ConfigDir(void) { char tmpstr[PATH_MAX] = { '\0' }; if (strlen(configdir) == 0) { getPlatformUserDir(tmpstr, sizeof(tmpstr)); if (!PHYSFS_setWriteDir(tmpstr)) // Workaround for PhysFS not creating the writedir as expected. { debug(LOG_FATAL, "Error setting write directory to \"%s\": %s", tmpstr, PHYSFS_getLastError()); exit(1); } if (!PHYSFS_mkdir(WZ_WRITEDIR)) // s.a. { debug(LOG_FATAL, "Error creating directory \"%s\": %s", WZ_WRITEDIR, PHYSFS_getLastError()); exit(1); } // Append the Warzone subdir sstrcat(tmpstr, WZ_WRITEDIR); sstrcat(tmpstr, PHYSFS_getDirSeparator()); if (!PHYSFS_setWriteDir(tmpstr)) { debug( LOG_FATAL, "Error setting write directory to \"%s\": %s", tmpstr, PHYSFS_getLastError() ); exit(1); } } else { sstrcpy(tmpstr, configdir); // Make sure that we have a directory separator at the end of the string if (tmpstr[strlen(tmpstr) - 1] != PHYSFS_getDirSeparator()[0]) sstrcat(tmpstr, PHYSFS_getDirSeparator()); debug(LOG_WZ, "Using custom configuration directory: %s", tmpstr); if (!PHYSFS_setWriteDir(tmpstr)) // Workaround for PhysFS not creating the writedir as expected. { debug(LOG_FATAL, "Error setting write directory to \"%s\": %s", tmpstr, PHYSFS_getLastError()); exit(1); } // NOTE: This is currently only used for mingw builds for now. #if defined (WZ_CC_MINGW) if (!OverrideRPTDirectory(tmpstr)) { // since it failed, we just use our default path, and not the user supplied one. debug(LOG_ERROR, "Error setting exception hanlder to use directory %s", tmpstr); } #endif } // User's home dir first so we allways see what we write PHYSFS_addToSearchPath( PHYSFS_getWriteDir(), PHYSFS_PREPEND ); PHYSFS_permitSymbolicLinks(1); debug(LOG_WZ, "Write dir: %s", PHYSFS_getWriteDir()); debug(LOG_WZ, "Base dir: %s", PHYSFS_getBaseDir()); }
// Initialise PhysicsFS, set up basic search paths and add arguments from .ini file. // The .ini file can be in either the user directory or the same directory as the program. // The user directory is searched first. void PHYSFSX_init(int argc, char *argv[]) { #if defined(__unix__) const char *path = NULL; #endif #ifdef macintosh // Mac OS 9 char base_dir[PATH_MAX]; int bundle = 0; #else #define base_dir PHYSFS_getBaseDir() #endif PHYSFS_init(argv[0]); atexit(PHYSFSX_deinit); PHYSFS_permitSymbolicLinks(1); #ifdef macintosh strcpy(base_dir, PHYSFS_getBaseDir()); if (strstr(base_dir, ".app:Contents:MacOSClassic")) // the Mac OS 9 program is still in the .app bundle { char *p; bundle = 1; if (base_dir[strlen(base_dir) - 1] == ':') base_dir[strlen(base_dir) - 1] = '\0'; p = strrchr(base_dir, ':'); *p = '\0'; // path to 'Contents' p = strrchr(base_dir, ':'); *p = '\0'; // path to bundle p = strrchr(base_dir, ':'); *p = '\0'; // path to directory containing bundle } #endif #if (defined(__APPLE__) && defined(__MACH__)) // others? chdir(base_dir); // make sure relative hogdir paths work #endif #if defined(__unix__) char fullPath[PATH_MAX + 5]; # if !(defined(__APPLE__) && defined(__MACH__)) path = "~/.d2x-rebirth/"; # else path = "~/Library/Preferences/D2X Rebirth/"; # endif if (path[0] == '~') // yes, this tilde can be put before non-unix paths. { const char *home = PHYSFS_getUserDir(); strcpy(fullPath, home); // prepend home to the path path++; if (*path == *PHYSFS_getDirSeparator()) path++; strncat(fullPath, path, PATH_MAX + 5 - strlen(home)); } else strncpy(fullPath, path, PATH_MAX + 5); PHYSFS_setWriteDir(fullPath); if (!PHYSFS_getWriteDir()) { // need to make it char *p; char ancestor[PATH_MAX + 5]; // the directory which actually exists char child[PATH_MAX + 5]; // the directory relative to the above we're trying to make strcpy(ancestor, fullPath); while (!PHYSFS_getWriteDir() && ((p = strrchr(ancestor, *PHYSFS_getDirSeparator())))) { if (p[1] == 0) { // separator at the end (intended here, for safety) *p = 0; // kill this separator if (!((p = strrchr(ancestor, *PHYSFS_getDirSeparator())))) break; // give up, this is (usually) the root directory } p[1] = 0; // go to parent PHYSFS_setWriteDir(ancestor); } strcpy(child, fullPath + strlen(ancestor)); for (p = child; (p = strchr(p, *PHYSFS_getDirSeparator())); p++) *p = '/'; PHYSFS_mkdir(child); PHYSFS_setWriteDir(fullPath); } PHYSFS_addToSearchPath(PHYSFS_getWriteDir(), 1); #endif PHYSFS_addToSearchPath(base_dir, 1); InitArgs( argc,argv ); PHYSFS_removeFromSearchPath(base_dir); if (!PHYSFS_getWriteDir()) { PHYSFS_setWriteDir(base_dir); if (!PHYSFS_getWriteDir()) Error("can't set write dir: %s\n", PHYSFS_getLastError()); else PHYSFS_addToSearchPath(PHYSFS_getWriteDir(), 0); } //tell PHYSFS where hogdir is if (GameArg.SysHogDir) PHYSFS_addToSearchPath(GameArg.SysHogDir,1); #if defined(__unix__) else if (!GameArg.SysNoHogDir) PHYSFS_addToSearchPath(SHAREPATH, 1); #endif PHYSFSX_addRelToSearchPath("data", 1); // 'Data' subdirectory // For Macintosh, add the 'Resources' directory in the .app bundle to the searchpaths #if defined(__APPLE__) && defined(__MACH__) { ProcessSerialNumber psn = { 0, kCurrentProcess }; FSRef fsref; OSStatus err; err = GetProcessBundleLocation(&psn, &fsref); if (err == noErr) err = FSRefMakePath(&fsref, (ubyte *)fullPath, PATH_MAX); if (err == noErr) { strncat(fullPath, "/Contents/Resources/", PATH_MAX + 4 - strlen(fullPath)); fullPath[PATH_MAX + 4] = '\0'; PHYSFS_addToSearchPath(fullPath, 1); } } #elif defined(macintosh) if (bundle) { base_dir[strlen(base_dir)] = ':'; // go back in the bundle base_dir[strlen(base_dir)] = ':'; // go back in 'Contents' strncat(base_dir, ":Resources:", PATH_MAX - 1 - strlen(base_dir)); base_dir[PATH_MAX - 1] = '\0'; PHYSFS_addToSearchPath(base_dir, 1); } #endif }
bool CResourceManager::SetSaveLocation(const std::string &location) { if (!PHYSFS_setWriteDir(location.c_str())) { GetLogger()->Error("Error while setting save location to \"%s\": %s\n", location.c_str(), PHYSFS_getLastError()); return false; } return true; }
static int physfsrwops_seek(SDL_RWops *rw, int offset, int whence) #endif { PHYSFS_File *handle = (PHYSFS_File *) rw->hidden.unknown.data1; PHYSFS_sint64 pos = 0; if (whence == RW_SEEK_SET) pos = (PHYSFS_sint64) offset; else if (whence == RW_SEEK_CUR) { const PHYSFS_sint64 current = PHYSFS_tell(handle); if (current == -1) { SDL_SetError("Can't find position in file: %s", PHYSFS_getLastError()); return -1; } /* if */ if (offset == 0) /* this is a "tell" call. We're done. */ { #if TARGET_SDL2 return (Sint64) current; #else return (int) current; #endif } /* if */ pos = current + ((PHYSFS_sint64) offset); } /* else if */ else if (whence == RW_SEEK_END) { const PHYSFS_sint64 len = PHYSFS_fileLength(handle); if (len == -1) { SDL_SetError("Can't find end of file: %s", PHYSFS_getLastError()); return -1; } /* if */ pos = len + ((PHYSFS_sint64) offset); } /* else if */ else { SDL_SetError("Invalid 'whence' parameter."); return -1; } /* else */ if ( pos < 0 ) { SDL_SetError("Attempt to seek past start of file."); return -1; } /* if */ if (!PHYSFS_seek(handle, (PHYSFS_uint64) pos)) { SDL_SetError("PhysicsFS error: %s", PHYSFS_getLastError()); return -1; } /* if */ #if TARGET_SDL2 return (Sint64) pos; #else return (int) pos; #endif } /* physfsrwops_seek */
const char *fs_error(void) { return PHYSFS_getLastError(); }
/*************************************************************************** Delete a savegame. saveGameName should be a .gam extension save game filename reference. We delete this file, any .es file with the same name, and any files in the directory with the same name. ***************************************************************************/ void deleteSaveGame(char* saveGameName) { char **files, **i; ASSERT( strlen(saveGameName) < MAX_STR_LENGTH,"deleteSaveGame; save game name too long" ); PHYSFS_delete(saveGameName); saveGameName[strlen(saveGameName)-4] = '\0';// strip extension strcat(saveGameName,".es"); // remove script data if it exists. PHYSFS_delete(saveGameName); saveGameName[strlen(saveGameName)-3] = '\0';// strip extension // check for a directory and remove that too. files = PHYSFS_enumerateFiles(saveGameName); for (i = files; *i != NULL; ++i) { char del_file[PATH_MAX]; // Construct the full path to the file by appending the // filename to the directory it is in. snprintf(del_file, sizeof(del_file), "%s/%s", saveGameName, *i); debug(LOG_SAVE, "Deleting [%s].", del_file); // Delete the file if (!PHYSFS_delete(del_file)) { debug(LOG_ERROR, "Warning [%s] could not be deleted due to PhysicsFS error: %s", del_file, PHYSFS_getLastError()); } } PHYSFS_freeList(files); if (!PHYSFS_delete(saveGameName)) // now (should be)empty directory { debug(LOG_ERROR, "Warning directory[%s] could not be deleted because %s", saveGameName,PHYSFS_getLastError()); } return; }
static bool cdAudio_OpenTrack(const char *filename) { if (!music_initialized) { return false; } debug(LOG_SOUND, "called(%s)", filename); cdAudio_Stop(); if (strncasecmp(filename + strlen(filename) - 4, ".ogg", 4) == 0) { PHYSFS_file *music_file = PHYSFS_openRead(filename); debug(LOG_WZ, "Reading...[directory: %s] %s", PHYSFS_getRealDir(filename), filename); if (music_file == NULL) { debug(LOG_ERROR, "Failed opening file [directory: %s] %s, with error %s", PHYSFS_getRealDir(filename), filename, PHYSFS_getLastError()); return false; } cdStream = sound_PlayStreamWithBuf(music_file, music_volume, cdAudio_TrackFinished, (char *)filename, bufferSize, buffer_count); if (cdStream == NULL) { PHYSFS_close(music_file); debug(LOG_ERROR, "Failed creating audio stream for %s", filename); return false; } debug(LOG_SOUND, "successful(%s)", filename); stopping = false; return true; } return false; // unhandled }
bool buildMapList() { if (!loadLevFile("gamedesc.lev", mod_campaign, false, NULL)) { return false; } loadLevFile("addon.lev", mod_multiplay, false, NULL); WZ_Maps.clear(); MapFileList realFileNames = listMapFiles(); for (MapFileList::iterator realFileName = realFileNames.begin(); realFileName != realFileNames.end(); ++realFileName) { bool mapmod = false; struct WZmaps CurrentMap; std::string realFilePathAndName = PHYSFS_getRealDir(realFileName->c_str()) + *realFileName; PHYSFS_addToSearchPath(realFilePathAndName.c_str(), PHYSFS_APPEND); char **filelist = PHYSFS_enumerateFiles(""); for (char **file = filelist; *file != NULL; ++file) { std::string checkfile = *file; size_t len = strlen(*file); if (len > 10 && !strcasecmp(*file + (len - 10), ".addon.lev")) // Do not add addon.lev again { loadLevFile(*file, mod_multiplay, true, realFileName->c_str()); } // add support for X player maps using a new name to prevent conflicts. if (len > 13 && !strcasecmp(*file + (len - 13), ".xplayers.lev")) { loadLevFile(*file, mod_multiplay, true, realFileName->c_str()); } } PHYSFS_freeList(filelist); if (PHYSFS_removeFromSearchPath(realFilePathAndName.c_str()) == 0) { debug(LOG_ERROR, "Could not unmount %s", PHYSFS_getLastError()); } // check what kind of map it is if (!PHYSFS_mount(realFilePathAndName.c_str(), "WZMap", PHYSFS_APPEND)) { debug(LOG_FATAL, "Could not mount %s, because: %s. Please delete the file, and run the game again. Game will now exit.", realFilePathAndName.c_str(), PHYSFS_getLastError()); exit(-1); } filelist = PHYSFS_enumerateFiles("WZMap"); for (char **file = filelist; *file != NULL; ++file) { if (PHYSFS_isDirectory(*file)) { std::string checkfile = *file; if (checkfile.compare("wrf")==0 || checkfile.compare("stats")==0 ||checkfile.compare("components")==0 || checkfile.compare("anims")==0 || checkfile.compare("effects")==0 ||checkfile.compare("messages")==0 || checkfile.compare("audio")==0 || checkfile.compare("sequenceaudio")==0 ||checkfile.compare("misc")==0 || checkfile.compare("features")==0 || checkfile.compare("script")==0 ||checkfile.compare("structs")==0 || checkfile.compare("tileset")==0 || checkfile.compare("images")==0 || checkfile.compare("texpages")==0 ) { mapmod = true; break; } } } PHYSFS_freeList(filelist); CurrentMap.MapName = realFileName->c_str(); CurrentMap.isMapMod = mapmod; WZ_Maps.push_back(CurrentMap); if (PHYSFS_removeFromSearchPath(realFilePathAndName.c_str()) == 0) { debug(LOG_ERROR, "Could not unmount %s", PHYSFS_getLastError()); } } return true; }
static MapFileList listMapFiles() { MapFileList ret, filtered, oldSearchPath; char **subdirlist = PHYSFS_enumerateFiles("maps"); for (char **i = subdirlist; *i != NULL; ++i) { std::string wzfile = *i; if (*i[0] == '.' || wzfile.substr(wzfile.find_last_of(".")+1) != "wz") { continue; } std::string realFileName = std::string("maps/") + *i; ret.push_back(realFileName); } PHYSFS_freeList(subdirlist); // save our current search path(s) debug(LOG_WZ, "Map search paths:"); char **searchPath = PHYSFS_getSearchPath(); for (char **i = searchPath; *i != NULL; i++) { debug(LOG_WZ, " [%s]", *i); oldSearchPath.push_back(*i); PHYSFS_removeFromSearchPath(*i); } PHYSFS_freeList(searchPath); for (MapFileList::iterator realFileName = ret.begin(); realFileName != ret.end(); ++realFileName) { std::string realFilePathAndName = PHYSFS_getWriteDir() + *realFileName; if (PHYSFS_addToSearchPath(realFilePathAndName.c_str(), PHYSFS_APPEND)) { int unsafe = 0; char **filelist = PHYSFS_enumerateFiles("multiplay/maps"); for (char **file = filelist; *file != NULL; ++file) { std::string isDir = std::string("multiplay/maps/") + *file; if (PHYSFS_isDirectory(isDir.c_str())) continue; std::string checkfile = *file; debug(LOG_WZ,"checking ... %s", *file); if (checkfile.substr(checkfile.find_last_of(".")+ 1) == "gam") { if (unsafe++ > 1) { debug(LOG_ERROR, "Map packs are not supported! %s NOT added.", realFilePathAndName.c_str()); break; } } } PHYSFS_freeList(filelist); if (unsafe < 2) { filtered.push_back(realFileName->c_str()); } PHYSFS_removeFromSearchPath(realFilePathAndName.c_str()); } else { debug(LOG_POPUP, "Could not mount %s, because: %s.\nPlease delete or move the file specified.", realFilePathAndName.c_str(), PHYSFS_getLastError()); } } // restore our search path(s) again for (MapFileList::iterator restorePaths = oldSearchPath.begin(); restorePaths != oldSearchPath.end(); ++restorePaths) { PHYSFS_addToSearchPath(restorePaths->c_str(), PHYSFS_APPEND); } debug(LOG_WZ, "Search paths restored"); printSearchPath(); return filtered; }
void sdl_log_write(Uint32 level, char* fmt, ...) { PHYSFS_file* h_file; va_list args; char timestring[255]; char logstr[MAX_PATH_LEN]; char logline[MAX_PATH_LEN]; char typestr[32]; cptr prev_write_dir; errlvl = level; // label the log informational level correctly switch (errlvl) { case ERRLVL_CRITICAL: sprintf(typestr, "ERROR"); break; case ERRLVL_WARNING: sprintf(typestr, "WARNING"); break; case ERRLVL_NO_ERR: sprintf(typestr, "INFO"); break; case LOG_START: sprintf(typestr, "START"); break; case LOG_STOP: sprintf(typestr, "STOP"); break; default: /* we don't like undefined behaviour */ errlvl = ERRLVL_CRITICAL; sprintf(typestr, "UNDEFINED"); break; } sdl_utl_get_datetime(timestring); if (timestring[0]) { // move the the time-stamped log entry to a temporary buffer va_start(args, fmt); vsprintf(logstr, fmt, args); va_end(args); // formulate the log text snprintf(logline, MAX_PATH_LEN, "%s [%s] %s\n", timestring, typestr, logstr); // push the current write path, if any, just in case and set our new one prev_write_dir = string_make(PHYSFS_getWriteDir()); PHYSFS_setWriteDir(SDL_LOG_DIR); // open the log file and write the entry h_file = my_fopen(SDL_LOG_FILE, "a"); if (h_file) { my_fprintf(h_file, "%s", logline); my_fclose(h_file); } else { printf("Log error - open file: %s (%s)\n", PHYSFS_getLastError(), SDL_LOG_FILE); } errlvl &= ~(LOG_START | LOG_STOP); // pop the previous write path if (!PHYSFS_setWriteDir(prev_write_dir)) { printf("Log error - restore write dir: %s\n", PHYSFS_getLastError()); } } }
int main(int argc, char **argv) { int i; int portnum = DEFAULT_PORTNUM; setbuf(stdout, NULL); setbuf(stderr, NULL); #ifndef LACKING_SIGNALS /* I'm not sure if this qualifies as a cheap trick... */ signal(SIGTERM, exit); signal(SIGINT, exit); signal(SIGFPE, exit); signal(SIGSEGV, exit); signal(SIGPIPE, exit); signal(SIGILL, exit); #endif if (argc == 1) { printf("USAGE: %s <archive1> [archive2 [... archiveN]]\n", argv[0]); return(42); } /* if */ if (!PHYSFS_init(argv[0])) { printf("PHYSFS_init() failed: %s\n", PHYSFS_getLastError()); return(42); } /* if */ /* normally, this is bad practice, but oh well. */ atexit(at_exit_cleanup); for (i = 1; i < argc; i++) { if (!PHYSFS_addToSearchPath(argv[i], 1)) printf(" WARNING: failed to add [%s] to search path.\n", argv[i]); } /* else */ listensocket = create_listen_socket(portnum); if (listensocket < 0) { printf("listen socket failed to create.\n"); return(42); } /* if */ while (1) /* infinite loop for now. */ { struct sockaddr addr; socklen_t len; int s = accept(listensocket, &addr, &len); if (s < 0) { printf("accept() failed: %s\n", strerror(errno)); close(listensocket); return(42); } /* if */ serve_http_request(s, &addr, len); } /* while */ return(0); } /* main */
//read in the player's saved games. returns errno (0 == no error) int read_player_file() { char filename[PATH_MAX]; PHYSFS_file *file; int player_file_size, shareware_file = -1, id = 0; short saved_game_version, player_struct_version; Assert(Player_num>=0 && Player_num<MAX_PLAYERS); memset(filename, '\0', PATH_MAX); snprintf(filename, PATH_MAX, GameArg.SysUsePlayersDir? "Players/%.8s.plr" : "%.8s.plr", Players[Player_num].callsign); if (!PHYSFSX_exists(filename,0)) return ENOENT; file = PHYSFSX_openReadBuffered(filename); if (!file) goto read_player_file_failed; new_player_config(); // Set defaults! // Unfortunatly d1x has been writing both shareware and registered // player files with a saved_game_version of 7 and 8, whereas the // original decent used 4 for shareware games and 7 for registered // games. Because of this the player files didn't get properly read // when reading d1x shareware player files in d1x registered or // vica versa. The problem is that the sizeof of the taunt macros // differ between the share and registered versions, causing the // reading of the player file to go wrong. Thus we now determine the // sizeof the player file to determine what kinda player file we are // dealing with so that we can do the right thing PHYSFS_seek(file, 0); player_file_size = PHYSFS_fileLength(file); PHYSFS_readSLE32(file, &id); saved_game_version = PHYSFSX_readShort(file); player_struct_version = PHYSFSX_readShort(file); PlayerCfg.NHighestLevels = PHYSFSX_readInt(file); PlayerCfg.DefaultDifficulty = PHYSFSX_readInt(file); PlayerCfg.AutoLeveling = PHYSFSX_readInt(file); if (id!=SAVE_FILE_ID) { nm_messagebox(TXT_ERROR, 1, TXT_OK, "Invalid player file"); PHYSFS_close(file); return -1; } if (saved_game_version<COMPATIBLE_SAVED_GAME_VERSION || player_struct_version<COMPATIBLE_PLAYER_STRUCT_VERSION) { nm_messagebox(TXT_ERROR, 1, TXT_OK, TXT_ERROR_PLR_VERSION); PHYSFS_close(file); return -1; } /* determine if we're dealing with a shareware or registered playerfile */ switch (saved_game_version) { case 4: shareware_file = 1; break; case 5: case 6: shareware_file = 0; break; case 7: /* version 7 doesn't have the saved games array */ if ((player_file_size - (sizeof(hli)*PlayerCfg.NHighestLevels)) == (2212 - sizeof(saved_games))) shareware_file = 1; if ((player_file_size - (sizeof(hli)*PlayerCfg.NHighestLevels)) == (2252 - sizeof(saved_games))) shareware_file = 0; break; case 8: if ((player_file_size - (sizeof(hli)*PlayerCfg.NHighestLevels)) == 2212) shareware_file = 1; if ((player_file_size - (sizeof(hli)*PlayerCfg.NHighestLevels)) == 2252) shareware_file = 0; /* d1x-rebirth v0.31 to v0.42 broke things by adding stuff to the player struct without thinking (sigh) */ if ((player_file_size - (sizeof(hli)*PlayerCfg.NHighestLevels)) == (2212 + 2*sizeof(int))) { shareware_file = 1; /* skip the cruft added to the player_info struct */ PHYSFS_seek(file, PHYSFS_tell(file)+2*sizeof(int)); } if ((player_file_size - (sizeof(hli)*PlayerCfg.NHighestLevels)) == (2252 + 2*sizeof(int))) { shareware_file = 0; /* skip the cruft added to the player_info struct */ PHYSFS_seek(file, PHYSFS_tell(file)+2*sizeof(int)); } } if (shareware_file == -1) { nm_messagebox(TXT_ERROR, 1, TXT_OK, "Error invalid or unknown\nplayerfile-size"); PHYSFS_close(file); return -1; } if (saved_game_version <= 5) { //deal with old-style highest level info PlayerCfg.HighestLevels[0].Shortname[0] = 0; //no name for mission 0 PlayerCfg.HighestLevels[0].LevelNum = PlayerCfg.NHighestLevels; //was highest level in old struct //This hack allows the player to start on level 8 if he's made it to //level 7 on the shareware. We do this because the shareware didn't //save the information that the player finished level 7, so the most //we know is that he made it to level 7. if (PlayerCfg.NHighestLevels==7) PlayerCfg.HighestLevels[0].LevelNum = 8; } else { //read new highest level info if (PHYSFS_read(file,PlayerCfg.HighestLevels,sizeof(hli),PlayerCfg.NHighestLevels) != PlayerCfg.NHighestLevels) goto read_player_file_failed; } if ( saved_game_version != 7 ) { // Read old & SW saved games. if (PHYSFS_read(file,saved_games,sizeof(saved_games),1) != 1) goto read_player_file_failed; } //read taunt macros { int i; int len = shareware_file? 25:35; #ifdef NETWORK for (i = 0; i < 4; i++) if (PHYSFS_read(file, PlayerCfg.NetworkMessageMacro[i], len, 1) != 1) goto read_player_file_failed; #else i = 0; PHYSFS_seek( file, PHYSFS_tell(file)+4*len ); #endif } //read kconfig data { ubyte dummy_joy_sens; if (PHYSFS_read(file, &PlayerCfg.KeySettings[0], sizeof(PlayerCfg.KeySettings[0]),1)!=1) goto read_player_file_failed; if (PHYSFS_read(file, &PlayerCfg.KeySettings[1], sizeof(PlayerCfg.KeySettings[1]),1)!=1) goto read_player_file_failed; PHYSFS_seek( file, PHYSFS_tell(file)+(sizeof(ubyte)*MAX_CONTROLS*3) ); // Skip obsolete Flightstick/Thrustmaster/Gravis map fields if (PHYSFS_read(file, &PlayerCfg.KeySettings[2], sizeof(PlayerCfg.KeySettings[2]),1)!=1) goto read_player_file_failed; PHYSFS_seek( file, PHYSFS_tell(file)+(sizeof(ubyte)*MAX_CONTROLS) ); // Skip obsolete Cyberman map field if (PHYSFS_read(file, &PlayerCfg.ControlType, sizeof(ubyte), 1 )!=1) goto read_player_file_failed; else if (PHYSFS_read(file, &dummy_joy_sens, sizeof(ubyte), 1 )!=1) goto read_player_file_failed; } if ( saved_game_version != 7 ) { int i, found=0; Assert( N_SAVE_SLOTS == 10 ); for (i=0; i<N_SAVE_SLOTS; i++ ) { if ( saved_games[i].name[0] ) { state_save_old_game(i, saved_games[i].name, &saved_games[i].sg_player, saved_games[i].difficulty_level, saved_games[i].primary_weapon, saved_games[i].secondary_weapon, saved_games[i].next_level_num ); // make sure we do not do this again, which would possibly overwrite // a new newstyle savegame saved_games[i].name[0] = 0; found++; } } if (found) write_player_file(); } if (!PHYSFS_close(file)) goto read_player_file_failed; filename[strlen(filename) - 4] = 0; strcat(filename, ".plx"); read_player_d1x(filename); kc_set_controls(); return EZERO; read_player_file_failed: nm_messagebox(TXT_ERROR, 1, TXT_OK, "%s\n\n%s", "Error reading PLR file", PHYSFS_getLastError()); if (file) PHYSFS_close(file); return -1; }
int flubPhysfsInit(const char *appPath) { char working_dir[512]; int k; if(_physfsCtx.init) { warning("Ignoring attempt to re-initialize physfs."); return 1; } if(!logValid()) { // The logger has not been initiated! return 0; } logDebugRegister("file", DBG_FILE, "general", DBG_FILE_DTL_GENERAL); debug(DBG_FILE, DBG_FILE_DTL_GENERAL, "Initializing PHYSFS"); if(!PHYSFS_init(appPath)) { fatal("Failed to initialize the virtual file system."); return 0; } else { if(!PHYSFS_mount(getcwd(working_dir, sizeof(working_dir)), NULL, 1)) { fatalf("Failed to mount the current working directory (%s).", working_dir); return 0; } else { infof("Mounted current working directory: %s", working_dir); } if(!PHYSFS_mount(PHYSFS_getBaseDir(), NULL, 1)) { fatalf("Failed to mount the application's base dir (%s).", PHYSFS_getBaseDir()); return 0; } else { infof("Mounted base directory: %s", PHYSFS_getBaseDir()); } if(appDefaults.archiveFile != NULL) { infof("Mounting app archive file \"%s\".", appDefaults.archiveFile); if(!PHYSFS_mount(appDefaults.archiveFile, NULL, 1)) { fatalf("Failed to mount the application's archive file: %s", PHYSFS_getLastError()); return 0; } } else { debug(DBG_FILE, DBG_FILE_DTL_GENERAL, "No application archive file specified."); } for(k = 0; _flubMemfileResources[k].name != NULL; k++) { if(!PHYSFS_mount(PHYSFS_getMemfileName(_flubMemfileResources[k].memfile), NULL, 1)) { errorf("Failed to mount %s", _flubMemfileResources[k].name); } else { debugf(DBG_FILE, DBG_FILE_DTL_GENERAL, "Mounted flub resource file image [%s].", _flubMemfileResources[k].name); } } if(appDefaults.resources != NULL) { for(k = 0; appDefaults.resources[k].name != NULL; k++) { if(!PHYSFS_mount(PHYSFS_getMemfileName(appDefaults.resources[k].memfile), NULL, 1)) { errorf("Failed to mount %s", appDefaults.resources[k].name); } else { debugf(DBG_FILE, DBG_FILE_DTL_GENERAL, "Mounted application resource file image [%s].", appDefaults.resources[k].name); } } } else { debugf(DBG_FILE, DBG_FILE_DTL_GENERAL, "No application resource file images specified."); } debug(DBG_FILE, DBG_FILE_DTL_GENERAL, "Virtual file system started."); } _physfsCtx.init = 1; return 1; }
bange::box::box(const char *config, int argc, char *argv[]){ error = false; window = NULL; this->escapekey = sf::Keyboard::Escape; mouseDelta = 0; JoystickConnected = -1; JoystickDisconnected = -1; mouseEntered = false; windowFocus = false; vm = luaL_newstate(); bange::PrepareVM(vm); //Create a lua table with arguments lua_createtable(vm, argc, 0); for (int i = 0; i < argc; i += 1){ lua_pushstring(vm, argv[i]); lua_rawseti(vm, -2, i+1); } lua_setglobal(vm, "Args"); //--- if (luaL_dofile(vm, config)){ std::cout << "bange(lua): Error reading config file \"" << config << "\": " << lua_tostring(vm, -1) << std::endl; error = true; return; } //Get Window dimensions sf::VideoMode videomode(640, 480); lua_Number wh = 0; if (vm::GetNumber(vm, "Width", wh)){ videomode.Width = wh;} if (vm::GetNumber(vm, "Height", wh)){ videomode.Height = wh;} //Get Title char title[128] = "BAN Game Engine"; vm::GetString(vm, "Title", title, 128); //Set styles (fullscreen, close, resize, titlebar, none) unsigned long windowstyle = sf::Style::Close; //Set Window settings sf::ContextSettings contextsettings; //Create window window = new sf::RenderWindow(videomode, title, windowstyle, contextsettings); //Set FPS lua_Number FPS = 60; vm::GetNumber(vm, "FPS", FPS); window->SetFramerateLimit( static_cast<unsigned int>(FPS) ); //Set KeyRepeat int keyrepeat = 0; vm::GetBoolean(vm, "KeyRepeat", keyrepeat); window->EnableKeyRepeat((bool)keyrepeat); //Set VerticalSync int verticalsync = 0; vm::GetBoolean(vm, "VerticalSync", verticalsync); window->EnableVerticalSync((bool)verticalsync); //Set EscapeKey lua_Number escapekey = 0; if (vm::GetNumber(vm, "EscapeKey", escapekey)){ this->escapekey = static_cast<sf::Keyboard::Key>(escapekey);} //Store in lua environment this box lua_pushlightuserdata(vm, this); lua_setfield(vm, LUA_REGISTRYINDEX, "bange::box"); //Store in lua environment box's window lua_pushlightuserdata(vm, this->window); lua_setfield(vm, LUA_REGISTRYINDEX, "bange::box::window"); //Add packages if (bange::vm::GetTable(vm, "Packages")){ lua_pushnil(vm); while(lua_next(vm, -2)){ if (!lua_isstring(vm, -1)){ lua_pop(vm, 1); continue; } if (PHYSFS_addToSearchPath(lua_tostring(vm, -1), 0) == 0){ std::cout << "bange(physfs): " << lua_tostring(vm, -1) << ": " << PHYSFS_getLastError() << std::endl; } //next lua_pop(vm, 1); } lua_pop(vm, 1); } //Execute the run file char runfile[128] = "run.lua"; vm::GetString(vm, "Run", runfile, 128); luaL_openlibs(vm); if (luaL_dofile(vm, runfile)){ std::cout << "bange(lua): Error reading run file \"" << runfile << "\": " << lua_tostring(vm, -1) << std::endl; error = true; return; } std::cout << "Texture maximum size: " << sf::Texture::GetMaximumSize() << std::endl; }
/* Load a string resource file */ bool strresLoad(STR_RES* psRes, const char* fileName) { bool retval; lexerinput_t input; input.type = LEXINPUT_PHYSFS; input.input.physfsfile = PHYSFS_openRead(fileName); debug(LOG_WZ, "Reading...[directory %s] %s", PHYSFS_getRealDir(fileName), fileName); if (!input.input.physfsfile) { debug(LOG_ERROR, "strresLoadFile: PHYSFS_openRead(\"%s\") failed with error: %s\n", fileName, PHYSFS_getLastError()); return false; } strres_set_extra(&input); retval = (strres_parse(psRes) == 0); strres_lex_destroy(); PHYSFS_close(input.input.physfsfile); return retval; }
int main(int argc, char **argv) { int rc; char buf[128]; PHYSFS_File *f; if (!PHYSFS_init(argv[0])) { fprintf(stderr, "PHYSFS_init(): %s\n", PHYSFS_getLastError()); return 1; } /* if */ if (!PHYSFS_addToSearchPath(".", 1)) { fprintf(stderr, "PHYSFS_addToSearchPath(): %s\n", PHYSFS_getLastError()); PHYSFS_deinit(); return 1; } /* if */ if (!PHYSFS_setWriteDir(".")) { fprintf(stderr, "PHYSFS_setWriteDir(): %s\n", PHYSFS_getLastError()); PHYSFS_deinit(); return 1; } /* if */ if (!PHYSFS_mkdir("/a/b/c")) { fprintf(stderr, "PHYSFS_mkdir(): %s\n", PHYSFS_getLastError()); PHYSFS_deinit(); return 1; } /* if */ if (!PHYSFS_mkdir("/a/b/C")) { fprintf(stderr, "PHYSFS_mkdir(): %s\n", PHYSFS_getLastError()); PHYSFS_deinit(); return 1; } /* if */ f = PHYSFS_openWrite("/a/b/c/x.txt"); PHYSFS_close(f); if (f == NULL) { fprintf(stderr, "PHYSFS_openWrite(): %s\n", PHYSFS_getLastError()); PHYSFS_deinit(); return 1; } /* if */ f = PHYSFS_openWrite("/a/b/C/X.txt"); PHYSFS_close(f); if (f == NULL) { fprintf(stderr, "PHYSFS_openWrite(): %s\n", PHYSFS_getLastError()); PHYSFS_deinit(); return 1; } /* if */ strcpy(buf, "/a/b/c/x.txt"); rc = PHYSFSEXT_locateCorrectCase(buf); if ((rc != 0) || (strcmp(buf, "/a/b/c/x.txt") != 0)) printf("test 1 failed\n"); strcpy(buf, "/a/B/c/x.txt"); rc = PHYSFSEXT_locateCorrectCase(buf); if ((rc != 0) || (strcmp(buf, "/a/b/c/x.txt") != 0)) printf("test 2 failed\n"); strcpy(buf, "/a/b/C/x.txt"); rc = PHYSFSEXT_locateCorrectCase(buf); if ((rc != 0) || (strcmp(buf, "/a/b/C/X.txt") != 0)) printf("test 3 failed\n"); strcpy(buf, "/a/b/c/X.txt"); rc = PHYSFSEXT_locateCorrectCase(buf); if ((rc != 0) || (strcmp(buf, "/a/b/c/x.txt") != 0)) printf("test 4 failed\n"); strcpy(buf, "/a/b/c/z.txt"); rc = PHYSFSEXT_locateCorrectCase(buf); if ((rc != -1) || (strcmp(buf, "/a/b/c/z.txt") != 0)) printf("test 5 failed\n"); strcpy(buf, "/A/B/Z/z.txt"); rc = PHYSFSEXT_locateCorrectCase(buf); if ((rc != -2) || (strcmp(buf, "/a/b/Z/z.txt") != 0)) printf("test 6 failed\n"); printf("Testing completed.\n"); printf(" If no errors were reported, you're good to go.\n"); PHYSFS_delete("/a/b/c/x.txt"); PHYSFS_delete("/a/b/C/X.txt"); PHYSFS_delete("/a/b/c"); PHYSFS_delete("/a/b/C"); PHYSFS_delete("/a/b"); PHYSFS_delete("/a"); PHYSFS_deinit(); return 0; } /* main */
void FS_Init(lua_State *L, char *argv[], char **pFilename) { #ifdef __MACOSX__ char *ch = NULL; const char *basedir; #endif FILE *fh; char magic[4] = "000"; /* array for the magic bytes used to recognize a zip archive */ char *dir = NULL; char *base = NULL; char appdata[4096]; // char **search_path = NULL; // char **copy; /* initialize PhysFS */ if (PHYSFS_init(argv[0]) ==0) { error(L, "Error: Could not initialize PhysFS: %s.", PHYSFS_getLastError()); } /* allow symlinks */ PHYSFS_permitSymbolicLinks(1); /* on Mac OS X applications are packed inside a folder with the ending .app; try to set the search path to this folder; if a file is not found in the base dir (the dir containing the app bundle) it is searched inside the bundle */ #ifdef __MACOSX__ ch = strstr(argv[0], "/Contents/MacOS"); if (ch != NULL) { /* substite the 'C' of 'Contents/MacOS' with a string terminator */ *(ch+1) = '\0'; if (*pFilename == NULL) { /* if no filename was selected */ chdir(argv[0]); } /* append app folder to search path */ if (PHYSFS_addToSearchPath(argv[0], 1) == 0) { error(L, "Error: Could not add application folder" "to search path: %s.", PHYSFS_getLastError()); } *(ch+1) = 'C'; } else { basedir = PHYSFS_getBaseDir(); if (*pFilename == NULL) { chdir(basedir); } if (PHYSFS_addToSearchPath(basedir, 1) == 0) { error(L, "Error: Could not add base dir to search path: %s.", PHYSFS_getLastError()); } } #else /* check whether we are on Linux or Unix */ #ifndef __WIN32__ /* on Linux or Unix: Try to append the share directory */ #ifdef SHARE_DIR PHYSFS_addToSearchPath(SHARE_DIR, 1); #endif #endif /* on every system but OS X, prepend base dir to search path */ if (PHYSFS_addToSearchPath(PHYSFS_getBaseDir(), 0) == 0) { error(L, "Error: Could not add base dir to search path: %s.", PHYSFS_getLastError()); } #endif /* * if a Lua file is given, try to mount the parent directory and change * the working directory * if an archive or directory is given, try to mount it */ if (*pFilename == NULL) { *pFilename = (char *)DEFAULT_FILE; if (PHYSFS_exists(*pFilename) == 0) { /* if default file not exists */ if (PHYSFS_exists(DEFAULT_ARCHIVE) != 0) { /* if default archive exists, prepend to search path */ if (PHYSFS_addToSearchPath(DEFAULT_ARCHIVE, 0) == 0) { error(L, "Error: Could not add default archive '" DEFAULT_ARCHIVE "' to search path: %s", PHYSFS_getLastError()); } } else { error(L, "Error: " "Neither the default Lua file '" DEFAULT_FILE "' nor the default archive '" DEFAULT_ARCHIVE "' could be found."); } } } else { /* try to change the working directory (only successful if directory is given) */ if (chdir(*pFilename) == 0) { /* prepend the new working directory to the search path */ if (PHYSFS_addToSearchPath(".", 0) == 0) { error(L, "Error: Could not add directory '%s' to search path: %s", argv[1], PHYSFS_getLastError()); } *pFilename = (char *)DEFAULT_FILE; } else { /* chdir was unsuccessful -> archive or Lua file was probably given on command line */ splitPath(*pFilename, &dir, &base); /* change the working directory to the directory with the archive or the Lua file */ chdir(dir); /* check if it's an archive; only zip is supported, so we check for the magic numbers */ fh = fopen(base, "r"); if (fh == NULL) { error(L, "Error: Could not open file '%s' for reading.", argv[1]); } fread(magic, 1, 4, fh); fclose(fh); /* look for the four signature bytes that every zip file has */ if (magic[0] == 0x50 && magic[1] == 0x4B && magic[2] == 0x03 && magic[3] == 0x04) { // fprintf(stdout, "Found zip archive: %s\n", base); if (PHYSFS_addToSearchPath(base, 0) == 0) { error(L, "Error: Could not add archive '%s' to search path: %s", argv[1], PHYSFS_getLastError()); } *pFilename = (char *)DEFAULT_FILE; } else { // fprintf(stdout, "Found Lua file: %s\n", base); /* prepend the new working directory to the search path */ if (PHYSFS_addToSearchPath(".", 0) == 0) { error(L, "Error: Could not add directory containing '%s' to search path: %s", base, PHYSFS_getLastError()); } /* change the filename to its basename -> later call to FS_runLuaFile will find it in the path */ *pFilename = base; } } } // char * xdgdatahome = getenv("XDG_DATA_HOME"); //if (!xdgdatahome) //{ strcpy(appdata, PHYSFS_getUserDir()); #ifdef __GNUC__ strcat(appdata, "/.local/share/"); #else strcat(appdata, "Application Data"); #endif //} //else // strcpy(appdata, xdgdatahome); // printf("%s", appdata); if(!PHYSFS_setWriteDir(appdata)) error(L, "Error: Could not set write directory '%s': %s", appdata, PHYSFS_getLastError()); strcat(appdata, "/Scriptum Plus/"); // strcat(appdata, appName); //char * relative_path = strcat("./Scriptum Plus/", appName); if(!PHYSFS_mkdir("/Scriptum Plus/")) error(L, "Error: Could not create write directory '%s': %s", appdata, PHYSFS_getLastError()); if(!PHYSFS_setWriteDir(appdata)) error(L, "Error: Could not set write directory '%s': %s", appdata, PHYSFS_getLastError()); PHYSFS_addToSearchPath(appdata, 0); atexit(FS_Quit); // search_path = PHYSFS_getSearchPath(); // copy = search_path; // while (*copy != NULL) { // printf("search path: %s\n", *copy++); // } // PHYSFS_freeList(search_path); }
bool NETstopLogging(void) { static const char dash_line[] = "-----------------------------------------------------------\n"; char buf[256]; int i; UDWORD totalBytessent = 0, totalBytesrecv = 0, totalPacketsent = 0, totalPacketrecv = 0; if (!pFileHandle) { return false; } /* Output stats */ for (i = 0; i < NUM_GAME_PACKETS; i++) { if (!strcmp(messageTypeToString(i), "(UNUSED)")) { continue; } else { snprintf(buf, sizeof(buf), "%-24s:\t received %u times, %u bytes; sent %u times, %u bytes\n", messageTypeToString(i), packetcount[1][i], packetsize[1][i], packetcount[0][i], packetsize[0][i]); } PHYSFS_write(pFileHandle, buf, strlen(buf), 1); totalBytessent += packetsize[0][i]; totalBytesrecv += packetsize[1][i]; totalPacketsent += packetcount[0][i]; totalPacketrecv += packetcount[1][i]; } snprintf(buf, sizeof(buf), "== Total bytes sent %u, Total bytes received %u ==\n", totalBytessent, totalBytesrecv); PHYSFS_write(pFileHandle, buf, strlen(buf), 1); snprintf(buf, sizeof(buf), "== Total packets sent %u, recv %u ==\n", totalPacketsent, totalPacketrecv); PHYSFS_write(pFileHandle, buf, strlen(buf), 1); snprintf(buf, sizeof(buf), "\n-Sync statistics -\n"); PHYSFS_write(pFileHandle, buf, strlen(buf), 1); PHYSFS_write(pFileHandle, dash_line, strlen(dash_line), 1); snprintf(buf, sizeof(buf), "joins: %u, kicks: %u, drops: %u, left %u\n", sync_counter.joins, sync_counter.kicks, sync_counter.drops, sync_counter.left); PHYSFS_write(pFileHandle, buf, strlen(buf), 1); snprintf(buf, sizeof(buf), "banned: %u, cantjoin: %u, rejected: %u\n", sync_counter.banned, sync_counter.cantjoin, sync_counter.rejected); PHYSFS_write(pFileHandle, buf, strlen(buf), 1); if (sync_counter.banned && IPlist) { snprintf(buf, sizeof(buf), "Banned list:\n"); PHYSFS_write(pFileHandle, buf, strlen(buf), 1); for (i = 0; i < MAX_BANS; i++) { if (IPlist[i].IPAddress[0] != '\0') { snprintf(buf, sizeof(buf), "player %s, IP: %s\n", IPlist[i].pname, IPlist[i].IPAddress); PHYSFS_write(pFileHandle, buf, strlen(buf), 1); } } } PHYSFS_write(pFileHandle, dash_line, strlen(dash_line), 1); PHYSFS_write(pFileHandle, dash_line, strlen(dash_line), 1); if (!PHYSFS_close(pFileHandle)) { debug(LOG_ERROR, "Could not close net log: %s", PHYSFS_getLastError()); return false; } pFileHandle = NULL; return true; }
//* // ======================================================================================================================= // ======================================================================================================================= // TRACK *sound_LoadTrackFromFile(const char *fileName) { TRACK *pTrack; PHYSFS_file *fileHandle; size_t filename_size; char *track_name; // Use PhysicsFS to open the file fileHandle = PHYSFS_openRead(fileName); debug(LOG_NEVER, "Reading...[directory: %s] %s", PHYSFS_getRealDir(fileName), fileName); if (fileHandle == NULL) { debug(LOG_ERROR, "sound_LoadTrackFromFile: PHYSFS_openRead(\"%s\") failed with error: %s\n", fileName, PHYSFS_getLastError()); return NULL; } if (GetLastResourceFilename() == NULL) { // This is a non fatal error. We just can't find filename for some reason. debug(LOG_WARNING, "sound_LoadTrackFromFile: missing resource filename?"); filename_size = 0; } else { filename_size = strlen(GetLastResourceFilename()) + 1; } // allocate track, plus the memory required to contain the filename // one malloc call ensures only one free call is required pTrack = (TRACK *)malloc(sizeof(TRACK) + filename_size); if (pTrack == NULL) { debug(LOG_FATAL, "sound_ConstructTrack: couldn't allocate memory\n"); abort(); return NULL; } // Initialize everyting (except for the filename) to zero memset(pTrack, 0, sizeof(TRACK)); // Set filename pointer; if the filename (as returned by // GetLastResourceFilename()) is a NULL pointer, then this will be a // NULL pointer as well. track_name = filename_size ? (char *)(pTrack + 1) : NULL; // Copy the filename into the struct, if we don't have a NULL pointer if (filename_size != 0) { strcpy(track_name, GetLastResourceFilename()); } pTrack->fileName = track_name; // Now use sound_ReadTrackFromBuffer to decode the file's contents pTrack = sound_DecodeOggVorbisTrack(pTrack, fileHandle); PHYSFS_close(fileHandle); return pTrack; }
// //////////////////////////////////////////////////////////////////////////// // save current keymaps to registry // FIXME: Use the endian-safe physfs functions. bool saveKeyMap(void) { KEY_MAPPING *psMapping; SDWORD count; char name[128]; PHYSFS_file *pfile; // KeyMapPath debug(LOG_WZ, "We are to write %s for keymap info", KeyMapPath); pfile = PHYSFS_openWrite(KeyMapPath); if (!pfile) { // NOTE: Changed to LOG_FATAL, since we want to inform user via pop-up (windows only) debug(LOG_FATAL, "saveKeyMap: %s could not be created: %s", KeyMapPath, PHYSFS_getLastError()); assert(false); return false; } #define WRITE(var, size) \ if (PHYSFS_write(pfile, var, 1, size) != size) { \ debug(LOG_FATAL, "saveKeyMap: could not write to %s %d bytes: %s", \ KeyMapPath, (int)size, PHYSFS_getLastError()); \ assert(false); \ return false; \ } // write out number of entries. count = 0; for (psMapping = keyMappings; psMapping; psMapping = psMapping->psNext) { count++; } WRITE(&count, sizeof(count)); WRITE(&keymapVersion, 8); for(psMapping = keyMappings; psMapping; psMapping = psMapping->psNext) { // save this map. // name sstrcpy(name, psMapping->pName); WRITE(&name, 128); WRITE(&psMapping->status, sizeof(KEY_STATUS)); // status WRITE(&psMapping->metaKeyCode, sizeof(KEY_CODE)); // metakey WRITE(&psMapping->subKeyCode, sizeof(KEY_CODE)); // subkey WRITE(&psMapping->action, sizeof(KEY_ACTION)); // action // function to map to! for (count = 0; keyMapSaveTable[count] != NULL && keyMapSaveTable[count] != psMapping->function; count++) {} if(keyMapSaveTable[count] == NULL) { debug( LOG_FATAL, "can't find keymapped function %s in the keymap save table at %d!", name, count ); abort(); } WRITE(&count, sizeof(count)); } if (!PHYSFS_close(pfile)) { debug(LOG_FATAL, "Error closing %s: %s", KeyMapPath, PHYSFS_getLastError()); assert(false); return false; } debug(LOG_WZ, "Keymap written ok to %s.", KeyMapPath); return true; // saved ok. #undef WRITE }
ResourceManager::ResourceManager(const std::string &path) { mDefaultBody = 0; mDefaultFemale = 0; mDefaultHair = 0; mDefaultChest = 0; mDefaultLegs = 0; mDefaultFeet = 0; mBodyWidth = 0; mBodyHeight = 0; mNumParts = 5; // TODO: Calculate based on body.cfg std::string datapath = ""; std::string error; std::string dirName; // physfs code PHYSFS_init(path.c_str()); // add paths // writable first, since thats where updates will go to #if defined __unix__ mWriteDataPath = PHYSFS_getUserDir(); #elif defined __APPLE__ mWriteDataPath = PHYSFS_getUserDir(); mWriteDataPath.append("Library/Application Support/"); #elif defined _WIN32 TCHAR writePath[MAX_PATH+1]; SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, writePath); int length = _tcslen(writePath); mWriteDataPath.assign(&writePath[0], &writePath[length]); #endif #ifndef __unix__ dirName = "townslife"; #else dirName = ".townslife"; #endif PHYSFS_setWriteDir(mWriteDataPath.c_str()); if (!doesExist(dirName)) { if (PHYSFS_mkdir(dirName.c_str()) == 0) { error = PHYSFS_getLastError(); } } mWriteDataPath.append("/" + dirName); PHYSFS_setWriteDir(mWriteDataPath.c_str()); mWriteDataPath.append("/"); addPath(mWriteDataPath); // now add cfg and /data directory #if defined __unix__ datapath = PHYSFS_getBaseDir(); addPath(datapath); addPath(datapath + "data/"); #elif defined __APPLE__ CFBundleRef mainBundle = CFBundleGetMainBundle(); CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle); char resPath[PATH_MAX]; CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)resPath, PATH_MAX); CFRelease(resourcesURL); addPath(resPath); #elif defined _WIN32 TCHAR exePath[MAX_PATH+1]; GetModuleFileName(0, exePath, MAX_PATH); length = _tcslen(exePath); datapath.append(&exePath[0], &exePath[length]); datapath = datapath.substr(0, datapath.find_last_of("\\") + 1); addPath(datapath); addPath(datapath + "data\\"); #endif }
// //////////////////////////////////////////////////////////////////////////// // load keymaps from registry. bool loadKeyMap(void) { KEY_STATUS status; KEY_CODE metaCode; KEY_CODE subCode; KEY_ACTION action; char name[128]; SDWORD count; UDWORD funcmap; char ver[8]; PHYSFS_file *pfile; PHYSFS_sint64 filesize; PHYSFS_sint64 countsize = 0; PHYSFS_sint64 length_read; // throw away any keymaps!! keyClearMappings(); if (!PHYSFS_exists(KeyMapPath)) { debug(LOG_WZ, "%s not found", KeyMapPath); return false; } pfile = PHYSFS_openRead(KeyMapPath); if (!pfile) { // NOTE: Changed to LOG_FATAL, since we want to inform user via pop-up (windows only) debug(LOG_FATAL, "loadKeyMap: [directory: %s] %s could not be opened: %s", PHYSFS_getRealDir(KeyMapPath), KeyMapPath, PHYSFS_getLastError()); assert(false); return false; } filesize = PHYSFS_fileLength(pfile); #define READ(var, size) \ length_read = PHYSFS_read(pfile, var, 1, size); \ countsize += length_read; \ if (length_read != size) { \ debug(LOG_FATAL, "loadKeyMap: Reading %s short: %s", \ KeyMapPath, PHYSFS_getLastError()); \ assert(false); \ (void) PHYSFS_close(pfile); \ return false; \ } READ(&count, sizeof(count)); READ(&ver, 8); // get version number. if (strncmp(ver, keymapVersion, 8) != 0) { /* If wrong version, create a new one instead. */ PHYSFS_close(pfile); return false; } for(; count > 0; count--) { READ(&name, 128); // name READ(&status, sizeof(KEY_STATUS)); // status READ(&metaCode, sizeof(KEY_CODE)); // metakey READ(&subCode, sizeof(KEY_CODE)); // subkey READ(&action, sizeof(KEY_ACTION)); // action READ(&funcmap, sizeof(funcmap)); // function // add mapping keyAddMapping( status, metaCode, subCode, action, keyMapSaveTable[funcmap],(char*)&name); } if (!PHYSFS_close(pfile)) { debug(LOG_ERROR, "Error closing %s: %s", KeyMapPath, PHYSFS_getLastError()); assert(false); return false; } if (countsize != filesize) { debug(LOG_FATAL, "File size different from bytes read!"); assert(false); } return true; }
void piggy_read_sounds(int pc_shareware) { ubyte * ptr; int i, sbytes; int lastsize = 0; ubyte * lastbuf = NULL; if (MacPig) { // Read Mac sounds converted to RAW format (too messy to read them directly from the resource fork code-wise) char soundfile[32] = "Sounds/sounds.array"; extern int ds_load(int skip, char * filename ); PHYSFS_file *array = PHYSFSX_openReadBuffered(soundfile); // hack for Mac Demo if (!array && (PHYSFSX_fsize(DEFAULT_PIGFILE_REGISTERED) == D1_MAC_SHARE_PIGSIZE)) { con_printf(CON_URGENT,"Warning: Missing Sounds/sounds.array for Mac data files"); return; } else if (array) { if (PHYSFS_read(array, Sounds, MAX_SOUNDS, 1) != 1) // make the 'Sounds' index array match with the sounds we're about to read in { con_printf(CON_URGENT,"Warning: Can't read Sounds/sounds.array: %s", PHYSFS_getLastError()); PHYSFS_close(array); return; } PHYSFS_close(array); } for (i = 0; i < MAX_SOUND_FILES; i++) { sprintf(soundfile, "SND%04d.raw", i); if (ds_load(0, soundfile) == 255) break; } return; } ptr = SoundBits; sbytes = 0; for (i=0; i<Num_sound_files; i++ ) { digi_sound *snd = &GameSounds[i]; if ( SoundOffset[i] > 0 ) { if ( piggy_is_needed(i) ) { PHYSFSX_fseek( Piggy_fp, SoundOffset[i], SEEK_SET ); // Read in the sound data!!! snd->data = ptr; #ifdef ALLEGRO ptr += snd->len; sbytes += snd->len; #else ptr += snd->length; sbytes += snd->length; #endif //Arne's decompress for shareware on all soundcards - [email protected] if (pc_shareware) { if (lastsize < SoundCompressed[i]) { if (lastbuf) d_free(lastbuf); lastbuf = d_malloc(SoundCompressed[i]); } PHYSFS_read( Piggy_fp, lastbuf, SoundCompressed[i], 1 ); sound_decompress( lastbuf, SoundCompressed[i], snd->data ); } else #ifdef ALLEGRO PHYSFS_read( Piggy_fp, snd->data, snd->len, 1 ); #else PHYSFS_read( Piggy_fp, snd->data, snd->length, 1 ); #endif } } } if (lastbuf) d_free(lastbuf); }
int main(int argc, char **argv) { char *buf = NULL; int rc = 0; (void)argc; #if (defined __MWERKS__) extern tSIOUXSettings SIOUXSettings; SIOUXSettings.asktosaveonclose = 0; SIOUXSettings.autocloseonquit = 1; SIOUXSettings.rows = 40; SIOUXSettings.columns = 120; #endif printf("\n"); if (!PHYSFS_init(argv[0])) { printf("PHYSFS_init() failed!\n reason: %s.\n", PHYSFS_getLastError()); return(1); } /* if */ output_versions(); output_archivers(); open_history_file(); printf("Enter commands. Enter \"help\" for instructions.\n"); do { #if (defined PHYSFS_HAVE_READLINE) buf = readline("> "); #else int i; buf = (char *) malloc(512); memset(buf, '\0', 512); printf("> "); for (i = 0; i < 511; i++) { int ch = fgetc(stdin); if (ch == EOF) { strcpy(buf, "quit"); break; } /* if */ else if ((ch == '\n') || (ch == '\r')) { buf[i] = '\0'; break; } /* else if */ else if (ch == '\b') { if (i > 0) i--; } /* else if */ else { buf[i] = (char) ch; } /* else */ } /* for */ #endif rc = process_command(buf); if (buf != NULL) free(buf); } while (rc); if (!PHYSFS_deinit()) printf("PHYSFS_deinit() failed!\n reason: %s.\n", PHYSFS_getLastError()); if (history_file) fclose(history_file); /* printf("\n\ntest_physfs written by ryan c. gordon.\n"); printf(" it makes you shoot teh railgun bettar.\n"); */ return(0); } /* main */
bool Mount(std::string path, std::string fsPath) { if (!IsLoaded()) { Logger::begin("Filesystem", Logger::LogLevel_Error) << "FS not loaded" << Logger::end(); assert(false); return false; } int result = PHYSFS_mount(path.c_str(), fsPath.c_str(), 1); if (result == 0) { Logger::begin("Filesystem", Logger::LogLevel_Error) << "Error Mounting " << PHYSFS_getLastError() << Logger::end(); } return result > 0; }
static int cmd_getlasterror(char *args) { (void)args; printf("last error is [%s].\n", PHYSFS_getLastError()); return(1); } /* cmd_getlasterror */
std::string makeSafePhysfsErrorString() { const char* physfserror = PHYSFS_getLastError(); return physfserror != 0 ? physfserror : "no physfs error message available."; }
static int cmd_stressbuffer(char *args) { int num; if (*args == '\"') { args++; args[strlen(args) - 1] = '\0'; } /* if */ num = atoi(args); if (num < 0) printf("buffer must be greater than or equal to zero.\n"); else { PHYSFS_File *f; int rndnum; printf("Stress testing with (%d) byte buffer...\n", num); f = PHYSFS_openWrite("test.txt"); if (f == NULL) printf("Couldn't open test.txt for writing: %s.\n", PHYSFS_getLastError()); else { int i, j; char buf[37]; char buf2[37]; if (!PHYSFS_setBuffer(f, num)) { printf("PHYSFS_setBuffer() failed: %s.\n", PHYSFS_getLastError()); PHYSFS_close(f); PHYSFS_delete("test.txt"); return(1); } /* if */ strcpy(buf, "abcdefghijklmnopqrstuvwxyz0123456789"); srand((unsigned int) time(NULL)); for (i = 0; i < 10; i++) { for (j = 0; j < 10000; j++) { PHYSFS_uint32 right = 1 + (PHYSFS_uint32) (35.0 * rand() / (RAND_MAX + 1.0)); PHYSFS_uint32 left = 36 - right; if (PHYSFS_write(f, buf, left, 1) != 1) { printf("PHYSFS_write() failed: %s.\n", PHYSFS_getLastError()); PHYSFS_close(f); return(1); } /* if */ rndnum = 1 + (int) (1000.0 * rand() / (RAND_MAX + 1.0)); if (rndnum == 42) { if (!PHYSFS_flush(f)) { printf("PHYSFS_flush() failed: %s.\n", PHYSFS_getLastError()); PHYSFS_close(f); return(1); } /* if */ } /* if */ if (PHYSFS_write(f, buf + left, 1, right) != right) { printf("PHYSFS_write() failed: %s.\n", PHYSFS_getLastError()); PHYSFS_close(f); return(1); } /* if */ rndnum = 1 + (int) (1000.0 * rand() / (RAND_MAX + 1.0)); if (rndnum == 42) { if (!PHYSFS_flush(f)) { printf("PHYSFS_flush() failed: %s.\n", PHYSFS_getLastError()); PHYSFS_close(f); return(1); } /* if */ } /* if */ } /* for */ if (!PHYSFS_flush(f)) { printf("PHYSFS_flush() failed: %s.\n", PHYSFS_getLastError()); PHYSFS_close(f); return(1); } /* if */ } /* for */ if (!PHYSFS_close(f)) { printf("PHYSFS_close() failed: %s.\n", PHYSFS_getLastError()); return(1); /* oh well. */ } /* if */ printf(" ... test file written ...\n"); f = PHYSFS_openRead("test.txt"); if (f == NULL) { printf("Failed to reopen stress file for reading: %s.\n", PHYSFS_getLastError()); return(1); } /* if */ if (!PHYSFS_setBuffer(f, num)) { printf("PHYSFS_setBuffer() failed: %s.\n", PHYSFS_getLastError()); PHYSFS_close(f); return(1); } /* if */ for (i = 0; i < 10; i++) { for (j = 0; j < 10000; j++) { PHYSFS_uint32 right = 1 + (PHYSFS_uint32) (35.0 * rand() / (RAND_MAX + 1.0)); PHYSFS_uint32 left = 36 - right; if (PHYSFS_read(f, buf2, left, 1) != 1) { printf("PHYSFS_read() failed: %s.\n", PHYSFS_getLastError()); PHYSFS_close(f); return(1); } /* if */ rndnum = 1 + (int) (1000.0 * rand() / (RAND_MAX + 1.0)); if (rndnum == 42) { if (!PHYSFS_flush(f)) { printf("PHYSFS_flush() failed: %s.\n", PHYSFS_getLastError()); PHYSFS_close(f); return(1); } /* if */ } /* if */ if (PHYSFS_read(f, buf2 + left, 1, right) != right) { printf("PHYSFS_read() failed: %s.\n", PHYSFS_getLastError()); PHYSFS_close(f); return(1); } /* if */ rndnum = 1 + (int) (1000.0 * rand() / (RAND_MAX + 1.0)); if (rndnum == 42) { if (!PHYSFS_flush(f)) { printf("PHYSFS_flush() failed: %s.\n", PHYSFS_getLastError()); PHYSFS_close(f); return(1); } /* if */ } /* if */ if (memcmp(buf, buf2, 36) != 0) { printf("readback is mismatched on iterations (%d, %d).\n", i, j); printf("wanted: ["); for (i = 0; i < 36; i++) printf("%c", buf[i]); printf("]\n"); printf(" got: ["); for (i = 0; i < 36; i++) printf("%c", buf2[i]); printf("]\n"); PHYSFS_close(f); return(1); } /* if */ } /* for */ if (!PHYSFS_flush(f)) { printf("PHYSFS_flush() failed: %s.\n", PHYSFS_getLastError()); PHYSFS_close(f); return(1); } /* if */ } /* for */ printf(" ... test file read ...\n"); if (!PHYSFS_eof(f)) printf("PHYSFS_eof() returned true! That's wrong.\n"); if (!PHYSFS_close(f)) { printf("PHYSFS_close() failed: %s.\n", PHYSFS_getLastError()); return(1); /* oh well. */ } /* if */ PHYSFS_delete("test.txt"); printf("stress test completed successfully.\n"); } /* else */ } /* else */ return(1); } /* cmd_stressbuffer */