Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

958 lines
38 KiB

  1. //===== Copyright � 1996-2005, Valve Corporation, All rights reserved. ======//
  2. //
  3. // Purpose:
  4. //
  5. // $NoKeywords: $
  6. //===========================================================================//
  7. #ifndef FILESYSTEM_H
  8. #define FILESYSTEM_H
  9. #ifdef _WIN32
  10. #pragma once
  11. #endif
  12. #include <limits.h>
  13. #include "tier0/threadtools.h"
  14. #include "tier0/memalloc.h"
  15. #include "tier0/tslist.h"
  16. #include "tier1/interface.h"
  17. #include "tier1/utlsymbol.h"
  18. #include "tier1/utlstring.h"
  19. #include "tier1/functors.h"
  20. #include "tier1/checksum_crc.h"
  21. #include "tier1/utlqueue.h"
  22. #include "appframework/iappsystem.h"
  23. #include "tier2/tier2.h"
  24. #ifdef _PS3
  25. #include <sysutil/sysutil_syscache.h>
  26. #include <sysutil/sysutil_gamecontent.h>
  27. struct HddCacheFileStatus;
  28. extern char gSrcGameDataPath[];
  29. class CFileGroupSystem;
  30. #endif
  31. //-----------------------------------------------------------------------------
  32. // Forward declarations
  33. //-----------------------------------------------------------------------------
  34. class CUtlBuffer;
  35. class KeyValues;
  36. class IFileList;
  37. typedef void * FileHandle_t;
  38. typedef int FileFindHandle_t;
  39. typedef void (*FileSystemLoggingFunc_t)( const char *fileName, const char *accessType );
  40. typedef int WaitForResourcesHandle_t;
  41. #ifdef _X360
  42. typedef void* HANDLE;
  43. #endif
  44. //-----------------------------------------------------------------------------
  45. // Enums used by the interface
  46. //-----------------------------------------------------------------------------
  47. #define FILESYSTEM_MAX_SEARCH_PATHS 128
  48. enum FileSystemSeek_t
  49. {
  50. FILESYSTEM_SEEK_HEAD = SEEK_SET,
  51. FILESYSTEM_SEEK_CURRENT = SEEK_CUR,
  52. FILESYSTEM_SEEK_TAIL = SEEK_END,
  53. };
  54. enum
  55. {
  56. FILESYSTEM_INVALID_FIND_HANDLE = -1
  57. };
  58. enum FileWarningLevel_t
  59. {
  60. // A problem!
  61. FILESYSTEM_WARNING = -1,
  62. // Don't print anything
  63. FILESYSTEM_WARNING_QUIET = 0,
  64. // On shutdown, report names of files left unclosed
  65. FILESYSTEM_WARNING_REPORTUNCLOSED,
  66. // Report number of times a file was opened, closed
  67. FILESYSTEM_WARNING_REPORTUSAGE,
  68. // Report all open/close events to console ( !slow! )
  69. FILESYSTEM_WARNING_REPORTALLACCESSES,
  70. // Report all open/close/read events to the console ( !slower! )
  71. FILESYSTEM_WARNING_REPORTALLACCESSES_READ,
  72. // Report all open/close/read/write events to the console ( !slower! )
  73. FILESYSTEM_WARNING_REPORTALLACCESSES_READWRITE,
  74. // Report all open/close/read/write events and all async I/O file events to the console ( !slower(est)! )
  75. FILESYSTEM_WARNING_REPORTALLACCESSES_ASYNC,
  76. };
  77. // search path filtering
  78. enum PathTypeFilter_t
  79. {
  80. FILTER_NONE = 0, // no filtering, all search path types match
  81. FILTER_CULLPACK = 1, // pack based search paths are culled (maps and zips)
  82. FILTER_CULLNONPACK = 2, // non-pack based search paths are culled
  83. FILTER_CULLLOCALIZED = 3, // Ignore localized paths, assumes CULLNONPACK
  84. FILTER_CULLLOCALIZED_ANY = 4, // Ignore any localized paths
  85. };
  86. // search path querying (bit flags)
  87. enum
  88. {
  89. PATH_IS_NORMAL = 0x00, // normal path, not pack based
  90. PATH_IS_PACKFILE = 0x01, // path is a pack file
  91. PATH_IS_MAPPACKFILE = 0x02, // path is a map pack file
  92. PATH_IS_DVDDEV = 0x04, // path is the dvddev cache
  93. };
  94. typedef uint32 PathTypeQuery_t;
  95. #define IS_PACKFILE( n ) ( n & ( PATH_IS_PACKFILE | PATH_IS_MAPPACKFILE ) )
  96. #define IS_DVDDEV( n ) ( n & PATH_IS_DVDDEV )
  97. enum DVDMode_t
  98. {
  99. DVDMODE_OFF = 0, // not using dvd
  100. DVDMODE_STRICT = 1, // dvd device only
  101. DVDMODE_DEV = 2, // dev mode, mutiple devices ok
  102. DVDMODE_DEV_VISTA = 3, // dev mode from a vista host, mutiple devices ok
  103. };
  104. #ifdef _PS3
  105. enum FsState_t
  106. {
  107. FS_STATE_INIT = 0,
  108. FS_STATE_LEVEL_LOAD = 1,
  109. FS_STATE_LEVEL_RUN = 2,
  110. FS_STATE_LEVEL_RESTORE = 3,
  111. FS_STATE_LEVEL_LOAD_END = 4,
  112. FS_STATE_EXITING = 5
  113. };
  114. enum Ps3FileType_t
  115. {
  116. PS3_FILETYPE_WAV,
  117. PS3_FILETYPE_ANI,
  118. PS3_FILETYPE_BSP,
  119. PS3_FILETYPE_VMT,
  120. PS3_FILETYPE_QPRE,
  121. PS3_FILETYPE_OTHER,
  122. PS3_FILETYPE_DIR,
  123. PS3_FILETYPE_UNKNOWN
  124. };
  125. #endif
  126. // In non-retail builds, enable the file blocking access tracking stuff...
  127. #if defined( TRACK_BLOCKING_IO )
  128. enum FileBlockingWarning_t
  129. {
  130. // Report how long synchronous i/o took to complete
  131. FILESYSTEM_BLOCKING_SYNCHRONOUS = 0,
  132. // Report how long async i/o took to complete if AsyncFileFinished caused it to load via "blocking" i/o
  133. FILESYSTEM_BLOCKING_ASYNCHRONOUS_BLOCK,
  134. // Report how long async i/o took to complete
  135. FILESYSTEM_BLOCKING_ASYNCHRONOUS,
  136. // Report how long the async "callback" took
  137. FILESYSTEM_BLOCKING_CALLBACKTIMING,
  138. FILESYSTEM_BLOCKING_NUMBINS,
  139. };
  140. #pragma pack(1)
  141. class FileBlockingItem
  142. {
  143. public:
  144. enum
  145. {
  146. FB_ACCESS_OPEN = 1,
  147. FB_ACCESS_CLOSE = 2,
  148. FB_ACCESS_READ = 3,
  149. FB_ACCESS_WRITE = 4,
  150. FB_ACCESS_APPEND = 5,
  151. FB_ACCESS_SIZE = 6
  152. };
  153. FileBlockingItem() :
  154. m_ItemType( (FileBlockingWarning_t)0 ),
  155. m_flElapsed( 0.0f ),
  156. m_nAccessType( 0 )
  157. {
  158. SetFileName( NULL );
  159. }
  160. FileBlockingItem( int type, char const *filename, float elapsed, int accessType ) :
  161. m_ItemType( (FileBlockingWarning_t)type ),
  162. m_flElapsed( elapsed ),
  163. m_nAccessType( accessType )
  164. {
  165. SetFileName( filename );
  166. }
  167. void SetFileName( char const *filename )
  168. {
  169. if ( !filename )
  170. {
  171. m_szFilename[ 0 ] = 0;
  172. return;
  173. }
  174. int len = V_strlen( filename );
  175. if ( len >= sizeof( m_szFilename ) )
  176. {
  177. V_strncpy( m_szFilename, &filename[ len - sizeof( m_szFilename ) + 1 ], sizeof( m_szFilename ) );
  178. }
  179. else
  180. {
  181. V_strncpy( m_szFilename, filename, sizeof( m_szFilename ) );
  182. }
  183. }
  184. char const *GetFileName() const
  185. {
  186. return m_szFilename;
  187. }
  188. FileBlockingWarning_t m_ItemType;
  189. float m_flElapsed;
  190. byte m_nAccessType;
  191. private:
  192. char m_szFilename[ 32 ];
  193. };
  194. #pragma pack()
  195. class IBlockingFileItemList
  196. {
  197. public:
  198. // You can't call any of the below calls without locking first
  199. virtual void LockMutex() = 0;
  200. virtual void UnlockMutex() = 0;
  201. virtual int First() const = 0;
  202. virtual int Next( int i ) const = 0;
  203. virtual int InvalidIndex() const = 0;
  204. virtual const FileBlockingItem& Get( int index ) const = 0;
  205. virtual void Reset() = 0;
  206. };
  207. #endif // TRACK_BLOCKING_IO
  208. enum FilesystemMountRetval_t
  209. {
  210. FILESYSTEM_MOUNT_OK = 0,
  211. FILESYSTEM_MOUNT_FAILED,
  212. };
  213. enum SearchPathAdd_t
  214. {
  215. PATH_ADD_TO_HEAD, // First path searched
  216. PATH_ADD_TO_TAIL, // Last path searched
  217. PATH_ADD_TO_TAIL_ATINDEX, // First path searched
  218. };
  219. enum FilesystemOpenExFlags_t
  220. {
  221. FSOPEN_UNBUFFERED = (1 << 0),
  222. FSOPEN_FORCE_TRACK_CRC = (1 << 1), // This makes it calculate a CRC for the file (if the file came from disk) regardless
  223. // of the IFileList passed to RegisterFileWhitelist.
  224. FSOPEN_NEVERINPACK = (1 << 2), // 360 only, hint to FS that file is not allowed to be in pack file
  225. };
  226. #define FILESYSTEM_INVALID_HANDLE ( FileHandle_t )0
  227. //-----------------------------------------------------------------------------
  228. // Structures used by the interface
  229. //-----------------------------------------------------------------------------
  230. struct FileSystemStatistics
  231. {
  232. CInterlockedUInt nReads,
  233. nWrites,
  234. nBytesRead,
  235. nBytesWritten,
  236. nSeeks;
  237. };
  238. //-----------------------------------------------------------------------------
  239. // File system allocation functions. Client must free on failure
  240. //-----------------------------------------------------------------------------
  241. typedef void *(*FSAllocFunc_t)( const char *pszFilename, unsigned nBytes );
  242. //-----------------------------------------------------------------------------
  243. // Used to display dirty disk error functions
  244. //-----------------------------------------------------------------------------
  245. typedef void (*FSDirtyDiskReportFunc_t)();
  246. //-----------------------------------------------------------------------------
  247. // Asynchronous support types
  248. //-----------------------------------------------------------------------------
  249. DECLARE_POINTER_HANDLE(FSAsyncControl_t);
  250. DECLARE_POINTER_HANDLE(FSAsyncFile_t);
  251. const FSAsyncFile_t FS_INVALID_ASYNC_FILE = (FSAsyncFile_t)(0x0000ffff);
  252. //---------------------------------------------------------
  253. // Async file status
  254. //---------------------------------------------------------
  255. enum FSAsyncStatus_t
  256. {
  257. FSASYNC_ERR_ALIGNMENT = -6, // read parameters invalid for unbuffered IO
  258. FSASYNC_ERR_FAILURE = -5, // hard subsystem failure
  259. FSASYNC_ERR_READING = -4, // read error on file
  260. FSASYNC_ERR_NOMEMORY = -3, // out of memory for file read
  261. FSASYNC_ERR_UNKNOWNID = -2, // caller's provided id is not recognized
  262. FSASYNC_ERR_FILEOPEN = -1, // filename could not be opened (bad path, not exist, etc)
  263. FSASYNC_OK = 0, // operation is successful
  264. FSASYNC_STATUS_PENDING, // file is properly queued, waiting for service
  265. FSASYNC_STATUS_INPROGRESS, // file is being accessed
  266. FSASYNC_STATUS_ABORTED, // file was aborted by caller
  267. FSASYNC_STATUS_UNSERVICED, // file is not yet queued
  268. };
  269. //---------------------------------------------------------
  270. // Async request flags
  271. //---------------------------------------------------------
  272. enum FSAsyncFlags_t
  273. {
  274. FSASYNC_FLAGS_ALLOCNOFREE = ( 1 << 0 ), // do the allocation for dataPtr, but don't free
  275. FSASYNC_FLAGS_FREEDATAPTR = ( 1 << 1 ), // free the memory for the dataPtr post callback
  276. FSASYNC_FLAGS_SYNC = ( 1 << 2 ), // Actually perform the operation synchronously. Used to simplify client code paths
  277. FSASYNC_FLAGS_NULLTERMINATE = ( 1 << 3 ), // allocate an extra byte and null terminate the buffer read in
  278. };
  279. //---------------------------------------------------------
  280. // Return value for CheckFileCRC.
  281. //---------------------------------------------------------
  282. enum EFileCRCStatus
  283. {
  284. k_eFileCRCStatus_CantOpenFile, // We don't have this file.
  285. k_eFileCRCStatus_GotCRC
  286. };
  287. // Used in CacheFileCRCs.
  288. enum ECacheCRCType
  289. {
  290. k_eCacheCRCType_SingleFile,
  291. k_eCacheCRCType_Directory,
  292. k_eCacheCRCType_Directory_Recursive
  293. };
  294. //---------------------------------------------------------
  295. // Optional completion callback for each async file serviced (or failed)
  296. // call is not reentrant, async i/o guaranteed suspended until return
  297. // Note: If you change the signature of the callback, you will have to account for it in FileSystemV12 (toml [4/18/2005] )
  298. //---------------------------------------------------------
  299. struct FileAsyncRequest_t;
  300. typedef void (*FSAsyncCallbackFunc_t)(const FileAsyncRequest_t &request, int nBytesRead, FSAsyncStatus_t err);
  301. //-----------------------------------------------------------------------------
  302. // Used to add results from async directory scans
  303. //-----------------------------------------------------------------------------
  304. typedef void (*FSAsyncScanAddFunc_t)( void* pContext, char* pFoundPath, char* pFoundFile );
  305. typedef void (*FSAsyncScanCompleteFunc_t)( void* pContext, FSAsyncStatus_t err );
  306. //---------------------------------------------------------
  307. // Description of an async request
  308. //---------------------------------------------------------
  309. struct FileAsyncRequest_t
  310. {
  311. FileAsyncRequest_t() { memset( this, 0, sizeof(*this) ); hSpecificAsyncFile = FS_INVALID_ASYNC_FILE; }
  312. const char * pszFilename; // file system name
  313. void * pData; // optional, system will alloc/free if NULL
  314. int nOffset; // optional initial seek_set, 0=beginning
  315. int nBytes; // optional read clamp, -1=exist test, 0=full read
  316. FSAsyncCallbackFunc_t pfnCallback; // optional completion callback
  317. void * pContext; // caller's unique file identifier
  318. int priority; // inter list priority, 0=lowest
  319. unsigned flags; // behavior modifier
  320. const char * pszPathID; // path ID (NOTE: this field is here to remain binary compatible with release HL2 filesystem interface)
  321. FSAsyncFile_t hSpecificAsyncFile; // Optional hint obtained using AsyncBeginRead()
  322. FSAllocFunc_t pfnAlloc; // custom allocator. can be null. not compatible with FSASYNC_FLAGS_FREEDATAPTR
  323. };
  324. class CUnverifiedCRCFile
  325. {
  326. public:
  327. char m_PathID[MAX_PATH];
  328. char m_Filename[MAX_PATH];
  329. CRC32_t m_CRC;
  330. };
  331. // Spew flags for SetWhitelistSpewFlags (set with the fs_whitelist_spew_flags cvar).
  332. // Update the comment for the fs_whitelist_spew_flags cvar if you change these.
  333. #define WHITELIST_SPEW_WHILE_LOADING 0x0001 // list files as they are added to the CRC tracker
  334. #define WHITELIST_SPEW_RELOAD_FILES 0x0002 // show files the filesystem is telling the engine to reload
  335. #define WHITELIST_SPEW_DONT_RELOAD_FILES 0x0004 // show files the filesystem is NOT telling the engine to reload
  336. // DLC license mask flags is 32 publisher defined bits
  337. // MSW 16 bits in 8.8: Type.SubVersion
  338. // LSW 16 bits: Flags
  339. // return id component
  340. #define DLC_LICENSE_ID( x ) ( ( ( (unsigned int)( x ) ) >> 24 ) & 0x000000FF )
  341. // returns minor version component (not generally used, i.e. we dont rev dlc's yet)
  342. #define DLC_LICENSE_MINORVERSION( x ) ( ( ( (unsigned int)( x ) ) >> 16 ) & 0x000000FF )
  343. // returns license flags
  344. #define DLC_LICENSE_FLAGS( x ) ( ( ( (unsigned int)( x ) ) & 0x0000FFFF ) )
  345. #define DLCFLAGS_PRESENCE_ONLY 0x0001 // causes no search path loadout
  346. //-----------------------------------------------------------------------------
  347. // Base file system interface
  348. //-----------------------------------------------------------------------------
  349. // This is the minimal interface that can be implemented to provide access to
  350. // a named set of files.
  351. #define BASEFILESYSTEM_INTERFACE_VERSION "VBaseFileSystem011"
  352. abstract_class IBaseFileSystem
  353. {
  354. public:
  355. virtual int Read( void* pOutput, int size, FileHandle_t file ) = 0;
  356. virtual int Write( void const* pInput, int size, FileHandle_t file ) = 0;
  357. // if pathID is NULL, all paths will be searched for the file
  358. virtual FileHandle_t Open( const char *pFileName, const char *pOptions, const char *pathID = 0 ) = 0;
  359. virtual void Close( FileHandle_t file ) = 0;
  360. virtual void Seek( FileHandle_t file, int pos, FileSystemSeek_t seekType ) = 0;
  361. virtual unsigned int Tell( FileHandle_t file ) = 0;
  362. virtual unsigned int Size( FileHandle_t file ) = 0;
  363. virtual unsigned int Size( const char *pFileName, const char *pPathID = 0 ) = 0;
  364. virtual void Flush( FileHandle_t file ) = 0;
  365. virtual bool Precache( const char *pFileName, const char *pPathID = 0 ) = 0;
  366. virtual bool FileExists( const char *pFileName, const char *pPathID = 0 ) = 0;
  367. virtual bool IsFileWritable( char const *pFileName, const char *pPathID = 0 ) = 0;
  368. virtual bool SetFileWritable( char const *pFileName, bool writable, const char *pPathID = 0 ) = 0;
  369. virtual long GetFileTime( const char *pFileName, const char *pPathID = 0 ) = 0;
  370. //--------------------------------------------------------
  371. // Reads/writes files to utlbuffers. Use this for optimal read performance when doing open/read/close
  372. //--------------------------------------------------------
  373. virtual bool ReadFile( const char *pFileName, const char *pPath, CUtlBuffer &buf, int nMaxBytes = 0, int nStartingByte = 0, FSAllocFunc_t pfnAlloc = NULL ) = 0;
  374. virtual bool WriteFile( const char *pFileName, const char *pPath, CUtlBuffer &buf ) = 0;
  375. virtual bool UnzipFile( const char *pFileName, const char *pPath, const char *pDestination ) = 0;
  376. };
  377. abstract_class IIoStats
  378. {
  379. public:
  380. virtual void OnFileSeek( int nTimeInMs ) = 0;
  381. virtual void OnFileRead( int nTimeInMs, int nBytesRead ) = 0;
  382. virtual void OnFileOpen( const char * pFileName ) = 0;
  383. virtual int GetNumberOfFileSeeks() = 0;
  384. virtual int GetTimeInFileSeek() = 0;
  385. virtual int GetNumberOfFileReads() = 0;
  386. virtual int GetTimeInFileReads() = 0;
  387. virtual int GetFileReadTotalSize() = 0;
  388. virtual int GetNumberOfFileOpens() = 0;
  389. virtual void Reset() = 0;
  390. protected:
  391. virtual ~IIoStats()
  392. {
  393. // Do nothing...
  394. }
  395. };
  396. //-----------------------------------------------------------------------------
  397. // Main file system interface
  398. //-----------------------------------------------------------------------------
  399. abstract_class IFileSystem : public IAppSystem, public IBaseFileSystem
  400. {
  401. public:
  402. //--------------------------------------------------------
  403. // Steam operations
  404. //--------------------------------------------------------
  405. virtual bool IsSteam() const = 0;
  406. // Supplying an extra app id will mount this app in addition
  407. // to the one specified in the environment variable "steamappid"
  408. //
  409. // If nExtraAppId is < -1, then it will mount that app ID only.
  410. // (Was needed by the dedicated server b/c the "SteamAppId" env var only gets passed to steam.dll
  411. // at load time, so the dedicated couldn't pass it in that way).
  412. virtual FilesystemMountRetval_t MountSteamContent( int nExtraAppId = -1 ) = 0;
  413. //--------------------------------------------------------
  414. // Search path manipulation
  415. //--------------------------------------------------------
  416. // Add paths in priority order (mod dir, game dir, ....)
  417. // If one or more .pak files are in the specified directory, then they are
  418. // added after the file system path
  419. // If the path is the relative path to a .bsp file, then any previous .bsp file
  420. // override is cleared and the current .bsp is searched for an embedded PAK file
  421. // and this file becomes the highest priority search path ( i.e., it's looked at first
  422. // even before the mod's file system path ).
  423. virtual void AddSearchPath( const char *pPath, const char *pathID, SearchPathAdd_t addType = PATH_ADD_TO_TAIL ) = 0;
  424. virtual bool RemoveSearchPath( const char *pPath, const char *pathID = 0 ) = 0;
  425. // Remove all search paths (including write path?)
  426. virtual void RemoveAllSearchPaths( void ) = 0;
  427. // Remove search paths associated with a given pathID
  428. virtual void RemoveSearchPaths( const char *szPathID ) = 0;
  429. // This is for optimization. If you mark a path ID as "by request only", then files inside it
  430. // will only be accessed if the path ID is specifically requested. Otherwise, it will be ignored.
  431. // If there are currently no search paths with the specified path ID, then it will still
  432. // remember it in case you add search paths with this path ID.
  433. virtual void MarkPathIDByRequestOnly( const char *pPathID, bool bRequestOnly ) = 0;
  434. // converts a partial path into a full path
  435. virtual const char *RelativePathToFullPath( const char *pFileName, const char *pPathID, char *pLocalPath, int localPathBufferSize, PathTypeFilter_t pathFilter = FILTER_NONE, PathTypeQuery_t *pPathType = NULL ) = 0;
  436. #if IsGameConsole()
  437. // Given a relative path, gets the PACK file that contained this file and its offset and size. Can be used to prefetch a file to a HDD for caching reason.
  438. virtual bool GetPackFileInfoFromRelativePath( const char *pFileName, const char *pPathID, char *pPackPath, int nPackPathBufferSize, int64 &nPosition, int64 &nLength ) = 0;
  439. #endif
  440. // Returns the search path, each path is separated by ;s. Returns the length of the string returned
  441. virtual int GetSearchPath( const char *pathID, bool bGetPackFiles, char *pPath, int nMaxLen ) = 0;
  442. // interface for custom pack files > 4Gb
  443. virtual bool AddPackFile( const char *fullpath, const char *pathID ) = 0;
  444. //--------------------------------------------------------
  445. // File manipulation operations
  446. //--------------------------------------------------------
  447. // Deletes a file (on the WritePath)
  448. virtual void RemoveFile( char const* pRelativePath, const char *pathID = 0 ) = 0;
  449. // Renames a file (on the WritePath)
  450. virtual bool RenameFile( char const *pOldPath, char const *pNewPath, const char *pathID = 0 ) = 0;
  451. // create a local directory structure
  452. virtual void CreateDirHierarchy( const char *path, const char *pathID = 0 ) = 0;
  453. // File I/O and info
  454. virtual bool IsDirectory( const char *pFileName, const char *pathID = 0 ) = 0;
  455. virtual void FileTimeToString( char* pStrip, int maxCharsIncludingTerminator, long fileTime ) = 0;
  456. //--------------------------------------------------------
  457. // Open file operations
  458. //--------------------------------------------------------
  459. virtual void SetBufferSize( FileHandle_t file, unsigned nBytes ) = 0;
  460. virtual bool IsOk( FileHandle_t file ) = 0;
  461. virtual bool EndOfFile( FileHandle_t file ) = 0;
  462. virtual char *ReadLine( char *pOutput, int maxChars, FileHandle_t file ) = 0;
  463. virtual int FPrintf( FileHandle_t file, const char *pFormat, ... ) FMTFUNCTION( 3, 4 ) = 0;
  464. //--------------------------------------------------------
  465. // Dynamic library operations
  466. //--------------------------------------------------------
  467. // load/unload modules
  468. virtual CSysModule *LoadModule( const char *pFileName, const char *pPathID = 0, bool bValidatedDllOnly = true ) = 0;
  469. virtual void UnloadModule( CSysModule *pModule ) = 0;
  470. //--------------------------------------------------------
  471. // File searching operations
  472. //--------------------------------------------------------
  473. // FindFirst/FindNext. Also see FindFirstEx.
  474. virtual const char *FindFirst( const char *pWildCard, FileFindHandle_t *pHandle ) = 0;
  475. virtual const char *FindNext( FileFindHandle_t handle ) = 0;
  476. virtual bool FindIsDirectory( FileFindHandle_t handle ) = 0;
  477. virtual void FindClose( FileFindHandle_t handle ) = 0;
  478. // Same as FindFirst, but you can filter by path ID, which can make it faster.
  479. virtual const char *FindFirstEx(
  480. const char *pWildCard,
  481. const char *pPathID,
  482. FileFindHandle_t *pHandle
  483. ) = 0;
  484. // Searches for a file in all paths and results absolute path names for the file, works in pack files (zip and vpk) too
  485. // Lets you search for something like sound/sound.cache and get a list of every sound cache
  486. virtual void FindFileAbsoluteList( CUtlVector< CUtlString > &outAbsolutePathNames, const char *pWildCard, const char *pPathID ) = 0;
  487. //--------------------------------------------------------
  488. // File name and directory operations
  489. //--------------------------------------------------------
  490. // FIXME: This method is obsolete! Use RelativePathToFullPath instead!
  491. // converts a partial path into a full path
  492. virtual const char *GetLocalPath( const char *pFileName, char *pLocalPath, int localPathBufferSize ) = 0;
  493. // Returns true on success ( based on current list of search paths, otherwise false if
  494. // it can't be resolved )
  495. virtual bool FullPathToRelativePath( const char *pFullpath, char *pRelative, int maxlen ) = 0;
  496. // Gets the current working directory
  497. virtual bool GetCurrentDirectory( char* pDirectory, int maxlen ) = 0;
  498. //--------------------------------------------------------
  499. // Filename dictionary operations
  500. //--------------------------------------------------------
  501. virtual FileNameHandle_t FindOrAddFileName( char const *pFileName ) = 0;
  502. virtual bool String( const FileNameHandle_t& handle, char *buf, int buflen ) = 0;
  503. //--------------------------------------------------------
  504. // Asynchronous file operations
  505. //--------------------------------------------------------
  506. //------------------------------------
  507. // Global operations
  508. //------------------------------------
  509. FSAsyncStatus_t AsyncRead( const FileAsyncRequest_t &request, FSAsyncControl_t *phControl = NULL ) { return AsyncReadMultiple( &request, 1, phControl ); }
  510. virtual FSAsyncStatus_t AsyncReadMultiple( const FileAsyncRequest_t *pRequests, int nRequests, FSAsyncControl_t *phControls = NULL ) = 0;
  511. virtual FSAsyncStatus_t AsyncAppend(const char *pFileName, const void *pSrc, int nSrcBytes, bool bFreeMemory, FSAsyncControl_t *pControl = NULL ) = 0;
  512. virtual FSAsyncStatus_t AsyncAppendFile(const char *pAppendToFileName, const char *pAppendFromFileName, FSAsyncControl_t *pControl = NULL ) = 0;
  513. virtual void AsyncFinishAll( int iToPriority = 0 ) = 0;
  514. virtual void AsyncFinishAllWrites() = 0;
  515. virtual FSAsyncStatus_t AsyncFlush() = 0;
  516. virtual bool AsyncSuspend() = 0;
  517. virtual bool AsyncResume() = 0;
  518. //------------------------------------
  519. // Functions to hold a file open if planning on doing mutiple reads. Use is optional,
  520. // and is taken only as a hint
  521. //------------------------------------
  522. virtual FSAsyncStatus_t AsyncBeginRead( const char *pszFile, FSAsyncFile_t *phFile ) = 0;
  523. virtual FSAsyncStatus_t AsyncEndRead( FSAsyncFile_t hFile ) = 0;
  524. //------------------------------------
  525. // Request management
  526. //------------------------------------
  527. virtual FSAsyncStatus_t AsyncFinish( FSAsyncControl_t hControl, bool wait = true ) = 0;
  528. virtual FSAsyncStatus_t AsyncGetResult( FSAsyncControl_t hControl, void **ppData, int *pSize ) = 0;
  529. virtual FSAsyncStatus_t AsyncAbort( FSAsyncControl_t hControl ) = 0;
  530. virtual FSAsyncStatus_t AsyncStatus( FSAsyncControl_t hControl ) = 0;
  531. // set a new priority for a file already in the queue
  532. virtual FSAsyncStatus_t AsyncSetPriority(FSAsyncControl_t hControl, int newPriority) = 0;
  533. virtual void AsyncAddRef( FSAsyncControl_t hControl ) = 0;
  534. virtual void AsyncRelease( FSAsyncControl_t hControl ) = 0;
  535. //--------------------------------------------------------
  536. // Remote resource management
  537. //--------------------------------------------------------
  538. // starts waiting for resources to be available
  539. // returns FILESYSTEM_INVALID_HANDLE if there is nothing to wait on
  540. virtual WaitForResourcesHandle_t WaitForResources( const char *resourcelist ) = 0;
  541. // get progress on waiting for resources; progress is a float [0, 1], complete is true on the waiting being done
  542. // returns false if no progress is available
  543. // any calls after complete is true or on an invalid handle will return false, 0.0f, true
  544. virtual bool GetWaitForResourcesProgress( WaitForResourcesHandle_t handle, float *progress /* out */ , bool *complete /* out */ ) = 0;
  545. // cancels a progress call
  546. virtual void CancelWaitForResources( WaitForResourcesHandle_t handle ) = 0;
  547. // hints that a set of files will be loaded in near future
  548. // HintResourceNeed() is not to be confused with resource precaching.
  549. virtual int HintResourceNeed( const char *hintlist, int forgetEverything ) = 0;
  550. // returns true if a file is on disk
  551. virtual bool IsFileImmediatelyAvailable(const char *pFileName) = 0;
  552. // copies file out of pak/bsp/steam cache onto disk (to be accessible by third-party code)
  553. virtual void GetLocalCopy( const char *pFileName ) = 0;
  554. //--------------------------------------------------------
  555. // Debugging operations
  556. //--------------------------------------------------------
  557. // Dump to printf/OutputDebugString the list of files that have not been closed
  558. virtual void PrintOpenedFiles( void ) = 0;
  559. virtual void PrintSearchPaths( void ) = 0;
  560. // output
  561. virtual void SetWarningFunc( void (*pfnWarning)( const char *fmt, ... ) ) = 0;
  562. virtual void SetWarningLevel( FileWarningLevel_t level ) = 0;
  563. virtual void AddLoggingFunc( void (*pfnLogFunc)( const char *fileName, const char *accessType ) ) = 0;
  564. virtual void RemoveLoggingFunc( FileSystemLoggingFunc_t logFunc ) = 0;
  565. // Returns the file system statistics retreived by the implementation. Returns NULL if not supported.
  566. virtual const FileSystemStatistics *GetFilesystemStatistics() = 0;
  567. #if defined( _PS3 )
  568. // EA cruft not used: virtual Ps3FileType_t GetPs3FileType(const char* path) = 0;
  569. virtual void LogFileAccess( const char *pFullFileName ) = 0;
  570. // Prefetches a full file in the HDD cache.
  571. virtual bool PrefetchFile( const char *pFileName, int nPriority, bool bPersist ) = 0;
  572. // Prefetches a file portion in the HDD cache.
  573. virtual bool PrefetchFile( const char *pFileName, int nPriority, bool bPersist, int64 nOffset, int64 nSize ) = 0;
  574. // Flushes the HDD cache.
  575. virtual void FlushCache() = 0;
  576. // Suspends all prefetches (like when the game is doing a file intensive operation not controlled by the HDD cache, like Bink movies).
  577. virtual void SuspendPrefetches( const char *pWhy ) = 0;
  578. // Resumes prefetches. This function has to to be called as many time as SuspendPrefetches() to effectively resumes prefetches.
  579. virtual void ResumePrefetches( const char * pWhy ) = 0;
  580. // Gets called when we are starting / ending a save (it allows the file system to reduce its HDD usage and use BluRay instead).
  581. virtual void OnSaveStateChanged( bool bSaving ) = 0;
  582. // Returns the prefetching state. If true, everything has been prefetched on the HDD.
  583. virtual bool IsPrefetchingDone() = 0;
  584. #endif //_PS3
  585. //--------------------------------------------------------
  586. // Start of new functions after Lost Coast release (7/05)
  587. //--------------------------------------------------------
  588. virtual FileHandle_t OpenEx( const char *pFileName, const char *pOptions, unsigned flags = 0, const char *pathID = 0, char **ppszResolvedFilename = NULL ) = 0;
  589. // Extended version of read provides more context to allow for more optimal reading
  590. virtual int ReadEx( void* pOutput, int sizeDest, int size, FileHandle_t file ) = 0;
  591. virtual int ReadFileEx( const char *pFileName, const char *pPath, void **ppBuf, bool bNullTerminate = false, bool bOptimalAlloc = false, int nMaxBytes = 0, int nStartingByte = 0, FSAllocFunc_t pfnAlloc = NULL ) = 0;
  592. virtual FileNameHandle_t FindFileName( char const *pFileName ) = 0;
  593. #if defined( TRACK_BLOCKING_IO )
  594. virtual void EnableBlockingFileAccessTracking( bool state ) = 0;
  595. virtual bool IsBlockingFileAccessEnabled() const = 0;
  596. virtual IBlockingFileItemList *RetrieveBlockingFileAccessInfo() = 0;
  597. #endif
  598. virtual void SetupPreloadData() = 0;
  599. virtual void DiscardPreloadData() = 0;
  600. // Fixme, we could do these via a string embedded into the compiled data, etc...
  601. enum KeyValuesPreloadType_t
  602. {
  603. TYPE_VMT,
  604. TYPE_SOUNDEMITTER,
  605. TYPE_SOUNDSCAPE,
  606. TYPE_SOUNDOPERATORS,
  607. NUM_PRELOAD_TYPES
  608. };
  609. // If the "PreloadedData" hasn't been purged, then this'll try and instance the KeyValues using the fast path of compiled keyvalues loaded during startup.
  610. // Otherwise, it'll just fall through to the regular KeyValues loading routines
  611. virtual KeyValues *LoadKeyValues( KeyValuesPreloadType_t type, char const *filename, char const *pPathID = 0 ) = 0;
  612. virtual bool LoadKeyValues( KeyValues& head, KeyValuesPreloadType_t type, char const *filename, char const *pPathID = 0 ) = 0;
  613. virtual FSAsyncStatus_t AsyncWrite(const char *pFileName, const void *pSrc, int nSrcBytes, bool bFreeMemory, bool bAppend = false, FSAsyncControl_t *pControl = NULL ) = 0;
  614. virtual FSAsyncStatus_t AsyncWriteFile(const char *pFileName, const CUtlBuffer *pSrc, int nSrcBytes, bool bFreeMemory, bool bAppend = false, FSAsyncControl_t *pControl = NULL ) = 0;
  615. // Async read functions with memory blame
  616. FSAsyncStatus_t AsyncReadCreditAlloc( const FileAsyncRequest_t &request, const char *pszFile, int line, FSAsyncControl_t *phControl = NULL ) { return AsyncReadMultipleCreditAlloc( &request, 1, pszFile, line, phControl ); }
  617. virtual FSAsyncStatus_t AsyncReadMultipleCreditAlloc( const FileAsyncRequest_t *pRequests, int nRequests, const char *pszFile, int line, FSAsyncControl_t *phControls = NULL ) = 0;
  618. virtual FSAsyncStatus_t AsyncDirectoryScan( const char* pSearchSpec, bool recurseFolders, void* pContext, FSAsyncScanAddFunc_t pfnAdd, FSAsyncScanCompleteFunc_t pfnDone, FSAsyncControl_t *pControl = NULL ) = 0;
  619. virtual bool GetFileTypeForFullPath( char const *pFullPath, wchar_t *buf, size_t bufSizeInBytes ) = 0;
  620. //--------------------------------------------------------
  621. //--------------------------------------------------------
  622. virtual bool ReadToBuffer( FileHandle_t hFile, CUtlBuffer &buf, int nMaxBytes = 0, FSAllocFunc_t pfnAlloc = NULL ) = 0;
  623. //--------------------------------------------------------
  624. // Optimal IO operations
  625. //--------------------------------------------------------
  626. virtual bool GetOptimalIOConstraints( FileHandle_t hFile, unsigned *pOffsetAlign, unsigned *pSizeAlign, unsigned *pBufferAlign ) = 0;
  627. inline unsigned GetOptimalReadSize( FileHandle_t hFile, unsigned nLogicalSize );
  628. virtual void *AllocOptimalReadBuffer( FileHandle_t hFile, unsigned nSize = 0, unsigned nOffset = 0 ) = 0;
  629. virtual void FreeOptimalReadBuffer( void * ) = 0;
  630. //--------------------------------------------------------
  631. //
  632. //--------------------------------------------------------
  633. virtual void BeginMapAccess() = 0;
  634. virtual void EndMapAccess() = 0;
  635. // Returns true on success, otherwise false if it can't be resolved
  636. virtual bool FullPathToRelativePathEx( const char *pFullpath, const char *pPathId, char *pRelative, int maxlen ) = 0;
  637. virtual int GetPathIndex( const FileNameHandle_t &handle ) = 0;
  638. virtual long GetPathTime( const char *pPath, const char *pPathID ) = 0;
  639. virtual DVDMode_t GetDVDMode() = 0;
  640. //--------------------------------------------------------
  641. // Whitelisting for pure servers.
  642. //--------------------------------------------------------
  643. // This should be called ONCE at startup. Multiplayer games (gameinfo.txt does not contain singleplayer_only)
  644. // want to enable this so sv_pure works.
  645. virtual void EnableWhitelistFileTracking( bool bEnable ) = 0;
  646. // This is called when the client connects to a server using a pure_server_whitelist.txt file.
  647. //
  648. // Files listed in pWantCRCList will have CRCs calculated for them IF they come off disk
  649. // (and those CRCs will come out of GetUnverifiedCRCFiles).
  650. //
  651. // Files listed in pAllowFromDiskList will be allowed to load from disk. All other files will
  652. // be forced to come from Steam.
  653. //
  654. // The filesystem hangs onto the whitelists you pass in here, and it will Release() them when it closes down
  655. // or when you call this function again.
  656. //
  657. // NOTE: The whitelists you pass in here will be accessed from multiple threads, so make sure the
  658. // IsFileInList function is thread safe.
  659. //
  660. // If pFilesToReload is non-null, the filesystem will hand back a list of files that should be reloaded because they
  661. // are now "dirty". For example, if you were on a non-pure server and you loaded a certain model, and then you connected
  662. // to a pure server that said that model had to come from Steam, then pFilesToReload would specify that model
  663. // and the engine should reload it so it can come from Steam.
  664. //
  665. // Be sure to call Release() on pFilesToReload.
  666. virtual void RegisterFileWhitelist( IFileList *pWantCRCList, IFileList *pAllowFromDiskList, IFileList **pFilesToReload ) = 0;
  667. // Called when the client logs onto a server. Any files that came off disk should be marked as
  668. // unverified because this server may have a different set of files it wants to guarantee.
  669. virtual void MarkAllCRCsUnverified() = 0;
  670. // As the server loads whitelists when it transitions maps, it calls this to calculate CRCs for any files marked
  671. // with check_crc. Then it calls CheckCachedFileCRC later when it gets client requests to verify CRCs.
  672. virtual void CacheFileCRCs( const char *pPathname, ECacheCRCType eType, IFileList *pFilter ) = 0;
  673. virtual EFileCRCStatus CheckCachedFileCRC( const char *pPathID, const char *pRelativeFilename, CRC32_t *pCRC ) = 0;
  674. // Fills in the list of files that have been loaded off disk and have not been verified.
  675. // Returns the number of files filled in (between 0 and nMaxFiles).
  676. //
  677. // This also removes any files it's returning from the unverified CRC list, so they won't be
  678. // returned from here again.
  679. // The client sends batches of these to the server to verify.
  680. virtual int GetUnverifiedCRCFiles( CUnverifiedCRCFile *pFiles, int nMaxFiles ) = 0;
  681. // Control debug message output.
  682. // Pass a combination of WHITELIST_SPEW_ flags.
  683. virtual int GetWhitelistSpewFlags() = 0;
  684. virtual void SetWhitelistSpewFlags( int flags ) = 0;
  685. // Installs a callback used to display a dirty disk dialog
  686. virtual void InstallDirtyDiskReportFunc( FSDirtyDiskReportFunc_t func ) = 0;
  687. virtual bool IsLaunchedFromXboxHDD() = 0;
  688. virtual bool IsInstalledToXboxHDDCache() = 0;
  689. virtual bool IsDVDHosted() = 0;
  690. virtual bool IsInstallAllowed() = 0;
  691. virtual int GetSearchPathID( char *pPath, int nMaxLen ) = 0;
  692. virtual bool FixupSearchPathsAfterInstall() = 0;
  693. virtual FSDirtyDiskReportFunc_t GetDirtyDiskReportFunc() = 0;
  694. virtual void AddVPKFile( char const *pszName, SearchPathAdd_t addType = PATH_ADD_TO_TAIL ) = 0;
  695. virtual void RemoveVPKFile( char const *pszName ) = 0;
  696. virtual void GetVPKFileNames( CUtlVector<CUtlString> &destVector ) = 0;
  697. virtual void RemoveAllMapSearchPaths() = 0;
  698. virtual void SyncDvdDevCache() = 0;
  699. virtual bool GetStringFromKVPool( CRC32_t poolKey, unsigned int key, char *pOutBuff, int buflen ) = 0;
  700. virtual bool DiscoverDLC( int iController ) = 0;
  701. virtual int IsAnyDLCPresent( bool *pbDLCSearchPathMounted = NULL ) = 0;
  702. virtual bool GetAnyDLCInfo( int iDLC, unsigned int *pLicenseMask, wchar_t *pTitleBuff, int nOutTitleSize ) = 0;
  703. virtual int IsAnyCorruptDLC() = 0;
  704. virtual bool GetAnyCorruptDLCInfo( int iCorruptDLC, wchar_t *pTitleBuff, int nOutTitleSize ) = 0;
  705. virtual bool AddDLCSearchPaths() = 0;
  706. virtual bool IsSpecificDLCPresent( unsigned int nDLCPackage ) = 0;
  707. // call this to look for CPU-hogs during loading processes. When you set this, a breakpoint
  708. // will be issued whenever the indicated # of seconds go by without an i/o request. Passing
  709. // 0.0 will turn off the functionality.
  710. virtual void SetIODelayAlarm( float flThreshhold ) = 0;
  711. virtual bool AddXLSPUpdateSearchPath( const void *pData, int nSize ) = 0;
  712. virtual IIoStats *GetIoStats() = 0;
  713. };
  714. //-----------------------------------------------------------------------------
  715. #if defined( _X360 ) && !defined( _CERT )
  716. extern char g_szXboxProfileLastFileOpened[MAX_PATH];
  717. #define SetLastProfileFileRead( s ) V_strncpy( g_szXboxProfileLastFileOpened, sizeof( g_szXboxProfileLastFileOpened), pFileName )
  718. #define GetLastProfileFileRead() (&g_szXboxProfileLastFileOpened[0])
  719. #else
  720. #define SetLastProfileFileRead( s ) ((void)0)
  721. #define GetLastProfileFileRead() NULL
  722. #endif
  723. #if defined( _X360 ) && defined( _BASETSD_H_ )
  724. class CXboxDiskCacheSetter
  725. {
  726. public:
  727. CXboxDiskCacheSetter( SIZE_T newSize )
  728. {
  729. m_oldSize = XGetFileCacheSize();
  730. XSetFileCacheSize( newSize );
  731. }
  732. ~CXboxDiskCacheSetter()
  733. {
  734. XSetFileCacheSize( m_oldSize );
  735. }
  736. private:
  737. SIZE_T m_oldSize;
  738. };
  739. #define DISK_INTENSIVE() CXboxDiskCacheSetter cacheSetter( 1024*1024 )
  740. #else
  741. #define DISK_INTENSIVE() ((void)0)
  742. #endif
  743. //-----------------------------------------------------------------------------
  744. inline unsigned IFileSystem::GetOptimalReadSize( FileHandle_t hFile, unsigned nLogicalSize )
  745. {
  746. unsigned align;
  747. if ( GetOptimalIOConstraints( hFile, &align, NULL, NULL ) )
  748. return AlignValue( nLogicalSize, align );
  749. else
  750. return nLogicalSize;
  751. }
  752. //-----------------------------------------------------------------------------
  753. // We include this here so it'll catch compile errors in VMPI early.
  754. #include "filesystem_passthru.h"
  755. //-----------------------------------------------------------------------------
  756. // Async memory tracking
  757. //-----------------------------------------------------------------------------
  758. #if (defined(_DEBUG) || defined(USE_MEM_DEBUG))
  759. #define AsyncRead( a, b ) AsyncReadCreditAlloc( a, __FILE__, __LINE__, b )
  760. #define AsyncReadMutiple( a, b, c ) AsyncReadMultipleCreditAlloc( a, b, __FILE__, __LINE__, c )
  761. #endif
  762. //-----------------------------------------------------------------------------
  763. // Globals Exposed
  764. //-----------------------------------------------------------------------------
  765. DECLARE_TIER2_INTERFACE( IFileSystem, g_pFullFileSystem );
  766. #endif // FILESYSTEM_H